2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "../ssl_locl.h"
12 #include "internal/constant_time_locl.h"
13 #include <openssl/rand.h>
14 #include "record_locl.h"
16 static const unsigned char ssl3_pad_1[48] = {
17 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
18 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
19 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
20 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
21 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
22 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
25 static const unsigned char ssl3_pad_2[48] = {
26 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
27 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
28 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
29 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
30 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
31 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
35 * Clear the contents of an SSL3_RECORD but retain any memory allocated
37 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
42 for (i = 0; i < num_recs; i++) {
45 memset(&r[i], 0, sizeof(*r));
50 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
54 for (i = 0; i < num_recs; i++) {
55 OPENSSL_free(r[i].comp);
60 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
62 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
66 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
67 * for us in the buffer.
69 static int ssl3_record_app_data_waiting(SSL *s)
75 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
77 p = SSL3_BUFFER_get_buf(rbuf);
81 left = SSL3_BUFFER_get_left(rbuf);
83 if (left < SSL3_RT_HEADER_LENGTH)
86 p += SSL3_BUFFER_get_offset(rbuf);
89 * We only check the type and record length, we will sanity check version
92 if (*p != SSL3_RT_APPLICATION_DATA)
98 if (left < SSL3_RT_HEADER_LENGTH + len)
105 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
106 * will be processed per call to ssl3_get_record. Without this limit an
107 * attacker could send empty records at a faster rate than we can process and
108 * cause ssl3_get_record to loop forever.
110 #define MAX_EMPTY_RECORDS 32
112 #define SSL2_RT_HEADER_LENGTH 2
114 * Call this to get new input records.
115 * It will return <= 0 if more data is needed, normally due to an error
116 * or non-blocking IO.
117 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
118 * rr[i].type - is the type of record
120 * rr[i].length, - number of bytes
121 * Multiple records will only be returned if the record types are all
122 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
125 /* used only by ssl3_read_bytes */
126 int ssl3_get_record(SSL *s)
129 int enc_err, rret, ret = -1;
132 SSL3_RECORD *rr, *thisrr;
136 unsigned char md[EVP_MAX_MD_SIZE];
137 unsigned int version;
140 size_t num_recs = 0, max_recs, j;
141 PACKET pkt, sslv2pkt;
143 rr = RECORD_LAYER_get_rrec(&s->rlayer);
144 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
145 max_recs = s->max_pipelines;
151 thisrr = &rr[num_recs];
153 /* check if we have the header */
154 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
155 (RECORD_LAYER_get_packet_length(&s->rlayer)
156 < SSL3_RT_HEADER_LENGTH)) {
160 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
161 SSL3_BUFFER_get_len(rbuf), 0,
162 num_recs == 0 ? 1 : 0, &n);
164 return rret; /* error or non-blocking */
165 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
167 p = RECORD_LAYER_get_packet(&s->rlayer);
168 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
169 RECORD_LAYER_get_packet_length(&s->rlayer))) {
170 al = SSL_AD_INTERNAL_ERROR;
171 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
175 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
176 || !PACKET_get_1(&sslv2pkt, &type)) {
177 al = SSL_AD_INTERNAL_ERROR;
178 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
182 * The first record received by the server may be a V2ClientHello.
184 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
185 && (sslv2len & 0x8000) != 0
186 && (type == SSL2_MT_CLIENT_HELLO)) {
190 * |num_recs| here will actually always be 0 because
191 * |num_recs > 0| only ever occurs when we are processing
192 * multiple app data records - which we know isn't the case here
193 * because it is an SSLv2ClientHello. We keep it using
194 * |num_recs| for the sake of consistency
196 thisrr->type = SSL3_RT_HANDSHAKE;
197 thisrr->rec_version = SSL2_VERSION;
199 thisrr->length = sslv2len & 0x7fff;
201 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
202 - SSL2_RT_HEADER_LENGTH) {
203 al = SSL_AD_RECORD_OVERFLOW;
204 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
208 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
209 al = SSL_AD_HANDSHAKE_FAILURE;
210 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
214 /* SSLv3+ style record */
216 * TODO(TLS1.3): This callback only provides the "outer" record
217 * type to the callback. Somehow we need to pass the "inner"
221 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
222 s->msg_callback_arg);
224 /* Pull apart the header into the SSL3_RECORD */
225 if (!PACKET_get_1(&pkt, &type)
226 || !PACKET_get_net_2(&pkt, &version)
227 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
228 al = SSL_AD_INTERNAL_ERROR;
229 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
233 thisrr->rec_version = version;
235 /* Lets check version. In TLSv1.3 we ignore this field */
236 if (!s->first_packet && !SSL_IS_TLS13(s)
237 && version != (unsigned int)s->version) {
238 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
239 if ((s->version & 0xFF00) == (version & 0xFF00)
240 && !s->enc_write_ctx && !s->write_hash) {
241 if (thisrr->type == SSL3_RT_ALERT) {
243 * The record is using an incorrect version number,
244 * but what we've got appears to be an alert. We
245 * haven't read the body yet to check whether its a
246 * fatal or not - but chances are it is. We probably
247 * shouldn't send a fatal alert back. We'll just
253 * Send back error using their minor version number :-)
255 s->version = (unsigned short)version;
257 al = SSL_AD_PROTOCOL_VERSION;
261 if ((version >> 8) != SSL3_VERSION_MAJOR) {
262 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
263 /* Go back to start of packet, look at the five bytes
265 p = RECORD_LAYER_get_packet(&s->rlayer);
266 if (strncmp((char *)p, "GET ", 4) == 0 ||
267 strncmp((char *)p, "POST ", 5) == 0 ||
268 strncmp((char *)p, "HEAD ", 5) == 0 ||
269 strncmp((char *)p, "PUT ", 4) == 0) {
270 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
272 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
273 SSLerr(SSL_F_SSL3_GET_RECORD,
274 SSL_R_HTTPS_PROXY_REQUEST);
278 /* Doesn't look like TLS - don't send an alert */
279 SSLerr(SSL_F_SSL3_GET_RECORD,
280 SSL_R_WRONG_VERSION_NUMBER);
283 SSLerr(SSL_F_SSL3_GET_RECORD,
284 SSL_R_WRONG_VERSION_NUMBER);
285 al = SSL_AD_PROTOCOL_VERSION;
290 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
291 && thisrr->type != SSL3_RT_APPLICATION_DATA) {
292 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
293 al = SSL_AD_UNEXPECTED_MESSAGE;
298 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
299 al = SSL_AD_RECORD_OVERFLOW;
300 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
305 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
309 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
310 * Calculate how much more data we need to read for the rest of the
313 if (thisrr->rec_version == SSL2_VERSION) {
314 more = thisrr->length + SSL2_RT_HEADER_LENGTH
315 - SSL3_RT_HEADER_LENGTH;
317 more = thisrr->length;
320 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
322 rret = ssl3_read_n(s, more, more, 1, 0, &n);
324 return rret; /* error or non-blocking io */
327 /* set state for later operations */
328 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
331 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
332 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
333 * + thisrr->length and we have that many bytes in s->packet
335 if (thisrr->rec_version == SSL2_VERSION) {
337 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
340 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
344 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
345 * points at thisrr->length bytes, which need to be copied into
346 * thisrr->data by either the decryption or by the decompression When
347 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
348 * be pointed at the new buffer
352 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
353 * thisrr->length bytes of encrypted compressed stuff.
356 /* check is not needed I believe */
357 if (thisrr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
358 al = SSL_AD_RECORD_OVERFLOW;
359 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
363 /* decrypt in place in 'thisrr->input' */
364 thisrr->data = thisrr->input;
365 thisrr->orig_len = thisrr->length;
367 /* Mark this record as not read by upper layers yet */
372 /* we have pulled in a full packet so zero things */
373 RECORD_LAYER_reset_packet_length(&s->rlayer);
374 RECORD_LAYER_clear_first_record(&s->rlayer);
375 } while (num_recs < max_recs
376 && thisrr->type == SSL3_RT_APPLICATION_DATA
377 && SSL_USE_EXPLICIT_IV(s)
378 && s->enc_read_ctx != NULL
379 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
380 & EVP_CIPH_FLAG_PIPELINE)
381 && ssl3_record_app_data_waiting(s));
384 * If in encrypt-then-mac mode calculate mac from encrypted record. All
385 * the details below are public so no timing details can leak.
387 if (SSL_READ_ETM(s) && s->read_hash) {
389 /* TODO(size_t): convert this to do size_t properly */
390 imac_size = EVP_MD_CTX_size(s->read_hash);
391 assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
392 if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
393 al = SSL_AD_INTERNAL_ERROR;
394 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
397 mac_size = (size_t)imac_size;
398 for (j = 0; j < num_recs; j++) {
401 if (thisrr->length < mac_size) {
402 al = SSL_AD_DECODE_ERROR;
403 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
406 thisrr->length -= mac_size;
407 mac = thisrr->data + thisrr->length;
408 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
409 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
410 al = SSL_AD_BAD_RECORD_MAC;
411 SSLerr(SSL_F_SSL3_GET_RECORD,
412 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
418 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
422 * 0: (in non-constant time) if the record is publicly invalid.
423 * 1: if the padding is valid
424 * -1: if the padding is invalid
427 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
429 * Valid early_data that we cannot decrypt might fail here as
430 * publicly invalid. We treat it like an empty record.
435 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
436 RECORD_LAYER_reset_read_sequence(&s->rlayer);
439 al = SSL_AD_DECRYPTION_FAILED;
440 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
444 printf("dec %"OSSLzu"\n", rr[0].length);
447 for (z = 0; z < rr[0].length; z++)
448 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
453 /* r->length is now the compressed data plus mac */
454 if ((sess != NULL) &&
455 (s->enc_read_ctx != NULL) &&
456 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
457 /* s->read_hash != NULL => mac_size != -1 */
458 unsigned char *mac = NULL;
459 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
461 mac_size = EVP_MD_CTX_size(s->read_hash);
462 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
464 for (j = 0; j < num_recs; j++) {
467 * orig_len is the length of the record before any padding was
468 * removed. This is public information, as is the MAC in use,
469 * therefore we can safely process the record in a different amount
470 * of time if it's too short to possibly contain a MAC.
472 if (thisrr->orig_len < mac_size ||
473 /* CBC records must have a padding length byte too. */
474 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
475 thisrr->orig_len < mac_size + 1)) {
476 al = SSL_AD_DECODE_ERROR;
477 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
481 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
483 * We update the length so that the TLS header bytes can be
484 * constructed correctly but we need to extract the MAC in
485 * constant time from within the record, without leaking the
486 * contents of the padding bytes.
489 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
490 thisrr->length -= mac_size;
493 * In this case there's no padding, so |rec->orig_len| equals
494 * |rec->length| and we checked that there's enough bytes for
497 thisrr->length -= mac_size;
498 mac = &thisrr->data[thisrr->length];
501 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
502 if (i == 0 || mac == NULL
503 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
505 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
511 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
513 * We assume this is unreadable early_data - we treat it like an
519 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
520 RECORD_LAYER_reset_read_sequence(&s->rlayer);
524 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
525 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
526 * failure is directly visible from the ciphertext anyway, we should
527 * not reveal which kind of error occurred -- this might become
528 * visible to an attacker (e.g. via a logfile)
530 al = SSL_AD_BAD_RECORD_MAC;
531 SSLerr(SSL_F_SSL3_GET_RECORD,
532 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
536 for (j = 0; j < num_recs; j++) {
539 /* thisrr->length is now just compressed */
540 if (s->expand != NULL) {
541 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
542 al = SSL_AD_RECORD_OVERFLOW;
543 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
546 if (!ssl3_do_uncompress(s, thisrr)) {
547 al = SSL_AD_DECOMPRESSION_FAILURE;
548 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
553 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
556 if (thisrr->length == 0) {
557 al = SSL_AD_UNEXPECTED_MESSAGE;
558 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
562 /* Strip trailing padding */
563 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
567 thisrr->length = end;
568 thisrr->type = thisrr->data[end];
569 if (thisrr->type != SSL3_RT_APPLICATION_DATA
570 && thisrr->type != SSL3_RT_ALERT
571 && thisrr->type != SSL3_RT_HANDSHAKE) {
572 al = SSL_AD_UNEXPECTED_MESSAGE;
573 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
578 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
579 al = SSL_AD_RECORD_OVERFLOW;
580 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
586 * So at this point the following is true
587 * thisrr->type is the type of record
588 * thisrr->length == number of bytes in record
589 * thisrr->off == offset to first valid byte
590 * thisrr->data == where to take bytes from, increment after use :-).
593 /* just read a 0 length packet */
594 if (thisrr->length == 0) {
595 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
596 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
597 > MAX_EMPTY_RECORDS) {
598 al = SSL_AD_UNEXPECTED_MESSAGE;
599 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
603 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
607 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
611 ssl3_send_alert(s, SSL3_AL_FATAL, al);
616 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
618 #ifndef OPENSSL_NO_COMP
621 if (rr->comp == NULL) {
622 rr->comp = (unsigned char *)
623 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
625 if (rr->comp == NULL)
628 /* TODO(size_t): Convert this call */
629 i = COMP_expand_block(ssl->expand, rr->comp,
630 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
640 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
642 #ifndef OPENSSL_NO_COMP
645 /* TODO(size_t): Convert this call */
646 i = COMP_compress_block(ssl->compress, wr->data,
647 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
648 wr->input, (int)wr->length);
654 wr->input = wr->data;
660 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
663 * 0: (in non-constant time) if the record is publically invalid (i.e. too
665 * 1: if the record's padding is valid / the encryption was successful.
666 * -1: if the record's padding is invalid or, if sending, an internal error
669 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send)
674 size_t bs, mac_size = 0;
676 const EVP_CIPHER *enc;
680 * We shouldn't ever be called with more than one record in the SSLv3 case
685 ds = s->enc_write_ctx;
686 if (s->enc_write_ctx == NULL)
689 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
691 ds = s->enc_read_ctx;
692 if (s->enc_read_ctx == NULL)
695 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
698 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
699 memmove(rec->data, rec->input, rec->length);
700 rec->input = rec->data;
703 /* TODO(size_t): Convert this call */
704 bs = EVP_CIPHER_CTX_block_size(ds);
708 if ((bs != 1) && send) {
711 /* we need to add 'i-1' padding bytes */
714 * the last of these zero bytes will be overwritten with the
717 memset(&rec->input[rec->length], 0, i);
719 rec->input[l - 1] = (unsigned char)(i - 1);
723 if (l == 0 || l % bs != 0)
725 /* otherwise, rec->length >= bs */
728 /* TODO(size_t): Convert this call */
729 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
732 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
733 /* TODO(size_t): convert me */
734 imac_size = EVP_MD_CTX_size(s->read_hash);
737 mac_size = (size_t)imac_size;
739 if ((bs != 1) && !send)
740 return ssl3_cbc_remove_padding(rec, bs, mac_size);
745 #define MAX_PADDING 256
747 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
750 * 0: (in non-constant time) if the record is publically invalid (i.e. too
752 * 1: if the record's padding is valid / the encryption was successful.
753 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
754 * an internal error occurred.
756 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
759 size_t reclen[SSL_MAX_PIPELINES];
760 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
761 int i, pad = 0, ret, tmpr;
762 size_t bs, mac_size = 0, ctr, padnum, loop;
763 unsigned char padval;
765 const EVP_CIPHER *enc;
771 if (EVP_MD_CTX_md(s->write_hash)) {
772 int n = EVP_MD_CTX_size(s->write_hash);
773 OPENSSL_assert(n >= 0);
775 ds = s->enc_write_ctx;
776 if (s->enc_write_ctx == NULL)
780 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
781 /* For TLSv1.1 and later explicit IV */
782 if (SSL_USE_EXPLICIT_IV(s)
783 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
784 ivlen = EVP_CIPHER_iv_length(enc);
788 for (ctr = 0; ctr < n_recs; ctr++) {
789 if (recs[ctr].data != recs[ctr].input) {
791 * we can't write into the input stream: Can this ever
794 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
796 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
797 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
804 if (EVP_MD_CTX_md(s->read_hash)) {
805 int n = EVP_MD_CTX_size(s->read_hash);
806 OPENSSL_assert(n >= 0);
808 ds = s->enc_read_ctx;
809 if (s->enc_read_ctx == NULL)
812 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
815 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
816 for (ctr = 0; ctr < n_recs; ctr++) {
817 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
818 recs[ctr].input = recs[ctr].data;
822 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
825 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
826 & EVP_CIPH_FLAG_PIPELINE)) {
828 * We shouldn't have been called with pipeline data if the
829 * cipher doesn't support pipelining
831 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
835 for (ctr = 0; ctr < n_recs; ctr++) {
836 reclen[ctr] = recs[ctr].length;
838 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
839 & EVP_CIPH_FLAG_AEAD_CIPHER) {
842 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
843 : RECORD_LAYER_get_read_sequence(&s->rlayer);
845 if (SSL_IS_DTLS(s)) {
846 /* DTLS does not support pipelining */
847 unsigned char dtlsseq[9], *p = dtlsseq;
849 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
850 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
851 memcpy(p, &seq[2], 6);
852 memcpy(buf[ctr], dtlsseq, 8);
854 memcpy(buf[ctr], seq, 8);
855 for (i = 7; i >= 0; i--) { /* increment */
862 buf[ctr][8] = recs[ctr].type;
863 buf[ctr][9] = (unsigned char)(s->version >> 8);
864 buf[ctr][10] = (unsigned char)(s->version);
865 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
866 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
867 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
868 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
874 recs[ctr].length += pad;
877 } else if ((bs != 1) && send) {
878 padnum = bs - (reclen[ctr] % bs);
880 /* Add weird padding of upto 256 bytes */
882 if (padnum > MAX_PADDING)
884 /* we need to add 'padnum' padding bytes of value padval */
885 padval = (unsigned char)(padnum - 1);
886 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
887 recs[ctr].input[loop] = padval;
888 reclen[ctr] += padnum;
889 recs[ctr].length += padnum;
893 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
898 unsigned char *data[SSL_MAX_PIPELINES];
900 /* Set the output buffers */
901 for (ctr = 0; ctr < n_recs; ctr++) {
902 data[ctr] = recs[ctr].data;
904 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
905 (int)n_recs, data) <= 0) {
906 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
908 /* Set the input buffers */
909 for (ctr = 0; ctr < n_recs; ctr++) {
910 data[ctr] = recs[ctr].input;
912 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
913 (int)n_recs, data) <= 0
914 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
915 (int)n_recs, reclen) <= 0) {
916 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
921 /* TODO(size_t): Convert this call */
922 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
923 (unsigned int)reclen[0]);
924 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
925 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
928 return -1; /* AEAD can fail to verify MAC */
930 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
931 for (ctr = 0; ctr < n_recs; ctr++) {
932 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
933 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
934 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
936 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
937 for (ctr = 0; ctr < n_recs; ctr++) {
938 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
939 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
940 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
946 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
947 imac_size = EVP_MD_CTX_size(s->read_hash);
950 mac_size = (size_t)imac_size;
952 if ((bs != 1) && !send) {
954 for (ctr = 0; ctr < n_recs; ctr++) {
955 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
957 * If tmpret == 0 then this means publicly invalid so we can
958 * short circuit things here. Otherwise we must respect constant
963 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
968 for (ctr = 0; ctr < n_recs; ctr++) {
969 recs[ctr].length -= pad;
976 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
978 unsigned char *mac_sec, *seq;
979 const EVP_MD_CTX *hash;
980 unsigned char *p, rec_char;
986 mac_sec = &(ssl->s3->write_mac_secret[0]);
987 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
988 hash = ssl->write_hash;
990 mac_sec = &(ssl->s3->read_mac_secret[0]);
991 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
992 hash = ssl->read_hash;
995 t = EVP_MD_CTX_size(hash);
999 npad = (48 / md_size) * md_size;
1002 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1003 ssl3_cbc_record_digest_supported(hash)) {
1005 * This is a CBC-encrypted record. We must avoid leaking any
1006 * timing-side channel information about how many blocks of data we
1007 * are hashing because that gives an attacker a timing-oracle.
1011 * npad is, at most, 48 bytes and that's with MD5:
1012 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1014 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1015 * goes up 4, but npad goes down by 8, resulting in a smaller
1018 unsigned char header[75];
1020 memcpy(header + j, mac_sec, md_size);
1022 memcpy(header + j, ssl3_pad_1, npad);
1024 memcpy(header + j, seq, 8);
1026 header[j++] = rec->type;
1027 header[j++] = (unsigned char)(rec->length >> 8);
1028 header[j++] = (unsigned char)(rec->length & 0xff);
1030 /* Final param == is SSLv3 */
1031 if (ssl3_cbc_digest_record(hash,
1034 rec->length + md_size, rec->orig_len,
1035 mac_sec, md_size, 1) <= 0)
1038 unsigned int md_size_u;
1039 /* Chop the digest off the end :-) */
1040 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1045 rec_char = rec->type;
1047 s2n(rec->length, p);
1048 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1049 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1050 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1051 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1052 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1053 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1054 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1055 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1056 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1057 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1058 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1059 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1060 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1061 EVP_MD_CTX_reset(md_ctx);
1065 EVP_MD_CTX_free(md_ctx);
1068 ssl3_record_sequence_update(seq);
1072 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1078 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1079 unsigned char header[13];
1080 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1081 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1085 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1086 hash = ssl->write_hash;
1088 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1089 hash = ssl->read_hash;
1092 t = EVP_MD_CTX_size(hash);
1093 OPENSSL_assert(t >= 0);
1096 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1100 hmac = EVP_MD_CTX_new();
1101 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1106 if (SSL_IS_DTLS(ssl)) {
1107 unsigned char dtlsseq[8], *p = dtlsseq;
1109 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1110 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1111 memcpy(p, &seq[2], 6);
1113 memcpy(header, dtlsseq, 8);
1115 memcpy(header, seq, 8);
1117 header[8] = rec->type;
1118 header[9] = (unsigned char)(ssl->version >> 8);
1119 header[10] = (unsigned char)(ssl->version);
1120 header[11] = (unsigned char)(rec->length >> 8);
1121 header[12] = (unsigned char)(rec->length & 0xff);
1123 if (!send && !SSL_READ_ETM(ssl) &&
1124 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1125 ssl3_cbc_record_digest_supported(mac_ctx)) {
1127 * This is a CBC-encrypted record. We must avoid leaking any
1128 * timing-side channel information about how many blocks of data we
1129 * are hashing because that gives an attacker a timing-oracle.
1131 /* Final param == not SSLv3 */
1132 if (ssl3_cbc_digest_record(mac_ctx,
1135 rec->length + md_size, rec->orig_len,
1136 ssl->s3->read_mac_secret,
1137 ssl->s3->read_mac_secret_size, 0) <= 0) {
1138 EVP_MD_CTX_free(hmac);
1142 /* TODO(size_t): Convert these calls */
1143 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1144 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1145 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1146 EVP_MD_CTX_free(hmac);
1151 EVP_MD_CTX_free(hmac);
1154 fprintf(stderr, "seq=");
1157 for (z = 0; z < 8; z++)
1158 fprintf(stderr, "%02X ", seq[z]);
1159 fprintf(stderr, "\n");
1161 fprintf(stderr, "rec=");
1164 for (z = 0; z < rec->length; z++)
1165 fprintf(stderr, "%02X ", rec->data[z]);
1166 fprintf(stderr, "\n");
1170 if (!SSL_IS_DTLS(ssl)) {
1171 for (i = 7; i >= 0; i--) {
1180 for (z = 0; z < md_size; z++)
1181 fprintf(stderr, "%02X ", md[z]);
1182 fprintf(stderr, "\n");
1189 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1190 * record in |rec| by updating |rec->length| in constant time.
1192 * block_size: the block size of the cipher used to encrypt the record.
1194 * 0: (in non-constant time) if the record is publicly invalid.
1195 * 1: if the padding was valid
1198 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1199 size_t block_size, size_t mac_size)
1201 size_t padding_length;
1203 const size_t overhead = 1 /* padding length byte */ + mac_size;
1206 * These lengths are all public so we can test them in non-constant time.
1208 if (overhead > rec->length)
1211 padding_length = rec->data[rec->length - 1];
1212 good = constant_time_ge_s(rec->length, padding_length + overhead);
1213 /* SSLv3 requires that the padding is minimal. */
1214 good &= constant_time_ge_s(block_size, padding_length + 1);
1215 rec->length -= good & (padding_length + 1);
1216 return constant_time_select_int_s(good, 1, -1);
1220 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1221 * record in |rec| in constant time and returns 1 if the padding is valid and
1222 * -1 otherwise. It also removes any explicit IV from the start of the record
1223 * without leaking any timing about whether there was enough space after the
1224 * padding was removed.
1226 * block_size: the block size of the cipher used to encrypt the record.
1228 * 0: (in non-constant time) if the record is publicly invalid.
1229 * 1: if the padding was valid
1232 int tls1_cbc_remove_padding(const SSL *s,
1234 size_t block_size, size_t mac_size)
1237 size_t padding_length, to_check, i;
1238 const size_t overhead = 1 /* padding length byte */ + mac_size;
1239 /* Check if version requires explicit IV */
1240 if (SSL_USE_EXPLICIT_IV(s)) {
1242 * These lengths are all public so we can test them in non-constant
1245 if (overhead + block_size > rec->length)
1247 /* We can now safely skip explicit IV */
1248 rec->data += block_size;
1249 rec->input += block_size;
1250 rec->length -= block_size;
1251 rec->orig_len -= block_size;
1252 } else if (overhead > rec->length)
1255 padding_length = rec->data[rec->length - 1];
1257 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1258 EVP_CIPH_FLAG_AEAD_CIPHER) {
1259 /* padding is already verified */
1260 rec->length -= padding_length + 1;
1264 good = constant_time_ge_s(rec->length, overhead + padding_length);
1266 * The padding consists of a length byte at the end of the record and
1267 * then that many bytes of padding, all with the same value as the length
1268 * byte. Thus, with the length byte included, there are i+1 bytes of
1269 * padding. We can't check just |padding_length+1| bytes because that
1270 * leaks decrypted information. Therefore we always have to check the
1271 * maximum amount of padding possible. (Again, the length of the record
1272 * is public information so we can use it.)
1274 to_check = 256; /* maximum amount of padding, inc length byte. */
1275 if (to_check > rec->length)
1276 to_check = rec->length;
1278 for (i = 0; i < to_check; i++) {
1279 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1280 unsigned char b = rec->data[rec->length - 1 - i];
1282 * The final |padding_length+1| bytes should all have the value
1283 * |padding_length|. Therefore the XOR should be zero.
1285 good &= ~(mask & (padding_length ^ b));
1289 * If any of the final |padding_length+1| bytes had the wrong value, one
1290 * or more of the lower eight bits of |good| will be cleared.
1292 good = constant_time_eq_s(0xff, good & 0xff);
1293 rec->length -= good & (padding_length + 1);
1295 return constant_time_select_int_s(good, 1, -1);
1299 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1300 * constant time (independent of the concrete value of rec->length, which may
1301 * vary within a 256-byte window).
1303 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1307 * rec->orig_len >= md_size
1308 * md_size <= EVP_MAX_MD_SIZE
1310 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1311 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1312 * a single or pair of cache-lines, then the variable memory accesses don't
1313 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1314 * not multi-core and are not considered vulnerable to cache-timing attacks.
1316 #define CBC_MAC_ROTATE_IN_PLACE
1318 void ssl3_cbc_copy_mac(unsigned char *out,
1319 const SSL3_RECORD *rec, size_t md_size)
1321 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1322 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1323 unsigned char *rotated_mac;
1325 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1329 * mac_end is the index of |rec->data| just after the end of the MAC.
1331 size_t mac_end = rec->length;
1332 size_t mac_start = mac_end - md_size;
1335 * scan_start contains the number of bytes that we can ignore because the
1336 * MAC's position can only vary by 255 bytes.
1338 size_t scan_start = 0;
1340 size_t rotate_offset;
1342 OPENSSL_assert(rec->orig_len >= md_size);
1343 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1345 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1346 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1349 /* This information is public so it's safe to branch based on it. */
1350 if (rec->orig_len > md_size + 255 + 1)
1351 scan_start = rec->orig_len - (md_size + 255 + 1);
1355 memset(rotated_mac, 0, md_size);
1356 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1357 size_t mac_started = constant_time_eq_s(i, mac_start);
1358 size_t mac_ended = constant_time_lt_s(i, mac_end);
1359 unsigned char b = rec->data[i];
1361 in_mac |= mac_started;
1362 in_mac &= mac_ended;
1363 rotate_offset |= j & mac_started;
1364 rotated_mac[j++] |= b & in_mac;
1365 j &= constant_time_lt_s(j, md_size);
1368 /* Now rotate the MAC */
1369 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1371 for (i = 0; i < md_size; i++) {
1372 /* in case cache-line is 32 bytes, touch second line */
1373 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1374 out[j++] = rotated_mac[rotate_offset++];
1375 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1378 memset(out, 0, md_size);
1379 rotate_offset = md_size - rotate_offset;
1380 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1381 for (i = 0; i < md_size; i++) {
1382 for (j = 0; j < md_size; j++)
1383 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1385 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1390 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1398 unsigned char md[EVP_MAX_MD_SIZE];
1400 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1404 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1405 * and we have that many bytes in s->packet
1407 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1410 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1411 * at rr->length bytes, which need to be copied into rr->data by either
1412 * the decryption or by the decompression When the data is 'copied' into
1413 * the rr->data buffer, rr->input will be pointed at the new buffer
1417 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1418 * bytes of encrypted compressed stuff.
1421 /* check is not needed I believe */
1422 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1423 al = SSL_AD_RECORD_OVERFLOW;
1424 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1428 /* decrypt in place in 'rr->input' */
1429 rr->data = rr->input;
1430 rr->orig_len = rr->length;
1432 if (SSL_READ_ETM(s) && s->read_hash) {
1434 mac_size = EVP_MD_CTX_size(s->read_hash);
1435 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1436 if (rr->orig_len < mac_size) {
1437 al = SSL_AD_DECODE_ERROR;
1438 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1441 rr->length -= mac_size;
1442 mac = rr->data + rr->length;
1443 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1444 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1445 al = SSL_AD_BAD_RECORD_MAC;
1446 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1447 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1452 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1455 * 0: (in non-constant time) if the record is publically invalid.
1456 * 1: if the padding is valid
1457 * -1: if the padding is invalid
1460 /* For DTLS we simply ignore bad packets. */
1462 RECORD_LAYER_reset_packet_length(&s->rlayer);
1466 printf("dec %ld\n", rr->length);
1469 for (z = 0; z < rr->length; z++)
1470 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1475 /* r->length is now the compressed data plus mac */
1476 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1477 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1478 /* s->read_hash != NULL => mac_size != -1 */
1479 unsigned char *mac = NULL;
1480 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1482 /* TODO(size_t): Convert this to do size_t properly */
1483 imac_size = EVP_MD_CTX_size(s->read_hash);
1484 if (imac_size < 0) {
1485 al = SSL_AD_INTERNAL_ERROR;
1486 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1489 mac_size = (size_t)imac_size;
1490 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1493 * orig_len is the length of the record before any padding was
1494 * removed. This is public information, as is the MAC in use,
1495 * therefore we can safely process the record in a different amount
1496 * of time if it's too short to possibly contain a MAC.
1498 if (rr->orig_len < mac_size ||
1499 /* CBC records must have a padding length byte too. */
1500 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1501 rr->orig_len < mac_size + 1)) {
1502 al = SSL_AD_DECODE_ERROR;
1503 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1507 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1509 * We update the length so that the TLS header bytes can be
1510 * constructed correctly but we need to extract the MAC in
1511 * constant time from within the record, without leaking the
1512 * contents of the padding bytes.
1515 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1516 rr->length -= mac_size;
1519 * In this case there's no padding, so |rec->orig_len| equals
1520 * |rec->length| and we checked that there's enough bytes for
1523 rr->length -= mac_size;
1524 mac = &rr->data[rr->length];
1527 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1528 if (i == 0 || mac == NULL
1529 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1531 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1536 /* decryption failed, silently discard message */
1538 RECORD_LAYER_reset_packet_length(&s->rlayer);
1542 /* r->length is now just compressed */
1543 if (s->expand != NULL) {
1544 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1545 al = SSL_AD_RECORD_OVERFLOW;
1546 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1547 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1550 if (!ssl3_do_uncompress(s, rr)) {
1551 al = SSL_AD_DECOMPRESSION_FAILURE;
1552 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1557 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1558 al = SSL_AD_RECORD_OVERFLOW;
1559 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1565 * So at this point the following is true
1566 * ssl->s3->rrec.type is the type of record
1567 * ssl->s3->rrec.length == number of bytes in record
1568 * ssl->s3->rrec.off == offset to first valid byte
1569 * ssl->s3->rrec.data == where to take bytes from, increment
1573 /* we have pulled in a full packet so zero things */
1574 RECORD_LAYER_reset_packet_length(&s->rlayer);
1576 /* Mark receipt of record. */
1577 dtls1_record_bitmap_update(s, bitmap);
1582 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1588 * retrieve a buffered record that belongs to the current epoch, ie,
1591 #define dtls1_get_processed_record(s) \
1592 dtls1_retrieve_buffered_record((s), \
1593 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1596 * Call this to get a new input record.
1597 * It will return <= 0 if more data is needed, normally due to an error
1598 * or non-blocking IO.
1599 * When it finishes, one packet has been decoded and can be found in
1600 * ssl->s3->rrec.type - is the type of record
1601 * ssl->s3->rrec.data, - data
1602 * ssl->s3->rrec.length, - number of bytes
1604 /* used only by dtls1_read_bytes */
1605 int dtls1_get_record(SSL *s)
1607 int ssl_major, ssl_minor;
1611 unsigned char *p = NULL;
1612 unsigned short version;
1613 DTLS1_BITMAP *bitmap;
1614 unsigned int is_next_epoch;
1616 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1620 * The epoch may have changed. If so, process all the pending records.
1621 * This is a non-blocking operation.
1623 if (!dtls1_process_buffered_records(s))
1626 /* if we're renegotiating, then there may be buffered records */
1627 if (dtls1_get_processed_record(s))
1630 /* get something from the wire */
1632 /* check if we have the header */
1633 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1634 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1635 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1636 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1637 /* read timeout is handled by dtls1_read_bytes */
1639 return rret; /* error or non-blocking */
1641 /* this packet contained a partial record, dump it */
1642 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1643 DTLS1_RT_HEADER_LENGTH) {
1644 RECORD_LAYER_reset_packet_length(&s->rlayer);
1648 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1650 p = RECORD_LAYER_get_packet(&s->rlayer);
1652 if (s->msg_callback)
1653 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1654 s, s->msg_callback_arg);
1656 /* Pull apart the header into the DTLS1_RECORD */
1660 version = (ssl_major << 8) | ssl_minor;
1662 /* sequence number is 64 bits, with top 2 bytes = epoch */
1665 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1670 /* Lets check version */
1671 if (!s->first_packet) {
1672 if (version != s->version) {
1673 /* unexpected version, silently discard */
1675 RECORD_LAYER_reset_packet_length(&s->rlayer);
1680 if ((version & 0xff00) != (s->version & 0xff00)) {
1681 /* wrong version, silently discard record */
1683 RECORD_LAYER_reset_packet_length(&s->rlayer);
1687 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1688 /* record too long, silently discard it */
1690 RECORD_LAYER_reset_packet_length(&s->rlayer);
1694 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1697 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1700 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1701 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1703 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1704 /* this packet contained a partial record, dump it */
1705 if (rret <= 0 || n != more) {
1707 RECORD_LAYER_reset_packet_length(&s->rlayer);
1712 * now n == rr->length, and s->packet_length ==
1713 * DTLS1_RT_HEADER_LENGTH + rr->length
1716 /* set state for later operations */
1717 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1719 /* match epochs. NULL means the packet is dropped on the floor */
1720 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1721 if (bitmap == NULL) {
1723 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1724 goto again; /* get another record */
1726 #ifndef OPENSSL_NO_SCTP
1727 /* Only do replay check if no SCTP bio */
1728 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1730 /* Check whether this is a repeat, or aged record. */
1732 * TODO: Does it make sense to have replay protection in epoch 0 where
1733 * we have no integrity negotiated yet?
1735 if (!dtls1_record_replay_check(s, bitmap)) {
1737 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1738 goto again; /* get another record */
1740 #ifndef OPENSSL_NO_SCTP
1744 /* just read a 0 length packet */
1745 if (rr->length == 0)
1749 * If this record is from the next epoch (either HM or ALERT), and a
1750 * handshake is currently in progress, buffer it since it cannot be
1751 * processed at this time.
1753 if (is_next_epoch) {
1754 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1755 if (dtls1_buffer_record
1756 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1761 RECORD_LAYER_reset_packet_length(&s->rlayer);
1765 if (!dtls1_process_record(s, bitmap)) {
1767 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1768 goto again; /* get another record */