2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "../ssl_locl.h"
12 #include "internal/constant_time_locl.h"
13 #include <openssl/rand.h>
14 #include "record_locl.h"
16 static const unsigned char ssl3_pad_1[48] = {
17 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
18 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
19 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
20 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
21 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
22 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
25 static const unsigned char ssl3_pad_2[48] = {
26 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
27 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
28 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
29 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
30 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
31 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
35 * Clear the contents of an SSL3_RECORD but retain any memory allocated
37 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
42 for (i = 0; i < num_recs; i++) {
45 memset(&r[i], 0, sizeof(*r));
50 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
54 for (i = 0; i < num_recs; i++) {
55 OPENSSL_free(r[i].comp);
60 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
62 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
66 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
67 * for us in the buffer.
69 static int ssl3_record_app_data_waiting(SSL *s)
75 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
77 p = SSL3_BUFFER_get_buf(rbuf);
81 left = SSL3_BUFFER_get_left(rbuf);
83 if (left < SSL3_RT_HEADER_LENGTH)
86 p += SSL3_BUFFER_get_offset(rbuf);
89 * We only check the type and record length, we will sanity check version
92 if (*p != SSL3_RT_APPLICATION_DATA)
98 if (left < SSL3_RT_HEADER_LENGTH + len)
104 int early_data_count_ok(SSL *s, size_t length, size_t overhead, int *al)
106 uint32_t max_early_data = s->max_early_data;
109 * If we are a client then we always use the max_early_data from the
110 * session. Otherwise we go with the lowest out of the max early data set in
111 * the session and the configured max_early_data.
113 if (!s->server || (s->hit
114 && s->session->ext.max_early_data < s->max_early_data))
115 max_early_data = s->session->ext.max_early_data;
117 if (max_early_data == 0) {
119 *al = SSL_AD_UNEXPECTED_MESSAGE;
120 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
124 /* If we are dealing with ciphertext we need to allow for the overhead */
125 max_early_data += overhead;
127 if (s->early_data_count + length > max_early_data) {
129 *al = SSL_AD_UNEXPECTED_MESSAGE;
130 SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
133 s->early_data_count += length;
139 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
140 * will be processed per call to ssl3_get_record. Without this limit an
141 * attacker could send empty records at a faster rate than we can process and
142 * cause ssl3_get_record to loop forever.
144 #define MAX_EMPTY_RECORDS 32
146 #define SSL2_RT_HEADER_LENGTH 2
148 * Call this to get new input records.
149 * It will return <= 0 if more data is needed, normally due to an error
150 * or non-blocking IO.
151 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
152 * rr[i].type - is the type of record
154 * rr[i].length, - number of bytes
155 * Multiple records will only be returned if the record types are all
156 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
159 /* used only by ssl3_read_bytes */
160 int ssl3_get_record(SSL *s)
163 int enc_err, rret, ret = -1;
166 SSL3_RECORD *rr, *thisrr;
170 unsigned char md[EVP_MAX_MD_SIZE];
171 unsigned int version;
174 size_t num_recs = 0, max_recs, j;
175 PACKET pkt, sslv2pkt;
176 size_t first_rec_len;
178 rr = RECORD_LAYER_get_rrec(&s->rlayer);
179 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
180 max_recs = s->max_pipelines;
186 thisrr = &rr[num_recs];
188 /* check if we have the header */
189 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
190 (RECORD_LAYER_get_packet_length(&s->rlayer)
191 < SSL3_RT_HEADER_LENGTH)) {
195 rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
196 SSL3_BUFFER_get_len(rbuf), 0,
197 num_recs == 0 ? 1 : 0, &n);
199 return rret; /* error or non-blocking */
200 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
202 p = RECORD_LAYER_get_packet(&s->rlayer);
203 if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
204 RECORD_LAYER_get_packet_length(&s->rlayer))) {
205 al = SSL_AD_INTERNAL_ERROR;
206 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
210 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
211 || !PACKET_get_1(&sslv2pkt, &type)) {
212 al = SSL_AD_INTERNAL_ERROR;
213 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
217 * The first record received by the server may be a V2ClientHello.
219 if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
220 && (sslv2len & 0x8000) != 0
221 && (type == SSL2_MT_CLIENT_HELLO)) {
225 * |num_recs| here will actually always be 0 because
226 * |num_recs > 0| only ever occurs when we are processing
227 * multiple app data records - which we know isn't the case here
228 * because it is an SSLv2ClientHello. We keep it using
229 * |num_recs| for the sake of consistency
231 thisrr->type = SSL3_RT_HANDSHAKE;
232 thisrr->rec_version = SSL2_VERSION;
234 thisrr->length = sslv2len & 0x7fff;
236 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
237 - SSL2_RT_HEADER_LENGTH) {
238 al = SSL_AD_RECORD_OVERFLOW;
239 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
243 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
244 al = SSL_AD_HANDSHAKE_FAILURE;
245 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
249 /* SSLv3+ style record */
251 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
252 s->msg_callback_arg);
254 /* Pull apart the header into the SSL3_RECORD */
255 if (!PACKET_get_1(&pkt, &type)
256 || !PACKET_get_net_2(&pkt, &version)
257 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
258 al = SSL_AD_INTERNAL_ERROR;
259 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
263 thisrr->rec_version = version;
265 /* Lets check version. In TLSv1.3 we ignore this field */
266 if (!s->first_packet && !SSL_IS_TLS13(s)
267 && version != (unsigned int)s->version) {
268 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
269 if ((s->version & 0xFF00) == (version & 0xFF00)
270 && !s->enc_write_ctx && !s->write_hash) {
271 if (thisrr->type == SSL3_RT_ALERT) {
273 * The record is using an incorrect version number,
274 * but what we've got appears to be an alert. We
275 * haven't read the body yet to check whether its a
276 * fatal or not - but chances are it is. We probably
277 * shouldn't send a fatal alert back. We'll just
283 * Send back error using their minor version number :-)
285 s->version = (unsigned short)version;
287 al = SSL_AD_PROTOCOL_VERSION;
291 if ((version >> 8) != SSL3_VERSION_MAJOR) {
292 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
293 /* Go back to start of packet, look at the five bytes
295 p = RECORD_LAYER_get_packet(&s->rlayer);
296 if (strncmp((char *)p, "GET ", 4) == 0 ||
297 strncmp((char *)p, "POST ", 5) == 0 ||
298 strncmp((char *)p, "HEAD ", 5) == 0 ||
299 strncmp((char *)p, "PUT ", 4) == 0) {
300 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
302 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
303 SSLerr(SSL_F_SSL3_GET_RECORD,
304 SSL_R_HTTPS_PROXY_REQUEST);
308 /* Doesn't look like TLS - don't send an alert */
309 SSLerr(SSL_F_SSL3_GET_RECORD,
310 SSL_R_WRONG_VERSION_NUMBER);
313 SSLerr(SSL_F_SSL3_GET_RECORD,
314 SSL_R_WRONG_VERSION_NUMBER);
315 al = SSL_AD_PROTOCOL_VERSION;
320 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
321 && thisrr->type != SSL3_RT_APPLICATION_DATA) {
322 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
323 al = SSL_AD_UNEXPECTED_MESSAGE;
328 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
329 al = SSL_AD_RECORD_OVERFLOW;
330 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
335 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
338 if (SSL_IS_TLS13(s)) {
339 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
340 al = SSL_AD_RECORD_OVERFLOW;
341 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
345 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
347 #ifndef OPENSSL_NO_COMP
349 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
350 * does not include the compression overhead anyway.
352 if (s->expand == NULL)
353 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
356 if (thisrr->length > len) {
357 al = SSL_AD_RECORD_OVERFLOW;
358 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
364 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
365 * Calculate how much more data we need to read for the rest of the
368 if (thisrr->rec_version == SSL2_VERSION) {
369 more = thisrr->length + SSL2_RT_HEADER_LENGTH
370 - SSL3_RT_HEADER_LENGTH;
372 more = thisrr->length;
375 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
377 rret = ssl3_read_n(s, more, more, 1, 0, &n);
379 return rret; /* error or non-blocking io */
382 /* set state for later operations */
383 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
386 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
387 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
388 * + thisrr->length and we have that many bytes in s->packet
390 if (thisrr->rec_version == SSL2_VERSION) {
392 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
395 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
399 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
400 * points at thisrr->length bytes, which need to be copied into
401 * thisrr->data by either the decryption or by the decompression When
402 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
403 * be pointed at the new buffer
407 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
408 * thisrr->length bytes of encrypted compressed stuff.
411 /* decrypt in place in 'thisrr->input' */
412 thisrr->data = thisrr->input;
413 thisrr->orig_len = thisrr->length;
415 /* Mark this record as not read by upper layers yet */
420 /* we have pulled in a full packet so zero things */
421 RECORD_LAYER_reset_packet_length(&s->rlayer);
422 RECORD_LAYER_clear_first_record(&s->rlayer);
423 } while (num_recs < max_recs
424 && thisrr->type == SSL3_RT_APPLICATION_DATA
425 && SSL_USE_EXPLICIT_IV(s)
426 && s->enc_read_ctx != NULL
427 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
428 & EVP_CIPH_FLAG_PIPELINE)
429 && ssl3_record_app_data_waiting(s));
432 * If in encrypt-then-mac mode calculate mac from encrypted record. All
433 * the details below are public so no timing details can leak.
435 if (SSL_READ_ETM(s) && s->read_hash) {
437 /* TODO(size_t): convert this to do size_t properly */
438 imac_size = EVP_MD_CTX_size(s->read_hash);
439 assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
440 if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
441 al = SSL_AD_INTERNAL_ERROR;
442 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
445 mac_size = (size_t)imac_size;
446 for (j = 0; j < num_recs; j++) {
449 if (thisrr->length < mac_size) {
450 al = SSL_AD_DECODE_ERROR;
451 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
454 thisrr->length -= mac_size;
455 mac = thisrr->data + thisrr->length;
456 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
457 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
458 al = SSL_AD_BAD_RECORD_MAC;
459 SSLerr(SSL_F_SSL3_GET_RECORD,
460 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
466 first_rec_len = rr[0].length;
468 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
472 * 0: (in non-constant time) if the record is publicly invalid.
473 * 1: if the padding is valid
474 * -1: if the padding is invalid
477 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
479 * Valid early_data that we cannot decrypt might fail here as
480 * publicly invalid. We treat it like an empty record.
485 if (!early_data_count_ok(s, thisrr->length,
486 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
491 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
492 RECORD_LAYER_reset_read_sequence(&s->rlayer);
495 al = SSL_AD_DECRYPTION_FAILED;
496 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
500 printf("dec %"OSSLzu"\n", rr[0].length);
503 for (z = 0; z < rr[0].length; z++)
504 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
509 /* r->length is now the compressed data plus mac */
510 if ((sess != NULL) &&
511 (s->enc_read_ctx != NULL) &&
512 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
513 /* s->read_hash != NULL => mac_size != -1 */
514 unsigned char *mac = NULL;
515 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
517 mac_size = EVP_MD_CTX_size(s->read_hash);
518 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
520 for (j = 0; j < num_recs; j++) {
523 * orig_len is the length of the record before any padding was
524 * removed. This is public information, as is the MAC in use,
525 * therefore we can safely process the record in a different amount
526 * of time if it's too short to possibly contain a MAC.
528 if (thisrr->orig_len < mac_size ||
529 /* CBC records must have a padding length byte too. */
530 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
531 thisrr->orig_len < mac_size + 1)) {
532 al = SSL_AD_DECODE_ERROR;
533 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
537 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
539 * We update the length so that the TLS header bytes can be
540 * constructed correctly but we need to extract the MAC in
541 * constant time from within the record, without leaking the
542 * contents of the padding bytes.
545 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
546 thisrr->length -= mac_size;
549 * In this case there's no padding, so |rec->orig_len| equals
550 * |rec->length| and we checked that there's enough bytes for
553 thisrr->length -= mac_size;
554 mac = &thisrr->data[thisrr->length];
557 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
558 if (i == 0 || mac == NULL
559 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
561 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
567 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
569 * We assume this is unreadable early_data - we treat it like an
574 * The record length may have been modified by the mac check above
575 * so we use the previously saved value
577 if (!early_data_count_ok(s, first_rec_len,
578 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
584 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
585 RECORD_LAYER_reset_read_sequence(&s->rlayer);
589 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
590 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
591 * failure is directly visible from the ciphertext anyway, we should
592 * not reveal which kind of error occurred -- this might become
593 * visible to an attacker (e.g. via a logfile)
595 al = SSL_AD_BAD_RECORD_MAC;
596 SSLerr(SSL_F_SSL3_GET_RECORD,
597 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
601 for (j = 0; j < num_recs; j++) {
604 /* thisrr->length is now just compressed */
605 if (s->expand != NULL) {
606 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
607 al = SSL_AD_RECORD_OVERFLOW;
608 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
611 if (!ssl3_do_uncompress(s, thisrr)) {
612 al = SSL_AD_DECOMPRESSION_FAILURE;
613 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
618 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
621 if (thisrr->length == 0) {
622 al = SSL_AD_UNEXPECTED_MESSAGE;
623 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
627 /* Strip trailing padding */
628 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
632 thisrr->length = end;
633 thisrr->type = thisrr->data[end];
634 if (thisrr->type != SSL3_RT_APPLICATION_DATA
635 && thisrr->type != SSL3_RT_ALERT
636 && thisrr->type != SSL3_RT_HANDSHAKE) {
637 al = SSL_AD_UNEXPECTED_MESSAGE;
638 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
642 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
643 &thisrr->data[end], 1, s, s->msg_callback_arg);
646 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
647 al = SSL_AD_RECORD_OVERFLOW;
648 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
654 * So at this point the following is true
655 * thisrr->type is the type of record
656 * thisrr->length == number of bytes in record
657 * thisrr->off == offset to first valid byte
658 * thisrr->data == where to take bytes from, increment after use :-).
661 /* just read a 0 length packet */
662 if (thisrr->length == 0) {
663 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
664 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
665 > MAX_EMPTY_RECORDS) {
666 al = SSL_AD_UNEXPECTED_MESSAGE;
667 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
671 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
675 if (s->early_data_state == SSL_EARLY_DATA_READING) {
677 if (thisrr->type == SSL3_RT_APPLICATION_DATA
678 && !early_data_count_ok(s, thisrr->length, 0, &al))
682 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
686 ssl3_send_alert(s, SSL3_AL_FATAL, al);
691 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
693 #ifndef OPENSSL_NO_COMP
696 if (rr->comp == NULL) {
697 rr->comp = (unsigned char *)
698 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
700 if (rr->comp == NULL)
703 /* TODO(size_t): Convert this call */
704 i = COMP_expand_block(ssl->expand, rr->comp,
705 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
715 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
717 #ifndef OPENSSL_NO_COMP
720 /* TODO(size_t): Convert this call */
721 i = COMP_compress_block(ssl->compress, wr->data,
722 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
723 wr->input, (int)wr->length);
729 wr->input = wr->data;
735 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
738 * 0: (in non-constant time) if the record is publically invalid (i.e. too
740 * 1: if the record's padding is valid / the encryption was successful.
741 * -1: if the record's padding is invalid or, if sending, an internal error
744 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
749 size_t bs, mac_size = 0;
751 const EVP_CIPHER *enc;
755 * We shouldn't ever be called with more than one record in the SSLv3 case
760 ds = s->enc_write_ctx;
761 if (s->enc_write_ctx == NULL)
764 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
766 ds = s->enc_read_ctx;
767 if (s->enc_read_ctx == NULL)
770 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
773 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
774 memmove(rec->data, rec->input, rec->length);
775 rec->input = rec->data;
778 /* TODO(size_t): Convert this call */
779 bs = EVP_CIPHER_CTX_block_size(ds);
783 if ((bs != 1) && sending) {
786 /* we need to add 'i-1' padding bytes */
789 * the last of these zero bytes will be overwritten with the
792 memset(&rec->input[rec->length], 0, i);
794 rec->input[l - 1] = (unsigned char)(i - 1);
798 if (l == 0 || l % bs != 0)
800 /* otherwise, rec->length >= bs */
803 /* TODO(size_t): Convert this call */
804 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
807 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
808 /* TODO(size_t): convert me */
809 imac_size = EVP_MD_CTX_size(s->read_hash);
812 mac_size = (size_t)imac_size;
814 if ((bs != 1) && !sending)
815 return ssl3_cbc_remove_padding(rec, bs, mac_size);
820 #define MAX_PADDING 256
822 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
825 * 0: (in non-constant time) if the record is publically invalid (i.e. too
827 * 1: if the record's padding is valid / the encryption was successful.
828 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
829 * an internal error occurred.
831 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
834 size_t reclen[SSL_MAX_PIPELINES];
835 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
836 int i, pad = 0, ret, tmpr;
837 size_t bs, mac_size = 0, ctr, padnum, loop;
838 unsigned char padval;
840 const EVP_CIPHER *enc;
846 if (EVP_MD_CTX_md(s->write_hash)) {
847 int n = EVP_MD_CTX_size(s->write_hash);
848 OPENSSL_assert(n >= 0);
850 ds = s->enc_write_ctx;
851 if (s->enc_write_ctx == NULL)
855 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
856 /* For TLSv1.1 and later explicit IV */
857 if (SSL_USE_EXPLICIT_IV(s)
858 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
859 ivlen = EVP_CIPHER_iv_length(enc);
863 for (ctr = 0; ctr < n_recs; ctr++) {
864 if (recs[ctr].data != recs[ctr].input) {
866 * we can't write into the input stream: Can this ever
869 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
871 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
872 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
879 if (EVP_MD_CTX_md(s->read_hash)) {
880 int n = EVP_MD_CTX_size(s->read_hash);
881 OPENSSL_assert(n >= 0);
883 ds = s->enc_read_ctx;
884 if (s->enc_read_ctx == NULL)
887 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
890 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
891 for (ctr = 0; ctr < n_recs; ctr++) {
892 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
893 recs[ctr].input = recs[ctr].data;
897 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
900 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
901 & EVP_CIPH_FLAG_PIPELINE)) {
903 * We shouldn't have been called with pipeline data if the
904 * cipher doesn't support pipelining
906 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
910 for (ctr = 0; ctr < n_recs; ctr++) {
911 reclen[ctr] = recs[ctr].length;
913 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
914 & EVP_CIPH_FLAG_AEAD_CIPHER) {
917 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
918 : RECORD_LAYER_get_read_sequence(&s->rlayer);
920 if (SSL_IS_DTLS(s)) {
921 /* DTLS does not support pipelining */
922 unsigned char dtlsseq[9], *p = dtlsseq;
924 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
925 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
926 memcpy(p, &seq[2], 6);
927 memcpy(buf[ctr], dtlsseq, 8);
929 memcpy(buf[ctr], seq, 8);
930 for (i = 7; i >= 0; i--) { /* increment */
937 buf[ctr][8] = recs[ctr].type;
938 buf[ctr][9] = (unsigned char)(s->version >> 8);
939 buf[ctr][10] = (unsigned char)(s->version);
940 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
941 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
942 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
943 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
949 recs[ctr].length += pad;
952 } else if ((bs != 1) && sending) {
953 padnum = bs - (reclen[ctr] % bs);
955 /* Add weird padding of upto 256 bytes */
957 if (padnum > MAX_PADDING)
959 /* we need to add 'padnum' padding bytes of value padval */
960 padval = (unsigned char)(padnum - 1);
961 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
962 recs[ctr].input[loop] = padval;
963 reclen[ctr] += padnum;
964 recs[ctr].length += padnum;
968 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
973 unsigned char *data[SSL_MAX_PIPELINES];
975 /* Set the output buffers */
976 for (ctr = 0; ctr < n_recs; ctr++) {
977 data[ctr] = recs[ctr].data;
979 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
980 (int)n_recs, data) <= 0) {
981 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
983 /* Set the input buffers */
984 for (ctr = 0; ctr < n_recs; ctr++) {
985 data[ctr] = recs[ctr].input;
987 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
988 (int)n_recs, data) <= 0
989 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
990 (int)n_recs, reclen) <= 0) {
991 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
996 /* TODO(size_t): Convert this call */
997 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
998 (unsigned int)reclen[0]);
999 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1000 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1003 return -1; /* AEAD can fail to verify MAC */
1005 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1006 for (ctr = 0; ctr < n_recs; ctr++) {
1007 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1008 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1009 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1011 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1012 for (ctr = 0; ctr < n_recs; ctr++) {
1013 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1014 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1015 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1021 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1022 imac_size = EVP_MD_CTX_size(s->read_hash);
1025 mac_size = (size_t)imac_size;
1027 if ((bs != 1) && !sending) {
1029 for (ctr = 0; ctr < n_recs; ctr++) {
1030 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1032 * If tmpret == 0 then this means publicly invalid so we can
1033 * short circuit things here. Otherwise we must respect constant
1038 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1042 if (pad && !sending) {
1043 for (ctr = 0; ctr < n_recs; ctr++) {
1044 recs[ctr].length -= pad;
1051 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1053 unsigned char *mac_sec, *seq;
1054 const EVP_MD_CTX *hash;
1055 unsigned char *p, rec_char;
1061 mac_sec = &(ssl->s3->write_mac_secret[0]);
1062 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1063 hash = ssl->write_hash;
1065 mac_sec = &(ssl->s3->read_mac_secret[0]);
1066 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1067 hash = ssl->read_hash;
1070 t = EVP_MD_CTX_size(hash);
1074 npad = (48 / md_size) * md_size;
1077 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1078 ssl3_cbc_record_digest_supported(hash)) {
1080 * This is a CBC-encrypted record. We must avoid leaking any
1081 * timing-side channel information about how many blocks of data we
1082 * are hashing because that gives an attacker a timing-oracle.
1086 * npad is, at most, 48 bytes and that's with MD5:
1087 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1089 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1090 * goes up 4, but npad goes down by 8, resulting in a smaller
1093 unsigned char header[75];
1095 memcpy(header + j, mac_sec, md_size);
1097 memcpy(header + j, ssl3_pad_1, npad);
1099 memcpy(header + j, seq, 8);
1101 header[j++] = rec->type;
1102 header[j++] = (unsigned char)(rec->length >> 8);
1103 header[j++] = (unsigned char)(rec->length & 0xff);
1105 /* Final param == is SSLv3 */
1106 if (ssl3_cbc_digest_record(hash,
1109 rec->length + md_size, rec->orig_len,
1110 mac_sec, md_size, 1) <= 0)
1113 unsigned int md_size_u;
1114 /* Chop the digest off the end :-) */
1115 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1120 rec_char = rec->type;
1122 s2n(rec->length, p);
1123 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1124 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1125 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1126 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1127 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1128 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1129 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1130 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1131 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1132 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1133 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1134 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1135 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1136 EVP_MD_CTX_reset(md_ctx);
1140 EVP_MD_CTX_free(md_ctx);
1143 ssl3_record_sequence_update(seq);
1147 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1153 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1154 unsigned char header[13];
1155 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1156 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1160 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1161 hash = ssl->write_hash;
1163 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1164 hash = ssl->read_hash;
1167 t = EVP_MD_CTX_size(hash);
1168 OPENSSL_assert(t >= 0);
1171 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1175 hmac = EVP_MD_CTX_new();
1176 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1181 if (SSL_IS_DTLS(ssl)) {
1182 unsigned char dtlsseq[8], *p = dtlsseq;
1184 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1185 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1186 memcpy(p, &seq[2], 6);
1188 memcpy(header, dtlsseq, 8);
1190 memcpy(header, seq, 8);
1192 header[8] = rec->type;
1193 header[9] = (unsigned char)(ssl->version >> 8);
1194 header[10] = (unsigned char)(ssl->version);
1195 header[11] = (unsigned char)(rec->length >> 8);
1196 header[12] = (unsigned char)(rec->length & 0xff);
1198 if (!sending && !SSL_READ_ETM(ssl) &&
1199 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1200 ssl3_cbc_record_digest_supported(mac_ctx)) {
1202 * This is a CBC-encrypted record. We must avoid leaking any
1203 * timing-side channel information about how many blocks of data we
1204 * are hashing because that gives an attacker a timing-oracle.
1206 /* Final param == not SSLv3 */
1207 if (ssl3_cbc_digest_record(mac_ctx,
1210 rec->length + md_size, rec->orig_len,
1211 ssl->s3->read_mac_secret,
1212 ssl->s3->read_mac_secret_size, 0) <= 0) {
1213 EVP_MD_CTX_free(hmac);
1217 /* TODO(size_t): Convert these calls */
1218 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1219 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1220 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1221 EVP_MD_CTX_free(hmac);
1226 EVP_MD_CTX_free(hmac);
1229 fprintf(stderr, "seq=");
1232 for (z = 0; z < 8; z++)
1233 fprintf(stderr, "%02X ", seq[z]);
1234 fprintf(stderr, "\n");
1236 fprintf(stderr, "rec=");
1239 for (z = 0; z < rec->length; z++)
1240 fprintf(stderr, "%02X ", rec->data[z]);
1241 fprintf(stderr, "\n");
1245 if (!SSL_IS_DTLS(ssl)) {
1246 for (i = 7; i >= 0; i--) {
1255 for (z = 0; z < md_size; z++)
1256 fprintf(stderr, "%02X ", md[z]);
1257 fprintf(stderr, "\n");
1264 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1265 * record in |rec| by updating |rec->length| in constant time.
1267 * block_size: the block size of the cipher used to encrypt the record.
1269 * 0: (in non-constant time) if the record is publicly invalid.
1270 * 1: if the padding was valid
1273 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1274 size_t block_size, size_t mac_size)
1276 size_t padding_length;
1278 const size_t overhead = 1 /* padding length byte */ + mac_size;
1281 * These lengths are all public so we can test them in non-constant time.
1283 if (overhead > rec->length)
1286 padding_length = rec->data[rec->length - 1];
1287 good = constant_time_ge_s(rec->length, padding_length + overhead);
1288 /* SSLv3 requires that the padding is minimal. */
1289 good &= constant_time_ge_s(block_size, padding_length + 1);
1290 rec->length -= good & (padding_length + 1);
1291 return constant_time_select_int_s(good, 1, -1);
1295 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1296 * record in |rec| in constant time and returns 1 if the padding is valid and
1297 * -1 otherwise. It also removes any explicit IV from the start of the record
1298 * without leaking any timing about whether there was enough space after the
1299 * padding was removed.
1301 * block_size: the block size of the cipher used to encrypt the record.
1303 * 0: (in non-constant time) if the record is publicly invalid.
1304 * 1: if the padding was valid
1307 int tls1_cbc_remove_padding(const SSL *s,
1309 size_t block_size, size_t mac_size)
1312 size_t padding_length, to_check, i;
1313 const size_t overhead = 1 /* padding length byte */ + mac_size;
1314 /* Check if version requires explicit IV */
1315 if (SSL_USE_EXPLICIT_IV(s)) {
1317 * These lengths are all public so we can test them in non-constant
1320 if (overhead + block_size > rec->length)
1322 /* We can now safely skip explicit IV */
1323 rec->data += block_size;
1324 rec->input += block_size;
1325 rec->length -= block_size;
1326 rec->orig_len -= block_size;
1327 } else if (overhead > rec->length)
1330 padding_length = rec->data[rec->length - 1];
1332 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1333 EVP_CIPH_FLAG_AEAD_CIPHER) {
1334 /* padding is already verified */
1335 rec->length -= padding_length + 1;
1339 good = constant_time_ge_s(rec->length, overhead + padding_length);
1341 * The padding consists of a length byte at the end of the record and
1342 * then that many bytes of padding, all with the same value as the length
1343 * byte. Thus, with the length byte included, there are i+1 bytes of
1344 * padding. We can't check just |padding_length+1| bytes because that
1345 * leaks decrypted information. Therefore we always have to check the
1346 * maximum amount of padding possible. (Again, the length of the record
1347 * is public information so we can use it.)
1349 to_check = 256; /* maximum amount of padding, inc length byte. */
1350 if (to_check > rec->length)
1351 to_check = rec->length;
1353 for (i = 0; i < to_check; i++) {
1354 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1355 unsigned char b = rec->data[rec->length - 1 - i];
1357 * The final |padding_length+1| bytes should all have the value
1358 * |padding_length|. Therefore the XOR should be zero.
1360 good &= ~(mask & (padding_length ^ b));
1364 * If any of the final |padding_length+1| bytes had the wrong value, one
1365 * or more of the lower eight bits of |good| will be cleared.
1367 good = constant_time_eq_s(0xff, good & 0xff);
1368 rec->length -= good & (padding_length + 1);
1370 return constant_time_select_int_s(good, 1, -1);
1374 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1375 * constant time (independent of the concrete value of rec->length, which may
1376 * vary within a 256-byte window).
1378 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1382 * rec->orig_len >= md_size
1383 * md_size <= EVP_MAX_MD_SIZE
1385 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1386 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1387 * a single or pair of cache-lines, then the variable memory accesses don't
1388 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1389 * not multi-core and are not considered vulnerable to cache-timing attacks.
1391 #define CBC_MAC_ROTATE_IN_PLACE
1393 void ssl3_cbc_copy_mac(unsigned char *out,
1394 const SSL3_RECORD *rec, size_t md_size)
1396 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1397 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1398 unsigned char *rotated_mac;
1400 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1404 * mac_end is the index of |rec->data| just after the end of the MAC.
1406 size_t mac_end = rec->length;
1407 size_t mac_start = mac_end - md_size;
1410 * scan_start contains the number of bytes that we can ignore because the
1411 * MAC's position can only vary by 255 bytes.
1413 size_t scan_start = 0;
1415 size_t rotate_offset;
1417 OPENSSL_assert(rec->orig_len >= md_size);
1418 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1420 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1421 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1424 /* This information is public so it's safe to branch based on it. */
1425 if (rec->orig_len > md_size + 255 + 1)
1426 scan_start = rec->orig_len - (md_size + 255 + 1);
1430 memset(rotated_mac, 0, md_size);
1431 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1432 size_t mac_started = constant_time_eq_s(i, mac_start);
1433 size_t mac_ended = constant_time_lt_s(i, mac_end);
1434 unsigned char b = rec->data[i];
1436 in_mac |= mac_started;
1437 in_mac &= mac_ended;
1438 rotate_offset |= j & mac_started;
1439 rotated_mac[j++] |= b & in_mac;
1440 j &= constant_time_lt_s(j, md_size);
1443 /* Now rotate the MAC */
1444 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1446 for (i = 0; i < md_size; i++) {
1447 /* in case cache-line is 32 bytes, touch second line */
1448 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1449 out[j++] = rotated_mac[rotate_offset++];
1450 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1453 memset(out, 0, md_size);
1454 rotate_offset = md_size - rotate_offset;
1455 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1456 for (i = 0; i < md_size; i++) {
1457 for (j = 0; j < md_size; j++)
1458 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1460 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1465 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1473 unsigned char md[EVP_MAX_MD_SIZE];
1475 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1479 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1480 * and we have that many bytes in s->packet
1482 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1485 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1486 * at rr->length bytes, which need to be copied into rr->data by either
1487 * the decryption or by the decompression When the data is 'copied' into
1488 * the rr->data buffer, rr->input will be pointed at the new buffer
1492 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1493 * bytes of encrypted compressed stuff.
1496 /* check is not needed I believe */
1497 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1498 al = SSL_AD_RECORD_OVERFLOW;
1499 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1503 /* decrypt in place in 'rr->input' */
1504 rr->data = rr->input;
1505 rr->orig_len = rr->length;
1507 if (SSL_READ_ETM(s) && s->read_hash) {
1509 mac_size = EVP_MD_CTX_size(s->read_hash);
1510 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1511 if (rr->orig_len < mac_size) {
1512 al = SSL_AD_DECODE_ERROR;
1513 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1516 rr->length -= mac_size;
1517 mac = rr->data + rr->length;
1518 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1519 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1520 al = SSL_AD_BAD_RECORD_MAC;
1521 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1522 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1527 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1530 * 0: (in non-constant time) if the record is publically invalid.
1531 * 1: if the padding is valid
1532 * -1: if the padding is invalid
1535 /* For DTLS we simply ignore bad packets. */
1537 RECORD_LAYER_reset_packet_length(&s->rlayer);
1541 printf("dec %ld\n", rr->length);
1544 for (z = 0; z < rr->length; z++)
1545 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1550 /* r->length is now the compressed data plus mac */
1551 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1552 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1553 /* s->read_hash != NULL => mac_size != -1 */
1554 unsigned char *mac = NULL;
1555 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1557 /* TODO(size_t): Convert this to do size_t properly */
1558 imac_size = EVP_MD_CTX_size(s->read_hash);
1559 if (imac_size < 0) {
1560 al = SSL_AD_INTERNAL_ERROR;
1561 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1564 mac_size = (size_t)imac_size;
1565 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1568 * orig_len is the length of the record before any padding was
1569 * removed. This is public information, as is the MAC in use,
1570 * therefore we can safely process the record in a different amount
1571 * of time if it's too short to possibly contain a MAC.
1573 if (rr->orig_len < mac_size ||
1574 /* CBC records must have a padding length byte too. */
1575 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1576 rr->orig_len < mac_size + 1)) {
1577 al = SSL_AD_DECODE_ERROR;
1578 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1582 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1584 * We update the length so that the TLS header bytes can be
1585 * constructed correctly but we need to extract the MAC in
1586 * constant time from within the record, without leaking the
1587 * contents of the padding bytes.
1590 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1591 rr->length -= mac_size;
1594 * In this case there's no padding, so |rec->orig_len| equals
1595 * |rec->length| and we checked that there's enough bytes for
1598 rr->length -= mac_size;
1599 mac = &rr->data[rr->length];
1602 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1603 if (i == 0 || mac == NULL
1604 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1606 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1611 /* decryption failed, silently discard message */
1613 RECORD_LAYER_reset_packet_length(&s->rlayer);
1617 /* r->length is now just compressed */
1618 if (s->expand != NULL) {
1619 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1620 al = SSL_AD_RECORD_OVERFLOW;
1621 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1622 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1625 if (!ssl3_do_uncompress(s, rr)) {
1626 al = SSL_AD_DECOMPRESSION_FAILURE;
1627 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1632 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1633 al = SSL_AD_RECORD_OVERFLOW;
1634 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1640 * So at this point the following is true
1641 * ssl->s3->rrec.type is the type of record
1642 * ssl->s3->rrec.length == number of bytes in record
1643 * ssl->s3->rrec.off == offset to first valid byte
1644 * ssl->s3->rrec.data == where to take bytes from, increment
1648 /* we have pulled in a full packet so zero things */
1649 RECORD_LAYER_reset_packet_length(&s->rlayer);
1651 /* Mark receipt of record. */
1652 dtls1_record_bitmap_update(s, bitmap);
1657 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1663 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1665 #define dtls1_get_processed_record(s) \
1666 dtls1_retrieve_buffered_record((s), \
1667 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1670 * Call this to get a new input record.
1671 * It will return <= 0 if more data is needed, normally due to an error
1672 * or non-blocking IO.
1673 * When it finishes, one packet has been decoded and can be found in
1674 * ssl->s3->rrec.type - is the type of record
1675 * ssl->s3->rrec.data, - data
1676 * ssl->s3->rrec.length, - number of bytes
1678 /* used only by dtls1_read_bytes */
1679 int dtls1_get_record(SSL *s)
1681 int ssl_major, ssl_minor;
1685 unsigned char *p = NULL;
1686 unsigned short version;
1687 DTLS1_BITMAP *bitmap;
1688 unsigned int is_next_epoch;
1690 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1694 * The epoch may have changed. If so, process all the pending records.
1695 * This is a non-blocking operation.
1697 if (!dtls1_process_buffered_records(s))
1700 /* if we're renegotiating, then there may be buffered records */
1701 if (dtls1_get_processed_record(s))
1704 /* get something from the wire */
1706 /* check if we have the header */
1707 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1708 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1709 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1710 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1711 /* read timeout is handled by dtls1_read_bytes */
1713 return rret; /* error or non-blocking */
1715 /* this packet contained a partial record, dump it */
1716 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1717 DTLS1_RT_HEADER_LENGTH) {
1718 RECORD_LAYER_reset_packet_length(&s->rlayer);
1722 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1724 p = RECORD_LAYER_get_packet(&s->rlayer);
1726 if (s->msg_callback)
1727 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1728 s, s->msg_callback_arg);
1730 /* Pull apart the header into the DTLS1_RECORD */
1734 version = (ssl_major << 8) | ssl_minor;
1736 /* sequence number is 64 bits, with top 2 bytes = epoch */
1739 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1744 /* Lets check version */
1745 if (!s->first_packet) {
1746 if (version != s->version) {
1747 /* unexpected version, silently discard */
1749 RECORD_LAYER_reset_packet_length(&s->rlayer);
1754 if ((version & 0xff00) != (s->version & 0xff00)) {
1755 /* wrong version, silently discard record */
1757 RECORD_LAYER_reset_packet_length(&s->rlayer);
1761 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1762 /* record too long, silently discard it */
1764 RECORD_LAYER_reset_packet_length(&s->rlayer);
1768 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1771 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1774 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1775 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1777 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1778 /* this packet contained a partial record, dump it */
1779 if (rret <= 0 || n != more) {
1781 RECORD_LAYER_reset_packet_length(&s->rlayer);
1786 * now n == rr->length, and s->packet_length ==
1787 * DTLS1_RT_HEADER_LENGTH + rr->length
1790 /* set state for later operations */
1791 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1793 /* match epochs. NULL means the packet is dropped on the floor */
1794 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1795 if (bitmap == NULL) {
1797 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1798 goto again; /* get another record */
1800 #ifndef OPENSSL_NO_SCTP
1801 /* Only do replay check if no SCTP bio */
1802 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1804 /* Check whether this is a repeat, or aged record. */
1806 * TODO: Does it make sense to have replay protection in epoch 0 where
1807 * we have no integrity negotiated yet?
1809 if (!dtls1_record_replay_check(s, bitmap)) {
1811 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1812 goto again; /* get another record */
1814 #ifndef OPENSSL_NO_SCTP
1818 /* just read a 0 length packet */
1819 if (rr->length == 0)
1823 * If this record is from the next epoch (either HM or ALERT), and a
1824 * handshake is currently in progress, buffer it since it cannot be
1825 * processed at this time.
1827 if (is_next_epoch) {
1828 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1829 if (dtls1_buffer_record
1830 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1835 RECORD_LAYER_reset_packet_length(&s->rlayer);
1839 if (!dtls1_process_record(s, bitmap)) {
1841 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1842 goto again; /* get another record */