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 */
344 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
345 * Calculate how much more data we need to read for the rest of the
348 if (thisrr->rec_version == SSL2_VERSION) {
349 more = thisrr->length + SSL2_RT_HEADER_LENGTH
350 - SSL3_RT_HEADER_LENGTH;
352 more = thisrr->length;
355 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
357 rret = ssl3_read_n(s, more, more, 1, 0, &n);
359 return rret; /* error or non-blocking io */
362 /* set state for later operations */
363 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
366 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
367 * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
368 * + thisrr->length and we have that many bytes in s->packet
370 if (thisrr->rec_version == SSL2_VERSION) {
372 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
375 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
379 * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
380 * points at thisrr->length bytes, which need to be copied into
381 * thisrr->data by either the decryption or by the decompression When
382 * the data is 'copied' into the thisrr->data buffer, thisrr->input will
383 * be pointed at the new buffer
387 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
388 * thisrr->length bytes of encrypted compressed stuff.
391 /* check is not needed I believe */
392 if (thisrr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
393 al = SSL_AD_RECORD_OVERFLOW;
394 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
398 /* decrypt in place in 'thisrr->input' */
399 thisrr->data = thisrr->input;
400 thisrr->orig_len = thisrr->length;
402 /* Mark this record as not read by upper layers yet */
407 /* we have pulled in a full packet so zero things */
408 RECORD_LAYER_reset_packet_length(&s->rlayer);
409 RECORD_LAYER_clear_first_record(&s->rlayer);
410 } while (num_recs < max_recs
411 && thisrr->type == SSL3_RT_APPLICATION_DATA
412 && SSL_USE_EXPLICIT_IV(s)
413 && s->enc_read_ctx != NULL
414 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
415 & EVP_CIPH_FLAG_PIPELINE)
416 && ssl3_record_app_data_waiting(s));
419 * If in encrypt-then-mac mode calculate mac from encrypted record. All
420 * the details below are public so no timing details can leak.
422 if (SSL_READ_ETM(s) && s->read_hash) {
424 /* TODO(size_t): convert this to do size_t properly */
425 imac_size = EVP_MD_CTX_size(s->read_hash);
426 assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
427 if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
428 al = SSL_AD_INTERNAL_ERROR;
429 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
432 mac_size = (size_t)imac_size;
433 for (j = 0; j < num_recs; j++) {
436 if (thisrr->length < mac_size) {
437 al = SSL_AD_DECODE_ERROR;
438 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
441 thisrr->length -= mac_size;
442 mac = thisrr->data + thisrr->length;
443 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
444 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
445 al = SSL_AD_BAD_RECORD_MAC;
446 SSLerr(SSL_F_SSL3_GET_RECORD,
447 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
453 first_rec_len = rr[0].length;
455 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
459 * 0: (in non-constant time) if the record is publicly invalid.
460 * 1: if the padding is valid
461 * -1: if the padding is invalid
464 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
466 * Valid early_data that we cannot decrypt might fail here as
467 * publicly invalid. We treat it like an empty record.
472 if (!early_data_count_ok(s, thisrr->length,
473 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
478 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
479 RECORD_LAYER_reset_read_sequence(&s->rlayer);
482 al = SSL_AD_DECRYPTION_FAILED;
483 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
487 printf("dec %"OSSLzu"\n", rr[0].length);
490 for (z = 0; z < rr[0].length; z++)
491 printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
496 /* r->length is now the compressed data plus mac */
497 if ((sess != NULL) &&
498 (s->enc_read_ctx != NULL) &&
499 (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
500 /* s->read_hash != NULL => mac_size != -1 */
501 unsigned char *mac = NULL;
502 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
504 mac_size = EVP_MD_CTX_size(s->read_hash);
505 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
507 for (j = 0; j < num_recs; j++) {
510 * orig_len is the length of the record before any padding was
511 * removed. This is public information, as is the MAC in use,
512 * therefore we can safely process the record in a different amount
513 * of time if it's too short to possibly contain a MAC.
515 if (thisrr->orig_len < mac_size ||
516 /* CBC records must have a padding length byte too. */
517 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
518 thisrr->orig_len < mac_size + 1)) {
519 al = SSL_AD_DECODE_ERROR;
520 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
524 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
526 * We update the length so that the TLS header bytes can be
527 * constructed correctly but we need to extract the MAC in
528 * constant time from within the record, without leaking the
529 * contents of the padding bytes.
532 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
533 thisrr->length -= mac_size;
536 * In this case there's no padding, so |rec->orig_len| equals
537 * |rec->length| and we checked that there's enough bytes for
540 thisrr->length -= mac_size;
541 mac = &thisrr->data[thisrr->length];
544 i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
545 if (i == 0 || mac == NULL
546 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
548 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
554 if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
556 * We assume this is unreadable early_data - we treat it like an
561 * The record length may have been modified by the mac check above
562 * so we use the previously saved value
564 if (!early_data_count_ok(s, first_rec_len,
565 EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
571 RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
572 RECORD_LAYER_reset_read_sequence(&s->rlayer);
576 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
577 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
578 * failure is directly visible from the ciphertext anyway, we should
579 * not reveal which kind of error occurred -- this might become
580 * visible to an attacker (e.g. via a logfile)
582 al = SSL_AD_BAD_RECORD_MAC;
583 SSLerr(SSL_F_SSL3_GET_RECORD,
584 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
588 for (j = 0; j < num_recs; j++) {
591 /* thisrr->length is now just compressed */
592 if (s->expand != NULL) {
593 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
594 al = SSL_AD_RECORD_OVERFLOW;
595 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
598 if (!ssl3_do_uncompress(s, thisrr)) {
599 al = SSL_AD_DECOMPRESSION_FAILURE;
600 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
605 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
608 if (thisrr->length == 0) {
609 al = SSL_AD_UNEXPECTED_MESSAGE;
610 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
614 /* Strip trailing padding */
615 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
619 thisrr->length = end;
620 thisrr->type = thisrr->data[end];
621 if (thisrr->type != SSL3_RT_APPLICATION_DATA
622 && thisrr->type != SSL3_RT_ALERT
623 && thisrr->type != SSL3_RT_HANDSHAKE) {
624 al = SSL_AD_UNEXPECTED_MESSAGE;
625 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
630 if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
631 al = SSL_AD_RECORD_OVERFLOW;
632 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
638 * So at this point the following is true
639 * thisrr->type is the type of record
640 * thisrr->length == number of bytes in record
641 * thisrr->off == offset to first valid byte
642 * thisrr->data == where to take bytes from, increment after use :-).
645 /* just read a 0 length packet */
646 if (thisrr->length == 0) {
647 RECORD_LAYER_inc_empty_record_count(&s->rlayer);
648 if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
649 > MAX_EMPTY_RECORDS) {
650 al = SSL_AD_UNEXPECTED_MESSAGE;
651 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
655 RECORD_LAYER_reset_empty_record_count(&s->rlayer);
659 if (s->early_data_state == SSL_EARLY_DATA_READING) {
661 if (thisrr->type == SSL3_RT_APPLICATION_DATA
662 && !early_data_count_ok(s, thisrr->length, 0, &al))
666 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
670 ssl3_send_alert(s, SSL3_AL_FATAL, al);
675 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
677 #ifndef OPENSSL_NO_COMP
680 if (rr->comp == NULL) {
681 rr->comp = (unsigned char *)
682 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
684 if (rr->comp == NULL)
687 /* TODO(size_t): Convert this call */
688 i = COMP_expand_block(ssl->expand, rr->comp,
689 SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
699 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
701 #ifndef OPENSSL_NO_COMP
704 /* TODO(size_t): Convert this call */
705 i = COMP_compress_block(ssl->compress, wr->data,
706 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
707 wr->input, (int)wr->length);
713 wr->input = wr->data;
719 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
722 * 0: (in non-constant time) if the record is publically invalid (i.e. too
724 * 1: if the record's padding is valid / the encryption was successful.
725 * -1: if the record's padding is invalid or, if sending, an internal error
728 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int send)
733 size_t bs, mac_size = 0;
735 const EVP_CIPHER *enc;
739 * We shouldn't ever be called with more than one record in the SSLv3 case
744 ds = s->enc_write_ctx;
745 if (s->enc_write_ctx == NULL)
748 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
750 ds = s->enc_read_ctx;
751 if (s->enc_read_ctx == NULL)
754 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
757 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
758 memmove(rec->data, rec->input, rec->length);
759 rec->input = rec->data;
762 /* TODO(size_t): Convert this call */
763 bs = EVP_CIPHER_CTX_block_size(ds);
767 if ((bs != 1) && send) {
770 /* we need to add 'i-1' padding bytes */
773 * the last of these zero bytes will be overwritten with the
776 memset(&rec->input[rec->length], 0, i);
778 rec->input[l - 1] = (unsigned char)(i - 1);
782 if (l == 0 || l % bs != 0)
784 /* otherwise, rec->length >= bs */
787 /* TODO(size_t): Convert this call */
788 if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
791 if (EVP_MD_CTX_md(s->read_hash) != NULL) {
792 /* TODO(size_t): convert me */
793 imac_size = EVP_MD_CTX_size(s->read_hash);
796 mac_size = (size_t)imac_size;
798 if ((bs != 1) && !send)
799 return ssl3_cbc_remove_padding(rec, bs, mac_size);
804 #define MAX_PADDING 256
806 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
809 * 0: (in non-constant time) if the record is publically invalid (i.e. too
811 * 1: if the record's padding is valid / the encryption was successful.
812 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
813 * an internal error occurred.
815 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int send)
818 size_t reclen[SSL_MAX_PIPELINES];
819 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
820 int i, pad = 0, ret, tmpr;
821 size_t bs, mac_size = 0, ctr, padnum, loop;
822 unsigned char padval;
824 const EVP_CIPHER *enc;
830 if (EVP_MD_CTX_md(s->write_hash)) {
831 int n = EVP_MD_CTX_size(s->write_hash);
832 OPENSSL_assert(n >= 0);
834 ds = s->enc_write_ctx;
835 if (s->enc_write_ctx == NULL)
839 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
840 /* For TLSv1.1 and later explicit IV */
841 if (SSL_USE_EXPLICIT_IV(s)
842 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
843 ivlen = EVP_CIPHER_iv_length(enc);
847 for (ctr = 0; ctr < n_recs; ctr++) {
848 if (recs[ctr].data != recs[ctr].input) {
850 * we can't write into the input stream: Can this ever
853 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
855 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
856 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
863 if (EVP_MD_CTX_md(s->read_hash)) {
864 int n = EVP_MD_CTX_size(s->read_hash);
865 OPENSSL_assert(n >= 0);
867 ds = s->enc_read_ctx;
868 if (s->enc_read_ctx == NULL)
871 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
874 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
875 for (ctr = 0; ctr < n_recs; ctr++) {
876 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
877 recs[ctr].input = recs[ctr].data;
881 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
884 if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
885 & EVP_CIPH_FLAG_PIPELINE)) {
887 * We shouldn't have been called with pipeline data if the
888 * cipher doesn't support pipelining
890 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
894 for (ctr = 0; ctr < n_recs; ctr++) {
895 reclen[ctr] = recs[ctr].length;
897 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
898 & EVP_CIPH_FLAG_AEAD_CIPHER) {
901 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
902 : RECORD_LAYER_get_read_sequence(&s->rlayer);
904 if (SSL_IS_DTLS(s)) {
905 /* DTLS does not support pipelining */
906 unsigned char dtlsseq[9], *p = dtlsseq;
908 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
909 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
910 memcpy(p, &seq[2], 6);
911 memcpy(buf[ctr], dtlsseq, 8);
913 memcpy(buf[ctr], seq, 8);
914 for (i = 7; i >= 0; i--) { /* increment */
921 buf[ctr][8] = recs[ctr].type;
922 buf[ctr][9] = (unsigned char)(s->version >> 8);
923 buf[ctr][10] = (unsigned char)(s->version);
924 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
925 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
926 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
927 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
933 recs[ctr].length += pad;
936 } else if ((bs != 1) && send) {
937 padnum = bs - (reclen[ctr] % bs);
939 /* Add weird padding of upto 256 bytes */
941 if (padnum > MAX_PADDING)
943 /* we need to add 'padnum' padding bytes of value padval */
944 padval = (unsigned char)(padnum - 1);
945 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
946 recs[ctr].input[loop] = padval;
947 reclen[ctr] += padnum;
948 recs[ctr].length += padnum;
952 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
957 unsigned char *data[SSL_MAX_PIPELINES];
959 /* Set the output buffers */
960 for (ctr = 0; ctr < n_recs; ctr++) {
961 data[ctr] = recs[ctr].data;
963 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
964 (int)n_recs, data) <= 0) {
965 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
967 /* Set the input buffers */
968 for (ctr = 0; ctr < n_recs; ctr++) {
969 data[ctr] = recs[ctr].input;
971 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
972 (int)n_recs, data) <= 0
973 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
974 (int)n_recs, reclen) <= 0) {
975 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
980 /* TODO(size_t): Convert this call */
981 tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
982 (unsigned int)reclen[0]);
983 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
984 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
987 return -1; /* AEAD can fail to verify MAC */
989 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
990 for (ctr = 0; ctr < n_recs; ctr++) {
991 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
992 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
993 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
995 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
996 for (ctr = 0; ctr < n_recs; ctr++) {
997 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
998 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
999 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1005 if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1006 imac_size = EVP_MD_CTX_size(s->read_hash);
1009 mac_size = (size_t)imac_size;
1011 if ((bs != 1) && !send) {
1013 for (ctr = 0; ctr < n_recs; ctr++) {
1014 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1016 * If tmpret == 0 then this means publicly invalid so we can
1017 * short circuit things here. Otherwise we must respect constant
1022 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1027 for (ctr = 0; ctr < n_recs; ctr++) {
1028 recs[ctr].length -= pad;
1035 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1037 unsigned char *mac_sec, *seq;
1038 const EVP_MD_CTX *hash;
1039 unsigned char *p, rec_char;
1045 mac_sec = &(ssl->s3->write_mac_secret[0]);
1046 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1047 hash = ssl->write_hash;
1049 mac_sec = &(ssl->s3->read_mac_secret[0]);
1050 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1051 hash = ssl->read_hash;
1054 t = EVP_MD_CTX_size(hash);
1058 npad = (48 / md_size) * md_size;
1061 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1062 ssl3_cbc_record_digest_supported(hash)) {
1064 * This is a CBC-encrypted record. We must avoid leaking any
1065 * timing-side channel information about how many blocks of data we
1066 * are hashing because that gives an attacker a timing-oracle.
1070 * npad is, at most, 48 bytes and that's with MD5:
1071 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1073 * With SHA-1 (the largest hash speced for SSLv3) the hash size
1074 * goes up 4, but npad goes down by 8, resulting in a smaller
1077 unsigned char header[75];
1079 memcpy(header + j, mac_sec, md_size);
1081 memcpy(header + j, ssl3_pad_1, npad);
1083 memcpy(header + j, seq, 8);
1085 header[j++] = rec->type;
1086 header[j++] = (unsigned char)(rec->length >> 8);
1087 header[j++] = (unsigned char)(rec->length & 0xff);
1089 /* Final param == is SSLv3 */
1090 if (ssl3_cbc_digest_record(hash,
1093 rec->length + md_size, rec->orig_len,
1094 mac_sec, md_size, 1) <= 0)
1097 unsigned int md_size_u;
1098 /* Chop the digest off the end :-) */
1099 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1104 rec_char = rec->type;
1106 s2n(rec->length, p);
1107 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1108 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1109 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1110 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1111 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1112 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1113 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1114 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1115 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1116 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1117 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1118 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1119 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1120 EVP_MD_CTX_reset(md_ctx);
1124 EVP_MD_CTX_free(md_ctx);
1127 ssl3_record_sequence_update(seq);
1131 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1137 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1138 unsigned char header[13];
1139 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1140 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1144 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1145 hash = ssl->write_hash;
1147 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1148 hash = ssl->read_hash;
1151 t = EVP_MD_CTX_size(hash);
1152 OPENSSL_assert(t >= 0);
1155 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1159 hmac = EVP_MD_CTX_new();
1160 if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1165 if (SSL_IS_DTLS(ssl)) {
1166 unsigned char dtlsseq[8], *p = dtlsseq;
1168 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1169 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1170 memcpy(p, &seq[2], 6);
1172 memcpy(header, dtlsseq, 8);
1174 memcpy(header, seq, 8);
1176 header[8] = rec->type;
1177 header[9] = (unsigned char)(ssl->version >> 8);
1178 header[10] = (unsigned char)(ssl->version);
1179 header[11] = (unsigned char)(rec->length >> 8);
1180 header[12] = (unsigned char)(rec->length & 0xff);
1182 if (!send && !SSL_READ_ETM(ssl) &&
1183 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1184 ssl3_cbc_record_digest_supported(mac_ctx)) {
1186 * This is a CBC-encrypted record. We must avoid leaking any
1187 * timing-side channel information about how many blocks of data we
1188 * are hashing because that gives an attacker a timing-oracle.
1190 /* Final param == not SSLv3 */
1191 if (ssl3_cbc_digest_record(mac_ctx,
1194 rec->length + md_size, rec->orig_len,
1195 ssl->s3->read_mac_secret,
1196 ssl->s3->read_mac_secret_size, 0) <= 0) {
1197 EVP_MD_CTX_free(hmac);
1201 /* TODO(size_t): Convert these calls */
1202 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1203 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1204 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1205 EVP_MD_CTX_free(hmac);
1210 EVP_MD_CTX_free(hmac);
1213 fprintf(stderr, "seq=");
1216 for (z = 0; z < 8; z++)
1217 fprintf(stderr, "%02X ", seq[z]);
1218 fprintf(stderr, "\n");
1220 fprintf(stderr, "rec=");
1223 for (z = 0; z < rec->length; z++)
1224 fprintf(stderr, "%02X ", rec->data[z]);
1225 fprintf(stderr, "\n");
1229 if (!SSL_IS_DTLS(ssl)) {
1230 for (i = 7; i >= 0; i--) {
1239 for (z = 0; z < md_size; z++)
1240 fprintf(stderr, "%02X ", md[z]);
1241 fprintf(stderr, "\n");
1248 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1249 * record in |rec| by updating |rec->length| in constant time.
1251 * block_size: the block size of the cipher used to encrypt the record.
1253 * 0: (in non-constant time) if the record is publicly invalid.
1254 * 1: if the padding was valid
1257 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1258 size_t block_size, size_t mac_size)
1260 size_t padding_length;
1262 const size_t overhead = 1 /* padding length byte */ + mac_size;
1265 * These lengths are all public so we can test them in non-constant time.
1267 if (overhead > rec->length)
1270 padding_length = rec->data[rec->length - 1];
1271 good = constant_time_ge_s(rec->length, padding_length + overhead);
1272 /* SSLv3 requires that the padding is minimal. */
1273 good &= constant_time_ge_s(block_size, padding_length + 1);
1274 rec->length -= good & (padding_length + 1);
1275 return constant_time_select_int_s(good, 1, -1);
1279 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1280 * record in |rec| in constant time and returns 1 if the padding is valid and
1281 * -1 otherwise. It also removes any explicit IV from the start of the record
1282 * without leaking any timing about whether there was enough space after the
1283 * padding was removed.
1285 * block_size: the block size of the cipher used to encrypt the record.
1287 * 0: (in non-constant time) if the record is publicly invalid.
1288 * 1: if the padding was valid
1291 int tls1_cbc_remove_padding(const SSL *s,
1293 size_t block_size, size_t mac_size)
1296 size_t padding_length, to_check, i;
1297 const size_t overhead = 1 /* padding length byte */ + mac_size;
1298 /* Check if version requires explicit IV */
1299 if (SSL_USE_EXPLICIT_IV(s)) {
1301 * These lengths are all public so we can test them in non-constant
1304 if (overhead + block_size > rec->length)
1306 /* We can now safely skip explicit IV */
1307 rec->data += block_size;
1308 rec->input += block_size;
1309 rec->length -= block_size;
1310 rec->orig_len -= block_size;
1311 } else if (overhead > rec->length)
1314 padding_length = rec->data[rec->length - 1];
1316 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1317 EVP_CIPH_FLAG_AEAD_CIPHER) {
1318 /* padding is already verified */
1319 rec->length -= padding_length + 1;
1323 good = constant_time_ge_s(rec->length, overhead + padding_length);
1325 * The padding consists of a length byte at the end of the record and
1326 * then that many bytes of padding, all with the same value as the length
1327 * byte. Thus, with the length byte included, there are i+1 bytes of
1328 * padding. We can't check just |padding_length+1| bytes because that
1329 * leaks decrypted information. Therefore we always have to check the
1330 * maximum amount of padding possible. (Again, the length of the record
1331 * is public information so we can use it.)
1333 to_check = 256; /* maximum amount of padding, inc length byte. */
1334 if (to_check > rec->length)
1335 to_check = rec->length;
1337 for (i = 0; i < to_check; i++) {
1338 unsigned char mask = constant_time_ge_8_s(padding_length, i);
1339 unsigned char b = rec->data[rec->length - 1 - i];
1341 * The final |padding_length+1| bytes should all have the value
1342 * |padding_length|. Therefore the XOR should be zero.
1344 good &= ~(mask & (padding_length ^ b));
1348 * If any of the final |padding_length+1| bytes had the wrong value, one
1349 * or more of the lower eight bits of |good| will be cleared.
1351 good = constant_time_eq_s(0xff, good & 0xff);
1352 rec->length -= good & (padding_length + 1);
1354 return constant_time_select_int_s(good, 1, -1);
1358 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1359 * constant time (independent of the concrete value of rec->length, which may
1360 * vary within a 256-byte window).
1362 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1366 * rec->orig_len >= md_size
1367 * md_size <= EVP_MAX_MD_SIZE
1369 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1370 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1371 * a single or pair of cache-lines, then the variable memory accesses don't
1372 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1373 * not multi-core and are not considered vulnerable to cache-timing attacks.
1375 #define CBC_MAC_ROTATE_IN_PLACE
1377 void ssl3_cbc_copy_mac(unsigned char *out,
1378 const SSL3_RECORD *rec, size_t md_size)
1380 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1381 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1382 unsigned char *rotated_mac;
1384 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1388 * mac_end is the index of |rec->data| just after the end of the MAC.
1390 size_t mac_end = rec->length;
1391 size_t mac_start = mac_end - md_size;
1394 * scan_start contains the number of bytes that we can ignore because the
1395 * MAC's position can only vary by 255 bytes.
1397 size_t scan_start = 0;
1399 size_t rotate_offset;
1401 OPENSSL_assert(rec->orig_len >= md_size);
1402 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1404 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1405 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1408 /* This information is public so it's safe to branch based on it. */
1409 if (rec->orig_len > md_size + 255 + 1)
1410 scan_start = rec->orig_len - (md_size + 255 + 1);
1414 memset(rotated_mac, 0, md_size);
1415 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1416 size_t mac_started = constant_time_eq_s(i, mac_start);
1417 size_t mac_ended = constant_time_lt_s(i, mac_end);
1418 unsigned char b = rec->data[i];
1420 in_mac |= mac_started;
1421 in_mac &= mac_ended;
1422 rotate_offset |= j & mac_started;
1423 rotated_mac[j++] |= b & in_mac;
1424 j &= constant_time_lt_s(j, md_size);
1427 /* Now rotate the MAC */
1428 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1430 for (i = 0; i < md_size; i++) {
1431 /* in case cache-line is 32 bytes, touch second line */
1432 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1433 out[j++] = rotated_mac[rotate_offset++];
1434 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1437 memset(out, 0, md_size);
1438 rotate_offset = md_size - rotate_offset;
1439 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1440 for (i = 0; i < md_size; i++) {
1441 for (j = 0; j < md_size; j++)
1442 out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1444 rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1449 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1457 unsigned char md[EVP_MAX_MD_SIZE];
1459 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1463 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1464 * and we have that many bytes in s->packet
1466 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1469 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1470 * at rr->length bytes, which need to be copied into rr->data by either
1471 * the decryption or by the decompression When the data is 'copied' into
1472 * the rr->data buffer, rr->input will be pointed at the new buffer
1476 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1477 * bytes of encrypted compressed stuff.
1480 /* check is not needed I believe */
1481 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1482 al = SSL_AD_RECORD_OVERFLOW;
1483 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1487 /* decrypt in place in 'rr->input' */
1488 rr->data = rr->input;
1489 rr->orig_len = rr->length;
1491 if (SSL_READ_ETM(s) && s->read_hash) {
1493 mac_size = EVP_MD_CTX_size(s->read_hash);
1494 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1495 if (rr->orig_len < mac_size) {
1496 al = SSL_AD_DECODE_ERROR;
1497 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1500 rr->length -= mac_size;
1501 mac = rr->data + rr->length;
1502 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1503 if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1504 al = SSL_AD_BAD_RECORD_MAC;
1505 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1506 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1511 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1514 * 0: (in non-constant time) if the record is publically invalid.
1515 * 1: if the padding is valid
1516 * -1: if the padding is invalid
1519 /* For DTLS we simply ignore bad packets. */
1521 RECORD_LAYER_reset_packet_length(&s->rlayer);
1525 printf("dec %ld\n", rr->length);
1528 for (z = 0; z < rr->length; z++)
1529 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1534 /* r->length is now the compressed data plus mac */
1535 if ((sess != NULL) && !SSL_READ_ETM(s) &&
1536 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1537 /* s->read_hash != NULL => mac_size != -1 */
1538 unsigned char *mac = NULL;
1539 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1541 /* TODO(size_t): Convert this to do size_t properly */
1542 imac_size = EVP_MD_CTX_size(s->read_hash);
1543 if (imac_size < 0) {
1544 al = SSL_AD_INTERNAL_ERROR;
1545 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1548 mac_size = (size_t)imac_size;
1549 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1552 * orig_len is the length of the record before any padding was
1553 * removed. This is public information, as is the MAC in use,
1554 * therefore we can safely process the record in a different amount
1555 * of time if it's too short to possibly contain a MAC.
1557 if (rr->orig_len < mac_size ||
1558 /* CBC records must have a padding length byte too. */
1559 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1560 rr->orig_len < mac_size + 1)) {
1561 al = SSL_AD_DECODE_ERROR;
1562 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1566 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1568 * We update the length so that the TLS header bytes can be
1569 * constructed correctly but we need to extract the MAC in
1570 * constant time from within the record, without leaking the
1571 * contents of the padding bytes.
1574 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1575 rr->length -= mac_size;
1578 * In this case there's no padding, so |rec->orig_len| equals
1579 * |rec->length| and we checked that there's enough bytes for
1582 rr->length -= mac_size;
1583 mac = &rr->data[rr->length];
1586 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1587 if (i == 0 || mac == NULL
1588 || CRYPTO_memcmp(md, mac, mac_size) != 0)
1590 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1595 /* decryption failed, silently discard message */
1597 RECORD_LAYER_reset_packet_length(&s->rlayer);
1601 /* r->length is now just compressed */
1602 if (s->expand != NULL) {
1603 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1604 al = SSL_AD_RECORD_OVERFLOW;
1605 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1606 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1609 if (!ssl3_do_uncompress(s, rr)) {
1610 al = SSL_AD_DECOMPRESSION_FAILURE;
1611 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1616 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1617 al = SSL_AD_RECORD_OVERFLOW;
1618 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1624 * So at this point the following is true
1625 * ssl->s3->rrec.type is the type of record
1626 * ssl->s3->rrec.length == number of bytes in record
1627 * ssl->s3->rrec.off == offset to first valid byte
1628 * ssl->s3->rrec.data == where to take bytes from, increment
1632 /* we have pulled in a full packet so zero things */
1633 RECORD_LAYER_reset_packet_length(&s->rlayer);
1635 /* Mark receipt of record. */
1636 dtls1_record_bitmap_update(s, bitmap);
1641 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1647 * retrieve a buffered record that belongs to the current epoch, ie,
1650 #define dtls1_get_processed_record(s) \
1651 dtls1_retrieve_buffered_record((s), \
1652 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1655 * Call this to get a new input record.
1656 * It will return <= 0 if more data is needed, normally due to an error
1657 * or non-blocking IO.
1658 * When it finishes, one packet has been decoded and can be found in
1659 * ssl->s3->rrec.type - is the type of record
1660 * ssl->s3->rrec.data, - data
1661 * ssl->s3->rrec.length, - number of bytes
1663 /* used only by dtls1_read_bytes */
1664 int dtls1_get_record(SSL *s)
1666 int ssl_major, ssl_minor;
1670 unsigned char *p = NULL;
1671 unsigned short version;
1672 DTLS1_BITMAP *bitmap;
1673 unsigned int is_next_epoch;
1675 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1679 * The epoch may have changed. If so, process all the pending records.
1680 * This is a non-blocking operation.
1682 if (!dtls1_process_buffered_records(s))
1685 /* if we're renegotiating, then there may be buffered records */
1686 if (dtls1_get_processed_record(s))
1689 /* get something from the wire */
1691 /* check if we have the header */
1692 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1693 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1694 rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1695 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1696 /* read timeout is handled by dtls1_read_bytes */
1698 return rret; /* error or non-blocking */
1700 /* this packet contained a partial record, dump it */
1701 if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1702 DTLS1_RT_HEADER_LENGTH) {
1703 RECORD_LAYER_reset_packet_length(&s->rlayer);
1707 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1709 p = RECORD_LAYER_get_packet(&s->rlayer);
1711 if (s->msg_callback)
1712 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1713 s, s->msg_callback_arg);
1715 /* Pull apart the header into the DTLS1_RECORD */
1719 version = (ssl_major << 8) | ssl_minor;
1721 /* sequence number is 64 bits, with top 2 bytes = epoch */
1724 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1729 /* Lets check version */
1730 if (!s->first_packet) {
1731 if (version != s->version) {
1732 /* unexpected version, silently discard */
1734 RECORD_LAYER_reset_packet_length(&s->rlayer);
1739 if ((version & 0xff00) != (s->version & 0xff00)) {
1740 /* wrong version, silently discard record */
1742 RECORD_LAYER_reset_packet_length(&s->rlayer);
1746 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1747 /* record too long, silently discard it */
1749 RECORD_LAYER_reset_packet_length(&s->rlayer);
1753 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1756 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1759 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1760 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1762 rret = ssl3_read_n(s, more, more, 1, 1, &n);
1763 /* this packet contained a partial record, dump it */
1764 if (rret <= 0 || n != more) {
1766 RECORD_LAYER_reset_packet_length(&s->rlayer);
1771 * now n == rr->length, and s->packet_length ==
1772 * DTLS1_RT_HEADER_LENGTH + rr->length
1775 /* set state for later operations */
1776 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1778 /* match epochs. NULL means the packet is dropped on the floor */
1779 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1780 if (bitmap == NULL) {
1782 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1783 goto again; /* get another record */
1785 #ifndef OPENSSL_NO_SCTP
1786 /* Only do replay check if no SCTP bio */
1787 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1789 /* Check whether this is a repeat, or aged record. */
1791 * TODO: Does it make sense to have replay protection in epoch 0 where
1792 * we have no integrity negotiated yet?
1794 if (!dtls1_record_replay_check(s, bitmap)) {
1796 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1797 goto again; /* get another record */
1799 #ifndef OPENSSL_NO_SCTP
1803 /* just read a 0 length packet */
1804 if (rr->length == 0)
1808 * If this record is from the next epoch (either HM or ALERT), and a
1809 * handshake is currently in progress, buffer it since it cannot be
1810 * processed at this time.
1812 if (is_next_epoch) {
1813 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1814 if (dtls1_buffer_record
1815 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1820 RECORD_LAYER_reset_packet_length(&s->rlayer);
1824 if (!dtls1_process_record(s, bitmap)) {
1826 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1827 goto again; /* get another record */