2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include "../ssl_locl.h"
11 #include "internal/constant_time_locl.h"
12 #include <openssl/rand.h>
13 #include "record_locl.h"
15 static const unsigned char ssl3_pad_1[48] = {
16 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
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
24 static const unsigned char ssl3_pad_2[48] = {
25 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
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
34 * Clear the contents of an SSL3_RECORD but retain any memory allocated
36 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
41 for (i = 0; i < num_recs; i++) {
44 memset(&r[i], 0, sizeof(*r));
49 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
53 for (i = 0; i < num_recs; i++) {
54 OPENSSL_free(r[i].comp);
59 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
61 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
65 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
66 * for us in the buffer.
68 static int ssl3_record_app_data_waiting(SSL *s)
74 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
76 p = SSL3_BUFFER_get_buf(rbuf);
80 left = SSL3_BUFFER_get_left(rbuf);
82 if (left < SSL3_RT_HEADER_LENGTH)
85 p += SSL3_BUFFER_get_offset(rbuf);
88 * We only check the type and record length, we will sanity check version
91 if (*p != SSL3_RT_APPLICATION_DATA)
97 if (left < SSL3_RT_HEADER_LENGTH + len)
103 int early_data_count_ok(SSL *s, size_t length, size_t overhead, int *al)
105 uint32_t max_early_data = s->max_early_data;
108 * If we are a client then we always use the max_early_data from the
109 * session. Otherwise we go with the lowest out of the max early data set in
110 * the session and the configured max_early_data.
112 if (!s->server || (s->hit
113 && s->session->ext.max_early_data < s->max_early_data))
114 max_early_data = s->session->ext.max_early_data;
116 if (max_early_data == 0) {
118 *al = SSL_AD_UNEXPECTED_MESSAGE;
119 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
123 /* If we are dealing with ciphertext we need to allow for the overhead */
124 max_early_data += overhead;
126 if (s->early_data_count + length > max_early_data) {
128 *al = SSL_AD_UNEXPECTED_MESSAGE;
129 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
132 s->early_data_count += length;
138 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
139 * will be processed per call to ssl3_get_record. Without this limit an
140 * attacker could send empty records at a faster rate than we can process and
141 * cause ssl3_get_record to loop forever.
143 #define MAX_EMPTY_RECORDS 32
145 #define SSL2_RT_HEADER_LENGTH 2
147 * Call this to get new input records.
148 * It will return <= 0 if more data is needed, normally due to an error
149 * or non-blocking IO.
150 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
151 * rr[i].type - is the type of record
153 * rr[i].length, - number of bytes
154 * Multiple records will only be returned if the record types are all
155 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
158 /* used only by ssl3_read_bytes */
159 int ssl3_get_record(SSL *s)
162 int enc_err, rret, ret = -1;
165 SSL3_RECORD *rr, *thisrr;
169 unsigned char md[EVP_MAX_MD_SIZE];
170 unsigned int version;
173 size_t num_recs = 0, max_recs, j;
174 PACKET pkt, sslv2pkt;
175 size_t first_rec_len;
177 rr = RECORD_LAYER_get_rrec(&s->rlayer);
178 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
179 max_recs = s->max_pipelines;
185 thisrr = &rr[num_recs];
187 /* check if we have the header */
188 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
189 (RECORD_LAYER_get_packet_length(&s->rlayer)
190 < SSL3_RT_HEADER_LENGTH)) {
194 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
195 SSL3_BUFFER_get_len(rbuf), 0,
196 num_recs == 0 ? 1 : 0, &n);
198 return rret; /* error or non-blocking */
199 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
201 p = RECORD_LAYER_get_packet(&s->rlayer);
202 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
203 RECORD_LAYER_get_packet_length(&s->rlayer))) {
204 al = SSL_AD_INTERNAL_ERROR;
205 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
209 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
210 || !PACKET_get_1(&sslv2pkt, &type)) {
211 al = SSL_AD_DECODE_ERROR;
212 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
216 * The first record received by the server may be a V2ClientHello.
218 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
219 && (sslv2len & 0x8000) != 0
220 && (type == SSL2_MT_CLIENT_HELLO)) {
224 * |num_recs| here will actually always be 0 because
225 * |num_recs > 0| only ever occurs when we are processing
226 * multiple app data records - which we know isn't the case here
227 * because it is an SSLv2ClientHello. We keep it using
228 * |num_recs| for the sake of consistency
230 thisrr->type = SSL3_RT_HANDSHAKE;
231 thisrr->rec_version = SSL2_VERSION;
233 thisrr->length = sslv2len & 0x7fff;
235 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
236 - SSL2_RT_HEADER_LENGTH) {
237 al = SSL_AD_RECORD_OVERFLOW;
238 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
242 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
243 al = SSL_AD_DECODE_ERROR;
244 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
248 /* SSLv3+ style record */
250 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
251 s->msg_callback_arg);
253 /* Pull apart the header into the SSL3_RECORD */
254 if (!PACKET_get_1(&pkt, &type)
255 || !PACKET_get_net_2(&pkt, &version)
256 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
257 al = SSL_AD_DECODE_ERROR;
258 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
262 thisrr->rec_version = version;
264 /* Lets check version. In TLSv1.3 we ignore this field */
265 if (!s->first_packet && !SSL_IS_TLS13(s)
266 && version != (unsigned int)s->version) {
267 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
268 if ((s->version & 0xFF00) == (version & 0xFF00)
269 && !s->enc_write_ctx && !s->write_hash) {
270 if (thisrr->type == SSL3_RT_ALERT) {
272 * The record is using an incorrect version number,
273 * but what we've got appears to be an alert. We
274 * haven't read the body yet to check whether its a
275 * fatal or not - but chances are it is. We probably
276 * shouldn't send a fatal alert back. We'll just
282 * Send back error using their minor version number :-)
284 s->version = (unsigned short)version;
286 al = SSL_AD_PROTOCOL_VERSION;
290 if ((version >> 8) != SSL3_VERSION_MAJOR) {
291 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
292 /* Go back to start of packet, look at the five bytes
294 p = RECORD_LAYER_get_packet(&s->rlayer);
295 if (strncmp((char *)p, "GET ", 4) == 0 ||
296 strncmp((char *)p, "POST ", 5) == 0 ||
297 strncmp((char *)p, "HEAD ", 5) == 0 ||
298 strncmp((char *)p, "PUT ", 4) == 0) {
299 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
301 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
302 SSLerr(SSL_F_SSL3_GET_RECORD,
303 SSL_R_HTTPS_PROXY_REQUEST);
307 /* Doesn't look like TLS - don't send an alert */
308 SSLerr(SSL_F_SSL3_GET_RECORD,
309 SSL_R_WRONG_VERSION_NUMBER);
312 SSLerr(SSL_F_SSL3_GET_RECORD,
313 SSL_R_WRONG_VERSION_NUMBER);
314 al = SSL_AD_PROTOCOL_VERSION;
319 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
320 && thisrr->type != SSL3_RT_APPLICATION_DATA) {
321 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
322 al = SSL_AD_UNEXPECTED_MESSAGE;
327 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
328 al = SSL_AD_RECORD_OVERFLOW;
329 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
334 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
337 if (SSL_IS_TLS13(s)) {
338 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
339 al = SSL_AD_RECORD_OVERFLOW;
340 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
344 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
346 #ifndef OPENSSL_NO_COMP
348 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
349 * does not include the compression overhead anyway.
351 if (s->expand == NULL)
352 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
355 if (thisrr->length > len) {
356 al = SSL_AD_RECORD_OVERFLOW;
357 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
363 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
364 * Calculate how much more data we need to read for the rest of the
367 if (thisrr->rec_version == SSL2_VERSION) {
368 more = thisrr->length + SSL2_RT_HEADER_LENGTH
369 - SSL3_RT_HEADER_LENGTH;
371 more = thisrr->length;
374 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
376 rret = ssl3_read_n(s, more, more, 1, 0, &n);
378 return rret; /* error or non-blocking io */
381 /* set state for later operations */
382 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
385 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
386 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
387 * + thisrr->length and we have that many bytes in s->packet
389 if (thisrr->rec_version == SSL2_VERSION) {
391 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
394 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
398 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
399 * points at thisrr->length bytes, which need to be copied into
400 * thisrr->data by either the decryption or by the decompression When
401 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
402 * be pointed at the new buffer
406 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
407 * thisrr->length bytes of encrypted compressed stuff.
410 /* decrypt in place in 'thisrr->input' */
411 thisrr->data = thisrr->input;
412 thisrr->orig_len = thisrr->length;
414 /* Mark this record as not read by upper layers yet */
419 /* we have pulled in a full packet so zero things */
420 RECORD_LAYER_reset_packet_length(&s->rlayer);
421 RECORD_LAYER_clear_first_record(&s->rlayer);
422 } while (num_recs < max_recs
423 && thisrr->type == SSL3_RT_APPLICATION_DATA
424 && SSL_USE_EXPLICIT_IV(s)
425 && s->enc_read_ctx != NULL
426 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
427 & EVP_CIPH_FLAG_PIPELINE)
428 && ssl3_record_app_data_waiting(s));
431 * If in encrypt-then-mac mode calculate mac from encrypted record. All
432 * the details below are public so no timing details can leak.
434 if (SSL_READ_ETM(s) && s->read_hash) {
436 /* TODO(size_t): convert this to do size_t properly */
437 imac_size = EVP_MD_CTX_size(s->read_hash);
438 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
439 al = SSL_AD_INTERNAL_ERROR;
440 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
443 mac_size = (size_t)imac_size;
444 for (j = 0; j < num_recs; j++) {
447 if (thisrr->length < mac_size) {
448 al = SSL_AD_DECODE_ERROR;
449 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
452 thisrr->length -= mac_size;
453 mac = thisrr->data + thisrr->length;
454 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
455 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
456 al = SSL_AD_BAD_RECORD_MAC;
457 SSLerr(SSL_F_SSL3_GET_RECORD,
458 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
464 first_rec_len = rr[0].length;
466 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
470 * 0: (in non-constant time) if the record is publicly invalid.
471 * 1: if the padding is valid
472 * -1: if the padding is invalid
475 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
477 * Valid early_data that we cannot decrypt might fail here as
478 * publicly invalid. We treat it like an empty record.
483 if (!early_data_count_ok(s, thisrr->length,
484 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
489 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
490 RECORD_LAYER_reset_read_sequence(&s->rlayer);
493 al = SSL_AD_DECRYPTION_FAILED;
494 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
498 printf("dec %"OSSLzu"\n", rr[0].length);
501 for (z = 0; z < rr[0].length; z++)
502 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
507 /* r->length is now the compressed data plus mac */
508 if ((sess != NULL) &&
509 (s->enc_read_ctx != NULL) &&
510 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
511 /* s->read_hash != NULL => mac_size != -1 */
512 unsigned char *mac = NULL;
513 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
515 mac_size = EVP_MD_CTX_size(s->read_hash);
516 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
517 al = SSL_AD_INTERNAL_ERROR;
518 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
522 for (j = 0; j < num_recs; j++) {
525 * orig_len is the length of the record before any padding was
526 * removed. This is public information, as is the MAC in use,
527 * therefore we can safely process the record in a different amount
528 * of time if it's too short to possibly contain a MAC.
530 if (thisrr->orig_len < mac_size ||
531 /* CBC records must have a padding length byte too. */
532 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
533 thisrr->orig_len < mac_size + 1)) {
534 al = SSL_AD_DECODE_ERROR;
535 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
539 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
541 * We update the length so that the TLS header bytes can be
542 * constructed correctly but we need to extract the MAC in
543 * constant time from within the record, without leaking the
544 * contents of the padding bytes.
547 if (!ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size)) {
548 al = SSL_AD_INTERNAL_ERROR;
549 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
552 thisrr->length -= mac_size;
555 * In this case there's no padding, so |rec->orig_len| equals
556 * |rec->length| and we checked that there's enough bytes for
559 thisrr->length -= mac_size;
560 mac = &thisrr->data[thisrr->length];
563 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
564 if (i == 0 || mac == NULL
565 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
567 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
573 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
575 * We assume this is unreadable early_data - we treat it like an
580 * The record length may have been modified by the mac check above
581 * so we use the previously saved value
583 if (!early_data_count_ok(s, first_rec_len,
584 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
590 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
591 RECORD_LAYER_reset_read_sequence(&s->rlayer);
595 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
596 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
597 * failure is directly visible from the ciphertext anyway, we should
598 * not reveal which kind of error occurred -- this might become
599 * visible to an attacker (e.g. via a logfile)
601 al = SSL_AD_BAD_RECORD_MAC;
602 SSLerr(SSL_F_SSL3_GET_RECORD,
603 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
607 for (j = 0; j < num_recs; j++) {
610 /* thisrr->length is now just compressed */
611 if (s->expand != NULL) {
612 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
613 al = SSL_AD_RECORD_OVERFLOW;
614 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
617 if (!ssl3_do_uncompress(s, thisrr)) {
618 al = SSL_AD_DECOMPRESSION_FAILURE;
619 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
624 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
627 if (thisrr->length == 0
628 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
629 al = SSL_AD_UNEXPECTED_MESSAGE;
630 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
634 /* Strip trailing padding */
635 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
639 thisrr->length = end;
640 thisrr->type = thisrr->data[end];
641 if (thisrr->type != SSL3_RT_APPLICATION_DATA
642 && thisrr->type != SSL3_RT_ALERT
643 && thisrr->type != SSL3_RT_HANDSHAKE) {
644 al = SSL_AD_UNEXPECTED_MESSAGE;
645 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
649 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
650 &thisrr->data[end], 1, s, s->msg_callback_arg);
654 * TLSv1.3 alert and handshake records are required to be non-zero in
658 && (thisrr->type == SSL3_RT_HANDSHAKE
659 || thisrr->type == SSL3_RT_ALERT)
660 && thisrr->length == 0) {
661 al = SSL_AD_UNEXPECTED_MESSAGE;
662 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_LENGTH);
666 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
667 al = SSL_AD_RECORD_OVERFLOW;
668 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
674 * So at this point the following is true
675 * thisrr->type is the type of record
676 * thisrr->length == number of bytes in record
677 * thisrr->off == offset to first valid byte
678 * thisrr->data == where to take bytes from, increment after use :-).
681 /* just read a 0 length packet */
682 if (thisrr->length == 0) {
683 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
684 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
685 > MAX_EMPTY_RECORDS) {
686 al = SSL_AD_UNEXPECTED_MESSAGE;
687 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
691 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
695 if (s->early_data_state == SSL_EARLY_DATA_READING) {
697 if (thisrr->type == SSL3_RT_APPLICATION_DATA
698 && !early_data_count_ok(s, thisrr->length, 0, &al))
702 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
706 ssl3_send_alert(s, SSL3_AL_FATAL, al);
711 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
713 #ifndef OPENSSL_NO_COMP
716 if (rr->comp == NULL) {
717 rr->comp = (unsigned char *)
718 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
720 if (rr->comp == NULL)
723 /* TODO(size_t): Convert this call */
724 i = COMP_expand_block(ssl->expand, rr->comp,
725 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
735 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
737 #ifndef OPENSSL_NO_COMP
740 /* TODO(size_t): Convert this call */
741 i = COMP_compress_block(ssl->compress, wr->data,
742 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
743 wr->input, (int)wr->length);
749 wr->input = wr->data;
755 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
758 * 0: (in non-constant time) if the record is publically invalid (i.e. too
760 * 1: if the record's padding is valid / the encryption was successful.
761 * -1: if the record's padding is invalid or, if sending, an internal error
764 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
769 size_t bs, mac_size = 0;
771 const EVP_CIPHER *enc;
775 * We shouldn't ever be called with more than one record in the SSLv3 case
780 ds = s->enc_write_ctx;
781 if (s->enc_write_ctx == NULL)
784 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
786 ds = s->enc_read_ctx;
787 if (s->enc_read_ctx == NULL)
790 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
793 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
794 memmove(rec->data, rec->input, rec->length);
795 rec->input = rec->data;
798 /* TODO(size_t): Convert this call */
799 bs = EVP_CIPHER_CTX_block_size(ds);
803 if ((bs != 1) && sending) {
806 /* we need to add 'i-1' padding bytes */
809 * the last of these zero bytes will be overwritten with the
812 memset(&rec->input[rec->length], 0, i);
814 rec->input[l - 1] = (unsigned char)(i - 1);
818 if (l == 0 || l % bs != 0)
820 /* otherwise, rec->length >= bs */
823 /* TODO(size_t): Convert this call */
824 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
827 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
828 /* TODO(size_t): convert me */
829 imac_size = EVP_MD_CTX_size(s->read_hash);
832 mac_size = (size_t)imac_size;
834 if ((bs != 1) && !sending)
835 return ssl3_cbc_remove_padding(rec, bs, mac_size);
840 #define MAX_PADDING 256
842 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
845 * 0: (in non-constant time) if the record is publically invalid (i.e. too
847 * 1: if the record's padding is valid / the encryption was successful.
848 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
849 * an internal error occurred.
851 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
854 size_t reclen[SSL_MAX_PIPELINES];
855 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
856 int i, pad = 0, ret, tmpr;
857 size_t bs, mac_size = 0, ctr, padnum, loop;
858 unsigned char padval;
860 const EVP_CIPHER *enc;
866 if (EVP_MD_CTX_md(s->write_hash)) {
867 int n = EVP_MD_CTX_size(s->write_hash);
868 if (!ossl_assert(n >= 0)) {
869 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
873 ds = s->enc_write_ctx;
874 if (s->enc_write_ctx == NULL)
878 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
879 /* For TLSv1.1 and later explicit IV */
880 if (SSL_USE_EXPLICIT_IV(s)
881 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
882 ivlen = EVP_CIPHER_iv_length(enc);
886 for (ctr = 0; ctr < n_recs; ctr++) {
887 if (recs[ctr].data != recs[ctr].input) {
889 * we can't write into the input stream: Can this ever
892 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
894 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
895 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
902 if (EVP_MD_CTX_md(s->read_hash)) {
903 int n = EVP_MD_CTX_size(s->read_hash);
904 if (!ossl_assert(n >= 0)) {
905 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
909 ds = s->enc_read_ctx;
910 if (s->enc_read_ctx == NULL)
913 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
916 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
917 for (ctr = 0; ctr < n_recs; ctr++) {
918 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
919 recs[ctr].input = recs[ctr].data;
923 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
926 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
927 & EVP_CIPH_FLAG_PIPELINE)) {
929 * We shouldn't have been called with pipeline data if the
930 * cipher doesn't support pipelining
932 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
936 for (ctr = 0; ctr < n_recs; ctr++) {
937 reclen[ctr] = recs[ctr].length;
939 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
940 & EVP_CIPH_FLAG_AEAD_CIPHER) {
943 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
944 : RECORD_LAYER_get_read_sequence(&s->rlayer);
946 if (SSL_IS_DTLS(s)) {
947 /* DTLS does not support pipelining */
948 unsigned char dtlsseq[9], *p = dtlsseq;
950 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
951 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
952 memcpy(p, &seq[2], 6);
953 memcpy(buf[ctr], dtlsseq, 8);
955 memcpy(buf[ctr], seq, 8);
956 for (i = 7; i >= 0; i--) { /* increment */
963 buf[ctr][8] = recs[ctr].type;
964 buf[ctr][9] = (unsigned char)(s->version >> 8);
965 buf[ctr][10] = (unsigned char)(s->version);
966 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
967 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
968 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
969 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
975 recs[ctr].length += pad;
978 } else if ((bs != 1) && sending) {
979 padnum = bs - (reclen[ctr] % bs);
981 /* Add weird padding of upto 256 bytes */
983 if (padnum > MAX_PADDING)
985 /* we need to add 'padnum' padding bytes of value padval */
986 padval = (unsigned char)(padnum - 1);
987 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
988 recs[ctr].input[loop] = padval;
989 reclen[ctr] += padnum;
990 recs[ctr].length += padnum;
994 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
999 unsigned char *data[SSL_MAX_PIPELINES];
1001 /* Set the output buffers */
1002 for (ctr = 0; ctr < n_recs; ctr++) {
1003 data[ctr] = recs[ctr].data;
1005 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1006 (int)n_recs, data) <= 0) {
1007 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
1009 /* Set the input buffers */
1010 for (ctr = 0; ctr < n_recs; ctr++) {
1011 data[ctr] = recs[ctr].input;
1013 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1014 (int)n_recs, data) <= 0
1015 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1016 (int)n_recs, reclen) <= 0) {
1017 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
1022 /* TODO(size_t): Convert this call */
1023 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1024 (unsigned int)reclen[0]);
1025 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1026 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1029 return -1; /* AEAD can fail to verify MAC */
1031 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1032 for (ctr = 0; ctr < n_recs; ctr++) {
1033 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1034 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1035 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1037 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1038 for (ctr = 0; ctr < n_recs; ctr++) {
1039 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1040 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1041 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1047 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1048 imac_size = EVP_MD_CTX_size(s->read_hash);
1051 mac_size = (size_t)imac_size;
1053 if ((bs != 1) && !sending) {
1055 for (ctr = 0; ctr < n_recs; ctr++) {
1056 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1058 * If tmpret == 0 then this means publicly invalid so we can
1059 * short circuit things here. Otherwise we must respect constant
1064 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1068 if (pad && !sending) {
1069 for (ctr = 0; ctr < n_recs; ctr++) {
1070 recs[ctr].length -= pad;
1077 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1079 unsigned char *mac_sec, *seq;
1080 const EVP_MD_CTX *hash;
1081 unsigned char *p, rec_char;
1087 mac_sec = &(ssl->s3->write_mac_secret[0]);
1088 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1089 hash = ssl->write_hash;
1091 mac_sec = &(ssl->s3->read_mac_secret[0]);
1092 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1093 hash = ssl->read_hash;
1096 t = EVP_MD_CTX_size(hash);
1100 npad = (48 / md_size) * md_size;
1103 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1104 ssl3_cbc_record_digest_supported(hash)) {
1106 * This is a CBC-encrypted record. We must avoid leaking any
1107 * timing-side channel information about how many blocks of data we
1108 * are hashing because that gives an attacker a timing-oracle.
1112 * npad is, at most, 48 bytes and that's with MD5:
1113 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1115 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1116 * goes up 4, but npad goes down by 8, resulting in a smaller
1119 unsigned char header[75];
1121 memcpy(header + j, mac_sec, md_size);
1123 memcpy(header + j, ssl3_pad_1, npad);
1125 memcpy(header + j, seq, 8);
1127 header[j++] = rec->type;
1128 header[j++] = (unsigned char)(rec->length >> 8);
1129 header[j++] = (unsigned char)(rec->length & 0xff);
1131 /* Final param == is SSLv3 */
1132 if (ssl3_cbc_digest_record(hash,
1135 rec->length + md_size, rec->orig_len,
1136 mac_sec, md_size, 1) <= 0)
1139 unsigned int md_size_u;
1140 /* Chop the digest off the end :-) */
1141 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1146 rec_char = rec->type;
1148 s2n(rec->length, p);
1149 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1150 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1151 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1152 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1153 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1154 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1155 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1156 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1157 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1158 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1159 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1160 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1161 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1162 EVP_MD_CTX_reset(md_ctx);
1166 EVP_MD_CTX_free(md_ctx);
1169 ssl3_record_sequence_update(seq);
1173 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1179 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1180 unsigned char header[13];
1181 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1182 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1186 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1187 hash = ssl->write_hash;
1189 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1190 hash = ssl->read_hash;
1193 t = EVP_MD_CTX_size(hash);
1194 if (!ossl_assert(t >= 0))
1198 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1202 hmac = EVP_MD_CTX_new();
1203 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1208 if (SSL_IS_DTLS(ssl)) {
1209 unsigned char dtlsseq[8], *p = dtlsseq;
1211 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1212 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1213 memcpy(p, &seq[2], 6);
1215 memcpy(header, dtlsseq, 8);
1217 memcpy(header, seq, 8);
1219 header[8] = rec->type;
1220 header[9] = (unsigned char)(ssl->version >> 8);
1221 header[10] = (unsigned char)(ssl->version);
1222 header[11] = (unsigned char)(rec->length >> 8);
1223 header[12] = (unsigned char)(rec->length & 0xff);
1225 if (!sending && !SSL_READ_ETM(ssl) &&
1226 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1227 ssl3_cbc_record_digest_supported(mac_ctx)) {
1229 * This is a CBC-encrypted record. We must avoid leaking any
1230 * timing-side channel information about how many blocks of data we
1231 * are hashing because that gives an attacker a timing-oracle.
1233 /* Final param == not SSLv3 */
1234 if (ssl3_cbc_digest_record(mac_ctx,
1237 rec->length + md_size, rec->orig_len,
1238 ssl->s3->read_mac_secret,
1239 ssl->s3->read_mac_secret_size, 0) <= 0) {
1240 EVP_MD_CTX_free(hmac);
1244 /* TODO(size_t): Convert these calls */
1245 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1246 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1247 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1248 EVP_MD_CTX_free(hmac);
1253 EVP_MD_CTX_free(hmac);
1256 fprintf(stderr, "seq=");
1259 for (z = 0; z < 8; z++)
1260 fprintf(stderr, "%02X ", seq[z]);
1261 fprintf(stderr, "\n");
1263 fprintf(stderr, "rec=");
1266 for (z = 0; z < rec->length; z++)
1267 fprintf(stderr, "%02X ", rec->data[z]);
1268 fprintf(stderr, "\n");
1272 if (!SSL_IS_DTLS(ssl)) {
1273 for (i = 7; i >= 0; i--) {
1282 for (z = 0; z < md_size; z++)
1283 fprintf(stderr, "%02X ", md[z]);
1284 fprintf(stderr, "\n");
1291 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1292 * record in |rec| by updating |rec->length| in constant time.
1294 * block_size: the block size of the cipher used to encrypt the record.
1296 * 0: (in non-constant time) if the record is publicly invalid.
1297 * 1: if the padding was valid
1300 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1301 size_t block_size, size_t mac_size)
1303 size_t padding_length;
1305 const size_t overhead = 1 /* padding length byte */ + mac_size;
1308 * These lengths are all public so we can test them in non-constant time.
1310 if (overhead > rec->length)
1313 padding_length = rec->data[rec->length - 1];
1314 good = constant_time_ge_s(rec->length, padding_length + overhead);
1315 /* SSLv3 requires that the padding is minimal. */
1316 good &= constant_time_ge_s(block_size, padding_length + 1);
1317 rec->length -= good & (padding_length + 1);
1318 return constant_time_select_int_s(good, 1, -1);
1322 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1323 * record in |rec| in constant time and returns 1 if the padding is valid and
1324 * -1 otherwise. It also removes any explicit IV from the start of the record
1325 * without leaking any timing about whether there was enough space after the
1326 * padding was removed.
1328 * block_size: the block size of the cipher used to encrypt the record.
1330 * 0: (in non-constant time) if the record is publicly invalid.
1331 * 1: if the padding was valid
1334 int tls1_cbc_remove_padding(const SSL *s,
1336 size_t block_size, size_t mac_size)
1339 size_t padding_length, to_check, i;
1340 const size_t overhead = 1 /* padding length byte */ + mac_size;
1341 /* Check if version requires explicit IV */
1342 if (SSL_USE_EXPLICIT_IV(s)) {
1344 * These lengths are all public so we can test them in non-constant
1347 if (overhead + block_size > rec->length)
1349 /* We can now safely skip explicit IV */
1350 rec->data += block_size;
1351 rec->input += block_size;
1352 rec->length -= block_size;
1353 rec->orig_len -= block_size;
1354 } else if (overhead > rec->length)
1357 padding_length = rec->data[rec->length - 1];
1359 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1360 EVP_CIPH_FLAG_AEAD_CIPHER) {
1361 /* padding is already verified */
1362 rec->length -= padding_length + 1;
1366 good = constant_time_ge_s(rec->length, overhead + padding_length);
1368 * The padding consists of a length byte at the end of the record and
1369 * then that many bytes of padding, all with the same value as the length
1370 * byte. Thus, with the length byte included, there are i+1 bytes of
1371 * padding. We can't check just |padding_length+1| bytes because that
1372 * leaks decrypted information. Therefore we always have to check the
1373 * maximum amount of padding possible. (Again, the length of the record
1374 * is public information so we can use it.)
1376 to_check = 256; /* maximum amount of padding, inc length byte. */
1377 if (to_check > rec->length)
1378 to_check = rec->length;
1380 for (i = 0; i < to_check; i++) {
1381 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1382 unsigned char b = rec->data[rec->length - 1 - i];
1384 * The final |padding_length+1| bytes should all have the value
1385 * |padding_length|. Therefore the XOR should be zero.
1387 good &= ~(mask & (padding_length ^ b));
1391 * If any of the final |padding_length+1| bytes had the wrong value, one
1392 * or more of the lower eight bits of |good| will be cleared.
1394 good = constant_time_eq_s(0xff, good & 0xff);
1395 rec->length -= good & (padding_length + 1);
1397 return constant_time_select_int_s(good, 1, -1);
1401 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1402 * constant time (independent of the concrete value of rec->length, which may
1403 * vary within a 256-byte window).
1405 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1409 * rec->orig_len >= md_size
1410 * md_size <= EVP_MAX_MD_SIZE
1412 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1413 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1414 * a single or pair of cache-lines, then the variable memory accesses don't
1415 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1416 * not multi-core and are not considered vulnerable to cache-timing attacks.
1418 #define CBC_MAC_ROTATE_IN_PLACE
1420 int ssl3_cbc_copy_mac(unsigned char *out,
1421 const SSL3_RECORD *rec, size_t md_size)
1423 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1424 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1425 unsigned char *rotated_mac;
1427 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1431 * mac_end is the index of |rec->data| just after the end of the MAC.
1433 size_t mac_end = rec->length;
1434 size_t mac_start = mac_end - md_size;
1437 * scan_start contains the number of bytes that we can ignore because the
1438 * MAC's position can only vary by 255 bytes.
1440 size_t scan_start = 0;
1442 size_t rotate_offset;
1444 if (!ossl_assert(rec->orig_len >= md_size
1445 && md_size <= EVP_MAX_MD_SIZE))
1448 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1449 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1452 /* This information is public so it's safe to branch based on it. */
1453 if (rec->orig_len > md_size + 255 + 1)
1454 scan_start = rec->orig_len - (md_size + 255 + 1);
1458 memset(rotated_mac, 0, md_size);
1459 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1460 size_t mac_started = constant_time_eq_s(i, mac_start);
1461 size_t mac_ended = constant_time_lt_s(i, mac_end);
1462 unsigned char b = rec->data[i];
1464 in_mac |= mac_started;
1465 in_mac &= mac_ended;
1466 rotate_offset |= j & mac_started;
1467 rotated_mac[j++] |= b & in_mac;
1468 j &= constant_time_lt_s(j, md_size);
1471 /* Now rotate the MAC */
1472 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1474 for (i = 0; i < md_size; i++) {
1475 /* in case cache-line is 32 bytes, touch second line */
1476 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1477 out[j++] = rotated_mac[rotate_offset++];
1478 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1481 memset(out, 0, md_size);
1482 rotate_offset = md_size - rotate_offset;
1483 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1484 for (i = 0; i < md_size; i++) {
1485 for (j = 0; j < md_size; j++)
1486 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1488 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1495 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1503 unsigned char md[EVP_MAX_MD_SIZE];
1505 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1509 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1510 * and we have that many bytes in s->packet
1512 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1515 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1516 * at rr->length bytes, which need to be copied into rr->data by either
1517 * the decryption or by the decompression When the data is 'copied' into
1518 * the rr->data buffer, rr->input will be pointed at the new buffer
1522 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1523 * bytes of encrypted compressed stuff.
1526 /* check is not needed I believe */
1527 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1528 al = SSL_AD_RECORD_OVERFLOW;
1529 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1533 /* decrypt in place in 'rr->input' */
1534 rr->data = rr->input;
1535 rr->orig_len = rr->length;
1537 if (SSL_READ_ETM(s) && s->read_hash) {
1539 mac_size = EVP_MD_CTX_size(s->read_hash);
1540 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1541 al = SSL_AD_INTERNAL_ERROR;
1542 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1545 if (rr->orig_len < mac_size) {
1546 al = SSL_AD_DECODE_ERROR;
1547 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1550 rr->length -= mac_size;
1551 mac = rr->data + rr->length;
1552 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1553 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1554 al = SSL_AD_BAD_RECORD_MAC;
1555 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1556 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1561 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1564 * 0: (in non-constant time) if the record is publically invalid.
1565 * 1: if the padding is valid
1566 * -1: if the padding is invalid
1569 /* For DTLS we simply ignore bad packets. */
1571 RECORD_LAYER_reset_packet_length(&s->rlayer);
1575 printf("dec %ld\n", rr->length);
1578 for (z = 0; z < rr->length; z++)
1579 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1584 /* r->length is now the compressed data plus mac */
1585 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1586 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1587 /* s->read_hash != NULL => mac_size != -1 */
1588 unsigned char *mac = NULL;
1589 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1591 /* TODO(size_t): Convert this to do size_t properly */
1592 imac_size = EVP_MD_CTX_size(s->read_hash);
1593 if (imac_size < 0) {
1594 al = SSL_AD_INTERNAL_ERROR;
1595 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1598 mac_size = (size_t)imac_size;
1599 if (!ossl_assert(mac_size <= EVP_MAX_MD_SIZE)) {
1600 al = SSL_AD_INTERNAL_ERROR;
1601 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1606 * orig_len is the length of the record before any padding was
1607 * removed. This is public information, as is the MAC in use,
1608 * therefore we can safely process the record in a different amount
1609 * of time if it's too short to possibly contain a MAC.
1611 if (rr->orig_len < mac_size ||
1612 /* CBC records must have a padding length byte too. */
1613 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1614 rr->orig_len < mac_size + 1)) {
1615 al = SSL_AD_DECODE_ERROR;
1616 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1620 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1622 * We update the length so that the TLS header bytes can be
1623 * constructed correctly but we need to extract the MAC in
1624 * constant time from within the record, without leaking the
1625 * contents of the padding bytes.
1628 if (!ssl3_cbc_copy_mac(mac_tmp, rr, mac_size)) {
1629 al = SSL_AD_INTERNAL_ERROR;
1630 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_R_INTERNAL_ERROR);
1633 rr->length -= mac_size;
1636 * In this case there's no padding, so |rec->orig_len| equals
1637 * |rec->length| and we checked that there's enough bytes for
1640 rr->length -= mac_size;
1641 mac = &rr->data[rr->length];
1644 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1645 if (i == 0 || mac == NULL
1646 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1648 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1653 /* decryption failed, silently discard message */
1655 RECORD_LAYER_reset_packet_length(&s->rlayer);
1659 /* r->length is now just compressed */
1660 if (s->expand != NULL) {
1661 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1662 al = SSL_AD_RECORD_OVERFLOW;
1663 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1664 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1667 if (!ssl3_do_uncompress(s, rr)) {
1668 al = SSL_AD_DECOMPRESSION_FAILURE;
1669 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1674 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1675 al = SSL_AD_RECORD_OVERFLOW;
1676 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1682 * So at this point the following is true
1683 * ssl->s3->rrec.type is the type of record
1684 * ssl->s3->rrec.length == number of bytes in record
1685 * ssl->s3->rrec.off == offset to first valid byte
1686 * ssl->s3->rrec.data == where to take bytes from, increment
1690 /* we have pulled in a full packet so zero things */
1691 RECORD_LAYER_reset_packet_length(&s->rlayer);
1693 /* Mark receipt of record. */
1694 dtls1_record_bitmap_update(s, bitmap);
1699 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1705 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1707 #define dtls1_get_processed_record(s) \
1708 dtls1_retrieve_buffered_record((s), \
1709 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1712 * Call this to get a new input record.
1713 * It will return <= 0 if more data is needed, normally due to an error
1714 * or non-blocking IO.
1715 * When it finishes, one packet has been decoded and can be found in
1716 * ssl->s3->rrec.type - is the type of record
1717 * ssl->s3->rrec.data, - data
1718 * ssl->s3->rrec.length, - number of bytes
1720 /* used only by dtls1_read_bytes */
1721 int dtls1_get_record(SSL *s)
1723 int ssl_major, ssl_minor;
1727 unsigned char *p = NULL;
1728 unsigned short version;
1729 DTLS1_BITMAP *bitmap;
1730 unsigned int is_next_epoch;
1732 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1736 * The epoch may have changed. If so, process all the pending records.
1737 * This is a non-blocking operation.
1739 if (!dtls1_process_buffered_records(s))
1742 /* if we're renegotiating, then there may be buffered records */
1743 if (dtls1_get_processed_record(s))
1746 /* get something from the wire */
1748 /* check if we have the header */
1749 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1750 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1751 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1752 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1753 /* read timeout is handled by dtls1_read_bytes */
1755 return rret; /* error or non-blocking */
1757 /* this packet contained a partial record, dump it */
1758 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1759 DTLS1_RT_HEADER_LENGTH) {
1760 RECORD_LAYER_reset_packet_length(&s->rlayer);
1764 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1766 p = RECORD_LAYER_get_packet(&s->rlayer);
1768 if (s->msg_callback)
1769 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1770 s, s->msg_callback_arg);
1772 /* Pull apart the header into the DTLS1_RECORD */
1776 version = (ssl_major << 8) | ssl_minor;
1778 /* sequence number is 64 bits, with top 2 bytes = epoch */
1781 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1786 /* Lets check version */
1787 if (!s->first_packet) {
1788 if (version != s->version) {
1789 /* unexpected version, silently discard */
1791 RECORD_LAYER_reset_packet_length(&s->rlayer);
1796 if ((version & 0xff00) != (s->version & 0xff00)) {
1797 /* wrong version, silently discard record */
1799 RECORD_LAYER_reset_packet_length(&s->rlayer);
1803 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1804 /* record too long, silently discard it */
1806 RECORD_LAYER_reset_packet_length(&s->rlayer);
1810 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1813 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1816 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1817 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1819 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1820 /* this packet contained a partial record, dump it */
1821 if (rret <= 0 || n != more) {
1823 RECORD_LAYER_reset_packet_length(&s->rlayer);
1828 * now n == rr->length, and s->packet_length ==
1829 * DTLS1_RT_HEADER_LENGTH + rr->length
1832 /* set state for later operations */
1833 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1835 /* match epochs. NULL means the packet is dropped on the floor */
1836 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1837 if (bitmap == NULL) {
1839 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1840 goto again; /* get another record */
1842 #ifndef OPENSSL_NO_SCTP
1843 /* Only do replay check if no SCTP bio */
1844 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1846 /* Check whether this is a repeat, or aged record. */
1848 * TODO: Does it make sense to have replay protection in epoch 0 where
1849 * we have no integrity negotiated yet?
1851 if (!dtls1_record_replay_check(s, bitmap)) {
1853 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1854 goto again; /* get another record */
1856 #ifndef OPENSSL_NO_SCTP
1860 /* just read a 0 length packet */
1861 if (rr->length == 0)
1865 * If this record is from the next epoch (either HM or ALERT), and a
1866 * handshake is currently in progress, buffer it since it cannot be
1867 * processed at this time.
1869 if (is_next_epoch) {
1870 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1871 if (dtls1_buffer_record
1872 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1877 RECORD_LAYER_reset_packet_length(&s->rlayer);
1881 if (!dtls1_process_record(s, bitmap)) {
1883 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1884 goto again; /* get another record */