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
10 #include "../ssl_locl.h"
11 #include "internal/constant_time_locl.h"
12 #include <openssl/rand.h>
13 #include "record_locl.h"
14 #include "internal/cryptlib.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)
104 int early_data_count_ok(SSL *s, size_t length, size_t overhead, int *al)
106 uint32_t max_early_data = s->max_early_data;
107 SSL_SESSION *sess = s->session;
110 * If we are a client then we always use the max_early_data from the
111 * session/psksession. Otherwise we go with the lowest out of the max early
112 * data set in the session and the configured max_early_data.
114 if (!s->server && sess->ext.max_early_data == 0) {
115 if (!ossl_assert(s->psksession != NULL
116 && s->psksession->ext.max_early_data > 0)) {
117 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, ERR_R_INTERNAL_ERROR);
120 sess = s->psksession;
123 || (s->hit && sess->ext.max_early_data < s->max_early_data))
124 max_early_data = sess->ext.max_early_data;
126 if (max_early_data == 0) {
128 *al = SSL_AD_UNEXPECTED_MESSAGE;
129 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
133 /* If we are dealing with ciphertext we need to allow for the overhead */
134 max_early_data += overhead;
136 if (s->early_data_count + length > max_early_data) {
138 *al = SSL_AD_UNEXPECTED_MESSAGE;
139 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
142 s->early_data_count += length;
148 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
149 * will be processed per call to ssl3_get_record. Without this limit an
150 * attacker could send empty records at a faster rate than we can process and
151 * cause ssl3_get_record to loop forever.
153 #define MAX_EMPTY_RECORDS 32
155 #define SSL2_RT_HEADER_LENGTH 2
157 * Call this to get new input records.
158 * It will return <= 0 if more data is needed, normally due to an error
159 * or non-blocking IO.
160 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
161 * rr[i].type - is the type of record
163 * rr[i].length, - number of bytes
164 * Multiple records will only be returned if the record types are all
165 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
168 /* used only by ssl3_read_bytes */
169 int ssl3_get_record(SSL *s)
172 int enc_err, rret, ret = -1;
175 SSL3_RECORD *rr, *thisrr;
179 unsigned char md[EVP_MAX_MD_SIZE];
180 unsigned int version;
183 size_t num_recs = 0, max_recs, j;
184 PACKET pkt, sslv2pkt;
185 size_t first_rec_len;
187 rr = RECORD_LAYER_get_rrec(&s->rlayer);
188 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
189 max_recs = s->max_pipelines;
195 thisrr = &rr[num_recs];
197 /* check if we have the header */
198 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
199 (RECORD_LAYER_get_packet_length(&s->rlayer)
200 < SSL3_RT_HEADER_LENGTH)) {
204 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
205 SSL3_BUFFER_get_len(rbuf), 0,
206 num_recs == 0 ? 1 : 0, &n);
208 return rret; /* error or non-blocking */
209 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
211 p = RECORD_LAYER_get_packet(&s->rlayer);
212 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
213 RECORD_LAYER_get_packet_length(&s->rlayer))) {
214 al = SSL_AD_INTERNAL_ERROR;
215 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
219 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
220 || !PACKET_get_1(&sslv2pkt, &type)) {
221 al = SSL_AD_DECODE_ERROR;
222 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
226 * The first record received by the server may be a V2ClientHello.
228 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
229 && (sslv2len & 0x8000) != 0
230 && (type == SSL2_MT_CLIENT_HELLO)) {
234 * |num_recs| here will actually always be 0 because
235 * |num_recs > 0| only ever occurs when we are processing
236 * multiple app data records - which we know isn't the case here
237 * because it is an SSLv2ClientHello. We keep it using
238 * |num_recs| for the sake of consistency
240 thisrr->type = SSL3_RT_HANDSHAKE;
241 thisrr->rec_version = SSL2_VERSION;
243 thisrr->length = sslv2len & 0x7fff;
245 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
246 - SSL2_RT_HEADER_LENGTH) {
247 al = SSL_AD_RECORD_OVERFLOW;
248 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
252 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
253 al = SSL_AD_DECODE_ERROR;
254 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
258 /* SSLv3+ style record */
260 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
261 s->msg_callback_arg);
263 /* Pull apart the header into the SSL3_RECORD */
264 if (!PACKET_get_1(&pkt, &type)
265 || !PACKET_get_net_2(&pkt, &version)
266 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
267 al = SSL_AD_DECODE_ERROR;
268 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
272 thisrr->rec_version = version;
274 /* Lets check version. In TLSv1.3 we ignore this field */
275 if (!s->first_packet && !SSL_IS_TLS13(s)
276 && version != (unsigned int)s->version) {
277 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
278 if ((s->version & 0xFF00) == (version & 0xFF00)
279 && !s->enc_write_ctx && !s->write_hash) {
280 if (thisrr->type == SSL3_RT_ALERT) {
282 * The record is using an incorrect version number,
283 * but what we've got appears to be an alert. We
284 * haven't read the body yet to check whether its a
285 * fatal or not - but chances are it is. We probably
286 * shouldn't send a fatal alert back. We'll just
292 * Send back error using their minor version number :-)
294 s->version = (unsigned short)version;
296 al = SSL_AD_PROTOCOL_VERSION;
300 if ((version >> 8) != SSL3_VERSION_MAJOR) {
301 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
302 /* Go back to start of packet, look at the five bytes
304 p = RECORD_LAYER_get_packet(&s->rlayer);
305 if (strncmp((char *)p, "GET ", 4) == 0 ||
306 strncmp((char *)p, "POST ", 5) == 0 ||
307 strncmp((char *)p, "HEAD ", 5) == 0 ||
308 strncmp((char *)p, "PUT ", 4) == 0) {
309 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
311 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
312 SSLerr(SSL_F_SSL3_GET_RECORD,
313 SSL_R_HTTPS_PROXY_REQUEST);
317 /* Doesn't look like TLS - don't send an alert */
318 SSLerr(SSL_F_SSL3_GET_RECORD,
319 SSL_R_WRONG_VERSION_NUMBER);
322 SSLerr(SSL_F_SSL3_GET_RECORD,
323 SSL_R_WRONG_VERSION_NUMBER);
324 al = SSL_AD_PROTOCOL_VERSION;
329 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
330 && thisrr->type != SSL3_RT_APPLICATION_DATA) {
331 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
332 al = SSL_AD_UNEXPECTED_MESSAGE;
337 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
338 al = SSL_AD_RECORD_OVERFLOW;
339 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
344 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
347 if (SSL_IS_TLS13(s)) {
348 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
349 al = SSL_AD_RECORD_OVERFLOW;
350 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
354 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
356 #ifndef OPENSSL_NO_COMP
358 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
359 * does not include the compression overhead anyway.
361 if (s->expand == NULL)
362 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
365 if (thisrr->length > len) {
366 al = SSL_AD_RECORD_OVERFLOW;
367 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
373 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
374 * Calculate how much more data we need to read for the rest of the
377 if (thisrr->rec_version == SSL2_VERSION) {
378 more = thisrr->length + SSL2_RT_HEADER_LENGTH
379 - SSL3_RT_HEADER_LENGTH;
381 more = thisrr->length;
384 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
386 rret = ssl3_read_n(s, more, more, 1, 0, &n);
388 return rret; /* error or non-blocking io */
391 /* set state for later operations */
392 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
395 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
396 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
397 * + thisrr->length and we have that many bytes in s->packet
399 if (thisrr->rec_version == SSL2_VERSION) {
401 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
404 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
408 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
409 * points at thisrr->length bytes, which need to be copied into
410 * thisrr->data by either the decryption or by the decompression When
411 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
412 * be pointed at the new buffer
416 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
417 * thisrr->length bytes of encrypted compressed stuff.
420 /* decrypt in place in 'thisrr->input' */
421 thisrr->data = thisrr->input;
422 thisrr->orig_len = thisrr->length;
424 /* Mark this record as not read by upper layers yet */
429 /* we have pulled in a full packet so zero things */
430 RECORD_LAYER_reset_packet_length(&s->rlayer);
431 RECORD_LAYER_clear_first_record(&s->rlayer);
432 } while (num_recs < max_recs
433 && thisrr->type == SSL3_RT_APPLICATION_DATA
434 && SSL_USE_EXPLICIT_IV(s)
435 && s->enc_read_ctx != NULL
436 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
437 & EVP_CIPH_FLAG_PIPELINE)
438 && ssl3_record_app_data_waiting(s));
441 * If in encrypt-then-mac mode calculate mac from encrypted record. All
442 * the details below are public so no timing details can leak.
444 if (SSL_READ_ETM(s) && s->read_hash) {
446 /* TODO(size_t): convert this to do size_t properly */
447 imac_size = EVP_MD_CTX_size(s->read_hash);
448 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
449 al = SSL_AD_INTERNAL_ERROR;
450 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
453 mac_size = (size_t)imac_size;
454 for (j = 0; j < num_recs; j++) {
457 if (thisrr->length < mac_size) {
458 al = SSL_AD_DECODE_ERROR;
459 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
462 thisrr->length -= mac_size;
463 mac = thisrr->data + thisrr->length;
464 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
465 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
466 al = SSL_AD_BAD_RECORD_MAC;
467 SSLerr(SSL_F_SSL3_GET_RECORD,
468 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
474 first_rec_len = rr[0].length;
476 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
480 * 0: (in non-constant time) if the record is publicly invalid.
481 * 1: if the padding is valid
482 * -1: if the padding is invalid
485 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
487 * Valid early_data that we cannot decrypt might fail here as
488 * publicly invalid. We treat it like an empty record.
493 if (!early_data_count_ok(s, thisrr->length,
494 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
499 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
500 RECORD_LAYER_reset_read_sequence(&s->rlayer);
503 al = SSL_AD_DECRYPTION_FAILED;
504 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
508 printf("dec %"OSSLzu"\n", rr[0].length);
511 for (z = 0; z < rr[0].length; z++)
512 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
517 /* r->length is now the compressed data plus mac */
518 if ((sess != NULL) &&
519 (s->enc_read_ctx != NULL) &&
520 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
521 /* s->read_hash != NULL => mac_size != -1 */
522 unsigned char *mac = NULL;
523 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
525 mac_size = EVP_MD_CTX_size(s->read_hash);
526 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
527 al = SSL_AD_INTERNAL_ERROR;
528 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
532 for (j = 0; j < num_recs; j++) {
535 * orig_len is the length of the record before any padding was
536 * removed. This is public information, as is the MAC in use,
537 * therefore we can safely process the record in a different amount
538 * of time if it's too short to possibly contain a MAC.
540 if (thisrr->orig_len < mac_size ||
541 /* CBC records must have a padding length byte too. */
542 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
543 thisrr->orig_len < mac_size + 1)) {
544 al = SSL_AD_DECODE_ERROR;
545 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
549 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
551 * We update the length so that the TLS header bytes can be
552 * constructed correctly but we need to extract the MAC in
553 * constant time from within the record, without leaking the
554 * contents of the padding bytes.
557 if (!ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size)) {
558 al = SSL_AD_INTERNAL_ERROR;
559 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
562 thisrr->length -= mac_size;
565 * In this case there's no padding, so |rec->orig_len| equals
566 * |rec->length| and we checked that there's enough bytes for
569 thisrr->length -= mac_size;
570 mac = &thisrr->data[thisrr->length];
573 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
574 if (i == 0 || mac == NULL
575 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
577 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
583 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
585 * We assume this is unreadable early_data - we treat it like an
590 * The record length may have been modified by the mac check above
591 * so we use the previously saved value
593 if (!early_data_count_ok(s, first_rec_len,
594 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
600 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
601 RECORD_LAYER_reset_read_sequence(&s->rlayer);
605 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
606 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
607 * failure is directly visible from the ciphertext anyway, we should
608 * not reveal which kind of error occurred -- this might become
609 * visible to an attacker (e.g. via a logfile)
611 al = SSL_AD_BAD_RECORD_MAC;
612 SSLerr(SSL_F_SSL3_GET_RECORD,
613 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
617 for (j = 0; j < num_recs; j++) {
620 /* thisrr->length is now just compressed */
621 if (s->expand != NULL) {
622 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
623 al = SSL_AD_RECORD_OVERFLOW;
624 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
627 if (!ssl3_do_uncompress(s, thisrr)) {
628 al = SSL_AD_DECOMPRESSION_FAILURE;
629 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
634 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
637 if (thisrr->length == 0
638 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
639 al = SSL_AD_UNEXPECTED_MESSAGE;
640 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
644 /* Strip trailing padding */
645 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
649 thisrr->length = end;
650 thisrr->type = thisrr->data[end];
651 if (thisrr->type != SSL3_RT_APPLICATION_DATA
652 && thisrr->type != SSL3_RT_ALERT
653 && thisrr->type != SSL3_RT_HANDSHAKE) {
654 al = SSL_AD_UNEXPECTED_MESSAGE;
655 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
659 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
660 &thisrr->data[end], 1, s, s->msg_callback_arg);
664 * TLSv1.3 alert and handshake records are required to be non-zero in
668 && (thisrr->type == SSL3_RT_HANDSHAKE
669 || thisrr->type == SSL3_RT_ALERT)
670 && thisrr->length == 0) {
671 al = SSL_AD_UNEXPECTED_MESSAGE;
672 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_LENGTH);
676 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
677 al = SSL_AD_RECORD_OVERFLOW;
678 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
684 * So at this point the following is true
685 * thisrr->type is the type of record
686 * thisrr->length == number of bytes in record
687 * thisrr->off == offset to first valid byte
688 * thisrr->data == where to take bytes from, increment after use :-).
691 /* just read a 0 length packet */
692 if (thisrr->length == 0) {
693 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
694 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
695 > MAX_EMPTY_RECORDS) {
696 al = SSL_AD_UNEXPECTED_MESSAGE;
697 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
701 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
705 if (s->early_data_state == SSL_EARLY_DATA_READING) {
707 if (thisrr->type == SSL3_RT_APPLICATION_DATA
708 && !early_data_count_ok(s, thisrr->length, 0, &al))
712 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
716 ssl3_send_alert(s, SSL3_AL_FATAL, al);
721 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
723 #ifndef OPENSSL_NO_COMP
726 if (rr->comp == NULL) {
727 rr->comp = (unsigned char *)
728 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
730 if (rr->comp == NULL)
733 /* TODO(size_t): Convert this call */
734 i = COMP_expand_block(ssl->expand, rr->comp,
735 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
745 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
747 #ifndef OPENSSL_NO_COMP
750 /* TODO(size_t): Convert this call */
751 i = COMP_compress_block(ssl->compress, wr->data,
752 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
753 wr->input, (int)wr->length);
759 wr->input = wr->data;
765 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
768 * 0: (in non-constant time) if the record is publically invalid (i.e. too
770 * 1: if the record's padding is valid / the encryption was successful.
771 * -1: if the record's padding is invalid or, if sending, an internal error
774 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
779 size_t bs, mac_size = 0;
781 const EVP_CIPHER *enc;
785 * We shouldn't ever be called with more than one record in the SSLv3 case
790 ds = s->enc_write_ctx;
791 if (s->enc_write_ctx == NULL)
794 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
796 ds = s->enc_read_ctx;
797 if (s->enc_read_ctx == NULL)
800 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
803 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
804 memmove(rec->data, rec->input, rec->length);
805 rec->input = rec->data;
808 /* TODO(size_t): Convert this call */
809 bs = EVP_CIPHER_CTX_block_size(ds);
813 if ((bs != 1) && sending) {
816 /* we need to add 'i-1' padding bytes */
819 * the last of these zero bytes will be overwritten with the
822 memset(&rec->input[rec->length], 0, i);
824 rec->input[l - 1] = (unsigned char)(i - 1);
828 if (l == 0 || l % bs != 0)
830 /* otherwise, rec->length >= bs */
833 /* TODO(size_t): Convert this call */
834 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
837 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
838 /* TODO(size_t): convert me */
839 imac_size = EVP_MD_CTX_size(s->read_hash);
842 mac_size = (size_t)imac_size;
844 if ((bs != 1) && !sending)
845 return ssl3_cbc_remove_padding(rec, bs, mac_size);
850 #define MAX_PADDING 256
852 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
855 * 0: (in non-constant time) if the record is publically invalid (i.e. too
857 * 1: if the record's padding is valid / the encryption was successful.
858 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
859 * an internal error occurred.
861 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
864 size_t reclen[SSL_MAX_PIPELINES];
865 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
866 int i, pad = 0, ret, tmpr;
867 size_t bs, mac_size = 0, ctr, padnum, loop;
868 unsigned char padval;
870 const EVP_CIPHER *enc;
876 if (EVP_MD_CTX_md(s->write_hash)) {
877 int n = EVP_MD_CTX_size(s->write_hash);
878 if (!ossl_assert(n >= 0)) {
879 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
883 ds = s->enc_write_ctx;
884 if (s->enc_write_ctx == NULL)
888 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
889 /* For TLSv1.1 and later explicit IV */
890 if (SSL_USE_EXPLICIT_IV(s)
891 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
892 ivlen = EVP_CIPHER_iv_length(enc);
896 for (ctr = 0; ctr < n_recs; ctr++) {
897 if (recs[ctr].data != recs[ctr].input) {
899 * we can't write into the input stream: Can this ever
902 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
904 } else if (ssl_randbytes(s, recs[ctr].input, ivlen) <= 0) {
905 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
912 if (EVP_MD_CTX_md(s->read_hash)) {
913 int n = EVP_MD_CTX_size(s->read_hash);
914 if (!ossl_assert(n >= 0)) {
915 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
919 ds = s->enc_read_ctx;
920 if (s->enc_read_ctx == NULL)
923 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
926 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
927 for (ctr = 0; ctr < n_recs; ctr++) {
928 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
929 recs[ctr].input = recs[ctr].data;
933 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
936 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
937 & EVP_CIPH_FLAG_PIPELINE)) {
939 * We shouldn't have been called with pipeline data if the
940 * cipher doesn't support pipelining
942 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
946 for (ctr = 0; ctr < n_recs; ctr++) {
947 reclen[ctr] = recs[ctr].length;
949 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
950 & EVP_CIPH_FLAG_AEAD_CIPHER) {
953 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
954 : RECORD_LAYER_get_read_sequence(&s->rlayer);
956 if (SSL_IS_DTLS(s)) {
957 /* DTLS does not support pipelining */
958 unsigned char dtlsseq[9], *p = dtlsseq;
960 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
961 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
962 memcpy(p, &seq[2], 6);
963 memcpy(buf[ctr], dtlsseq, 8);
965 memcpy(buf[ctr], seq, 8);
966 for (i = 7; i >= 0; i--) { /* increment */
973 buf[ctr][8] = recs[ctr].type;
974 buf[ctr][9] = (unsigned char)(s->version >> 8);
975 buf[ctr][10] = (unsigned char)(s->version);
976 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
977 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
978 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
979 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
985 recs[ctr].length += pad;
988 } else if ((bs != 1) && sending) {
989 padnum = bs - (reclen[ctr] % bs);
991 /* Add weird padding of upto 256 bytes */
993 if (padnum > MAX_PADDING)
995 /* we need to add 'padnum' padding bytes of value padval */
996 padval = (unsigned char)(padnum - 1);
997 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
998 recs[ctr].input[loop] = padval;
999 reclen[ctr] += padnum;
1000 recs[ctr].length += padnum;
1004 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
1009 unsigned char *data[SSL_MAX_PIPELINES];
1011 /* Set the output buffers */
1012 for (ctr = 0; ctr < n_recs; ctr++) {
1013 data[ctr] = recs[ctr].data;
1015 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1016 (int)n_recs, data) <= 0) {
1017 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
1019 /* Set the input buffers */
1020 for (ctr = 0; ctr < n_recs; ctr++) {
1021 data[ctr] = recs[ctr].input;
1023 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1024 (int)n_recs, data) <= 0
1025 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1026 (int)n_recs, reclen) <= 0) {
1027 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
1032 /* TODO(size_t): Convert this call */
1033 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1034 (unsigned int)reclen[0]);
1035 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1036 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1039 return -1; /* AEAD can fail to verify MAC */
1041 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1042 for (ctr = 0; ctr < n_recs; ctr++) {
1043 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1044 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1045 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1047 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1048 for (ctr = 0; ctr < n_recs; ctr++) {
1049 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1050 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1051 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1057 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1058 imac_size = EVP_MD_CTX_size(s->read_hash);
1061 mac_size = (size_t)imac_size;
1063 if ((bs != 1) && !sending) {
1065 for (ctr = 0; ctr < n_recs; ctr++) {
1066 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1068 * If tmpret == 0 then this means publicly invalid so we can
1069 * short circuit things here. Otherwise we must respect constant
1074 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1078 if (pad && !sending) {
1079 for (ctr = 0; ctr < n_recs; ctr++) {
1080 recs[ctr].length -= pad;
1087 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1089 unsigned char *mac_sec, *seq;
1090 const EVP_MD_CTX *hash;
1091 unsigned char *p, rec_char;
1097 mac_sec = &(ssl->s3->write_mac_secret[0]);
1098 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1099 hash = ssl->write_hash;
1101 mac_sec = &(ssl->s3->read_mac_secret[0]);
1102 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1103 hash = ssl->read_hash;
1106 t = EVP_MD_CTX_size(hash);
1110 npad = (48 / md_size) * md_size;
1113 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1114 ssl3_cbc_record_digest_supported(hash)) {
1116 * This is a CBC-encrypted record. We must avoid leaking any
1117 * timing-side channel information about how many blocks of data we
1118 * are hashing because that gives an attacker a timing-oracle.
1122 * npad is, at most, 48 bytes and that's with MD5:
1123 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1125 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1126 * goes up 4, but npad goes down by 8, resulting in a smaller
1129 unsigned char header[75];
1131 memcpy(header + j, mac_sec, md_size);
1133 memcpy(header + j, ssl3_pad_1, npad);
1135 memcpy(header + j, seq, 8);
1137 header[j++] = rec->type;
1138 header[j++] = (unsigned char)(rec->length >> 8);
1139 header[j++] = (unsigned char)(rec->length & 0xff);
1141 /* Final param == is SSLv3 */
1142 if (ssl3_cbc_digest_record(hash,
1145 rec->length + md_size, rec->orig_len,
1146 mac_sec, md_size, 1) <= 0)
1149 unsigned int md_size_u;
1150 /* Chop the digest off the end :-) */
1151 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1156 rec_char = rec->type;
1158 s2n(rec->length, p);
1159 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1160 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1161 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1162 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1163 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1164 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1165 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1166 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1167 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1168 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1169 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1170 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1171 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1172 EVP_MD_CTX_reset(md_ctx);
1176 EVP_MD_CTX_free(md_ctx);
1179 ssl3_record_sequence_update(seq);
1183 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1189 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1190 unsigned char header[13];
1191 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1192 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1196 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1197 hash = ssl->write_hash;
1199 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1200 hash = ssl->read_hash;
1203 t = EVP_MD_CTX_size(hash);
1204 if (!ossl_assert(t >= 0))
1208 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1212 hmac = EVP_MD_CTX_new();
1213 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1218 if (SSL_IS_DTLS(ssl)) {
1219 unsigned char dtlsseq[8], *p = dtlsseq;
1221 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1222 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1223 memcpy(p, &seq[2], 6);
1225 memcpy(header, dtlsseq, 8);
1227 memcpy(header, seq, 8);
1229 header[8] = rec->type;
1230 header[9] = (unsigned char)(ssl->version >> 8);
1231 header[10] = (unsigned char)(ssl->version);
1232 header[11] = (unsigned char)(rec->length >> 8);
1233 header[12] = (unsigned char)(rec->length & 0xff);
1235 if (!sending && !SSL_READ_ETM(ssl) &&
1236 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1237 ssl3_cbc_record_digest_supported(mac_ctx)) {
1239 * This is a CBC-encrypted record. We must avoid leaking any
1240 * timing-side channel information about how many blocks of data we
1241 * are hashing because that gives an attacker a timing-oracle.
1243 /* Final param == not SSLv3 */
1244 if (ssl3_cbc_digest_record(mac_ctx,
1247 rec->length + md_size, rec->orig_len,
1248 ssl->s3->read_mac_secret,
1249 ssl->s3->read_mac_secret_size, 0) <= 0) {
1250 EVP_MD_CTX_free(hmac);
1254 /* TODO(size_t): Convert these calls */
1255 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1256 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1257 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1258 EVP_MD_CTX_free(hmac);
1263 EVP_MD_CTX_free(hmac);
1266 fprintf(stderr, "seq=");
1269 for (z = 0; z < 8; z++)
1270 fprintf(stderr, "%02X ", seq[z]);
1271 fprintf(stderr, "\n");
1273 fprintf(stderr, "rec=");
1276 for (z = 0; z < rec->length; z++)
1277 fprintf(stderr, "%02X ", rec->data[z]);
1278 fprintf(stderr, "\n");
1282 if (!SSL_IS_DTLS(ssl)) {
1283 for (i = 7; i >= 0; i--) {
1292 for (z = 0; z < md_size; z++)
1293 fprintf(stderr, "%02X ", md[z]);
1294 fprintf(stderr, "\n");
1301 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1302 * record in |rec| by updating |rec->length| in constant time.
1304 * block_size: the block size of the cipher used to encrypt the record.
1306 * 0: (in non-constant time) if the record is publicly invalid.
1307 * 1: if the padding was valid
1310 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1311 size_t block_size, size_t mac_size)
1313 size_t padding_length;
1315 const size_t overhead = 1 /* padding length byte */ + mac_size;
1318 * These lengths are all public so we can test them in non-constant time.
1320 if (overhead > rec->length)
1323 padding_length = rec->data[rec->length - 1];
1324 good = constant_time_ge_s(rec->length, padding_length + overhead);
1325 /* SSLv3 requires that the padding is minimal. */
1326 good &= constant_time_ge_s(block_size, padding_length + 1);
1327 rec->length -= good & (padding_length + 1);
1328 return constant_time_select_int_s(good, 1, -1);
1332 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1333 * record in |rec| in constant time and returns 1 if the padding is valid and
1334 * -1 otherwise. It also removes any explicit IV from the start of the record
1335 * without leaking any timing about whether there was enough space after the
1336 * padding was removed.
1338 * block_size: the block size of the cipher used to encrypt the record.
1340 * 0: (in non-constant time) if the record is publicly invalid.
1341 * 1: if the padding was valid
1344 int tls1_cbc_remove_padding(const SSL *s,
1346 size_t block_size, size_t mac_size)
1349 size_t padding_length, to_check, i;
1350 const size_t overhead = 1 /* padding length byte */ + mac_size;
1351 /* Check if version requires explicit IV */
1352 if (SSL_USE_EXPLICIT_IV(s)) {
1354 * These lengths are all public so we can test them in non-constant
1357 if (overhead + block_size > rec->length)
1359 /* We can now safely skip explicit IV */
1360 rec->data += block_size;
1361 rec->input += block_size;
1362 rec->length -= block_size;
1363 rec->orig_len -= block_size;
1364 } else if (overhead > rec->length)
1367 padding_length = rec->data[rec->length - 1];
1369 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1370 EVP_CIPH_FLAG_AEAD_CIPHER) {
1371 /* padding is already verified */
1372 rec->length -= padding_length + 1;
1376 good = constant_time_ge_s(rec->length, overhead + padding_length);
1378 * The padding consists of a length byte at the end of the record and
1379 * then that many bytes of padding, all with the same value as the length
1380 * byte. Thus, with the length byte included, there are i+1 bytes of
1381 * padding. We can't check just |padding_length+1| bytes because that
1382 * leaks decrypted information. Therefore we always have to check the
1383 * maximum amount of padding possible. (Again, the length of the record
1384 * is public information so we can use it.)
1386 to_check = 256; /* maximum amount of padding, inc length byte. */
1387 if (to_check > rec->length)
1388 to_check = rec->length;
1390 for (i = 0; i < to_check; i++) {
1391 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1392 unsigned char b = rec->data[rec->length - 1 - i];
1394 * The final |padding_length+1| bytes should all have the value
1395 * |padding_length|. Therefore the XOR should be zero.
1397 good &= ~(mask & (padding_length ^ b));
1401 * If any of the final |padding_length+1| bytes had the wrong value, one
1402 * or more of the lower eight bits of |good| will be cleared.
1404 good = constant_time_eq_s(0xff, good & 0xff);
1405 rec->length -= good & (padding_length + 1);
1407 return constant_time_select_int_s(good, 1, -1);
1411 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1412 * constant time (independent of the concrete value of rec->length, which may
1413 * vary within a 256-byte window).
1415 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1419 * rec->orig_len >= md_size
1420 * md_size <= EVP_MAX_MD_SIZE
1422 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1423 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1424 * a single or pair of cache-lines, then the variable memory accesses don't
1425 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1426 * not multi-core and are not considered vulnerable to cache-timing attacks.
1428 #define CBC_MAC_ROTATE_IN_PLACE
1430 int ssl3_cbc_copy_mac(unsigned char *out,
1431 const SSL3_RECORD *rec, size_t md_size)
1433 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1434 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1435 unsigned char *rotated_mac;
1437 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1441 * mac_end is the index of |rec->data| just after the end of the MAC.
1443 size_t mac_end = rec->length;
1444 size_t mac_start = mac_end - md_size;
1447 * scan_start contains the number of bytes that we can ignore because the
1448 * MAC's position can only vary by 255 bytes.
1450 size_t scan_start = 0;
1452 size_t rotate_offset;
1454 if (!ossl_assert(rec->orig_len >= md_size
1455 && md_size <= EVP_MAX_MD_SIZE))
1458 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1459 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1462 /* This information is public so it's safe to branch based on it. */
1463 if (rec->orig_len > md_size + 255 + 1)
1464 scan_start = rec->orig_len - (md_size + 255 + 1);
1468 memset(rotated_mac, 0, md_size);
1469 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1470 size_t mac_started = constant_time_eq_s(i, mac_start);
1471 size_t mac_ended = constant_time_lt_s(i, mac_end);
1472 unsigned char b = rec->data[i];
1474 in_mac |= mac_started;
1475 in_mac &= mac_ended;
1476 rotate_offset |= j & mac_started;
1477 rotated_mac[j++] |= b & in_mac;
1478 j &= constant_time_lt_s(j, md_size);
1481 /* Now rotate the MAC */
1482 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1484 for (i = 0; i < md_size; i++) {
1485 /* in case cache-line is 32 bytes, touch second line */
1486 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1487 out[j++] = rotated_mac[rotate_offset++];
1488 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1491 memset(out, 0, md_size);
1492 rotate_offset = md_size - rotate_offset;
1493 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1494 for (i = 0; i < md_size; i++) {
1495 for (j = 0; j < md_size; j++)
1496 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1498 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1505 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1513 unsigned char md[EVP_MAX_MD_SIZE];
1515 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1519 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1520 * and we have that many bytes in s->packet
1522 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1525 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1526 * at rr->length bytes, which need to be copied into rr->data by either
1527 * the decryption or by the decompression When the data is 'copied' into
1528 * the rr->data buffer, rr->input will be pointed at the new buffer
1532 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1533 * bytes of encrypted compressed stuff.
1536 /* check is not needed I believe */
1537 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1538 al = SSL_AD_RECORD_OVERFLOW;
1539 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1543 /* decrypt in place in 'rr->input' */
1544 rr->data = rr->input;
1545 rr->orig_len = rr->length;
1547 if (SSL_READ_ETM(s) && s->read_hash) {
1549 mac_size = EVP_MD_CTX_size(s->read_hash);
1550 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1551 al = SSL_AD_INTERNAL_ERROR;
1552 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1555 if (rr->orig_len < mac_size) {
1556 al = SSL_AD_DECODE_ERROR;
1557 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1560 rr->length -= mac_size;
1561 mac = rr->data + rr->length;
1562 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1563 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1564 al = SSL_AD_BAD_RECORD_MAC;
1565 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1566 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1571 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1574 * 0: (in non-constant time) if the record is publically invalid.
1575 * 1: if the padding is valid
1576 * -1: if the padding is invalid
1579 /* For DTLS we simply ignore bad packets. */
1581 RECORD_LAYER_reset_packet_length(&s->rlayer);
1585 printf("dec %ld\n", rr->length);
1588 for (z = 0; z < rr->length; z++)
1589 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1594 /* r->length is now the compressed data plus mac */
1595 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1596 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1597 /* s->read_hash != NULL => mac_size != -1 */
1598 unsigned char *mac = NULL;
1599 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1601 /* TODO(size_t): Convert this to do size_t properly */
1602 imac_size = EVP_MD_CTX_size(s->read_hash);
1603 if (imac_size < 0) {
1604 al = SSL_AD_INTERNAL_ERROR;
1605 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1608 mac_size = (size_t)imac_size;
1609 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1610 al = SSL_AD_INTERNAL_ERROR;
1611 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1616 * orig_len is the length of the record before any padding was
1617 * removed. This is public information, as is the MAC in use,
1618 * therefore we can safely process the record in a different amount
1619 * of time if it's too short to possibly contain a MAC.
1621 if (rr->orig_len < mac_size ||
1622 /* CBC records must have a padding length byte too. */
1623 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1624 rr->orig_len < mac_size + 1)) {
1625 al = SSL_AD_DECODE_ERROR;
1626 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1630 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1632 * We update the length so that the TLS header bytes can be
1633 * constructed correctly but we need to extract the MAC in
1634 * constant time from within the record, without leaking the
1635 * contents of the padding bytes.
1638 if (!ssl3_cbc_copy_mac(mac_tmp, rr, mac_size)) {
1639 al = SSL_AD_INTERNAL_ERROR;
1640 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1643 rr->length -= mac_size;
1646 * In this case there's no padding, so |rec->orig_len| equals
1647 * |rec->length| and we checked that there's enough bytes for
1650 rr->length -= mac_size;
1651 mac = &rr->data[rr->length];
1654 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1655 if (i == 0 || mac == NULL
1656 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1658 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1663 /* decryption failed, silently discard message */
1665 RECORD_LAYER_reset_packet_length(&s->rlayer);
1669 /* r->length is now just compressed */
1670 if (s->expand != NULL) {
1671 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1672 al = SSL_AD_RECORD_OVERFLOW;
1673 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1674 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1677 if (!ssl3_do_uncompress(s, rr)) {
1678 al = SSL_AD_DECOMPRESSION_FAILURE;
1679 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1684 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1685 al = SSL_AD_RECORD_OVERFLOW;
1686 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1692 * So at this point the following is true
1693 * ssl->s3->rrec.type is the type of record
1694 * ssl->s3->rrec.length == number of bytes in record
1695 * ssl->s3->rrec.off == offset to first valid byte
1696 * ssl->s3->rrec.data == where to take bytes from, increment
1700 /* we have pulled in a full packet so zero things */
1701 RECORD_LAYER_reset_packet_length(&s->rlayer);
1703 /* Mark receipt of record. */
1704 dtls1_record_bitmap_update(s, bitmap);
1709 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1715 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1717 #define dtls1_get_processed_record(s) \
1718 dtls1_retrieve_buffered_record((s), \
1719 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1722 * Call this to get a new input record.
1723 * It will return <= 0 if more data is needed, normally due to an error
1724 * or non-blocking IO.
1725 * When it finishes, one packet has been decoded and can be found in
1726 * ssl->s3->rrec.type - is the type of record
1727 * ssl->s3->rrec.data, - data
1728 * ssl->s3->rrec.length, - number of bytes
1730 /* used only by dtls1_read_bytes */
1731 int dtls1_get_record(SSL *s)
1733 int ssl_major, ssl_minor;
1737 unsigned char *p = NULL;
1738 unsigned short version;
1739 DTLS1_BITMAP *bitmap;
1740 unsigned int is_next_epoch;
1742 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1746 * The epoch may have changed. If so, process all the pending records.
1747 * This is a non-blocking operation.
1749 if (!dtls1_process_buffered_records(s))
1752 /* if we're renegotiating, then there may be buffered records */
1753 if (dtls1_get_processed_record(s))
1756 /* get something from the wire */
1758 /* check if we have the header */
1759 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1760 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1761 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1762 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1763 /* read timeout is handled by dtls1_read_bytes */
1765 return rret; /* error or non-blocking */
1767 /* this packet contained a partial record, dump it */
1768 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1769 DTLS1_RT_HEADER_LENGTH) {
1770 RECORD_LAYER_reset_packet_length(&s->rlayer);
1774 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1776 p = RECORD_LAYER_get_packet(&s->rlayer);
1778 if (s->msg_callback)
1779 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1780 s, s->msg_callback_arg);
1782 /* Pull apart the header into the DTLS1_RECORD */
1786 version = (ssl_major << 8) | ssl_minor;
1788 /* sequence number is 64 bits, with top 2 bytes = epoch */
1791 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1796 /* Lets check version */
1797 if (!s->first_packet) {
1798 if (version != s->version) {
1799 /* unexpected version, silently discard */
1801 RECORD_LAYER_reset_packet_length(&s->rlayer);
1806 if ((version & 0xff00) != (s->version & 0xff00)) {
1807 /* wrong version, silently discard record */
1809 RECORD_LAYER_reset_packet_length(&s->rlayer);
1813 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1814 /* record too long, silently discard it */
1816 RECORD_LAYER_reset_packet_length(&s->rlayer);
1820 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1823 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1826 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1827 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1829 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1830 /* this packet contained a partial record, dump it */
1831 if (rret <= 0 || n != more) {
1833 RECORD_LAYER_reset_packet_length(&s->rlayer);
1838 * now n == rr->length, and s->packet_length ==
1839 * DTLS1_RT_HEADER_LENGTH + rr->length
1842 /* set state for later operations */
1843 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1845 /* match epochs. NULL means the packet is dropped on the floor */
1846 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1847 if (bitmap == NULL) {
1849 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1850 goto again; /* get another record */
1852 #ifndef OPENSSL_NO_SCTP
1853 /* Only do replay check if no SCTP bio */
1854 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1856 /* Check whether this is a repeat, or aged record. */
1858 * TODO: Does it make sense to have replay protection in epoch 0 where
1859 * we have no integrity negotiated yet?
1861 if (!dtls1_record_replay_check(s, bitmap)) {
1863 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1864 goto again; /* get another record */
1866 #ifndef OPENSSL_NO_SCTP
1870 /* just read a 0 length packet */
1871 if (rr->length == 0)
1875 * If this record is from the next epoch (either HM or ALERT), and a
1876 * handshake is currently in progress, buffer it since it cannot be
1877 * processed at this time.
1879 if (is_next_epoch) {
1880 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1881 if (dtls1_buffer_record
1882 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1887 RECORD_LAYER_reset_packet_length(&s->rlayer);
1891 if (!dtls1_process_record(s, bitmap)) {
1893 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1894 goto again; /* get another record */