2 * Copyright 1995-2018 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 send)
106 uint32_t 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 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_EARLY_DATA_COUNT_OK,
118 ERR_R_INTERNAL_ERROR);
121 sess = s->psksession;
125 max_early_data = sess->ext.max_early_data;
126 else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
127 max_early_data = s->recv_max_early_data;
129 max_early_data = s->recv_max_early_data < sess->ext.max_early_data
130 ? s->recv_max_early_data : sess->ext.max_early_data;
132 if (max_early_data == 0) {
133 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
134 SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
138 /* If we are dealing with ciphertext we need to allow for the overhead */
139 max_early_data += overhead;
141 if (s->early_data_count + length > max_early_data) {
142 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
143 SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
146 s->early_data_count += length;
152 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
153 * will be processed per call to ssl3_get_record. Without this limit an
154 * attacker could send empty records at a faster rate than we can process and
155 * cause ssl3_get_record to loop forever.
157 #define MAX_EMPTY_RECORDS 32
159 #define SSL2_RT_HEADER_LENGTH 2
161 * Call this to get new input records.
162 * It will return <= 0 if more data is needed, normally due to an error
163 * or non-blocking IO.
164 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
165 * rr[i].type - is the type of record
167 * rr[i].length, - number of bytes
168 * Multiple records will only be returned if the record types are all
169 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
172 /* used only by ssl3_read_bytes */
173 int ssl3_get_record(SSL *s)
178 SSL3_RECORD *rr, *thisrr;
182 unsigned char md[EVP_MAX_MD_SIZE];
183 unsigned int version;
186 size_t num_recs = 0, max_recs, j;
187 PACKET pkt, sslv2pkt;
188 size_t first_rec_len;
190 rr = RECORD_LAYER_get_rrec(&s->rlayer);
191 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
192 max_recs = s->max_pipelines;
198 thisrr = &rr[num_recs];
200 /* check if we have the header */
201 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
202 (RECORD_LAYER_get_packet_length(&s->rlayer)
203 < SSL3_RT_HEADER_LENGTH)) {
207 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
208 SSL3_BUFFER_get_len(rbuf), 0,
209 num_recs == 0 ? 1 : 0, &n);
211 return rret; /* error or non-blocking */
212 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
214 p = RECORD_LAYER_get_packet(&s->rlayer);
215 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
216 RECORD_LAYER_get_packet_length(&s->rlayer))) {
217 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
218 ERR_R_INTERNAL_ERROR);
222 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
223 || !PACKET_get_1(&sslv2pkt, &type)) {
224 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
225 ERR_R_INTERNAL_ERROR);
229 * The first record received by the server may be a V2ClientHello.
231 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
232 && (sslv2len & 0x8000) != 0
233 && (type == SSL2_MT_CLIENT_HELLO)) {
237 * |num_recs| here will actually always be 0 because
238 * |num_recs > 0| only ever occurs when we are processing
239 * multiple app data records - which we know isn't the case here
240 * because it is an SSLv2ClientHello. We keep it using
241 * |num_recs| for the sake of consistency
243 thisrr->type = SSL3_RT_HANDSHAKE;
244 thisrr->rec_version = SSL2_VERSION;
246 thisrr->length = sslv2len & 0x7fff;
248 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
249 - SSL2_RT_HEADER_LENGTH) {
250 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
251 SSL_R_PACKET_LENGTH_TOO_LONG);
255 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
256 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
257 SSL_R_LENGTH_TOO_SHORT);
261 /* SSLv3+ style record */
263 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
264 s->msg_callback_arg);
266 /* Pull apart the header into the SSL3_RECORD */
267 if (!PACKET_get_1(&pkt, &type)
268 || !PACKET_get_net_2(&pkt, &version)
269 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
270 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
271 ERR_R_INTERNAL_ERROR);
275 thisrr->rec_version = version;
278 * Lets check version. In TLSv1.3 we only check this field
279 * when encryption is occurring (see later check). For the
280 * ServerHello after an HRR we haven't actually selected TLSv1.3
281 * yet, but we still treat it as TLSv1.3, so we must check for
284 if (!s->first_packet && !SSL_IS_TLS13(s)
285 && s->hello_retry_request != SSL_HRR_PENDING
286 && version != (unsigned int)s->version) {
287 if ((s->version & 0xFF00) == (version & 0xFF00)
288 && !s->enc_write_ctx && !s->write_hash) {
289 if (thisrr->type == SSL3_RT_ALERT) {
291 * The record is using an incorrect version number,
292 * but what we've got appears to be an alert. We
293 * haven't read the body yet to check whether its a
294 * fatal or not - but chances are it is. We probably
295 * shouldn't send a fatal alert back. We'll just
298 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
299 SSL_R_WRONG_VERSION_NUMBER);
303 * Send back error using their minor version number :-)
305 s->version = (unsigned short)version;
307 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL3_GET_RECORD,
308 SSL_R_WRONG_VERSION_NUMBER);
312 if ((version >> 8) != SSL3_VERSION_MAJOR) {
313 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
314 /* Go back to start of packet, look at the five bytes
316 p = RECORD_LAYER_get_packet(&s->rlayer);
317 if (strncmp((char *)p, "GET ", 4) == 0 ||
318 strncmp((char *)p, "POST ", 5) == 0 ||
319 strncmp((char *)p, "HEAD ", 5) == 0 ||
320 strncmp((char *)p, "PUT ", 4) == 0) {
321 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
324 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
325 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
326 SSL_R_HTTPS_PROXY_REQUEST);
330 /* Doesn't look like TLS - don't send an alert */
331 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
332 SSL_R_WRONG_VERSION_NUMBER);
335 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
336 SSL_F_SSL3_GET_RECORD,
337 SSL_R_WRONG_VERSION_NUMBER);
342 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
343 if (thisrr->type != SSL3_RT_APPLICATION_DATA
344 && (thisrr->type != SSL3_RT_CHANGE_CIPHER_SPEC
345 || !SSL_IS_FIRST_HANDSHAKE(s))) {
346 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
347 SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
350 if (thisrr->rec_version != TLS1_2_VERSION) {
351 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
352 SSL_R_WRONG_VERSION_NUMBER);
358 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
359 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
360 SSL_R_PACKET_LENGTH_TOO_LONG);
365 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
368 if (SSL_IS_TLS13(s)) {
369 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
370 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
371 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
375 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
377 #ifndef OPENSSL_NO_COMP
379 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
380 * does not include the compression overhead anyway.
382 if (s->expand == NULL)
383 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
386 if (thisrr->length > len) {
387 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
388 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
394 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
395 * Calculate how much more data we need to read for the rest of the
398 if (thisrr->rec_version == SSL2_VERSION) {
399 more = thisrr->length + SSL2_RT_HEADER_LENGTH
400 - SSL3_RT_HEADER_LENGTH;
402 more = thisrr->length;
405 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
407 rret = ssl3_read_n(s, more, more, 1, 0, &n);
409 return rret; /* error or non-blocking io */
412 /* set state for later operations */
413 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
416 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
417 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
418 * + thisrr->length and we have that many bytes in s->packet
420 if (thisrr->rec_version == SSL2_VERSION) {
422 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
425 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
429 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
430 * points at thisrr->length bytes, which need to be copied into
431 * thisrr->data by either the decryption or by the decompression When
432 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
433 * be pointed at the new buffer
437 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
438 * thisrr->length bytes of encrypted compressed stuff.
441 /* decrypt in place in 'thisrr->input' */
442 thisrr->data = thisrr->input;
443 thisrr->orig_len = thisrr->length;
445 /* Mark this record as not read by upper layers yet */
450 /* we have pulled in a full packet so zero things */
451 RECORD_LAYER_reset_packet_length(&s->rlayer);
452 RECORD_LAYER_clear_first_record(&s->rlayer);
453 } while (num_recs < max_recs
454 && thisrr->type == SSL3_RT_APPLICATION_DATA
455 && SSL_USE_EXPLICIT_IV(s)
456 && s->enc_read_ctx != NULL
457 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
458 & EVP_CIPH_FLAG_PIPELINE)
459 && ssl3_record_app_data_waiting(s));
462 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
463 && (SSL_IS_TLS13(s) || s->hello_retry_request != SSL_HRR_NONE)
464 && SSL_IS_FIRST_HANDSHAKE(s)) {
466 * CCS messages must be exactly 1 byte long, containing the value 0x01
468 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
469 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL3_GET_RECORD,
470 SSL_R_INVALID_CCS_MESSAGE);
474 * CCS messages are ignored in TLSv1.3. We treat it like an empty
477 thisrr->type = SSL3_RT_HANDSHAKE;
478 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
479 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
480 > MAX_EMPTY_RECORDS) {
481 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
482 SSL_R_UNEXPECTED_CCS_MESSAGE);
486 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
492 * If in encrypt-then-mac mode calculate mac from encrypted record. All
493 * the details below are public so no timing details can leak.
495 if (SSL_READ_ETM(s) && s->read_hash) {
497 /* TODO(size_t): convert this to do size_t properly */
498 imac_size = EVP_MD_CTX_size(s->read_hash);
499 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
500 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
504 mac_size = (size_t)imac_size;
505 for (j = 0; j < num_recs; j++) {
508 if (thisrr->length < mac_size) {
509 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
510 SSL_R_LENGTH_TOO_SHORT);
513 thisrr->length -= mac_size;
514 mac = thisrr->data + thisrr->length;
515 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
516 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
517 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
518 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
524 first_rec_len = rr[0].length;
526 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
530 * 0: (in non-constant time) if the record is publicly invalid.
531 * 1: if the padding is valid
532 * -1: if the padding is invalid
535 if (ossl_statem_in_error(s)) {
536 /* SSLfatal() already got called */
539 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
541 * Valid early_data that we cannot decrypt might fail here as
542 * publicly invalid. We treat it like an empty record.
547 if (!early_data_count_ok(s, thisrr->length,
548 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
549 /* SSLfatal() already called */
555 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
556 RECORD_LAYER_reset_read_sequence(&s->rlayer);
559 SSLfatal(s, SSL_AD_DECRYPTION_FAILED, SSL_F_SSL3_GET_RECORD,
560 SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
564 printf("dec %lu\n", (unsigned long)rr[0].length);
567 for (z = 0; z < rr[0].length; z++)
568 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
573 /* r->length is now the compressed data plus mac */
574 if ((sess != NULL) &&
575 (s->enc_read_ctx != NULL) &&
576 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
577 /* s->read_hash != NULL => mac_size != -1 */
578 unsigned char *mac = NULL;
579 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
581 mac_size = EVP_MD_CTX_size(s->read_hash);
582 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
583 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
584 ERR_R_INTERNAL_ERROR);
588 for (j = 0; j < num_recs; j++) {
591 * orig_len is the length of the record before any padding was
592 * removed. This is public information, as is the MAC in use,
593 * therefore we can safely process the record in a different amount
594 * of time if it's too short to possibly contain a MAC.
596 if (thisrr->orig_len < mac_size ||
597 /* CBC records must have a padding length byte too. */
598 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
599 thisrr->orig_len < mac_size + 1)) {
600 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
601 SSL_R_LENGTH_TOO_SHORT);
605 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
607 * We update the length so that the TLS header bytes can be
608 * constructed correctly but we need to extract the MAC in
609 * constant time from within the record, without leaking the
610 * contents of the padding bytes.
613 if (!ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size)) {
614 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
615 ERR_R_INTERNAL_ERROR);
618 thisrr->length -= mac_size;
621 * In this case there's no padding, so |rec->orig_len| equals
622 * |rec->length| and we checked that there's enough bytes for
625 thisrr->length -= mac_size;
626 mac = &thisrr->data[thisrr->length];
629 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
630 if (i == 0 || mac == NULL
631 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
633 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
639 if (ossl_statem_in_error(s)) {
640 /* We already called SSLfatal() */
643 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
645 * We assume this is unreadable early_data - we treat it like an
650 * The record length may have been modified by the mac check above
651 * so we use the previously saved value
653 if (!early_data_count_ok(s, first_rec_len,
654 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
655 /* SSLfatal() already called */
662 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
663 RECORD_LAYER_reset_read_sequence(&s->rlayer);
667 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
668 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
669 * failure is directly visible from the ciphertext anyway, we should
670 * not reveal which kind of error occurred -- this might become
671 * visible to an attacker (e.g. via a logfile)
673 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
674 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
678 for (j = 0; j < num_recs; j++) {
681 /* thisrr->length is now just compressed */
682 if (s->expand != NULL) {
683 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
684 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
685 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
688 if (!ssl3_do_uncompress(s, thisrr)) {
689 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE, SSL_F_SSL3_GET_RECORD,
690 SSL_R_BAD_DECOMPRESSION);
695 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
698 if (thisrr->length == 0
699 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
700 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
701 SSL_R_BAD_RECORD_TYPE);
705 /* Strip trailing padding */
706 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
710 thisrr->length = end;
711 thisrr->type = thisrr->data[end];
712 if (thisrr->type != SSL3_RT_APPLICATION_DATA
713 && thisrr->type != SSL3_RT_ALERT
714 && thisrr->type != SSL3_RT_HANDSHAKE) {
715 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
716 SSL_R_BAD_RECORD_TYPE);
720 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
721 &thisrr->data[end], 1, s, s->msg_callback_arg);
725 * TLSv1.3 alert and handshake records are required to be non-zero in
729 && (thisrr->type == SSL3_RT_HANDSHAKE
730 || thisrr->type == SSL3_RT_ALERT)
731 && thisrr->length == 0) {
732 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
737 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
738 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
739 SSL_R_DATA_LENGTH_TOO_LONG);
743 /* If received packet overflows current Max Fragment Length setting */
744 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
745 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
746 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
747 SSL_R_DATA_LENGTH_TOO_LONG);
753 * So at this point the following is true
754 * thisrr->type is the type of record
755 * thisrr->length == number of bytes in record
756 * thisrr->off == offset to first valid byte
757 * thisrr->data == where to take bytes from, increment after use :-).
760 /* just read a 0 length packet */
761 if (thisrr->length == 0) {
762 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
763 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
764 > MAX_EMPTY_RECORDS) {
765 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
766 SSL_R_RECORD_TOO_SMALL);
770 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
774 if (s->early_data_state == SSL_EARLY_DATA_READING) {
776 if (thisrr->type == SSL3_RT_APPLICATION_DATA
777 && !early_data_count_ok(s, thisrr->length, 0, 0)) {
778 /* SSLfatal already called */
783 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
787 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
789 #ifndef OPENSSL_NO_COMP
792 if (rr->comp == NULL) {
793 rr->comp = (unsigned char *)
794 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
796 if (rr->comp == NULL)
799 /* TODO(size_t): Convert this call */
800 i = COMP_expand_block(ssl->expand, rr->comp,
801 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
811 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
813 #ifndef OPENSSL_NO_COMP
816 /* TODO(size_t): Convert this call */
817 i = COMP_compress_block(ssl->compress, wr->data,
818 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
819 wr->input, (int)wr->length);
825 wr->input = wr->data;
831 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|. Will call
832 * SSLfatal() for internal errors, but not otherwise.
835 * 0: (in non-constant time) if the record is publically invalid (i.e. too
837 * 1: if the record's padding is valid / the encryption was successful.
838 * -1: if the record's padding is invalid or, if sending, an internal error
841 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
846 size_t bs, mac_size = 0;
848 const EVP_CIPHER *enc;
852 * We shouldn't ever be called with more than one record in the SSLv3 case
857 ds = s->enc_write_ctx;
858 if (s->enc_write_ctx == NULL)
861 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
863 ds = s->enc_read_ctx;
864 if (s->enc_read_ctx == NULL)
867 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
870 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
871 memmove(rec->data, rec->input, rec->length);
872 rec->input = rec->data;
875 /* TODO(size_t): Convert this call */
876 bs = EVP_CIPHER_CTX_block_size(ds);
880 if ((bs != 1) && sending) {
883 /* we need to add 'i-1' padding bytes */
886 * the last of these zero bytes will be overwritten with the
889 memset(&rec->input[rec->length], 0, i);
891 rec->input[l - 1] = (unsigned char)(i - 1);
895 if (l == 0 || l % bs != 0)
897 /* otherwise, rec->length >= bs */
900 /* TODO(size_t): Convert this call */
901 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
904 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
905 /* TODO(size_t): convert me */
906 imac_size = EVP_MD_CTX_size(s->read_hash);
908 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_ENC,
909 ERR_R_INTERNAL_ERROR);
912 mac_size = (size_t)imac_size;
914 if ((bs != 1) && !sending)
915 return ssl3_cbc_remove_padding(rec, bs, mac_size);
920 #define MAX_PADDING 256
922 * tls1_enc encrypts/decrypts |n_recs| in |recs|. Will call SSLfatal() for
923 * internal errors, but not otherwise.
926 * 0: (in non-constant time) if the record is publically invalid (i.e. too
928 * 1: if the record's padding is valid / the encryption was successful.
929 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
930 * an internal error occurred.
932 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
935 size_t reclen[SSL_MAX_PIPELINES];
936 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
937 int i, pad = 0, ret, tmpr;
938 size_t bs, mac_size = 0, ctr, padnum, loop;
939 unsigned char padval;
941 const EVP_CIPHER *enc;
944 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
945 ERR_R_INTERNAL_ERROR);
950 if (EVP_MD_CTX_md(s->write_hash)) {
951 int n = EVP_MD_CTX_size(s->write_hash);
952 if (!ossl_assert(n >= 0)) {
953 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
954 ERR_R_INTERNAL_ERROR);
958 ds = s->enc_write_ctx;
959 if (s->enc_write_ctx == NULL)
963 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
964 /* For TLSv1.1 and later explicit IV */
965 if (SSL_USE_EXPLICIT_IV(s)
966 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
967 ivlen = EVP_CIPHER_iv_length(enc);
971 for (ctr = 0; ctr < n_recs; ctr++) {
972 if (recs[ctr].data != recs[ctr].input) {
974 * we can't write into the input stream: Can this ever
977 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
978 ERR_R_INTERNAL_ERROR);
980 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
981 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
982 ERR_R_INTERNAL_ERROR);
989 if (EVP_MD_CTX_md(s->read_hash)) {
990 int n = EVP_MD_CTX_size(s->read_hash);
991 if (!ossl_assert(n >= 0)) {
992 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
993 ERR_R_INTERNAL_ERROR);
997 ds = s->enc_read_ctx;
998 if (s->enc_read_ctx == NULL)
1001 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
1004 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
1005 for (ctr = 0; ctr < n_recs; ctr++) {
1006 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
1007 recs[ctr].input = recs[ctr].data;
1011 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
1014 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1015 & EVP_CIPH_FLAG_PIPELINE)) {
1017 * We shouldn't have been called with pipeline data if the
1018 * cipher doesn't support pipelining
1020 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1021 SSL_R_PIPELINE_FAILURE);
1025 for (ctr = 0; ctr < n_recs; ctr++) {
1026 reclen[ctr] = recs[ctr].length;
1028 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1029 & EVP_CIPH_FLAG_AEAD_CIPHER) {
1032 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1033 : RECORD_LAYER_get_read_sequence(&s->rlayer);
1035 if (SSL_IS_DTLS(s)) {
1036 /* DTLS does not support pipelining */
1037 unsigned char dtlsseq[9], *p = dtlsseq;
1039 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
1040 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
1041 memcpy(p, &seq[2], 6);
1042 memcpy(buf[ctr], dtlsseq, 8);
1044 memcpy(buf[ctr], seq, 8);
1045 for (i = 7; i >= 0; i--) { /* increment */
1052 buf[ctr][8] = recs[ctr].type;
1053 buf[ctr][9] = (unsigned char)(s->version >> 8);
1054 buf[ctr][10] = (unsigned char)(s->version);
1055 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
1056 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
1057 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
1058 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
1060 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1061 ERR_R_INTERNAL_ERROR);
1067 recs[ctr].length += pad;
1070 } else if ((bs != 1) && sending) {
1071 padnum = bs - (reclen[ctr] % bs);
1073 /* Add weird padding of upto 256 bytes */
1075 if (padnum > MAX_PADDING) {
1076 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1077 ERR_R_INTERNAL_ERROR);
1080 /* we need to add 'padnum' padding bytes of value padval */
1081 padval = (unsigned char)(padnum - 1);
1082 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
1083 recs[ctr].input[loop] = padval;
1084 reclen[ctr] += padnum;
1085 recs[ctr].length += padnum;
1089 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
1094 unsigned char *data[SSL_MAX_PIPELINES];
1096 /* Set the output buffers */
1097 for (ctr = 0; ctr < n_recs; ctr++) {
1098 data[ctr] = recs[ctr].data;
1100 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1101 (int)n_recs, data) <= 0) {
1102 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1103 SSL_R_PIPELINE_FAILURE);
1106 /* Set the input buffers */
1107 for (ctr = 0; ctr < n_recs; ctr++) {
1108 data[ctr] = recs[ctr].input;
1110 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1111 (int)n_recs, data) <= 0
1112 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1113 (int)n_recs, reclen) <= 0) {
1114 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1115 SSL_R_PIPELINE_FAILURE);
1120 /* TODO(size_t): Convert this call */
1121 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1122 (unsigned int)reclen[0]);
1123 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1124 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1127 return -1; /* AEAD can fail to verify MAC */
1130 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1131 for (ctr = 0; ctr < n_recs; ctr++) {
1132 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1133 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1134 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1136 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1137 for (ctr = 0; ctr < n_recs; ctr++) {
1138 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1139 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1140 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1146 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1147 imac_size = EVP_MD_CTX_size(s->read_hash);
1148 if (imac_size < 0) {
1149 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1150 ERR_R_INTERNAL_ERROR);
1153 mac_size = (size_t)imac_size;
1155 if ((bs != 1) && !sending) {
1157 for (ctr = 0; ctr < n_recs; ctr++) {
1158 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1160 * If tmpret == 0 then this means publicly invalid so we can
1161 * short circuit things here. Otherwise we must respect constant
1166 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1170 if (pad && !sending) {
1171 for (ctr = 0; ctr < n_recs; ctr++) {
1172 recs[ctr].length -= pad;
1179 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1181 unsigned char *mac_sec, *seq;
1182 const EVP_MD_CTX *hash;
1183 unsigned char *p, rec_char;
1189 mac_sec = &(ssl->s3->write_mac_secret[0]);
1190 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1191 hash = ssl->write_hash;
1193 mac_sec = &(ssl->s3->read_mac_secret[0]);
1194 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1195 hash = ssl->read_hash;
1198 t = EVP_MD_CTX_size(hash);
1202 npad = (48 / md_size) * md_size;
1205 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1206 ssl3_cbc_record_digest_supported(hash)) {
1208 * This is a CBC-encrypted record. We must avoid leaking any
1209 * timing-side channel information about how many blocks of data we
1210 * are hashing because that gives an attacker a timing-oracle.
1214 * npad is, at most, 48 bytes and that's with MD5:
1215 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1217 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1218 * goes up 4, but npad goes down by 8, resulting in a smaller
1221 unsigned char header[75];
1223 memcpy(header + j, mac_sec, md_size);
1225 memcpy(header + j, ssl3_pad_1, npad);
1227 memcpy(header + j, seq, 8);
1229 header[j++] = rec->type;
1230 header[j++] = (unsigned char)(rec->length >> 8);
1231 header[j++] = (unsigned char)(rec->length & 0xff);
1233 /* Final param == is SSLv3 */
1234 if (ssl3_cbc_digest_record(hash,
1237 rec->length + md_size, rec->orig_len,
1238 mac_sec, md_size, 1) <= 0)
1241 unsigned int md_size_u;
1242 /* Chop the digest off the end :-) */
1243 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1248 rec_char = rec->type;
1250 s2n(rec->length, p);
1251 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1252 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1253 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1254 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1255 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1256 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1257 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1258 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1259 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1260 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1261 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1262 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1263 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1264 EVP_MD_CTX_free(md_ctx);
1268 EVP_MD_CTX_free(md_ctx);
1271 ssl3_record_sequence_update(seq);
1275 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1281 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1282 unsigned char header[13];
1283 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1284 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1288 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1289 hash = ssl->write_hash;
1291 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1292 hash = ssl->read_hash;
1295 t = EVP_MD_CTX_size(hash);
1296 if (!ossl_assert(t >= 0))
1300 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1304 hmac = EVP_MD_CTX_new();
1305 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
1306 EVP_MD_CTX_free(hmac);
1312 if (SSL_IS_DTLS(ssl)) {
1313 unsigned char dtlsseq[8], *p = dtlsseq;
1315 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1316 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1317 memcpy(p, &seq[2], 6);
1319 memcpy(header, dtlsseq, 8);
1321 memcpy(header, seq, 8);
1323 header[8] = rec->type;
1324 header[9] = (unsigned char)(ssl->version >> 8);
1325 header[10] = (unsigned char)(ssl->version);
1326 header[11] = (unsigned char)(rec->length >> 8);
1327 header[12] = (unsigned char)(rec->length & 0xff);
1329 if (!sending && !SSL_READ_ETM(ssl) &&
1330 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1331 ssl3_cbc_record_digest_supported(mac_ctx)) {
1333 * This is a CBC-encrypted record. We must avoid leaking any
1334 * timing-side channel information about how many blocks of data we
1335 * are hashing because that gives an attacker a timing-oracle.
1337 /* Final param == not SSLv3 */
1338 if (ssl3_cbc_digest_record(mac_ctx,
1341 rec->length + md_size, rec->orig_len,
1342 ssl->s3->read_mac_secret,
1343 ssl->s3->read_mac_secret_size, 0) <= 0) {
1344 EVP_MD_CTX_free(hmac);
1348 /* TODO(size_t): Convert these calls */
1349 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1350 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1351 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1352 EVP_MD_CTX_free(hmac);
1357 EVP_MD_CTX_free(hmac);
1360 fprintf(stderr, "seq=");
1363 for (z = 0; z < 8; z++)
1364 fprintf(stderr, "%02X ", seq[z]);
1365 fprintf(stderr, "\n");
1367 fprintf(stderr, "rec=");
1370 for (z = 0; z < rec->length; z++)
1371 fprintf(stderr, "%02X ", rec->data[z]);
1372 fprintf(stderr, "\n");
1376 if (!SSL_IS_DTLS(ssl)) {
1377 for (i = 7; i >= 0; i--) {
1386 for (z = 0; z < md_size; z++)
1387 fprintf(stderr, "%02X ", md[z]);
1388 fprintf(stderr, "\n");
1395 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1396 * record in |rec| by updating |rec->length| in constant time.
1398 * block_size: the block size of the cipher used to encrypt the record.
1400 * 0: (in non-constant time) if the record is publicly invalid.
1401 * 1: if the padding was valid
1404 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1405 size_t block_size, size_t mac_size)
1407 size_t padding_length;
1409 const size_t overhead = 1 /* padding length byte */ + mac_size;
1412 * These lengths are all public so we can test them in non-constant time.
1414 if (overhead > rec->length)
1417 padding_length = rec->data[rec->length - 1];
1418 good = constant_time_ge_s(rec->length, padding_length + overhead);
1419 /* SSLv3 requires that the padding is minimal. */
1420 good &= constant_time_ge_s(block_size, padding_length + 1);
1421 rec->length -= good & (padding_length + 1);
1422 return constant_time_select_int_s(good, 1, -1);
1426 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1427 * record in |rec| in constant time and returns 1 if the padding is valid and
1428 * -1 otherwise. It also removes any explicit IV from the start of the record
1429 * without leaking any timing about whether there was enough space after the
1430 * padding was removed.
1432 * block_size: the block size of the cipher used to encrypt the record.
1434 * 0: (in non-constant time) if the record is publicly invalid.
1435 * 1: if the padding was valid
1438 int tls1_cbc_remove_padding(const SSL *s,
1440 size_t block_size, size_t mac_size)
1443 size_t padding_length, to_check, i;
1444 const size_t overhead = 1 /* padding length byte */ + mac_size;
1445 /* Check if version requires explicit IV */
1446 if (SSL_USE_EXPLICIT_IV(s)) {
1448 * These lengths are all public so we can test them in non-constant
1451 if (overhead + block_size > rec->length)
1453 /* We can now safely skip explicit IV */
1454 rec->data += block_size;
1455 rec->input += block_size;
1456 rec->length -= block_size;
1457 rec->orig_len -= block_size;
1458 } else if (overhead > rec->length)
1461 padding_length = rec->data[rec->length - 1];
1463 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1464 EVP_CIPH_FLAG_AEAD_CIPHER) {
1465 /* padding is already verified */
1466 rec->length -= padding_length + 1;
1470 good = constant_time_ge_s(rec->length, overhead + padding_length);
1472 * The padding consists of a length byte at the end of the record and
1473 * then that many bytes of padding, all with the same value as the length
1474 * byte. Thus, with the length byte included, there are i+1 bytes of
1475 * padding. We can't check just |padding_length+1| bytes because that
1476 * leaks decrypted information. Therefore we always have to check the
1477 * maximum amount of padding possible. (Again, the length of the record
1478 * is public information so we can use it.)
1480 to_check = 256; /* maximum amount of padding, inc length byte. */
1481 if (to_check > rec->length)
1482 to_check = rec->length;
1484 for (i = 0; i < to_check; i++) {
1485 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1486 unsigned char b = rec->data[rec->length - 1 - i];
1488 * The final |padding_length+1| bytes should all have the value
1489 * |padding_length|. Therefore the XOR should be zero.
1491 good &= ~(mask & (padding_length ^ b));
1495 * If any of the final |padding_length+1| bytes had the wrong value, one
1496 * or more of the lower eight bits of |good| will be cleared.
1498 good = constant_time_eq_s(0xff, good & 0xff);
1499 rec->length -= good & (padding_length + 1);
1501 return constant_time_select_int_s(good, 1, -1);
1505 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1506 * constant time (independent of the concrete value of rec->length, which may
1507 * vary within a 256-byte window).
1509 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1513 * rec->orig_len >= md_size
1514 * md_size <= EVP_MAX_MD_SIZE
1516 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1517 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1518 * a single or pair of cache-lines, then the variable memory accesses don't
1519 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1520 * not multi-core and are not considered vulnerable to cache-timing attacks.
1522 #define CBC_MAC_ROTATE_IN_PLACE
1524 int ssl3_cbc_copy_mac(unsigned char *out,
1525 const SSL3_RECORD *rec, size_t md_size)
1527 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1528 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1529 unsigned char *rotated_mac;
1531 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1535 * mac_end is the index of |rec->data| just after the end of the MAC.
1537 size_t mac_end = rec->length;
1538 size_t mac_start = mac_end - md_size;
1541 * scan_start contains the number of bytes that we can ignore because the
1542 * MAC's position can only vary by 255 bytes.
1544 size_t scan_start = 0;
1546 size_t rotate_offset;
1548 if (!ossl_assert(rec->orig_len >= md_size
1549 && md_size <= EVP_MAX_MD_SIZE))
1552 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1553 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1556 /* This information is public so it's safe to branch based on it. */
1557 if (rec->orig_len > md_size + 255 + 1)
1558 scan_start = rec->orig_len - (md_size + 255 + 1);
1562 memset(rotated_mac, 0, md_size);
1563 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1564 size_t mac_started = constant_time_eq_s(i, mac_start);
1565 size_t mac_ended = constant_time_lt_s(i, mac_end);
1566 unsigned char b = rec->data[i];
1568 in_mac |= mac_started;
1569 in_mac &= mac_ended;
1570 rotate_offset |= j & mac_started;
1571 rotated_mac[j++] |= b & in_mac;
1572 j &= constant_time_lt_s(j, md_size);
1575 /* Now rotate the MAC */
1576 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1578 for (i = 0; i < md_size; i++) {
1579 /* in case cache-line is 32 bytes, touch second line */
1580 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1581 out[j++] = rotated_mac[rotate_offset++];
1582 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1585 memset(out, 0, md_size);
1586 rotate_offset = md_size - rotate_offset;
1587 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1588 for (i = 0; i < md_size; i++) {
1589 for (j = 0; j < md_size; j++)
1590 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1592 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1599 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1607 unsigned char md[EVP_MAX_MD_SIZE];
1609 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1613 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1614 * and we have that many bytes in s->packet
1616 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1619 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1620 * at rr->length bytes, which need to be copied into rr->data by either
1621 * the decryption or by the decompression When the data is 'copied' into
1622 * the rr->data buffer, rr->input will be pointed at the new buffer
1626 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1627 * bytes of encrypted compressed stuff.
1630 /* check is not needed I believe */
1631 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1632 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1633 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1637 /* decrypt in place in 'rr->input' */
1638 rr->data = rr->input;
1639 rr->orig_len = rr->length;
1641 if (SSL_READ_ETM(s) && s->read_hash) {
1643 mac_size = EVP_MD_CTX_size(s->read_hash);
1644 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1645 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1646 ERR_R_INTERNAL_ERROR);
1649 if (rr->orig_len < mac_size) {
1650 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1651 SSL_R_LENGTH_TOO_SHORT);
1654 rr->length -= mac_size;
1655 mac = rr->data + rr->length;
1656 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1657 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1658 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_DTLS1_PROCESS_RECORD,
1659 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1664 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1667 * 0: (in non-constant time) if the record is publically invalid.
1668 * 1: if the padding is valid
1669 * -1: if the padding is invalid
1672 if (ossl_statem_in_error(s)) {
1673 /* SSLfatal() got called */
1676 /* For DTLS we simply ignore bad packets. */
1678 RECORD_LAYER_reset_packet_length(&s->rlayer);
1682 printf("dec %ld\n", rr->length);
1685 for (z = 0; z < rr->length; z++)
1686 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1691 /* r->length is now the compressed data plus mac */
1692 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1693 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1694 /* s->read_hash != NULL => mac_size != -1 */
1695 unsigned char *mac = NULL;
1696 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1698 /* TODO(size_t): Convert this to do size_t properly */
1699 imac_size = EVP_MD_CTX_size(s->read_hash);
1700 if (imac_size < 0) {
1701 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1705 mac_size = (size_t)imac_size;
1706 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1707 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1708 ERR_R_INTERNAL_ERROR);
1713 * orig_len is the length of the record before any padding was
1714 * removed. This is public information, as is the MAC in use,
1715 * therefore we can safely process the record in a different amount
1716 * of time if it's too short to possibly contain a MAC.
1718 if (rr->orig_len < mac_size ||
1719 /* CBC records must have a padding length byte too. */
1720 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1721 rr->orig_len < mac_size + 1)) {
1722 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1723 SSL_R_LENGTH_TOO_SHORT);
1727 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1729 * We update the length so that the TLS header bytes can be
1730 * constructed correctly but we need to extract the MAC in
1731 * constant time from within the record, without leaking the
1732 * contents of the padding bytes.
1735 if (!ssl3_cbc_copy_mac(mac_tmp, rr, mac_size)) {
1736 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1737 ERR_R_INTERNAL_ERROR);
1740 rr->length -= mac_size;
1743 * In this case there's no padding, so |rec->orig_len| equals
1744 * |rec->length| and we checked that there's enough bytes for
1747 rr->length -= mac_size;
1748 mac = &rr->data[rr->length];
1751 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1752 if (i == 0 || mac == NULL
1753 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1755 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1760 /* decryption failed, silently discard message */
1762 RECORD_LAYER_reset_packet_length(&s->rlayer);
1766 /* r->length is now just compressed */
1767 if (s->expand != NULL) {
1768 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1769 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1770 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1773 if (!ssl3_do_uncompress(s, rr)) {
1774 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE,
1775 SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1780 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1781 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1782 SSL_R_DATA_LENGTH_TOO_LONG);
1788 * So at this point the following is true
1789 * ssl->s3->rrec.type is the type of record
1790 * ssl->s3->rrec.length == number of bytes in record
1791 * ssl->s3->rrec.off == offset to first valid byte
1792 * ssl->s3->rrec.data == where to take bytes from, increment
1796 /* we have pulled in a full packet so zero things */
1797 RECORD_LAYER_reset_packet_length(&s->rlayer);
1799 /* Mark receipt of record. */
1800 dtls1_record_bitmap_update(s, bitmap);
1806 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1808 #define dtls1_get_processed_record(s) \
1809 dtls1_retrieve_buffered_record((s), \
1810 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1813 * Call this to get a new input record.
1814 * It will return <= 0 if more data is needed, normally due to an error
1815 * or non-blocking IO.
1816 * When it finishes, one packet has been decoded and can be found in
1817 * ssl->s3->rrec.type - is the type of record
1818 * ssl->s3->rrec.data, - data
1819 * ssl->s3->rrec.length, - number of bytes
1821 /* used only by dtls1_read_bytes */
1822 int dtls1_get_record(SSL *s)
1824 int ssl_major, ssl_minor;
1828 unsigned char *p = NULL;
1829 unsigned short version;
1830 DTLS1_BITMAP *bitmap;
1831 unsigned int is_next_epoch;
1833 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1837 * The epoch may have changed. If so, process all the pending records.
1838 * This is a non-blocking operation.
1840 if (!dtls1_process_buffered_records(s)) {
1841 /* SSLfatal() already called */
1845 /* if we're renegotiating, then there may be buffered records */
1846 if (dtls1_get_processed_record(s))
1849 /* get something from the wire */
1851 /* check if we have the header */
1852 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1853 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1854 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1855 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1856 /* read timeout is handled by dtls1_read_bytes */
1858 /* SSLfatal() already called if appropriate */
1859 return rret; /* error or non-blocking */
1862 /* this packet contained a partial record, dump it */
1863 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1864 DTLS1_RT_HEADER_LENGTH) {
1865 RECORD_LAYER_reset_packet_length(&s->rlayer);
1869 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1871 p = RECORD_LAYER_get_packet(&s->rlayer);
1873 if (s->msg_callback)
1874 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1875 s, s->msg_callback_arg);
1877 /* Pull apart the header into the DTLS1_RECORD */
1881 version = (ssl_major << 8) | ssl_minor;
1883 /* sequence number is 64 bits, with top 2 bytes = epoch */
1886 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1893 * Lets check the version. We tolerate alerts that don't have the exact
1894 * version number (e.g. because of protocol version errors)
1896 if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
1897 if (version != s->version) {
1898 /* unexpected version, silently discard */
1901 RECORD_LAYER_reset_packet_length(&s->rlayer);
1906 if ((version & 0xff00) != (s->version & 0xff00)) {
1907 /* wrong version, silently discard record */
1910 RECORD_LAYER_reset_packet_length(&s->rlayer);
1914 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1915 /* record too long, silently discard it */
1918 RECORD_LAYER_reset_packet_length(&s->rlayer);
1922 /* If received packet overflows own-client Max Fragment Length setting */
1923 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1924 && rr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
1925 /* record too long, silently discard it */
1928 RECORD_LAYER_reset_packet_length(&s->rlayer);
1932 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1935 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1938 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1939 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1941 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1942 /* this packet contained a partial record, dump it */
1943 if (rret <= 0 || n != more) {
1944 if (ossl_statem_in_error(s)) {
1945 /* ssl3_read_n() called SSLfatal() */
1950 RECORD_LAYER_reset_packet_length(&s->rlayer);
1955 * now n == rr->length, and s->packet_length ==
1956 * DTLS1_RT_HEADER_LENGTH + rr->length
1959 /* set state for later operations */
1960 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1962 /* match epochs. NULL means the packet is dropped on the floor */
1963 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1964 if (bitmap == NULL) {
1966 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1967 goto again; /* get another record */
1969 #ifndef OPENSSL_NO_SCTP
1970 /* Only do replay check if no SCTP bio */
1971 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1973 /* Check whether this is a repeat, or aged record. */
1975 * TODO: Does it make sense to have replay protection in epoch 0 where
1976 * we have no integrity negotiated yet?
1978 if (!dtls1_record_replay_check(s, bitmap)) {
1981 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1982 goto again; /* get another record */
1984 #ifndef OPENSSL_NO_SCTP
1988 /* just read a 0 length packet */
1989 if (rr->length == 0) {
1995 * If this record is from the next epoch (either HM or ALERT), and a
1996 * handshake is currently in progress, buffer it since it cannot be
1997 * processed at this time.
1999 if (is_next_epoch) {
2000 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
2001 if (dtls1_buffer_record (s,
2002 &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
2004 /* SSLfatal() already called */
2010 RECORD_LAYER_reset_packet_length(&s->rlayer);
2014 if (!dtls1_process_record(s, bitmap)) {
2015 if (ossl_statem_in_error(s)) {
2016 /* dtls1_process_record() called SSLfatal */
2021 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
2022 goto again; /* get another record */