2 * Copyright 1995-2017 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 = 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 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_EARLY_DATA_COUNT_OK,
118 ERR_R_INTERNAL_ERROR);
121 sess = s->psksession;
124 || (s->hit && sess->ext.max_early_data < s->max_early_data))
125 max_early_data = sess->ext.max_early_data;
127 if (max_early_data == 0) {
128 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
129 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) {
137 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
138 SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
141 s->early_data_count += length;
147 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
148 * will be processed per call to ssl3_get_record. Without this limit an
149 * attacker could send empty records at a faster rate than we can process and
150 * cause ssl3_get_record to loop forever.
152 #define MAX_EMPTY_RECORDS 32
154 #define SSL2_RT_HEADER_LENGTH 2
156 * Call this to get new input records.
157 * It will return <= 0 if more data is needed, normally due to an error
158 * or non-blocking IO.
159 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
160 * rr[i].type - is the type of record
162 * rr[i].length, - number of bytes
163 * Multiple records will only be returned if the record types are all
164 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
167 /* used only by ssl3_read_bytes */
168 int ssl3_get_record(SSL *s)
173 SSL3_RECORD *rr, *thisrr;
177 unsigned char md[EVP_MAX_MD_SIZE];
178 unsigned int version;
181 size_t num_recs = 0, max_recs, j;
182 PACKET pkt, sslv2pkt;
183 size_t first_rec_len;
185 rr = RECORD_LAYER_get_rrec(&s->rlayer);
186 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
187 max_recs = s->max_pipelines;
193 thisrr = &rr[num_recs];
195 /* check if we have the header */
196 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
197 (RECORD_LAYER_get_packet_length(&s->rlayer)
198 < SSL3_RT_HEADER_LENGTH)) {
202 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
203 SSL3_BUFFER_get_len(rbuf), 0,
204 num_recs == 0 ? 1 : 0, &n);
206 return rret; /* error or non-blocking */
207 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
209 p = RECORD_LAYER_get_packet(&s->rlayer);
210 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
211 RECORD_LAYER_get_packet_length(&s->rlayer))) {
212 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
213 ERR_R_INTERNAL_ERROR);
217 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
218 || !PACKET_get_1(&sslv2pkt, &type)) {
219 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
220 ERR_R_INTERNAL_ERROR);
224 * The first record received by the server may be a V2ClientHello.
226 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
227 && (sslv2len & 0x8000) != 0
228 && (type == SSL2_MT_CLIENT_HELLO)) {
232 * |num_recs| here will actually always be 0 because
233 * |num_recs > 0| only ever occurs when we are processing
234 * multiple app data records - which we know isn't the case here
235 * because it is an SSLv2ClientHello. We keep it using
236 * |num_recs| for the sake of consistency
238 thisrr->type = SSL3_RT_HANDSHAKE;
239 thisrr->rec_version = SSL2_VERSION;
241 thisrr->length = sslv2len & 0x7fff;
243 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
244 - SSL2_RT_HEADER_LENGTH) {
245 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
246 SSL_R_PACKET_LENGTH_TOO_LONG);
250 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
251 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
252 SSL_R_LENGTH_TOO_SHORT);
256 /* SSLv3+ style record */
258 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
259 s->msg_callback_arg);
261 /* Pull apart the header into the SSL3_RECORD */
262 if (!PACKET_get_1(&pkt, &type)
263 || !PACKET_get_net_2(&pkt, &version)
264 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
265 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
266 ERR_R_INTERNAL_ERROR);
270 thisrr->rec_version = version;
273 * Lets check version. In TLSv1.3 we ignore this field. For the
274 * ServerHello after an HRR we haven't actually selected TLSv1.3
275 * yet, but we still treat it as TLSv1.3, so we must check for
278 if (!s->first_packet && !SSL_IS_TLS13(s)
279 && !s->hello_retry_request
280 && version != (unsigned int)s->version) {
281 if ((s->version & 0xFF00) == (version & 0xFF00)
282 && !s->enc_write_ctx && !s->write_hash) {
283 if (thisrr->type == SSL3_RT_ALERT) {
285 * The record is using an incorrect version number,
286 * but what we've got appears to be an alert. We
287 * haven't read the body yet to check whether its a
288 * fatal or not - but chances are it is. We probably
289 * shouldn't send a fatal alert back. We'll just
292 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
293 SSL_R_WRONG_VERSION_NUMBER);
297 * Send back error using their minor version number :-)
299 s->version = (unsigned short)version;
301 SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL3_GET_RECORD,
302 SSL_R_WRONG_VERSION_NUMBER);
306 if ((version >> 8) != SSL3_VERSION_MAJOR) {
307 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
308 /* Go back to start of packet, look at the five bytes
310 p = RECORD_LAYER_get_packet(&s->rlayer);
311 if (strncmp((char *)p, "GET ", 4) == 0 ||
312 strncmp((char *)p, "POST ", 5) == 0 ||
313 strncmp((char *)p, "HEAD ", 5) == 0 ||
314 strncmp((char *)p, "PUT ", 4) == 0) {
315 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
318 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
319 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
320 SSL_R_HTTPS_PROXY_REQUEST);
324 /* Doesn't look like TLS - don't send an alert */
325 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
326 SSL_R_WRONG_VERSION_NUMBER);
329 SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
330 SSL_F_SSL3_GET_RECORD,
331 SSL_R_WRONG_VERSION_NUMBER);
337 && s->enc_read_ctx != NULL
338 && thisrr->type != SSL3_RT_APPLICATION_DATA
339 && (thisrr->type != SSL3_RT_CHANGE_CIPHER_SPEC
340 || !SSL_IS_FIRST_HANDSHAKE(s))) {
341 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
342 SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
347 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
348 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
349 SSL_R_PACKET_LENGTH_TOO_LONG);
354 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
357 if (SSL_IS_TLS13(s)) {
358 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
359 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
360 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
364 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
366 #ifndef OPENSSL_NO_COMP
368 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
369 * does not include the compression overhead anyway.
371 if (s->expand == NULL)
372 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
375 if (thisrr->length > len) {
376 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
377 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
383 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
384 * Calculate how much more data we need to read for the rest of the
387 if (thisrr->rec_version == SSL2_VERSION) {
388 more = thisrr->length + SSL2_RT_HEADER_LENGTH
389 - SSL3_RT_HEADER_LENGTH;
391 more = thisrr->length;
394 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
396 rret = ssl3_read_n(s, more, more, 1, 0, &n);
398 return rret; /* error or non-blocking io */
401 /* set state for later operations */
402 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
405 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
406 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
407 * + thisrr->length and we have that many bytes in s->packet
409 if (thisrr->rec_version == SSL2_VERSION) {
411 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
414 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
418 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
419 * points at thisrr->length bytes, which need to be copied into
420 * thisrr->data by either the decryption or by the decompression When
421 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
422 * be pointed at the new buffer
426 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
427 * thisrr->length bytes of encrypted compressed stuff.
430 /* decrypt in place in 'thisrr->input' */
431 thisrr->data = thisrr->input;
432 thisrr->orig_len = thisrr->length;
434 /* Mark this record as not read by upper layers yet */
439 /* we have pulled in a full packet so zero things */
440 RECORD_LAYER_reset_packet_length(&s->rlayer);
441 RECORD_LAYER_clear_first_record(&s->rlayer);
442 } while (num_recs < max_recs
443 && thisrr->type == SSL3_RT_APPLICATION_DATA
444 && SSL_USE_EXPLICIT_IV(s)
445 && s->enc_read_ctx != NULL
446 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
447 & EVP_CIPH_FLAG_PIPELINE)
448 && ssl3_record_app_data_waiting(s));
451 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
453 && SSL_IS_FIRST_HANDSHAKE(s)) {
455 * CCS messages must be exactly 1 byte long, containing the value 0x01
457 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
458 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL3_GET_RECORD,
459 SSL_R_INVALID_CCS_MESSAGE);
463 * CCS messages are ignored in TLSv1.3. We treat it like an empty
466 thisrr->type = SSL3_RT_HANDSHAKE;
467 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
468 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
469 > MAX_EMPTY_RECORDS) {
470 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
471 SSL_R_UNEXPECTED_CCS_MESSAGE);
475 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
481 * If in encrypt-then-mac mode calculate mac from encrypted record. All
482 * the details below are public so no timing details can leak.
484 if (SSL_READ_ETM(s) && s->read_hash) {
486 /* TODO(size_t): convert this to do size_t properly */
487 imac_size = EVP_MD_CTX_size(s->read_hash);
488 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
489 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
493 mac_size = (size_t)imac_size;
494 for (j = 0; j < num_recs; j++) {
497 if (thisrr->length < mac_size) {
498 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
499 SSL_R_LENGTH_TOO_SHORT);
502 thisrr->length -= mac_size;
503 mac = thisrr->data + thisrr->length;
504 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
505 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
506 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
507 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
513 first_rec_len = rr[0].length;
515 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
519 * 0: (in non-constant time) if the record is publicly invalid.
520 * 1: if the padding is valid
521 * -1: if the padding is invalid
524 if (ossl_statem_in_error(s)) {
525 /* SSLfatal() already got called */
528 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
530 * Valid early_data that we cannot decrypt might fail here as
531 * publicly invalid. We treat it like an empty record.
536 if (!early_data_count_ok(s, thisrr->length,
537 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
538 /* SSLfatal() already called */
544 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
545 RECORD_LAYER_reset_read_sequence(&s->rlayer);
548 SSLfatal(s, SSL_AD_DECRYPTION_FAILED, SSL_F_SSL3_GET_RECORD,
549 SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
553 printf("dec %"OSSLzu"\n", rr[0].length);
556 for (z = 0; z < rr[0].length; z++)
557 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
562 /* r->length is now the compressed data plus mac */
563 if ((sess != NULL) &&
564 (s->enc_read_ctx != NULL) &&
565 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
566 /* s->read_hash != NULL => mac_size != -1 */
567 unsigned char *mac = NULL;
568 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
570 mac_size = EVP_MD_CTX_size(s->read_hash);
571 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
572 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
573 ERR_R_INTERNAL_ERROR);
577 for (j = 0; j < num_recs; j++) {
580 * orig_len is the length of the record before any padding was
581 * removed. This is public information, as is the MAC in use,
582 * therefore we can safely process the record in a different amount
583 * of time if it's too short to possibly contain a MAC.
585 if (thisrr->orig_len < mac_size ||
586 /* CBC records must have a padding length byte too. */
587 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
588 thisrr->orig_len < mac_size + 1)) {
589 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
590 SSL_R_LENGTH_TOO_SHORT);
594 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
596 * We update the length so that the TLS header bytes can be
597 * constructed correctly but we need to extract the MAC in
598 * constant time from within the record, without leaking the
599 * contents of the padding bytes.
602 if (!ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size)) {
603 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
604 ERR_R_INTERNAL_ERROR);
607 thisrr->length -= mac_size;
610 * In this case there's no padding, so |rec->orig_len| equals
611 * |rec->length| and we checked that there's enough bytes for
614 thisrr->length -= mac_size;
615 mac = &thisrr->data[thisrr->length];
618 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
619 if (i == 0 || mac == NULL
620 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
622 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
628 if (ossl_statem_in_error(s)) {
629 /* We already called SSLfatal() */
632 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
634 * We assume this is unreadable early_data - we treat it like an
639 * The record length may have been modified by the mac check above
640 * so we use the previously saved value
642 if (!early_data_count_ok(s, first_rec_len,
643 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
644 /* SSLfatal() already called */
651 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
652 RECORD_LAYER_reset_read_sequence(&s->rlayer);
656 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
657 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
658 * failure is directly visible from the ciphertext anyway, we should
659 * not reveal which kind of error occurred -- this might become
660 * visible to an attacker (e.g. via a logfile)
662 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
663 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
667 for (j = 0; j < num_recs; j++) {
670 /* thisrr->length is now just compressed */
671 if (s->expand != NULL) {
672 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
673 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
674 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
677 if (!ssl3_do_uncompress(s, thisrr)) {
678 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE, SSL_F_SSL3_GET_RECORD,
679 SSL_R_BAD_DECOMPRESSION);
684 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
687 if (thisrr->length == 0
688 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
689 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
690 SSL_R_BAD_RECORD_TYPE);
694 /* Strip trailing padding */
695 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
699 thisrr->length = end;
700 thisrr->type = thisrr->data[end];
701 if (thisrr->type != SSL3_RT_APPLICATION_DATA
702 && thisrr->type != SSL3_RT_ALERT
703 && thisrr->type != SSL3_RT_HANDSHAKE) {
704 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
705 SSL_R_BAD_RECORD_TYPE);
709 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
710 &thisrr->data[end], 1, s, s->msg_callback_arg);
714 * TLSv1.3 alert and handshake records are required to be non-zero in
718 && (thisrr->type == SSL3_RT_HANDSHAKE
719 || thisrr->type == SSL3_RT_ALERT)
720 && thisrr->length == 0) {
721 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
726 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
727 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
728 SSL_R_DATA_LENGTH_TOO_LONG);
732 /* If received packet overflows current Max Fragment Length setting */
733 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
734 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
735 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
736 SSL_R_DATA_LENGTH_TOO_LONG);
742 * So at this point the following is true
743 * thisrr->type is the type of record
744 * thisrr->length == number of bytes in record
745 * thisrr->off == offset to first valid byte
746 * thisrr->data == where to take bytes from, increment after use :-).
749 /* just read a 0 length packet */
750 if (thisrr->length == 0) {
751 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
752 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
753 > MAX_EMPTY_RECORDS) {
754 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
755 SSL_R_RECORD_TOO_SMALL);
759 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
763 if (s->early_data_state == SSL_EARLY_DATA_READING) {
765 if (thisrr->type == SSL3_RT_APPLICATION_DATA
766 && !early_data_count_ok(s, thisrr->length, 0, 0)) {
767 /* SSLfatal already called */
772 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
776 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
778 #ifndef OPENSSL_NO_COMP
781 if (rr->comp == NULL) {
782 rr->comp = (unsigned char *)
783 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
785 if (rr->comp == NULL)
788 /* TODO(size_t): Convert this call */
789 i = COMP_expand_block(ssl->expand, rr->comp,
790 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
800 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
802 #ifndef OPENSSL_NO_COMP
805 /* TODO(size_t): Convert this call */
806 i = COMP_compress_block(ssl->compress, wr->data,
807 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
808 wr->input, (int)wr->length);
814 wr->input = wr->data;
820 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|. Will call
821 * SSLfatal() for internal errors, but not otherwise.
824 * 0: (in non-constant time) if the record is publically invalid (i.e. too
826 * 1: if the record's padding is valid / the encryption was successful.
827 * -1: if the record's padding is invalid or, if sending, an internal error
830 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
835 size_t bs, mac_size = 0;
837 const EVP_CIPHER *enc;
841 * We shouldn't ever be called with more than one record in the SSLv3 case
846 ds = s->enc_write_ctx;
847 if (s->enc_write_ctx == NULL)
850 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
852 ds = s->enc_read_ctx;
853 if (s->enc_read_ctx == NULL)
856 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
859 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
860 memmove(rec->data, rec->input, rec->length);
861 rec->input = rec->data;
864 /* TODO(size_t): Convert this call */
865 bs = EVP_CIPHER_CTX_block_size(ds);
869 if ((bs != 1) && sending) {
872 /* we need to add 'i-1' padding bytes */
875 * the last of these zero bytes will be overwritten with the
878 memset(&rec->input[rec->length], 0, i);
880 rec->input[l - 1] = (unsigned char)(i - 1);
884 if (l == 0 || l % bs != 0)
886 /* otherwise, rec->length >= bs */
889 /* TODO(size_t): Convert this call */
890 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
893 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
894 /* TODO(size_t): convert me */
895 imac_size = EVP_MD_CTX_size(s->read_hash);
897 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_ENC,
898 ERR_R_INTERNAL_ERROR);
901 mac_size = (size_t)imac_size;
903 if ((bs != 1) && !sending)
904 return ssl3_cbc_remove_padding(rec, bs, mac_size);
909 #define MAX_PADDING 256
911 * tls1_enc encrypts/decrypts |n_recs| in |recs|. Will call SSLfatal() for
912 * internal errors, but not otherwise.
915 * 0: (in non-constant time) if the record is publically invalid (i.e. too
917 * 1: if the record's padding is valid / the encryption was successful.
918 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
919 * an internal error occurred.
921 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
924 size_t reclen[SSL_MAX_PIPELINES];
925 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
926 int i, pad = 0, ret, tmpr;
927 size_t bs, mac_size = 0, ctr, padnum, loop;
928 unsigned char padval;
930 const EVP_CIPHER *enc;
933 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
934 ERR_R_INTERNAL_ERROR);
939 if (EVP_MD_CTX_md(s->write_hash)) {
940 int n = EVP_MD_CTX_size(s->write_hash);
941 if (!ossl_assert(n >= 0)) {
942 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
943 ERR_R_INTERNAL_ERROR);
947 ds = s->enc_write_ctx;
948 if (s->enc_write_ctx == NULL)
952 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
953 /* For TLSv1.1 and later explicit IV */
954 if (SSL_USE_EXPLICIT_IV(s)
955 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
956 ivlen = EVP_CIPHER_iv_length(enc);
960 for (ctr = 0; ctr < n_recs; ctr++) {
961 if (recs[ctr].data != recs[ctr].input) {
963 * we can't write into the input stream: Can this ever
966 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
967 ERR_R_INTERNAL_ERROR);
969 } else if (ssl_randbytes(s, recs[ctr].input, ivlen) <= 0) {
970 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
971 ERR_R_INTERNAL_ERROR);
978 if (EVP_MD_CTX_md(s->read_hash)) {
979 int n = EVP_MD_CTX_size(s->read_hash);
980 if (!ossl_assert(n >= 0)) {
981 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
982 ERR_R_INTERNAL_ERROR);
986 ds = s->enc_read_ctx;
987 if (s->enc_read_ctx == NULL)
990 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
993 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
994 for (ctr = 0; ctr < n_recs; ctr++) {
995 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
996 recs[ctr].input = recs[ctr].data;
1000 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
1003 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1004 & EVP_CIPH_FLAG_PIPELINE)) {
1006 * We shouldn't have been called with pipeline data if the
1007 * cipher doesn't support pipelining
1009 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1010 SSL_R_PIPELINE_FAILURE);
1014 for (ctr = 0; ctr < n_recs; ctr++) {
1015 reclen[ctr] = recs[ctr].length;
1017 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1018 & EVP_CIPH_FLAG_AEAD_CIPHER) {
1021 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1022 : RECORD_LAYER_get_read_sequence(&s->rlayer);
1024 if (SSL_IS_DTLS(s)) {
1025 /* DTLS does not support pipelining */
1026 unsigned char dtlsseq[9], *p = dtlsseq;
1028 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
1029 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
1030 memcpy(p, &seq[2], 6);
1031 memcpy(buf[ctr], dtlsseq, 8);
1033 memcpy(buf[ctr], seq, 8);
1034 for (i = 7; i >= 0; i--) { /* increment */
1041 buf[ctr][8] = recs[ctr].type;
1042 buf[ctr][9] = (unsigned char)(s->version >> 8);
1043 buf[ctr][10] = (unsigned char)(s->version);
1044 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
1045 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
1046 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
1047 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
1049 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1050 ERR_R_INTERNAL_ERROR);
1056 recs[ctr].length += pad;
1059 } else if ((bs != 1) && sending) {
1060 padnum = bs - (reclen[ctr] % bs);
1062 /* Add weird padding of upto 256 bytes */
1064 if (padnum > MAX_PADDING) {
1065 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1066 ERR_R_INTERNAL_ERROR);
1069 /* we need to add 'padnum' padding bytes of value padval */
1070 padval = (unsigned char)(padnum - 1);
1071 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
1072 recs[ctr].input[loop] = padval;
1073 reclen[ctr] += padnum;
1074 recs[ctr].length += padnum;
1078 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
1083 unsigned char *data[SSL_MAX_PIPELINES];
1085 /* Set the output buffers */
1086 for (ctr = 0; ctr < n_recs; ctr++) {
1087 data[ctr] = recs[ctr].data;
1089 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1090 (int)n_recs, data) <= 0) {
1091 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1092 SSL_R_PIPELINE_FAILURE);
1095 /* Set the input buffers */
1096 for (ctr = 0; ctr < n_recs; ctr++) {
1097 data[ctr] = recs[ctr].input;
1099 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1100 (int)n_recs, data) <= 0
1101 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1102 (int)n_recs, reclen) <= 0) {
1103 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1104 SSL_R_PIPELINE_FAILURE);
1109 /* TODO(size_t): Convert this call */
1110 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1111 (unsigned int)reclen[0]);
1112 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1113 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1116 return -1; /* AEAD can fail to verify MAC */
1119 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1120 for (ctr = 0; ctr < n_recs; ctr++) {
1121 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1122 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1123 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1125 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1126 for (ctr = 0; ctr < n_recs; ctr++) {
1127 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1128 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1129 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1135 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1136 imac_size = EVP_MD_CTX_size(s->read_hash);
1137 if (imac_size < 0) {
1138 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1139 ERR_R_INTERNAL_ERROR);
1142 mac_size = (size_t)imac_size;
1144 if ((bs != 1) && !sending) {
1146 for (ctr = 0; ctr < n_recs; ctr++) {
1147 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1149 * If tmpret == 0 then this means publicly invalid so we can
1150 * short circuit things here. Otherwise we must respect constant
1155 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1159 if (pad && !sending) {
1160 for (ctr = 0; ctr < n_recs; ctr++) {
1161 recs[ctr].length -= pad;
1168 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1170 unsigned char *mac_sec, *seq;
1171 const EVP_MD_CTX *hash;
1172 unsigned char *p, rec_char;
1178 mac_sec = &(ssl->s3->write_mac_secret[0]);
1179 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1180 hash = ssl->write_hash;
1182 mac_sec = &(ssl->s3->read_mac_secret[0]);
1183 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1184 hash = ssl->read_hash;
1187 t = EVP_MD_CTX_size(hash);
1191 npad = (48 / md_size) * md_size;
1194 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1195 ssl3_cbc_record_digest_supported(hash)) {
1197 * This is a CBC-encrypted record. We must avoid leaking any
1198 * timing-side channel information about how many blocks of data we
1199 * are hashing because that gives an attacker a timing-oracle.
1203 * npad is, at most, 48 bytes and that's with MD5:
1204 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1206 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1207 * goes up 4, but npad goes down by 8, resulting in a smaller
1210 unsigned char header[75];
1212 memcpy(header + j, mac_sec, md_size);
1214 memcpy(header + j, ssl3_pad_1, npad);
1216 memcpy(header + j, seq, 8);
1218 header[j++] = rec->type;
1219 header[j++] = (unsigned char)(rec->length >> 8);
1220 header[j++] = (unsigned char)(rec->length & 0xff);
1222 /* Final param == is SSLv3 */
1223 if (ssl3_cbc_digest_record(hash,
1226 rec->length + md_size, rec->orig_len,
1227 mac_sec, md_size, 1) <= 0)
1230 unsigned int md_size_u;
1231 /* Chop the digest off the end :-) */
1232 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1237 rec_char = rec->type;
1239 s2n(rec->length, p);
1240 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1241 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1242 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1243 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1244 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1245 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1246 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1247 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1248 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1249 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1250 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1251 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1252 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1253 EVP_MD_CTX_reset(md_ctx);
1257 EVP_MD_CTX_free(md_ctx);
1260 ssl3_record_sequence_update(seq);
1264 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1270 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1271 unsigned char header[13];
1272 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1273 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1277 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1278 hash = ssl->write_hash;
1280 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1281 hash = ssl->read_hash;
1284 t = EVP_MD_CTX_size(hash);
1285 if (!ossl_assert(t >= 0))
1289 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1293 hmac = EVP_MD_CTX_new();
1294 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1299 if (SSL_IS_DTLS(ssl)) {
1300 unsigned char dtlsseq[8], *p = dtlsseq;
1302 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1303 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1304 memcpy(p, &seq[2], 6);
1306 memcpy(header, dtlsseq, 8);
1308 memcpy(header, seq, 8);
1310 header[8] = rec->type;
1311 header[9] = (unsigned char)(ssl->version >> 8);
1312 header[10] = (unsigned char)(ssl->version);
1313 header[11] = (unsigned char)(rec->length >> 8);
1314 header[12] = (unsigned char)(rec->length & 0xff);
1316 if (!sending && !SSL_READ_ETM(ssl) &&
1317 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1318 ssl3_cbc_record_digest_supported(mac_ctx)) {
1320 * This is a CBC-encrypted record. We must avoid leaking any
1321 * timing-side channel information about how many blocks of data we
1322 * are hashing because that gives an attacker a timing-oracle.
1324 /* Final param == not SSLv3 */
1325 if (ssl3_cbc_digest_record(mac_ctx,
1328 rec->length + md_size, rec->orig_len,
1329 ssl->s3->read_mac_secret,
1330 ssl->s3->read_mac_secret_size, 0) <= 0) {
1331 EVP_MD_CTX_free(hmac);
1335 /* TODO(size_t): Convert these calls */
1336 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1337 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1338 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1339 EVP_MD_CTX_free(hmac);
1344 EVP_MD_CTX_free(hmac);
1347 fprintf(stderr, "seq=");
1350 for (z = 0; z < 8; z++)
1351 fprintf(stderr, "%02X ", seq[z]);
1352 fprintf(stderr, "\n");
1354 fprintf(stderr, "rec=");
1357 for (z = 0; z < rec->length; z++)
1358 fprintf(stderr, "%02X ", rec->data[z]);
1359 fprintf(stderr, "\n");
1363 if (!SSL_IS_DTLS(ssl)) {
1364 for (i = 7; i >= 0; i--) {
1373 for (z = 0; z < md_size; z++)
1374 fprintf(stderr, "%02X ", md[z]);
1375 fprintf(stderr, "\n");
1382 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1383 * record in |rec| by updating |rec->length| in constant time.
1385 * block_size: the block size of the cipher used to encrypt the record.
1387 * 0: (in non-constant time) if the record is publicly invalid.
1388 * 1: if the padding was valid
1391 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1392 size_t block_size, size_t mac_size)
1394 size_t padding_length;
1396 const size_t overhead = 1 /* padding length byte */ + mac_size;
1399 * These lengths are all public so we can test them in non-constant time.
1401 if (overhead > rec->length)
1404 padding_length = rec->data[rec->length - 1];
1405 good = constant_time_ge_s(rec->length, padding_length + overhead);
1406 /* SSLv3 requires that the padding is minimal. */
1407 good &= constant_time_ge_s(block_size, padding_length + 1);
1408 rec->length -= good & (padding_length + 1);
1409 return constant_time_select_int_s(good, 1, -1);
1413 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1414 * record in |rec| in constant time and returns 1 if the padding is valid and
1415 * -1 otherwise. It also removes any explicit IV from the start of the record
1416 * without leaking any timing about whether there was enough space after the
1417 * padding was removed.
1419 * block_size: the block size of the cipher used to encrypt the record.
1421 * 0: (in non-constant time) if the record is publicly invalid.
1422 * 1: if the padding was valid
1425 int tls1_cbc_remove_padding(const SSL *s,
1427 size_t block_size, size_t mac_size)
1430 size_t padding_length, to_check, i;
1431 const size_t overhead = 1 /* padding length byte */ + mac_size;
1432 /* Check if version requires explicit IV */
1433 if (SSL_USE_EXPLICIT_IV(s)) {
1435 * These lengths are all public so we can test them in non-constant
1438 if (overhead + block_size > rec->length)
1440 /* We can now safely skip explicit IV */
1441 rec->data += block_size;
1442 rec->input += block_size;
1443 rec->length -= block_size;
1444 rec->orig_len -= block_size;
1445 } else if (overhead > rec->length)
1448 padding_length = rec->data[rec->length - 1];
1450 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1451 EVP_CIPH_FLAG_AEAD_CIPHER) {
1452 /* padding is already verified */
1453 rec->length -= padding_length + 1;
1457 good = constant_time_ge_s(rec->length, overhead + padding_length);
1459 * The padding consists of a length byte at the end of the record and
1460 * then that many bytes of padding, all with the same value as the length
1461 * byte. Thus, with the length byte included, there are i+1 bytes of
1462 * padding. We can't check just |padding_length+1| bytes because that
1463 * leaks decrypted information. Therefore we always have to check the
1464 * maximum amount of padding possible. (Again, the length of the record
1465 * is public information so we can use it.)
1467 to_check = 256; /* maximum amount of padding, inc length byte. */
1468 if (to_check > rec->length)
1469 to_check = rec->length;
1471 for (i = 0; i < to_check; i++) {
1472 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1473 unsigned char b = rec->data[rec->length - 1 - i];
1475 * The final |padding_length+1| bytes should all have the value
1476 * |padding_length|. Therefore the XOR should be zero.
1478 good &= ~(mask & (padding_length ^ b));
1482 * If any of the final |padding_length+1| bytes had the wrong value, one
1483 * or more of the lower eight bits of |good| will be cleared.
1485 good = constant_time_eq_s(0xff, good & 0xff);
1486 rec->length -= good & (padding_length + 1);
1488 return constant_time_select_int_s(good, 1, -1);
1492 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1493 * constant time (independent of the concrete value of rec->length, which may
1494 * vary within a 256-byte window).
1496 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1500 * rec->orig_len >= md_size
1501 * md_size <= EVP_MAX_MD_SIZE
1503 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1504 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1505 * a single or pair of cache-lines, then the variable memory accesses don't
1506 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1507 * not multi-core and are not considered vulnerable to cache-timing attacks.
1509 #define CBC_MAC_ROTATE_IN_PLACE
1511 int ssl3_cbc_copy_mac(unsigned char *out,
1512 const SSL3_RECORD *rec, size_t md_size)
1514 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1515 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1516 unsigned char *rotated_mac;
1518 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1522 * mac_end is the index of |rec->data| just after the end of the MAC.
1524 size_t mac_end = rec->length;
1525 size_t mac_start = mac_end - md_size;
1528 * scan_start contains the number of bytes that we can ignore because the
1529 * MAC's position can only vary by 255 bytes.
1531 size_t scan_start = 0;
1533 size_t rotate_offset;
1535 if (!ossl_assert(rec->orig_len >= md_size
1536 && md_size <= EVP_MAX_MD_SIZE))
1539 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1540 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1543 /* This information is public so it's safe to branch based on it. */
1544 if (rec->orig_len > md_size + 255 + 1)
1545 scan_start = rec->orig_len - (md_size + 255 + 1);
1549 memset(rotated_mac, 0, md_size);
1550 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1551 size_t mac_started = constant_time_eq_s(i, mac_start);
1552 size_t mac_ended = constant_time_lt_s(i, mac_end);
1553 unsigned char b = rec->data[i];
1555 in_mac |= mac_started;
1556 in_mac &= mac_ended;
1557 rotate_offset |= j & mac_started;
1558 rotated_mac[j++] |= b & in_mac;
1559 j &= constant_time_lt_s(j, md_size);
1562 /* Now rotate the MAC */
1563 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1565 for (i = 0; i < md_size; i++) {
1566 /* in case cache-line is 32 bytes, touch second line */
1567 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1568 out[j++] = rotated_mac[rotate_offset++];
1569 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1572 memset(out, 0, md_size);
1573 rotate_offset = md_size - rotate_offset;
1574 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1575 for (i = 0; i < md_size; i++) {
1576 for (j = 0; j < md_size; j++)
1577 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1579 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1586 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1594 unsigned char md[EVP_MAX_MD_SIZE];
1596 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1600 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1601 * and we have that many bytes in s->packet
1603 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1606 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1607 * at rr->length bytes, which need to be copied into rr->data by either
1608 * the decryption or by the decompression When the data is 'copied' into
1609 * the rr->data buffer, rr->input will be pointed at the new buffer
1613 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1614 * bytes of encrypted compressed stuff.
1617 /* check is not needed I believe */
1618 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1619 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1620 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1624 /* decrypt in place in 'rr->input' */
1625 rr->data = rr->input;
1626 rr->orig_len = rr->length;
1628 if (SSL_READ_ETM(s) && s->read_hash) {
1630 mac_size = EVP_MD_CTX_size(s->read_hash);
1631 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1632 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1633 ERR_R_INTERNAL_ERROR);
1636 if (rr->orig_len < mac_size) {
1637 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1638 SSL_R_LENGTH_TOO_SHORT);
1641 rr->length -= mac_size;
1642 mac = rr->data + rr->length;
1643 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1644 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1645 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_DTLS1_PROCESS_RECORD,
1646 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1651 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1654 * 0: (in non-constant time) if the record is publically invalid.
1655 * 1: if the padding is valid
1656 * -1: if the padding is invalid
1659 if (ossl_statem_in_error(s)) {
1660 /* SSLfatal() got called */
1663 /* For DTLS we simply ignore bad packets. */
1665 RECORD_LAYER_reset_packet_length(&s->rlayer);
1669 printf("dec %ld\n", rr->length);
1672 for (z = 0; z < rr->length; z++)
1673 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1678 /* r->length is now the compressed data plus mac */
1679 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1680 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1681 /* s->read_hash != NULL => mac_size != -1 */
1682 unsigned char *mac = NULL;
1683 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1685 /* TODO(size_t): Convert this to do size_t properly */
1686 imac_size = EVP_MD_CTX_size(s->read_hash);
1687 if (imac_size < 0) {
1688 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1692 mac_size = (size_t)imac_size;
1693 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1694 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1695 ERR_R_INTERNAL_ERROR);
1700 * orig_len is the length of the record before any padding was
1701 * removed. This is public information, as is the MAC in use,
1702 * therefore we can safely process the record in a different amount
1703 * of time if it's too short to possibly contain a MAC.
1705 if (rr->orig_len < mac_size ||
1706 /* CBC records must have a padding length byte too. */
1707 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1708 rr->orig_len < mac_size + 1)) {
1709 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1710 SSL_R_LENGTH_TOO_SHORT);
1714 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1716 * We update the length so that the TLS header bytes can be
1717 * constructed correctly but we need to extract the MAC in
1718 * constant time from within the record, without leaking the
1719 * contents of the padding bytes.
1722 if (!ssl3_cbc_copy_mac(mac_tmp, rr, mac_size)) {
1723 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1724 ERR_R_INTERNAL_ERROR);
1727 rr->length -= mac_size;
1730 * In this case there's no padding, so |rec->orig_len| equals
1731 * |rec->length| and we checked that there's enough bytes for
1734 rr->length -= mac_size;
1735 mac = &rr->data[rr->length];
1738 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1739 if (i == 0 || mac == NULL
1740 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1742 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1747 /* decryption failed, silently discard message */
1749 RECORD_LAYER_reset_packet_length(&s->rlayer);
1753 /* r->length is now just compressed */
1754 if (s->expand != NULL) {
1755 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1756 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1757 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1760 if (!ssl3_do_uncompress(s, rr)) {
1761 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE,
1762 SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1767 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1768 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1769 SSL_R_DATA_LENGTH_TOO_LONG);
1775 * So at this point the following is true
1776 * ssl->s3->rrec.type is the type of record
1777 * ssl->s3->rrec.length == number of bytes in record
1778 * ssl->s3->rrec.off == offset to first valid byte
1779 * ssl->s3->rrec.data == where to take bytes from, increment
1783 /* we have pulled in a full packet so zero things */
1784 RECORD_LAYER_reset_packet_length(&s->rlayer);
1786 /* Mark receipt of record. */
1787 dtls1_record_bitmap_update(s, bitmap);
1793 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1795 #define dtls1_get_processed_record(s) \
1796 dtls1_retrieve_buffered_record((s), \
1797 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1800 * Call this to get a new input record.
1801 * It will return <= 0 if more data is needed, normally due to an error
1802 * or non-blocking IO.
1803 * When it finishes, one packet has been decoded and can be found in
1804 * ssl->s3->rrec.type - is the type of record
1805 * ssl->s3->rrec.data, - data
1806 * ssl->s3->rrec.length, - number of bytes
1808 /* used only by dtls1_read_bytes */
1809 int dtls1_get_record(SSL *s)
1811 int ssl_major, ssl_minor;
1815 unsigned char *p = NULL;
1816 unsigned short version;
1817 DTLS1_BITMAP *bitmap;
1818 unsigned int is_next_epoch;
1820 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1824 * The epoch may have changed. If so, process all the pending records.
1825 * This is a non-blocking operation.
1827 if (!dtls1_process_buffered_records(s)) {
1828 /* SSLfatal() already called */
1832 /* if we're renegotiating, then there may be buffered records */
1833 if (dtls1_get_processed_record(s))
1836 /* get something from the wire */
1838 /* check if we have the header */
1839 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1840 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1841 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1842 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1843 /* read timeout is handled by dtls1_read_bytes */
1845 /* SSLfatal() already called if appropriate */
1846 return rret; /* error or non-blocking */
1849 /* this packet contained a partial record, dump it */
1850 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1851 DTLS1_RT_HEADER_LENGTH) {
1852 RECORD_LAYER_reset_packet_length(&s->rlayer);
1856 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1858 p = RECORD_LAYER_get_packet(&s->rlayer);
1860 if (s->msg_callback)
1861 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1862 s, s->msg_callback_arg);
1864 /* Pull apart the header into the DTLS1_RECORD */
1868 version = (ssl_major << 8) | ssl_minor;
1870 /* sequence number is 64 bits, with top 2 bytes = epoch */
1873 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1878 /* Lets check version */
1879 if (!s->first_packet) {
1880 if (version != s->version) {
1881 /* unexpected version, silently discard */
1883 RECORD_LAYER_reset_packet_length(&s->rlayer);
1888 if ((version & 0xff00) != (s->version & 0xff00)) {
1889 /* wrong version, silently discard record */
1891 RECORD_LAYER_reset_packet_length(&s->rlayer);
1895 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1896 /* record too long, silently discard it */
1898 RECORD_LAYER_reset_packet_length(&s->rlayer);
1902 /* If received packet overflows own-client Max Fragment Length setting */
1903 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1904 && rr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
1905 /* record too long, silently discard it */
1907 RECORD_LAYER_reset_packet_length(&s->rlayer);
1911 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1914 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1917 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1918 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1920 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1921 /* this packet contained a partial record, dump it */
1922 if (rret <= 0 || n != more) {
1923 if (ossl_statem_in_error(s)) {
1924 /* ssl3_read_n() called SSLfatal() */
1928 RECORD_LAYER_reset_packet_length(&s->rlayer);
1933 * now n == rr->length, and s->packet_length ==
1934 * DTLS1_RT_HEADER_LENGTH + rr->length
1937 /* set state for later operations */
1938 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1940 /* match epochs. NULL means the packet is dropped on the floor */
1941 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1942 if (bitmap == NULL) {
1944 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1945 goto again; /* get another record */
1947 #ifndef OPENSSL_NO_SCTP
1948 /* Only do replay check if no SCTP bio */
1949 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1951 /* Check whether this is a repeat, or aged record. */
1953 * TODO: Does it make sense to have replay protection in epoch 0 where
1954 * we have no integrity negotiated yet?
1956 if (!dtls1_record_replay_check(s, bitmap)) {
1958 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1959 goto again; /* get another record */
1961 #ifndef OPENSSL_NO_SCTP
1965 /* just read a 0 length packet */
1966 if (rr->length == 0)
1970 * If this record is from the next epoch (either HM or ALERT), and a
1971 * handshake is currently in progress, buffer it since it cannot be
1972 * processed at this time.
1974 if (is_next_epoch) {
1975 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1976 if (dtls1_buffer_record (s,
1977 &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1979 /* SSLfatal() already called */
1984 RECORD_LAYER_reset_packet_length(&s->rlayer);
1988 if (!dtls1_process_record(s, bitmap)) {
1989 if (ossl_statem_in_error(s)) {
1990 /* dtls1_process_record() called SSLfatal */
1994 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1995 goto again; /* get another record */