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 || thisrr->type != SSL3_RT_APPLICATION_DATA) {
623 al = SSL_AD_UNEXPECTED_MESSAGE;
624 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
628 /* Strip trailing padding */
629 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
633 thisrr->length = end;
634 thisrr->type = thisrr->data[end];
635 if (thisrr->type != SSL3_RT_APPLICATION_DATA
636 && thisrr->type != SSL3_RT_ALERT
637 && thisrr->type != SSL3_RT_HANDSHAKE) {
638 al = SSL_AD_UNEXPECTED_MESSAGE;
639 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
643 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
644 &thisrr->data[end], 1, s, s->msg_callback_arg);
647 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
648 al = SSL_AD_RECORD_OVERFLOW;
649 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
655 * So at this point the following is true
656 * thisrr->type is the type of record
657 * thisrr->length == number of bytes in record
658 * thisrr->off == offset to first valid byte
659 * thisrr->data == where to take bytes from, increment after use :-).
662 /* just read a 0 length packet */
663 if (thisrr->length == 0) {
664 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
665 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
666 > MAX_EMPTY_RECORDS) {
667 al = SSL_AD_UNEXPECTED_MESSAGE;
668 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
672 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
676 if (s->early_data_state == SSL_EARLY_DATA_READING) {
678 if (thisrr->type == SSL3_RT_APPLICATION_DATA
679 && !early_data_count_ok(s, thisrr->length, 0, &al))
683 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
687 ssl3_send_alert(s, SSL3_AL_FATAL, al);
692 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
694 #ifndef OPENSSL_NO_COMP
697 if (rr->comp == NULL) {
698 rr->comp = (unsigned char *)
699 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
701 if (rr->comp == NULL)
704 /* TODO(size_t): Convert this call */
705 i = COMP_expand_block(ssl->expand, rr->comp,
706 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
716 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
718 #ifndef OPENSSL_NO_COMP
721 /* TODO(size_t): Convert this call */
722 i = COMP_compress_block(ssl->compress, wr->data,
723 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
724 wr->input, (int)wr->length);
730 wr->input = wr->data;
736 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
739 * 0: (in non-constant time) if the record is publically invalid (i.e. too
741 * 1: if the record's padding is valid / the encryption was successful.
742 * -1: if the record's padding is invalid or, if sending, an internal error
745 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
750 size_t bs, mac_size = 0;
752 const EVP_CIPHER *enc;
756 * We shouldn't ever be called with more than one record in the SSLv3 case
761 ds = s->enc_write_ctx;
762 if (s->enc_write_ctx == NULL)
765 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
767 ds = s->enc_read_ctx;
768 if (s->enc_read_ctx == NULL)
771 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
774 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
775 memmove(rec->data, rec->input, rec->length);
776 rec->input = rec->data;
779 /* TODO(size_t): Convert this call */
780 bs = EVP_CIPHER_CTX_block_size(ds);
784 if ((bs != 1) && sending) {
787 /* we need to add 'i-1' padding bytes */
790 * the last of these zero bytes will be overwritten with the
793 memset(&rec->input[rec->length], 0, i);
795 rec->input[l - 1] = (unsigned char)(i - 1);
799 if (l == 0 || l % bs != 0)
801 /* otherwise, rec->length >= bs */
804 /* TODO(size_t): Convert this call */
805 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
808 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
809 /* TODO(size_t): convert me */
810 imac_size = EVP_MD_CTX_size(s->read_hash);
813 mac_size = (size_t)imac_size;
815 if ((bs != 1) && !sending)
816 return ssl3_cbc_remove_padding(rec, bs, mac_size);
821 #define MAX_PADDING 256
823 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
826 * 0: (in non-constant time) if the record is publically invalid (i.e. too
828 * 1: if the record's padding is valid / the encryption was successful.
829 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
830 * an internal error occurred.
832 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
835 size_t reclen[SSL_MAX_PIPELINES];
836 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
837 int i, pad = 0, ret, tmpr;
838 size_t bs, mac_size = 0, ctr, padnum, loop;
839 unsigned char padval;
841 const EVP_CIPHER *enc;
847 if (EVP_MD_CTX_md(s->write_hash)) {
848 int n = EVP_MD_CTX_size(s->write_hash);
849 OPENSSL_assert(n >= 0);
851 ds = s->enc_write_ctx;
852 if (s->enc_write_ctx == NULL)
856 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
857 /* For TLSv1.1 and later explicit IV */
858 if (SSL_USE_EXPLICIT_IV(s)
859 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
860 ivlen = EVP_CIPHER_iv_length(enc);
864 for (ctr = 0; ctr < n_recs; ctr++) {
865 if (recs[ctr].data != recs[ctr].input) {
867 * we can't write into the input stream: Can this ever
870 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
872 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
873 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
880 if (EVP_MD_CTX_md(s->read_hash)) {
881 int n = EVP_MD_CTX_size(s->read_hash);
882 OPENSSL_assert(n >= 0);
884 ds = s->enc_read_ctx;
885 if (s->enc_read_ctx == NULL)
888 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
891 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
892 for (ctr = 0; ctr < n_recs; ctr++) {
893 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
894 recs[ctr].input = recs[ctr].data;
898 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
901 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
902 & EVP_CIPH_FLAG_PIPELINE)) {
904 * We shouldn't have been called with pipeline data if the
905 * cipher doesn't support pipelining
907 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
911 for (ctr = 0; ctr < n_recs; ctr++) {
912 reclen[ctr] = recs[ctr].length;
914 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
915 & EVP_CIPH_FLAG_AEAD_CIPHER) {
918 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
919 : RECORD_LAYER_get_read_sequence(&s->rlayer);
921 if (SSL_IS_DTLS(s)) {
922 /* DTLS does not support pipelining */
923 unsigned char dtlsseq[9], *p = dtlsseq;
925 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
926 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
927 memcpy(p, &seq[2], 6);
928 memcpy(buf[ctr], dtlsseq, 8);
930 memcpy(buf[ctr], seq, 8);
931 for (i = 7; i >= 0; i--) { /* increment */
938 buf[ctr][8] = recs[ctr].type;
939 buf[ctr][9] = (unsigned char)(s->version >> 8);
940 buf[ctr][10] = (unsigned char)(s->version);
941 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
942 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
943 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
944 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
950 recs[ctr].length += pad;
953 } else if ((bs != 1) && sending) {
954 padnum = bs - (reclen[ctr] % bs);
956 /* Add weird padding of upto 256 bytes */
958 if (padnum > MAX_PADDING)
960 /* we need to add 'padnum' padding bytes of value padval */
961 padval = (unsigned char)(padnum - 1);
962 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
963 recs[ctr].input[loop] = padval;
964 reclen[ctr] += padnum;
965 recs[ctr].length += padnum;
969 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
974 unsigned char *data[SSL_MAX_PIPELINES];
976 /* Set the output buffers */
977 for (ctr = 0; ctr < n_recs; ctr++) {
978 data[ctr] = recs[ctr].data;
980 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
981 (int)n_recs, data) <= 0) {
982 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
984 /* Set the input buffers */
985 for (ctr = 0; ctr < n_recs; ctr++) {
986 data[ctr] = recs[ctr].input;
988 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
989 (int)n_recs, data) <= 0
990 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
991 (int)n_recs, reclen) <= 0) {
992 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
997 /* TODO(size_t): Convert this call */
998 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
999 (unsigned int)reclen[0]);
1000 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1001 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1004 return -1; /* AEAD can fail to verify MAC */
1006 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1007 for (ctr = 0; ctr < n_recs; ctr++) {
1008 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1009 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1010 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1012 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1013 for (ctr = 0; ctr < n_recs; ctr++) {
1014 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1015 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1016 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1022 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1023 imac_size = EVP_MD_CTX_size(s->read_hash);
1026 mac_size = (size_t)imac_size;
1028 if ((bs != 1) && !sending) {
1030 for (ctr = 0; ctr < n_recs; ctr++) {
1031 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1033 * If tmpret == 0 then this means publicly invalid so we can
1034 * short circuit things here. Otherwise we must respect constant
1039 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1043 if (pad && !sending) {
1044 for (ctr = 0; ctr < n_recs; ctr++) {
1045 recs[ctr].length -= pad;
1052 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1054 unsigned char *mac_sec, *seq;
1055 const EVP_MD_CTX *hash;
1056 unsigned char *p, rec_char;
1062 mac_sec = &(ssl->s3->write_mac_secret[0]);
1063 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1064 hash = ssl->write_hash;
1066 mac_sec = &(ssl->s3->read_mac_secret[0]);
1067 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1068 hash = ssl->read_hash;
1071 t = EVP_MD_CTX_size(hash);
1075 npad = (48 / md_size) * md_size;
1078 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1079 ssl3_cbc_record_digest_supported(hash)) {
1081 * This is a CBC-encrypted record. We must avoid leaking any
1082 * timing-side channel information about how many blocks of data we
1083 * are hashing because that gives an attacker a timing-oracle.
1087 * npad is, at most, 48 bytes and that's with MD5:
1088 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1090 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1091 * goes up 4, but npad goes down by 8, resulting in a smaller
1094 unsigned char header[75];
1096 memcpy(header + j, mac_sec, md_size);
1098 memcpy(header + j, ssl3_pad_1, npad);
1100 memcpy(header + j, seq, 8);
1102 header[j++] = rec->type;
1103 header[j++] = (unsigned char)(rec->length >> 8);
1104 header[j++] = (unsigned char)(rec->length & 0xff);
1106 /* Final param == is SSLv3 */
1107 if (ssl3_cbc_digest_record(hash,
1110 rec->length + md_size, rec->orig_len,
1111 mac_sec, md_size, 1) <= 0)
1114 unsigned int md_size_u;
1115 /* Chop the digest off the end :-) */
1116 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1121 rec_char = rec->type;
1123 s2n(rec->length, p);
1124 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1125 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1126 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1127 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1128 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1129 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1130 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1131 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1132 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1133 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1134 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1135 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1136 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1137 EVP_MD_CTX_reset(md_ctx);
1141 EVP_MD_CTX_free(md_ctx);
1144 ssl3_record_sequence_update(seq);
1148 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1154 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1155 unsigned char header[13];
1156 int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1157 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1161 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1162 hash = ssl->write_hash;
1164 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1165 hash = ssl->read_hash;
1168 t = EVP_MD_CTX_size(hash);
1169 OPENSSL_assert(t >= 0);
1172 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1176 hmac = EVP_MD_CTX_new();
1177 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1182 if (SSL_IS_DTLS(ssl)) {
1183 unsigned char dtlsseq[8], *p = dtlsseq;
1185 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1186 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1187 memcpy(p, &seq[2], 6);
1189 memcpy(header, dtlsseq, 8);
1191 memcpy(header, seq, 8);
1193 header[8] = rec->type;
1194 header[9] = (unsigned char)(ssl->version >> 8);
1195 header[10] = (unsigned char)(ssl->version);
1196 header[11] = (unsigned char)(rec->length >> 8);
1197 header[12] = (unsigned char)(rec->length & 0xff);
1199 if (!sending && !SSL_READ_ETM(ssl) &&
1200 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1201 ssl3_cbc_record_digest_supported(mac_ctx)) {
1203 * This is a CBC-encrypted record. We must avoid leaking any
1204 * timing-side channel information about how many blocks of data we
1205 * are hashing because that gives an attacker a timing-oracle.
1207 /* Final param == not SSLv3 */
1208 if (ssl3_cbc_digest_record(mac_ctx,
1211 rec->length + md_size, rec->orig_len,
1212 ssl->s3->read_mac_secret,
1213 ssl->s3->read_mac_secret_size, 0) <= 0) {
1214 EVP_MD_CTX_free(hmac);
1218 /* TODO(size_t): Convert these calls */
1219 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1220 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1221 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1222 EVP_MD_CTX_free(hmac);
1227 EVP_MD_CTX_free(hmac);
1230 fprintf(stderr, "seq=");
1233 for (z = 0; z < 8; z++)
1234 fprintf(stderr, "%02X ", seq[z]);
1235 fprintf(stderr, "\n");
1237 fprintf(stderr, "rec=");
1240 for (z = 0; z < rec->length; z++)
1241 fprintf(stderr, "%02X ", rec->data[z]);
1242 fprintf(stderr, "\n");
1246 if (!SSL_IS_DTLS(ssl)) {
1247 for (i = 7; i >= 0; i--) {
1256 for (z = 0; z < md_size; z++)
1257 fprintf(stderr, "%02X ", md[z]);
1258 fprintf(stderr, "\n");
1265 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1266 * record in |rec| by updating |rec->length| in constant time.
1268 * block_size: the block size of the cipher used to encrypt the record.
1270 * 0: (in non-constant time) if the record is publicly invalid.
1271 * 1: if the padding was valid
1274 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1275 size_t block_size, size_t mac_size)
1277 size_t padding_length;
1279 const size_t overhead = 1 /* padding length byte */ + mac_size;
1282 * These lengths are all public so we can test them in non-constant time.
1284 if (overhead > rec->length)
1287 padding_length = rec->data[rec->length - 1];
1288 good = constant_time_ge_s(rec->length, padding_length + overhead);
1289 /* SSLv3 requires that the padding is minimal. */
1290 good &= constant_time_ge_s(block_size, padding_length + 1);
1291 rec->length -= good & (padding_length + 1);
1292 return constant_time_select_int_s(good, 1, -1);
1296 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1297 * record in |rec| in constant time and returns 1 if the padding is valid and
1298 * -1 otherwise. It also removes any explicit IV from the start of the record
1299 * without leaking any timing about whether there was enough space after the
1300 * padding was removed.
1302 * block_size: the block size of the cipher used to encrypt the record.
1304 * 0: (in non-constant time) if the record is publicly invalid.
1305 * 1: if the padding was valid
1308 int tls1_cbc_remove_padding(const SSL *s,
1310 size_t block_size, size_t mac_size)
1313 size_t padding_length, to_check, i;
1314 const size_t overhead = 1 /* padding length byte */ + mac_size;
1315 /* Check if version requires explicit IV */
1316 if (SSL_USE_EXPLICIT_IV(s)) {
1318 * These lengths are all public so we can test them in non-constant
1321 if (overhead + block_size > rec->length)
1323 /* We can now safely skip explicit IV */
1324 rec->data += block_size;
1325 rec->input += block_size;
1326 rec->length -= block_size;
1327 rec->orig_len -= block_size;
1328 } else if (overhead > rec->length)
1331 padding_length = rec->data[rec->length - 1];
1333 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1334 EVP_CIPH_FLAG_AEAD_CIPHER) {
1335 /* padding is already verified */
1336 rec->length -= padding_length + 1;
1340 good = constant_time_ge_s(rec->length, overhead + padding_length);
1342 * The padding consists of a length byte at the end of the record and
1343 * then that many bytes of padding, all with the same value as the length
1344 * byte. Thus, with the length byte included, there are i+1 bytes of
1345 * padding. We can't check just |padding_length+1| bytes because that
1346 * leaks decrypted information. Therefore we always have to check the
1347 * maximum amount of padding possible. (Again, the length of the record
1348 * is public information so we can use it.)
1350 to_check = 256; /* maximum amount of padding, inc length byte. */
1351 if (to_check > rec->length)
1352 to_check = rec->length;
1354 for (i = 0; i < to_check; i++) {
1355 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1356 unsigned char b = rec->data[rec->length - 1 - i];
1358 * The final |padding_length+1| bytes should all have the value
1359 * |padding_length|. Therefore the XOR should be zero.
1361 good &= ~(mask & (padding_length ^ b));
1365 * If any of the final |padding_length+1| bytes had the wrong value, one
1366 * or more of the lower eight bits of |good| will be cleared.
1368 good = constant_time_eq_s(0xff, good & 0xff);
1369 rec->length -= good & (padding_length + 1);
1371 return constant_time_select_int_s(good, 1, -1);
1375 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1376 * constant time (independent of the concrete value of rec->length, which may
1377 * vary within a 256-byte window).
1379 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1383 * rec->orig_len >= md_size
1384 * md_size <= EVP_MAX_MD_SIZE
1386 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1387 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1388 * a single or pair of cache-lines, then the variable memory accesses don't
1389 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1390 * not multi-core and are not considered vulnerable to cache-timing attacks.
1392 #define CBC_MAC_ROTATE_IN_PLACE
1394 void ssl3_cbc_copy_mac(unsigned char *out,
1395 const SSL3_RECORD *rec, size_t md_size)
1397 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1398 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1399 unsigned char *rotated_mac;
1401 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1405 * mac_end is the index of |rec->data| just after the end of the MAC.
1407 size_t mac_end = rec->length;
1408 size_t mac_start = mac_end - md_size;
1411 * scan_start contains the number of bytes that we can ignore because the
1412 * MAC's position can only vary by 255 bytes.
1414 size_t scan_start = 0;
1416 size_t rotate_offset;
1418 OPENSSL_assert(rec->orig_len >= md_size);
1419 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1421 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1422 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1425 /* This information is public so it's safe to branch based on it. */
1426 if (rec->orig_len > md_size + 255 + 1)
1427 scan_start = rec->orig_len - (md_size + 255 + 1);
1431 memset(rotated_mac, 0, md_size);
1432 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1433 size_t mac_started = constant_time_eq_s(i, mac_start);
1434 size_t mac_ended = constant_time_lt_s(i, mac_end);
1435 unsigned char b = rec->data[i];
1437 in_mac |= mac_started;
1438 in_mac &= mac_ended;
1439 rotate_offset |= j & mac_started;
1440 rotated_mac[j++] |= b & in_mac;
1441 j &= constant_time_lt_s(j, md_size);
1444 /* Now rotate the MAC */
1445 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1447 for (i = 0; i < md_size; i++) {
1448 /* in case cache-line is 32 bytes, touch second line */
1449 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1450 out[j++] = rotated_mac[rotate_offset++];
1451 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1454 memset(out, 0, md_size);
1455 rotate_offset = md_size - rotate_offset;
1456 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1457 for (i = 0; i < md_size; i++) {
1458 for (j = 0; j < md_size; j++)
1459 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1461 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1466 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1474 unsigned char md[EVP_MAX_MD_SIZE];
1476 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1480 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1481 * and we have that many bytes in s->packet
1483 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1486 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1487 * at rr->length bytes, which need to be copied into rr->data by either
1488 * the decryption or by the decompression When the data is 'copied' into
1489 * the rr->data buffer, rr->input will be pointed at the new buffer
1493 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1494 * bytes of encrypted compressed stuff.
1497 /* check is not needed I believe */
1498 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1499 al = SSL_AD_RECORD_OVERFLOW;
1500 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1504 /* decrypt in place in 'rr->input' */
1505 rr->data = rr->input;
1506 rr->orig_len = rr->length;
1508 if (SSL_READ_ETM(s) && s->read_hash) {
1510 mac_size = EVP_MD_CTX_size(s->read_hash);
1511 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1512 if (rr->orig_len < mac_size) {
1513 al = SSL_AD_DECODE_ERROR;
1514 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1517 rr->length -= mac_size;
1518 mac = rr->data + rr->length;
1519 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1520 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1521 al = SSL_AD_BAD_RECORD_MAC;
1522 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1523 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1528 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1531 * 0: (in non-constant time) if the record is publically invalid.
1532 * 1: if the padding is valid
1533 * -1: if the padding is invalid
1536 /* For DTLS we simply ignore bad packets. */
1538 RECORD_LAYER_reset_packet_length(&s->rlayer);
1542 printf("dec %ld\n", rr->length);
1545 for (z = 0; z < rr->length; z++)
1546 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1551 /* r->length is now the compressed data plus mac */
1552 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1553 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1554 /* s->read_hash != NULL => mac_size != -1 */
1555 unsigned char *mac = NULL;
1556 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1558 /* TODO(size_t): Convert this to do size_t properly */
1559 imac_size = EVP_MD_CTX_size(s->read_hash);
1560 if (imac_size < 0) {
1561 al = SSL_AD_INTERNAL_ERROR;
1562 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1565 mac_size = (size_t)imac_size;
1566 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1569 * orig_len is the length of the record before any padding was
1570 * removed. This is public information, as is the MAC in use,
1571 * therefore we can safely process the record in a different amount
1572 * of time if it's too short to possibly contain a MAC.
1574 if (rr->orig_len < mac_size ||
1575 /* CBC records must have a padding length byte too. */
1576 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1577 rr->orig_len < mac_size + 1)) {
1578 al = SSL_AD_DECODE_ERROR;
1579 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1583 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1585 * We update the length so that the TLS header bytes can be
1586 * constructed correctly but we need to extract the MAC in
1587 * constant time from within the record, without leaking the
1588 * contents of the padding bytes.
1591 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1592 rr->length -= mac_size;
1595 * In this case there's no padding, so |rec->orig_len| equals
1596 * |rec->length| and we checked that there's enough bytes for
1599 rr->length -= mac_size;
1600 mac = &rr->data[rr->length];
1603 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1604 if (i == 0 || mac == NULL
1605 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1607 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1612 /* decryption failed, silently discard message */
1614 RECORD_LAYER_reset_packet_length(&s->rlayer);
1618 /* r->length is now just compressed */
1619 if (s->expand != NULL) {
1620 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1621 al = SSL_AD_RECORD_OVERFLOW;
1622 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1623 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1626 if (!ssl3_do_uncompress(s, rr)) {
1627 al = SSL_AD_DECOMPRESSION_FAILURE;
1628 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1633 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1634 al = SSL_AD_RECORD_OVERFLOW;
1635 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1641 * So at this point the following is true
1642 * ssl->s3->rrec.type is the type of record
1643 * ssl->s3->rrec.length == number of bytes in record
1644 * ssl->s3->rrec.off == offset to first valid byte
1645 * ssl->s3->rrec.data == where to take bytes from, increment
1649 /* we have pulled in a full packet so zero things */
1650 RECORD_LAYER_reset_packet_length(&s->rlayer);
1652 /* Mark receipt of record. */
1653 dtls1_record_bitmap_update(s, bitmap);
1658 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1664 * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1666 #define dtls1_get_processed_record(s) \
1667 dtls1_retrieve_buffered_record((s), \
1668 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1671 * Call this to get a new input record.
1672 * It will return <= 0 if more data is needed, normally due to an error
1673 * or non-blocking IO.
1674 * When it finishes, one packet has been decoded and can be found in
1675 * ssl->s3->rrec.type - is the type of record
1676 * ssl->s3->rrec.data, - data
1677 * ssl->s3->rrec.length, - number of bytes
1679 /* used only by dtls1_read_bytes */
1680 int dtls1_get_record(SSL *s)
1682 int ssl_major, ssl_minor;
1686 unsigned char *p = NULL;
1687 unsigned short version;
1688 DTLS1_BITMAP *bitmap;
1689 unsigned int is_next_epoch;
1691 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1695 * The epoch may have changed. If so, process all the pending records.
1696 * This is a non-blocking operation.
1698 if (!dtls1_process_buffered_records(s))
1701 /* if we're renegotiating, then there may be buffered records */
1702 if (dtls1_get_processed_record(s))
1705 /* get something from the wire */
1707 /* check if we have the header */
1708 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1709 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1710 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1711 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1712 /* read timeout is handled by dtls1_read_bytes */
1714 return rret; /* error or non-blocking */
1716 /* this packet contained a partial record, dump it */
1717 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1718 DTLS1_RT_HEADER_LENGTH) {
1719 RECORD_LAYER_reset_packet_length(&s->rlayer);
1723 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1725 p = RECORD_LAYER_get_packet(&s->rlayer);
1727 if (s->msg_callback)
1728 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1729 s, s->msg_callback_arg);
1731 /* Pull apart the header into the DTLS1_RECORD */
1735 version = (ssl_major << 8) | ssl_minor;
1737 /* sequence number is 64 bits, with top 2 bytes = epoch */
1740 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1745 /* Lets check version */
1746 if (!s->first_packet) {
1747 if (version != s->version) {
1748 /* unexpected version, silently discard */
1750 RECORD_LAYER_reset_packet_length(&s->rlayer);
1755 if ((version & 0xff00) != (s->version & 0xff00)) {
1756 /* wrong version, silently discard record */
1758 RECORD_LAYER_reset_packet_length(&s->rlayer);
1762 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1763 /* record too long, silently discard it */
1765 RECORD_LAYER_reset_packet_length(&s->rlayer);
1769 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1772 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1775 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1776 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1778 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1779 /* this packet contained a partial record, dump it */
1780 if (rret <= 0 || n != more) {
1782 RECORD_LAYER_reset_packet_length(&s->rlayer);
1787 * now n == rr->length, and s->packet_length ==
1788 * DTLS1_RT_HEADER_LENGTH + rr->length
1791 /* set state for later operations */
1792 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1794 /* match epochs. NULL means the packet is dropped on the floor */
1795 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1796 if (bitmap == NULL) {
1798 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1799 goto again; /* get another record */
1801 #ifndef OPENSSL_NO_SCTP
1802 /* Only do replay check if no SCTP bio */
1803 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1805 /* Check whether this is a repeat, or aged record. */
1807 * TODO: Does it make sense to have replay protection in epoch 0 where
1808 * we have no integrity negotiated yet?
1810 if (!dtls1_record_replay_check(s, bitmap)) {
1812 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1813 goto again; /* get another record */
1815 #ifndef OPENSSL_NO_SCTP
1819 /* just read a 0 length packet */
1820 if (rr->length == 0)
1824 * If this record is from the next epoch (either HM or ALERT), and a
1825 * handshake is currently in progress, buffer it since it cannot be
1826 * processed at this time.
1828 if (is_next_epoch) {
1829 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1830 if (dtls1_buffer_record
1831 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1836 RECORD_LAYER_reset_packet_length(&s->rlayer);
1840 if (!dtls1_process_record(s, bitmap)) {
1842 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1843 goto again; /* get another record */