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 * TODO(TLS1.3): This callback only provides the "outer" record
252 * type to the callback. Somehow we need to pass the "inner"
256 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
257 s->msg_callback_arg);
259 /* Pull apart the header into the SSL3_RECORD */
260 if (!PACKET_get_1(&pkt, &type)
261 || !PACKET_get_net_2(&pkt, &version)
262 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
263 al = SSL_AD_INTERNAL_ERROR;
264 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
268 thisrr->rec_version = version;
270 /* Lets check version. In TLSv1.3 we ignore this field */
271 if (!s->first_packet && !SSL_IS_TLS13(s)
272 && version != (unsigned int)s->version) {
273 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
274 if ((s->version & 0xFF00) == (version & 0xFF00)
275 && !s->enc_write_ctx && !s->write_hash) {
276 if (thisrr->type == SSL3_RT_ALERT) {
278 * The record is using an incorrect version number,
279 * but what we've got appears to be an alert. We
280 * haven't read the body yet to check whether its a
281 * fatal or not - but chances are it is. We probably
282 * shouldn't send a fatal alert back. We'll just
288 * Send back error using their minor version number :-)
290 s->version = (unsigned short)version;
292 al = SSL_AD_PROTOCOL_VERSION;
296 if ((version >> 8) != SSL3_VERSION_MAJOR) {
297 if (RECORD_LAYER_is_first_record(&s->rlayer)) {
298 /* Go back to start of packet, look at the five bytes
300 p = RECORD_LAYER_get_packet(&s->rlayer);
301 if (strncmp((char *)p, "GET ", 4) == 0 ||
302 strncmp((char *)p, "POST ", 5) == 0 ||
303 strncmp((char *)p, "HEAD ", 5) == 0 ||
304 strncmp((char *)p, "PUT ", 4) == 0) {
305 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
307 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
308 SSLerr(SSL_F_SSL3_GET_RECORD,
309 SSL_R_HTTPS_PROXY_REQUEST);
313 /* Doesn't look like TLS - don't send an alert */
314 SSLerr(SSL_F_SSL3_GET_RECORD,
315 SSL_R_WRONG_VERSION_NUMBER);
318 SSLerr(SSL_F_SSL3_GET_RECORD,
319 SSL_R_WRONG_VERSION_NUMBER);
320 al = SSL_AD_PROTOCOL_VERSION;
325 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
326 && thisrr->type != SSL3_RT_APPLICATION_DATA) {
327 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
328 al = SSL_AD_UNEXPECTED_MESSAGE;
333 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
334 al = SSL_AD_RECORD_OVERFLOW;
335 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
340 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
343 if (SSL_IS_TLS13(s)) {
344 if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
345 al = SSL_AD_RECORD_OVERFLOW;
346 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
350 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
352 if (s->expand == NULL)
353 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
355 if (thisrr->length > len) {
356 al = SSL_AD_RECORD_OVERFLOW;
357 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
363 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
364 * Calculate how much more data we need to read for the rest of the
367 if (thisrr->rec_version == SSL2_VERSION) {
368 more = thisrr->length + SSL2_RT_HEADER_LENGTH
369 - SSL3_RT_HEADER_LENGTH;
371 more = thisrr->length;
374 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
376 rret = ssl3_read_n(s, more, more, 1, 0, &n);
378 return rret; /* error or non-blocking io */
381 /* set state for later operations */
382 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
385 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
386 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
387 * + thisrr->length and we have that many bytes in s->packet
389 if (thisrr->rec_version == SSL2_VERSION) {
391 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
394 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
398 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
399 * points at thisrr->length bytes, which need to be copied into
400 * thisrr->data by either the decryption or by the decompression When
401 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
402 * be pointed at the new buffer
406 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
407 * thisrr->length bytes of encrypted compressed stuff.
410 /* decrypt in place in 'thisrr->input' */
411 thisrr->data = thisrr->input;
412 thisrr->orig_len = thisrr->length;
414 /* Mark this record as not read by upper layers yet */
419 /* we have pulled in a full packet so zero things */
420 RECORD_LAYER_reset_packet_length(&s->rlayer);
421 RECORD_LAYER_clear_first_record(&s->rlayer);
422 } while (num_recs < max_recs
423 && thisrr->type == SSL3_RT_APPLICATION_DATA
424 && SSL_USE_EXPLICIT_IV(s)
425 && s->enc_read_ctx != NULL
426 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
427 & EVP_CIPH_FLAG_PIPELINE)
428 && ssl3_record_app_data_waiting(s));
431 * If in encrypt-then-mac mode calculate mac from encrypted record. All
432 * the details below are public so no timing details can leak.
434 if (SSL_READ_ETM(s) && s->read_hash) {
436 /* TODO(size_t): convert this to do size_t properly */
437 imac_size = EVP_MD_CTX_size(s->read_hash);
438 assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
439 if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
440 al = SSL_AD_INTERNAL_ERROR;
441 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
444 mac_size = (size_t)imac_size;
445 for (j = 0; j < num_recs; j++) {
448 if (thisrr->length < mac_size) {
449 al = SSL_AD_DECODE_ERROR;
450 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
453 thisrr->length -= mac_size;
454 mac = thisrr->data + thisrr->length;
455 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
456 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
457 al = SSL_AD_BAD_RECORD_MAC;
458 SSLerr(SSL_F_SSL3_GET_RECORD,
459 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
465 first_rec_len = rr[0].length;
467 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
471 * 0: (in non-constant time) if the record is publicly invalid.
472 * 1: if the padding is valid
473 * -1: if the padding is invalid
476 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
478 * Valid early_data that we cannot decrypt might fail here as
479 * publicly invalid. We treat it like an empty record.
484 if (!early_data_count_ok(s, thisrr->length,
485 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
490 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
491 RECORD_LAYER_reset_read_sequence(&s->rlayer);
494 al = SSL_AD_DECRYPTION_FAILED;
495 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
499 printf("dec %"OSSLzu"\n", rr[0].length);
502 for (z = 0; z < rr[0].length; z++)
503 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
508 /* r->length is now the compressed data plus mac */
509 if ((sess != NULL) &&
510 (s->enc_read_ctx != NULL) &&
511 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
512 /* s->read_hash != NULL => mac_size != -1 */
513 unsigned char *mac = NULL;
514 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
516 mac_size = EVP_MD_CTX_size(s->read_hash);
517 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
519 for (j = 0; j < num_recs; j++) {
522 * orig_len is the length of the record before any padding was
523 * removed. This is public information, as is the MAC in use,
524 * therefore we can safely process the record in a different amount
525 * of time if it's too short to possibly contain a MAC.
527 if (thisrr->orig_len < mac_size ||
528 /* CBC records must have a padding length byte too. */
529 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
530 thisrr->orig_len < mac_size + 1)) {
531 al = SSL_AD_DECODE_ERROR;
532 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
536 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
538 * We update the length so that the TLS header bytes can be
539 * constructed correctly but we need to extract the MAC in
540 * constant time from within the record, without leaking the
541 * contents of the padding bytes.
544 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
545 thisrr->length -= mac_size;
548 * In this case there's no padding, so |rec->orig_len| equals
549 * |rec->length| and we checked that there's enough bytes for
552 thisrr->length -= mac_size;
553 mac = &thisrr->data[thisrr->length];
556 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
557 if (i == 0 || mac == NULL
558 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
560 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
566 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
568 * We assume this is unreadable early_data - we treat it like an
573 * The record length may have been modified by the mac check above
574 * so we use the previously saved value
576 if (!early_data_count_ok(s, first_rec_len,
577 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
583 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
584 RECORD_LAYER_reset_read_sequence(&s->rlayer);
588 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
589 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
590 * failure is directly visible from the ciphertext anyway, we should
591 * not reveal which kind of error occurred -- this might become
592 * visible to an attacker (e.g. via a logfile)
594 al = SSL_AD_BAD_RECORD_MAC;
595 SSLerr(SSL_F_SSL3_GET_RECORD,
596 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
600 for (j = 0; j < num_recs; j++) {
603 /* thisrr->length is now just compressed */
604 if (s->expand != NULL) {
605 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
606 al = SSL_AD_RECORD_OVERFLOW;
607 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
610 if (!ssl3_do_uncompress(s, thisrr)) {
611 al = SSL_AD_DECOMPRESSION_FAILURE;
612 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
617 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
620 if (thisrr->length == 0) {
621 al = SSL_AD_UNEXPECTED_MESSAGE;
622 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
626 /* Strip trailing padding */
627 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
631 thisrr->length = end;
632 thisrr->type = thisrr->data[end];
633 if (thisrr->type != SSL3_RT_APPLICATION_DATA
634 && thisrr->type != SSL3_RT_ALERT
635 && thisrr->type != SSL3_RT_HANDSHAKE) {
636 al = SSL_AD_UNEXPECTED_MESSAGE;
637 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
642 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
643 al = SSL_AD_RECORD_OVERFLOW;
644 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
650 * So at this point the following is true
651 * thisrr->type is the type of record
652 * thisrr->length == number of bytes in record
653 * thisrr->off == offset to first valid byte
654 * thisrr->data == where to take bytes from, increment after use :-).
657 /* just read a 0 length packet */
658 if (thisrr->length == 0) {
659 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
660 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
661 > MAX_EMPTY_RECORDS) {
662 al = SSL_AD_UNEXPECTED_MESSAGE;
663 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
667 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
671 if (s->early_data_state == SSL_EARLY_DATA_READING) {
673 if (thisrr->type == SSL3_RT_APPLICATION_DATA
674 && !early_data_count_ok(s, thisrr->length, 0, &al))
678 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
682 ssl3_send_alert(s, SSL3_AL_FATAL, al);
687 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
689 #ifndef OPENSSL_NO_COMP
692 if (rr->comp == NULL) {
693 rr->comp = (unsigned char *)
694 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
696 if (rr->comp == NULL)
699 /* TODO(size_t): Convert this call */
700 i = COMP_expand_block(ssl->expand, rr->comp,
701 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
711 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
713 #ifndef OPENSSL_NO_COMP
716 /* TODO(size_t): Convert this call */
717 i = COMP_compress_block(ssl->compress, wr->data,
718 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
719 wr->input, (int)wr->length);
725 wr->input = wr->data;
731 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
734 * 0: (in non-constant time) if the record is publically invalid (i.e. too
736 * 1: if the record's padding is valid / the encryption was successful.
737 * -1: if the record's padding is invalid or, if sending, an internal error
740 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send)
745 size_t bs, mac_size = 0;
747 const EVP_CIPHER *enc;
751 * We shouldn't ever be called with more than one record in the SSLv3 case
756 ds = s->enc_write_ctx;
757 if (s->enc_write_ctx == NULL)
760 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
762 ds = s->enc_read_ctx;
763 if (s->enc_read_ctx == NULL)
766 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
769 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
770 memmove(rec->data, rec->input, rec->length);
771 rec->input = rec->data;
774 /* TODO(size_t): Convert this call */
775 bs = EVP_CIPHER_CTX_block_size(ds);
779 if ((bs != 1) && send) {
782 /* we need to add 'i-1' padding bytes */
785 * the last of these zero bytes will be overwritten with the
788 memset(&rec->input[rec->length], 0, i);
790 rec->input[l - 1] = (unsigned char)(i - 1);
794 if (l == 0 || l % bs != 0)
796 /* otherwise, rec->length >= bs */
799 /* TODO(size_t): Convert this call */
800 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
803 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
804 /* TODO(size_t): convert me */
805 imac_size = EVP_MD_CTX_size(s->read_hash);
808 mac_size = (size_t)imac_size;
810 if ((bs != 1) && !send)
811 return ssl3_cbc_remove_padding(rec, bs, mac_size);
816 #define MAX_PADDING 256
818 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
821 * 0: (in non-constant time) if the record is publically invalid (i.e. too
823 * 1: if the record's padding is valid / the encryption was successful.
824 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
825 * an internal error occurred.
827 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
830 size_t reclen[SSL_MAX_PIPELINES];
831 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
832 int i, pad = 0, ret, tmpr;
833 size_t bs, mac_size = 0, ctr, padnum, loop;
834 unsigned char padval;
836 const EVP_CIPHER *enc;
842 if (EVP_MD_CTX_md(s->write_hash)) {
843 int n = EVP_MD_CTX_size(s->write_hash);
844 OPENSSL_assert(n >= 0);
846 ds = s->enc_write_ctx;
847 if (s->enc_write_ctx == NULL)
851 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
852 /* For TLSv1.1 and later explicit IV */
853 if (SSL_USE_EXPLICIT_IV(s)
854 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
855 ivlen = EVP_CIPHER_iv_length(enc);
859 for (ctr = 0; ctr < n_recs; ctr++) {
860 if (recs[ctr].data != recs[ctr].input) {
862 * we can't write into the input stream: Can this ever
865 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
867 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
868 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
875 if (EVP_MD_CTX_md(s->read_hash)) {
876 int n = EVP_MD_CTX_size(s->read_hash);
877 OPENSSL_assert(n >= 0);
879 ds = s->enc_read_ctx;
880 if (s->enc_read_ctx == NULL)
883 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
886 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
887 for (ctr = 0; ctr < n_recs; ctr++) {
888 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
889 recs[ctr].input = recs[ctr].data;
893 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
896 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
897 & EVP_CIPH_FLAG_PIPELINE)) {
899 * We shouldn't have been called with pipeline data if the
900 * cipher doesn't support pipelining
902 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
906 for (ctr = 0; ctr < n_recs; ctr++) {
907 reclen[ctr] = recs[ctr].length;
909 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
910 & EVP_CIPH_FLAG_AEAD_CIPHER) {
913 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
914 : RECORD_LAYER_get_read_sequence(&s->rlayer);
916 if (SSL_IS_DTLS(s)) {
917 /* DTLS does not support pipelining */
918 unsigned char dtlsseq[9], *p = dtlsseq;
920 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
921 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
922 memcpy(p, &seq[2], 6);
923 memcpy(buf[ctr], dtlsseq, 8);
925 memcpy(buf[ctr], seq, 8);
926 for (i = 7; i >= 0; i--) { /* increment */
933 buf[ctr][8] = recs[ctr].type;
934 buf[ctr][9] = (unsigned char)(s->version >> 8);
935 buf[ctr][10] = (unsigned char)(s->version);
936 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
937 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
938 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
939 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
945 recs[ctr].length += pad;
948 } else if ((bs != 1) && send) {
949 padnum = bs - (reclen[ctr] % bs);
951 /* Add weird padding of upto 256 bytes */
953 if (padnum > MAX_PADDING)
955 /* we need to add 'padnum' padding bytes of value padval */
956 padval = (unsigned char)(padnum - 1);
957 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
958 recs[ctr].input[loop] = padval;
959 reclen[ctr] += padnum;
960 recs[ctr].length += padnum;
964 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
969 unsigned char *data[SSL_MAX_PIPELINES];
971 /* Set the output buffers */
972 for (ctr = 0; ctr < n_recs; ctr++) {
973 data[ctr] = recs[ctr].data;
975 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
976 (int)n_recs, data) <= 0) {
977 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
979 /* Set the input buffers */
980 for (ctr = 0; ctr < n_recs; ctr++) {
981 data[ctr] = recs[ctr].input;
983 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
984 (int)n_recs, data) <= 0
985 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
986 (int)n_recs, reclen) <= 0) {
987 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
992 /* TODO(size_t): Convert this call */
993 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
994 (unsigned int)reclen[0]);
995 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
996 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
999 return -1; /* AEAD can fail to verify MAC */
1001 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1002 for (ctr = 0; ctr < n_recs; ctr++) {
1003 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1004 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1005 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1007 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1008 for (ctr = 0; ctr < n_recs; ctr++) {
1009 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1010 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1011 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1017 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1018 imac_size = EVP_MD_CTX_size(s->read_hash);
1021 mac_size = (size_t)imac_size;
1023 if ((bs != 1) && !send) {
1025 for (ctr = 0; ctr < n_recs; ctr++) {
1026 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1028 * If tmpret == 0 then this means publicly invalid so we can
1029 * short circuit things here. Otherwise we must respect constant
1034 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1039 for (ctr = 0; ctr < n_recs; ctr++) {
1040 recs[ctr].length -= pad;
1047 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1049 unsigned char *mac_sec, *seq;
1050 const EVP_MD_CTX *hash;
1051 unsigned char *p, rec_char;
1057 mac_sec = &(ssl->s3->write_mac_secret[0]);
1058 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1059 hash = ssl->write_hash;
1061 mac_sec = &(ssl->s3->read_mac_secret[0]);
1062 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1063 hash = ssl->read_hash;
1066 t = EVP_MD_CTX_size(hash);
1070 npad = (48 / md_size) * md_size;
1073 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1074 ssl3_cbc_record_digest_supported(hash)) {
1076 * This is a CBC-encrypted record. We must avoid leaking any
1077 * timing-side channel information about how many blocks of data we
1078 * are hashing because that gives an attacker a timing-oracle.
1082 * npad is, at most, 48 bytes and that's with MD5:
1083 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1085 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1086 * goes up 4, but npad goes down by 8, resulting in a smaller
1089 unsigned char header[75];
1091 memcpy(header + j, mac_sec, md_size);
1093 memcpy(header + j, ssl3_pad_1, npad);
1095 memcpy(header + j, seq, 8);
1097 header[j++] = rec->type;
1098 header[j++] = (unsigned char)(rec->length >> 8);
1099 header[j++] = (unsigned char)(rec->length & 0xff);
1101 /* Final param == is SSLv3 */
1102 if (ssl3_cbc_digest_record(hash,
1105 rec->length + md_size, rec->orig_len,
1106 mac_sec, md_size, 1) <= 0)
1109 unsigned int md_size_u;
1110 /* Chop the digest off the end :-) */
1111 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1116 rec_char = rec->type;
1118 s2n(rec->length, p);
1119 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1120 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1121 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1122 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1123 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1124 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1125 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1126 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1127 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1128 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1129 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1130 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1131 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1132 EVP_MD_CTX_reset(md_ctx);
1136 EVP_MD_CTX_free(md_ctx);
1139 ssl3_record_sequence_update(seq);
1143 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1149 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1150 unsigned char header[13];
1151 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1152 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1156 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1157 hash = ssl->write_hash;
1159 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1160 hash = ssl->read_hash;
1163 t = EVP_MD_CTX_size(hash);
1164 OPENSSL_assert(t >= 0);
1167 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1171 hmac = EVP_MD_CTX_new();
1172 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1177 if (SSL_IS_DTLS(ssl)) {
1178 unsigned char dtlsseq[8], *p = dtlsseq;
1180 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1181 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1182 memcpy(p, &seq[2], 6);
1184 memcpy(header, dtlsseq, 8);
1186 memcpy(header, seq, 8);
1188 header[8] = rec->type;
1189 header[9] = (unsigned char)(ssl->version >> 8);
1190 header[10] = (unsigned char)(ssl->version);
1191 header[11] = (unsigned char)(rec->length >> 8);
1192 header[12] = (unsigned char)(rec->length & 0xff);
1194 if (!send && !SSL_READ_ETM(ssl) &&
1195 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1196 ssl3_cbc_record_digest_supported(mac_ctx)) {
1198 * This is a CBC-encrypted record. We must avoid leaking any
1199 * timing-side channel information about how many blocks of data we
1200 * are hashing because that gives an attacker a timing-oracle.
1202 /* Final param == not SSLv3 */
1203 if (ssl3_cbc_digest_record(mac_ctx,
1206 rec->length + md_size, rec->orig_len,
1207 ssl->s3->read_mac_secret,
1208 ssl->s3->read_mac_secret_size, 0) <= 0) {
1209 EVP_MD_CTX_free(hmac);
1213 /* TODO(size_t): Convert these calls */
1214 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1215 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1216 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1217 EVP_MD_CTX_free(hmac);
1222 EVP_MD_CTX_free(hmac);
1225 fprintf(stderr, "seq=");
1228 for (z = 0; z < 8; z++)
1229 fprintf(stderr, "%02X ", seq[z]);
1230 fprintf(stderr, "\n");
1232 fprintf(stderr, "rec=");
1235 for (z = 0; z < rec->length; z++)
1236 fprintf(stderr, "%02X ", rec->data[z]);
1237 fprintf(stderr, "\n");
1241 if (!SSL_IS_DTLS(ssl)) {
1242 for (i = 7; i >= 0; i--) {
1251 for (z = 0; z < md_size; z++)
1252 fprintf(stderr, "%02X ", md[z]);
1253 fprintf(stderr, "\n");
1260 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1261 * record in |rec| by updating |rec->length| in constant time.
1263 * block_size: the block size of the cipher used to encrypt the record.
1265 * 0: (in non-constant time) if the record is publicly invalid.
1266 * 1: if the padding was valid
1269 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1270 size_t block_size, size_t mac_size)
1272 size_t padding_length;
1274 const size_t overhead = 1 /* padding length byte */ + mac_size;
1277 * These lengths are all public so we can test them in non-constant time.
1279 if (overhead > rec->length)
1282 padding_length = rec->data[rec->length - 1];
1283 good = constant_time_ge_s(rec->length, padding_length + overhead);
1284 /* SSLv3 requires that the padding is minimal. */
1285 good &= constant_time_ge_s(block_size, padding_length + 1);
1286 rec->length -= good & (padding_length + 1);
1287 return constant_time_select_int_s(good, 1, -1);
1291 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1292 * record in |rec| in constant time and returns 1 if the padding is valid and
1293 * -1 otherwise. It also removes any explicit IV from the start of the record
1294 * without leaking any timing about whether there was enough space after the
1295 * padding was removed.
1297 * block_size: the block size of the cipher used to encrypt the record.
1299 * 0: (in non-constant time) if the record is publicly invalid.
1300 * 1: if the padding was valid
1303 int tls1_cbc_remove_padding(const SSL *s,
1305 size_t block_size, size_t mac_size)
1308 size_t padding_length, to_check, i;
1309 const size_t overhead = 1 /* padding length byte */ + mac_size;
1310 /* Check if version requires explicit IV */
1311 if (SSL_USE_EXPLICIT_IV(s)) {
1313 * These lengths are all public so we can test them in non-constant
1316 if (overhead + block_size > rec->length)
1318 /* We can now safely skip explicit IV */
1319 rec->data += block_size;
1320 rec->input += block_size;
1321 rec->length -= block_size;
1322 rec->orig_len -= block_size;
1323 } else if (overhead > rec->length)
1326 padding_length = rec->data[rec->length - 1];
1328 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1329 EVP_CIPH_FLAG_AEAD_CIPHER) {
1330 /* padding is already verified */
1331 rec->length -= padding_length + 1;
1335 good = constant_time_ge_s(rec->length, overhead + padding_length);
1337 * The padding consists of a length byte at the end of the record and
1338 * then that many bytes of padding, all with the same value as the length
1339 * byte. Thus, with the length byte included, there are i+1 bytes of
1340 * padding. We can't check just |padding_length+1| bytes because that
1341 * leaks decrypted information. Therefore we always have to check the
1342 * maximum amount of padding possible. (Again, the length of the record
1343 * is public information so we can use it.)
1345 to_check = 256; /* maximum amount of padding, inc length byte. */
1346 if (to_check > rec->length)
1347 to_check = rec->length;
1349 for (i = 0; i < to_check; i++) {
1350 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1351 unsigned char b = rec->data[rec->length - 1 - i];
1353 * The final |padding_length+1| bytes should all have the value
1354 * |padding_length|. Therefore the XOR should be zero.
1356 good &= ~(mask & (padding_length ^ b));
1360 * If any of the final |padding_length+1| bytes had the wrong value, one
1361 * or more of the lower eight bits of |good| will be cleared.
1363 good = constant_time_eq_s(0xff, good & 0xff);
1364 rec->length -= good & (padding_length + 1);
1366 return constant_time_select_int_s(good, 1, -1);
1370 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1371 * constant time (independent of the concrete value of rec->length, which may
1372 * vary within a 256-byte window).
1374 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1378 * rec->orig_len >= md_size
1379 * md_size <= EVP_MAX_MD_SIZE
1381 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1382 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1383 * a single or pair of cache-lines, then the variable memory accesses don't
1384 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1385 * not multi-core and are not considered vulnerable to cache-timing attacks.
1387 #define CBC_MAC_ROTATE_IN_PLACE
1389 void ssl3_cbc_copy_mac(unsigned char *out,
1390 const SSL3_RECORD *rec, size_t md_size)
1392 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1393 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1394 unsigned char *rotated_mac;
1396 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1400 * mac_end is the index of |rec->data| just after the end of the MAC.
1402 size_t mac_end = rec->length;
1403 size_t mac_start = mac_end - md_size;
1406 * scan_start contains the number of bytes that we can ignore because the
1407 * MAC's position can only vary by 255 bytes.
1409 size_t scan_start = 0;
1411 size_t rotate_offset;
1413 OPENSSL_assert(rec->orig_len >= md_size);
1414 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1416 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1417 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1420 /* This information is public so it's safe to branch based on it. */
1421 if (rec->orig_len > md_size + 255 + 1)
1422 scan_start = rec->orig_len - (md_size + 255 + 1);
1426 memset(rotated_mac, 0, md_size);
1427 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1428 size_t mac_started = constant_time_eq_s(i, mac_start);
1429 size_t mac_ended = constant_time_lt_s(i, mac_end);
1430 unsigned char b = rec->data[i];
1432 in_mac |= mac_started;
1433 in_mac &= mac_ended;
1434 rotate_offset |= j & mac_started;
1435 rotated_mac[j++] |= b & in_mac;
1436 j &= constant_time_lt_s(j, md_size);
1439 /* Now rotate the MAC */
1440 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1442 for (i = 0; i < md_size; i++) {
1443 /* in case cache-line is 32 bytes, touch second line */
1444 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1445 out[j++] = rotated_mac[rotate_offset++];
1446 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1449 memset(out, 0, md_size);
1450 rotate_offset = md_size - rotate_offset;
1451 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1452 for (i = 0; i < md_size; i++) {
1453 for (j = 0; j < md_size; j++)
1454 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1456 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1461 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1469 unsigned char md[EVP_MAX_MD_SIZE];
1471 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1475 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1476 * and we have that many bytes in s->packet
1478 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1481 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1482 * at rr->length bytes, which need to be copied into rr->data by either
1483 * the decryption or by the decompression When the data is 'copied' into
1484 * the rr->data buffer, rr->input will be pointed at the new buffer
1488 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1489 * bytes of encrypted compressed stuff.
1492 /* check is not needed I believe */
1493 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1494 al = SSL_AD_RECORD_OVERFLOW;
1495 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1499 /* decrypt in place in 'rr->input' */
1500 rr->data = rr->input;
1501 rr->orig_len = rr->length;
1503 if (SSL_READ_ETM(s) && s->read_hash) {
1505 mac_size = EVP_MD_CTX_size(s->read_hash);
1506 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1507 if (rr->orig_len < mac_size) {
1508 al = SSL_AD_DECODE_ERROR;
1509 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1512 rr->length -= mac_size;
1513 mac = rr->data + rr->length;
1514 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1515 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1516 al = SSL_AD_BAD_RECORD_MAC;
1517 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1518 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1523 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1526 * 0: (in non-constant time) if the record is publically invalid.
1527 * 1: if the padding is valid
1528 * -1: if the padding is invalid
1531 /* For DTLS we simply ignore bad packets. */
1533 RECORD_LAYER_reset_packet_length(&s->rlayer);
1537 printf("dec %ld\n", rr->length);
1540 for (z = 0; z < rr->length; z++)
1541 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1546 /* r->length is now the compressed data plus mac */
1547 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1548 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1549 /* s->read_hash != NULL => mac_size != -1 */
1550 unsigned char *mac = NULL;
1551 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1553 /* TODO(size_t): Convert this to do size_t properly */
1554 imac_size = EVP_MD_CTX_size(s->read_hash);
1555 if (imac_size < 0) {
1556 al = SSL_AD_INTERNAL_ERROR;
1557 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1560 mac_size = (size_t)imac_size;
1561 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1564 * orig_len is the length of the record before any padding was
1565 * removed. This is public information, as is the MAC in use,
1566 * therefore we can safely process the record in a different amount
1567 * of time if it's too short to possibly contain a MAC.
1569 if (rr->orig_len < mac_size ||
1570 /* CBC records must have a padding length byte too. */
1571 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1572 rr->orig_len < mac_size + 1)) {
1573 al = SSL_AD_DECODE_ERROR;
1574 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1578 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1580 * We update the length so that the TLS header bytes can be
1581 * constructed correctly but we need to extract the MAC in
1582 * constant time from within the record, without leaking the
1583 * contents of the padding bytes.
1586 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1587 rr->length -= mac_size;
1590 * In this case there's no padding, so |rec->orig_len| equals
1591 * |rec->length| and we checked that there's enough bytes for
1594 rr->length -= mac_size;
1595 mac = &rr->data[rr->length];
1598 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1599 if (i == 0 || mac == NULL
1600 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1602 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1607 /* decryption failed, silently discard message */
1609 RECORD_LAYER_reset_packet_length(&s->rlayer);
1613 /* r->length is now just compressed */
1614 if (s->expand != NULL) {
1615 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1616 al = SSL_AD_RECORD_OVERFLOW;
1617 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1618 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1621 if (!ssl3_do_uncompress(s, rr)) {
1622 al = SSL_AD_DECOMPRESSION_FAILURE;
1623 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1628 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1629 al = SSL_AD_RECORD_OVERFLOW;
1630 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1636 * So at this point the following is true
1637 * ssl->s3->rrec.type is the type of record
1638 * ssl->s3->rrec.length == number of bytes in record
1639 * ssl->s3->rrec.off == offset to first valid byte
1640 * ssl->s3->rrec.data == where to take bytes from, increment
1644 /* we have pulled in a full packet so zero things */
1645 RECORD_LAYER_reset_packet_length(&s->rlayer);
1647 /* Mark receipt of record. */
1648 dtls1_record_bitmap_update(s, bitmap);
1653 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1659 * retrieve a buffered record that belongs to the current epoch, ie,
1662 #define dtls1_get_processed_record(s) \
1663 dtls1_retrieve_buffered_record((s), \
1664 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1667 * Call this to get a new input record.
1668 * It will return <= 0 if more data is needed, normally due to an error
1669 * or non-blocking IO.
1670 * When it finishes, one packet has been decoded and can be found in
1671 * ssl->s3->rrec.type - is the type of record
1672 * ssl->s3->rrec.data, - data
1673 * ssl->s3->rrec.length, - number of bytes
1675 /* used only by dtls1_read_bytes */
1676 int dtls1_get_record(SSL *s)
1678 int ssl_major, ssl_minor;
1682 unsigned char *p = NULL;
1683 unsigned short version;
1684 DTLS1_BITMAP *bitmap;
1685 unsigned int is_next_epoch;
1687 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1691 * The epoch may have changed. If so, process all the pending records.
1692 * This is a non-blocking operation.
1694 if (!dtls1_process_buffered_records(s))
1697 /* if we're renegotiating, then there may be buffered records */
1698 if (dtls1_get_processed_record(s))
1701 /* get something from the wire */
1703 /* check if we have the header */
1704 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1705 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1706 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1707 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1708 /* read timeout is handled by dtls1_read_bytes */
1710 return rret; /* error or non-blocking */
1712 /* this packet contained a partial record, dump it */
1713 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1714 DTLS1_RT_HEADER_LENGTH) {
1715 RECORD_LAYER_reset_packet_length(&s->rlayer);
1719 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1721 p = RECORD_LAYER_get_packet(&s->rlayer);
1723 if (s->msg_callback)
1724 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1725 s, s->msg_callback_arg);
1727 /* Pull apart the header into the DTLS1_RECORD */
1731 version = (ssl_major << 8) | ssl_minor;
1733 /* sequence number is 64 bits, with top 2 bytes = epoch */
1736 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1741 /* Lets check version */
1742 if (!s->first_packet) {
1743 if (version != s->version) {
1744 /* unexpected version, silently discard */
1746 RECORD_LAYER_reset_packet_length(&s->rlayer);
1751 if ((version & 0xff00) != (s->version & 0xff00)) {
1752 /* wrong version, silently discard record */
1754 RECORD_LAYER_reset_packet_length(&s->rlayer);
1758 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1759 /* record too long, silently discard it */
1761 RECORD_LAYER_reset_packet_length(&s->rlayer);
1765 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1768 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1771 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1772 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1774 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1775 /* this packet contained a partial record, dump it */
1776 if (rret <= 0 || n != more) {
1778 RECORD_LAYER_reset_packet_length(&s->rlayer);
1783 * now n == rr->length, and s->packet_length ==
1784 * DTLS1_RT_HEADER_LENGTH + rr->length
1787 /* set state for later operations */
1788 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1790 /* match epochs. NULL means the packet is dropped on the floor */
1791 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1792 if (bitmap == NULL) {
1794 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1795 goto again; /* get another record */
1797 #ifndef OPENSSL_NO_SCTP
1798 /* Only do replay check if no SCTP bio */
1799 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1801 /* Check whether this is a repeat, or aged record. */
1803 * TODO: Does it make sense to have replay protection in epoch 0 where
1804 * we have no integrity negotiated yet?
1806 if (!dtls1_record_replay_check(s, bitmap)) {
1808 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1809 goto again; /* get another record */
1811 #ifndef OPENSSL_NO_SCTP
1815 /* just read a 0 length packet */
1816 if (rr->length == 0)
1820 * If this record is from the next epoch (either HM or ALERT), and a
1821 * handshake is currently in progress, buffer it since it cannot be
1822 * processed at this time.
1824 if (is_next_epoch) {
1825 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1826 if (dtls1_buffer_record
1827 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1832 RECORD_LAYER_reset_packet_length(&s->rlayer);
1836 if (!dtls1_process_record(s, bitmap)) {
1838 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1839 goto again; /* get another record */