1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2015 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
111 #include "../ssl_locl.h"
112 #include "internal/constant_time_locl.h"
113 #include <openssl/rand.h>
114 #include "record_locl.h"
116 static const unsigned char ssl3_pad_1[48] = {
117 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
118 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
119 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
120 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
121 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
122 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
125 static const unsigned char ssl3_pad_2[48] = {
126 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
127 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
128 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
129 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
130 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
131 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
135 * Clear the contents of an SSL3_RECORD but retain any memory allocated
137 void SSL3_RECORD_clear(SSL3_RECORD *r, unsigned int num_recs)
142 for (i = 0; i < num_recs; i++) {
145 memset(&r[i], 0, sizeof(*r));
150 void SSL3_RECORD_release(SSL3_RECORD *r, unsigned int num_recs)
154 for (i = 0; i < num_recs; i++) {
155 OPENSSL_free(r[i].comp);
160 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
162 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
167 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
168 * for us in the buffer.
170 static int ssl3_record_app_data_waiting(SSL *s)
176 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
178 p = SSL3_BUFFER_get_buf(rbuf);
182 left = SSL3_BUFFER_get_left(rbuf);
184 if (left < SSL3_RT_HEADER_LENGTH)
187 p += SSL3_BUFFER_get_offset(rbuf);
190 * We only check the type and record length, we will sanity check version
193 if (*p != SSL3_RT_APPLICATION_DATA)
199 if (left < SSL3_RT_HEADER_LENGTH + len)
206 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
207 * will be processed per call to ssl3_get_record. Without this limit an
208 * attacker could send empty records at a faster rate than we can process and
209 * cause ssl3_get_record to loop forever.
211 #define MAX_EMPTY_RECORDS 32
213 #define SSL2_RT_HEADER_LENGTH 2
215 * Call this to get new input records.
216 * It will return <= 0 if more data is needed, normally due to an error
217 * or non-blocking IO.
218 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
219 * rr[i].type - is the type of record
221 * rr[i].length, - number of bytes
222 * Multiple records will only be returned if the record types are all
223 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
226 /* used only by ssl3_read_bytes */
227 int ssl3_get_record(SSL *s)
229 int ssl_major, ssl_minor, al;
230 int enc_err, n, i, ret = -1;
235 unsigned char md[EVP_MAX_MD_SIZE];
238 unsigned empty_record_count = 0, curr_empty = 0;
239 unsigned int num_recs = 0;
240 unsigned int max_recs;
243 rr = RECORD_LAYER_get_rrec(&s->rlayer);
244 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
245 max_recs = s->max_pipelines;
252 /* check if we have the header */
253 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
254 (RECORD_LAYER_get_packet_length(&s->rlayer)
255 < SSL3_RT_HEADER_LENGTH)) {
256 n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
257 SSL3_BUFFER_get_len(rbuf), 0, num_recs == 0 ? 1 : 0);
259 return (n); /* error or non-blocking */
260 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
262 p = RECORD_LAYER_get_packet(&s->rlayer);
265 * Check whether this is a regular record or an SSLv2 style record.
266 * The latter is only used in an initial ClientHello for old
267 * clients. We check s->read_hash and s->enc_read_ctx to ensure this
268 * does not apply during renegotiation
270 if (s->first_packet && s->server && !s->read_hash
272 && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
273 /* SSLv2 style record */
274 rr[num_recs].type = SSL3_RT_HANDSHAKE;
275 rr[num_recs].rec_version = SSL2_VERSION;
277 rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
279 if (rr[num_recs].length > SSL3_BUFFER_get_len(&rbuf[num_recs])
280 - SSL2_RT_HEADER_LENGTH) {
281 al = SSL_AD_RECORD_OVERFLOW;
282 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
286 if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
287 al = SSL_AD_HANDSHAKE_FAILURE;
288 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
292 /* SSLv3+ style record */
294 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
295 s->msg_callback_arg);
297 /* Pull apart the header into the SSL3_RECORD */
298 rr[num_recs].type = *(p++);
301 version = (ssl_major << 8) | ssl_minor;
302 rr[num_recs].rec_version = version;
303 n2s(p, rr[num_recs].length);
305 /* Lets check version */
306 if (!s->first_packet && version != s->version) {
307 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
308 if ((s->version & 0xFF00) == (version & 0xFF00)
309 && !s->enc_write_ctx && !s->write_hash) {
310 if (rr->type == SSL3_RT_ALERT) {
312 * The record is using an incorrect version number,
313 * but what we've got appears to be an alert. We
314 * haven't read the body yet to check whether its a
315 * fatal or not - but chances are it is. We probably
316 * shouldn't send a fatal alert back. We'll just
322 * Send back error using their minor version number :-)
324 s->version = (unsigned short)version;
326 al = SSL_AD_PROTOCOL_VERSION;
330 if ((version >> 8) != SSL3_VERSION_MAJOR) {
331 if (s->first_packet) {
332 /* Go back to start of packet, look at the five bytes
334 p = RECORD_LAYER_get_packet(&s->rlayer);
335 if (strncmp((char *)p, "GET ", 4) == 0 ||
336 strncmp((char *)p, "POST ", 5) == 0 ||
337 strncmp((char *)p, "HEAD ", 5) == 0 ||
338 strncmp((char *)p, "PUT ", 4) == 0) {
339 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
341 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
342 SSLerr(SSL_F_SSL3_GET_RECORD,
343 SSL_R_HTTPS_PROXY_REQUEST);
347 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
351 if (rr[num_recs].length >
352 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
353 al = SSL_AD_RECORD_OVERFLOW;
354 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
359 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
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 (rr[num_recs].rec_version == SSL2_VERSION) {
368 i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
369 - SSL3_RT_HEADER_LENGTH;
371 i = rr[num_recs].length;
374 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
376 n = ssl3_read_n(s, i, i, 1, 0);
378 return (n); /* 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 + rr->length,
386 * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
387 * and we have that many bytes in s->packet
389 if(rr[num_recs].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 'rr' rr->input points
399 * at rr->length bytes, which need to be copied into rr->data by either
400 * the decryption or by the decompression When the data is 'copied' into
401 * the rr->data buffer, rr->input will be pointed at the new buffer
405 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
406 * bytes of encrypted compressed stuff.
409 /* check is not needed I believe */
410 if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
411 al = SSL_AD_RECORD_OVERFLOW;
412 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
416 /* decrypt in place in 'rr->input' */
417 rr[num_recs].data = rr[num_recs].input;
418 rr[num_recs].orig_len = rr[num_recs].length;
421 /* we have pulled in a full packet so zero things */
422 RECORD_LAYER_reset_packet_length(&s->rlayer);
423 } while (num_recs < max_recs && rr->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));
432 * If in encrypt-then-mac mode calculate mac from encrypted record. All
433 * the details below are public so no timing details can leak.
435 if (SSL_USE_ETM(s) && s->read_hash) {
437 mac_size = EVP_MD_CTX_size(s->read_hash);
438 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
439 for (j = 0; j < num_recs; j++) {
440 if (rr[j].length < mac_size) {
441 al = SSL_AD_DECODE_ERROR;
442 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
445 rr[j].length -= mac_size;
446 mac = rr[j].data + rr[j].length;
447 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
448 if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
449 al = SSL_AD_BAD_RECORD_MAC;
450 SSLerr(SSL_F_SSL3_GET_RECORD,
451 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
457 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
460 * 0: (in non-constant time) if the record is publically invalid.
461 * 1: if the padding is valid
462 * -1: if the padding is invalid
465 al = SSL_AD_DECRYPTION_FAILED;
466 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
470 printf("dec %d\n", rr->length);
473 for (z = 0; z < rr->length; z++)
474 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
479 /* r->length is now the compressed data plus mac */
480 if ((sess != NULL) &&
481 (s->enc_read_ctx != NULL) &&
482 (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
483 /* s->read_hash != NULL => mac_size != -1 */
484 unsigned char *mac = NULL;
485 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
487 mac_size = EVP_MD_CTX_size(s->read_hash);
488 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
490 for (j=0; j < num_recs; j++) {
492 * orig_len is the length of the record before any padding was
493 * removed. This is public information, as is the MAC in use,
494 * therefore we can safely process the record in a different amount
495 * of time if it's too short to possibly contain a MAC.
497 if (rr[j].orig_len < mac_size ||
498 /* CBC records must have a padding length byte too. */
499 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
500 rr[j].orig_len < mac_size + 1)) {
501 al = SSL_AD_DECODE_ERROR;
502 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
506 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
508 * We update the length so that the TLS header bytes can be
509 * constructed correctly but we need to extract the MAC in
510 * constant time from within the record, without leaking the
511 * contents of the padding bytes.
514 ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
515 rr[j].length -= mac_size;
518 * In this case there's no padding, so |rec->orig_len| equals
519 * |rec->length| and we checked that there's enough bytes for
522 rr[j].length -= mac_size;
523 mac = &rr[j].data[rr[j].length];
526 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
527 if (i < 0 || mac == NULL
528 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
530 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
537 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
538 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
539 * failure is directly visible from the ciphertext anyway, we should
540 * not reveal which kind of error occurred -- this might become
541 * visible to an attacker (e.g. via a logfile)
543 al = SSL_AD_BAD_RECORD_MAC;
544 SSLerr(SSL_F_SSL3_GET_RECORD,
545 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
549 for (j = 0; j < num_recs; j++) {
550 /* rr[j].length is now just compressed */
551 if (s->expand != NULL) {
552 if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
553 al = SSL_AD_RECORD_OVERFLOW;
554 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
557 if (!ssl3_do_uncompress(s, &rr[j])) {
558 al = SSL_AD_DECOMPRESSION_FAILURE;
559 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
564 if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
565 al = SSL_AD_RECORD_OVERFLOW;
566 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
572 * So at this point the following is true
573 * rr[j].type is the type of record
574 * rr[j].length == number of bytes in record
575 * rr[j].off == offset to first valid byte
576 * rr[j].data == where to take bytes from, increment after use :-).
579 /* just read a 0 length packet */
580 if (rr[j].length == 0) {
582 empty_record_count++;
583 if (empty_record_count > MAX_EMPTY_RECORDS) {
584 al = SSL_AD_UNEXPECTED_MESSAGE;
585 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
590 if (curr_empty == num_recs) {
591 /* We have no data - do it all again */
597 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
601 ssl3_send_alert(s, SSL3_AL_FATAL, al);
606 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
608 #ifndef OPENSSL_NO_COMP
611 if (rr->comp == NULL) {
612 rr->comp = (unsigned char *)
613 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
615 if (rr->comp == NULL)
618 i = COMP_expand_block(ssl->expand, rr->comp,
619 SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
630 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
632 #ifndef OPENSSL_NO_COMP
635 i = COMP_compress_block(ssl->compress, wr->data,
636 SSL3_RT_MAX_COMPRESSED_LENGTH,
637 wr->input, (int)wr->length);
643 wr->input = wr->data;
649 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
652 * 0: (in non-constant time) if the record is publically invalid (i.e. too
654 * 1: if the record's padding is valid / the encryption was successful.
655 * -1: if the record's padding is invalid or, if sending, an internal error
658 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
663 int bs, i, mac_size = 0;
664 const EVP_CIPHER *enc;
668 * We shouldn't ever be called with more than one record in the SSLv3 case
673 ds = s->enc_write_ctx;
674 if (s->enc_write_ctx == NULL)
677 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
679 ds = s->enc_read_ctx;
680 if (s->enc_read_ctx == NULL)
683 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
686 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
687 memmove(rec->data, rec->input, rec->length);
688 rec->input = rec->data;
691 bs = EVP_CIPHER_CTX_block_size(ds);
695 if ((bs != 1) && send) {
696 i = bs - ((int)l % bs);
698 /* we need to add 'i-1' padding bytes */
701 * the last of these zero bytes will be overwritten with the
704 memset(&rec->input[rec->length], 0, i);
706 rec->input[l - 1] = (i - 1);
710 if (l == 0 || l % bs != 0)
712 /* otherwise, rec->length >= bs */
715 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
718 if (EVP_MD_CTX_md(s->read_hash) != NULL)
719 mac_size = EVP_MD_CTX_size(s->read_hash);
720 if ((bs != 1) && !send)
721 return ssl3_cbc_remove_padding(rec, bs, mac_size);
727 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
730 * 0: (in non-constant time) if the record is publically invalid (i.e. too
732 * 1: if the record's padding is valid / the encryption was successful.
733 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
734 * an internal error occurred.
736 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
739 size_t reclen[SSL_MAX_PIPELINES];
740 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
741 int bs, i, j, k, pad = 0, ret, mac_size = 0;
742 const EVP_CIPHER *enc;
746 if (EVP_MD_CTX_md(s->write_hash)) {
747 int n = EVP_MD_CTX_size(s->write_hash);
748 OPENSSL_assert(n >= 0);
750 ds = s->enc_write_ctx;
751 if (s->enc_write_ctx == NULL)
755 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
756 /* For TLSv1.1 and later explicit IV */
757 if (SSL_USE_EXPLICIT_IV(s)
758 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
759 ivlen = EVP_CIPHER_iv_length(enc);
763 for (ctr = 0; ctr < n_recs; ctr++) {
764 if (recs[ctr].data != recs[ctr].input) {
766 * we can't write into the input stream: Can this ever
769 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
771 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
772 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
779 if (EVP_MD_CTX_md(s->read_hash)) {
780 int n = EVP_MD_CTX_size(s->read_hash);
781 OPENSSL_assert(n >= 0);
783 ds = s->enc_read_ctx;
784 if (s->enc_read_ctx == NULL)
787 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
790 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
791 for (ctr = 0; ctr < n_recs; ctr++) {
792 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
793 recs[ctr].input = recs[ctr].data;
797 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
800 if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
801 & EVP_CIPH_FLAG_PIPELINE)) {
803 * We shouldn't have been called with pipeline data if the
804 * cipher doesn't support pipelining
806 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
810 for (ctr = 0; ctr < n_recs; ctr++) {
811 reclen[ctr] = recs[ctr].length;
813 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
814 & EVP_CIPH_FLAG_AEAD_CIPHER) {
817 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
818 : RECORD_LAYER_get_read_sequence(&s->rlayer);
820 if (SSL_IS_DTLS(s)) {
821 /* DTLS does not support pipelining */
822 unsigned char dtlsseq[9], *p = dtlsseq;
824 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
825 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
826 memcpy(p, &seq[2], 6);
827 memcpy(buf[ctr], dtlsseq, 8);
829 memcpy(buf[ctr], seq, 8);
830 for (i = 7; i >= 0; i--) { /* increment */
837 buf[ctr][8] = recs[ctr].type;
838 buf[ctr][9] = (unsigned char)(s->version >> 8);
839 buf[ctr][10] = (unsigned char)(s->version);
840 buf[ctr][11] = recs[ctr].length >> 8;
841 buf[ctr][12] = recs[ctr].length & 0xff;
842 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
843 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
849 recs[ctr].length += pad;
852 } else if ((bs != 1) && send) {
853 i = bs - ((int)reclen[ctr] % bs);
855 /* Add weird padding of upto 256 bytes */
857 /* we need to add 'i' padding bytes of value j */
859 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
860 recs[ctr].input[k] = j;
862 recs[ctr].length += i;
866 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
871 unsigned char *data[SSL_MAX_PIPELINES];
873 /* Set the output buffers */
874 for(ctr = 0; ctr < n_recs; ctr++) {
875 data[ctr] = recs[ctr].data;
877 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
878 n_recs, data) <= 0) {
879 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
881 /* Set the input buffers */
882 for(ctr = 0; ctr < n_recs; ctr++) {
883 data[ctr] = recs[ctr].input;
885 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
887 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
888 n_recs, reclen) <= 0) {
889 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
894 i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
895 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
896 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
899 return -1; /* AEAD can fail to verify MAC */
901 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
902 for (ctr = 0; ctr < n_recs; ctr++) {
903 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
904 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
905 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
907 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
908 for (ctr = 0; ctr < n_recs; ctr++) {
909 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
910 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
911 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
917 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
918 mac_size = EVP_MD_CTX_size(s->read_hash);
919 if ((bs != 1) && !send) {
921 for (ctr = 0; ctr < n_recs; ctr++) {
922 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
929 for (ctr = 0; ctr < n_recs; ctr++) {
930 recs[ctr].length -= pad;
937 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
939 unsigned char *mac_sec, *seq;
940 const EVP_MD_CTX *hash;
941 unsigned char *p, rec_char;
947 mac_sec = &(ssl->s3->write_mac_secret[0]);
948 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
949 hash = ssl->write_hash;
951 mac_sec = &(ssl->s3->read_mac_secret[0]);
952 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
953 hash = ssl->read_hash;
956 t = EVP_MD_CTX_size(hash);
960 npad = (48 / md_size) * md_size;
963 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
964 ssl3_cbc_record_digest_supported(hash)) {
966 * This is a CBC-encrypted record. We must avoid leaking any
967 * timing-side channel information about how many blocks of data we
968 * are hashing because that gives an attacker a timing-oracle.
972 * npad is, at most, 48 bytes and that's with MD5:
973 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
975 * With SHA-1 (the largest hash speced for SSLv3) the hash size
976 * goes up 4, but npad goes down by 8, resulting in a smaller
979 unsigned char header[75];
981 memcpy(header + j, mac_sec, md_size);
983 memcpy(header + j, ssl3_pad_1, npad);
985 memcpy(header + j, seq, 8);
987 header[j++] = rec->type;
988 header[j++] = rec->length >> 8;
989 header[j++] = rec->length & 0xff;
991 /* Final param == is SSLv3 */
992 if (ssl3_cbc_digest_record(hash,
995 rec->length + md_size, rec->orig_len,
996 mac_sec, md_size, 1) <= 0)
999 unsigned int md_size_u;
1000 /* Chop the digest off the end :-) */
1001 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1006 rec_char = rec->type;
1008 s2n(rec->length, p);
1009 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1010 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1011 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1012 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1013 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1014 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1015 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1016 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1017 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1018 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1019 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1020 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1021 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1022 EVP_MD_CTX_reset(md_ctx);
1025 md_size = md_size_u;
1027 EVP_MD_CTX_free(md_ctx);
1030 ssl3_record_sequence_update(seq);
1034 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1040 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1041 unsigned char header[13];
1042 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1043 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1047 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1048 hash = ssl->write_hash;
1050 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1051 hash = ssl->read_hash;
1054 t = EVP_MD_CTX_size(hash);
1055 OPENSSL_assert(t >= 0);
1058 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1062 hmac = EVP_MD_CTX_new();
1064 || !EVP_MD_CTX_copy(hmac, hash))
1069 if (SSL_IS_DTLS(ssl)) {
1070 unsigned char dtlsseq[8], *p = dtlsseq;
1072 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1073 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1074 memcpy(p, &seq[2], 6);
1076 memcpy(header, dtlsseq, 8);
1078 memcpy(header, seq, 8);
1080 header[8] = rec->type;
1081 header[9] = (unsigned char)(ssl->version >> 8);
1082 header[10] = (unsigned char)(ssl->version);
1083 header[11] = (rec->length) >> 8;
1084 header[12] = (rec->length) & 0xff;
1086 if (!send && !SSL_USE_ETM(ssl) &&
1087 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1088 ssl3_cbc_record_digest_supported(mac_ctx)) {
1090 * This is a CBC-encrypted record. We must avoid leaking any
1091 * timing-side channel information about how many blocks of data we
1092 * are hashing because that gives an attacker a timing-oracle.
1094 /* Final param == not SSLv3 */
1095 if (ssl3_cbc_digest_record(mac_ctx,
1098 rec->length + md_size, rec->orig_len,
1099 ssl->s3->read_mac_secret,
1100 ssl->s3->read_mac_secret_size, 0) <= 0) {
1101 EVP_MD_CTX_free(hmac);
1105 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1106 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1107 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1108 EVP_MD_CTX_free(hmac);
1111 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1112 tls_fips_digest_extra(ssl->enc_read_ctx,
1113 mac_ctx, rec->input,
1114 rec->length, rec->orig_len);
1117 EVP_MD_CTX_free(hmac);
1120 fprintf(stderr, "seq=");
1123 for (z = 0; z < 8; z++)
1124 fprintf(stderr, "%02X ", seq[z]);
1125 fprintf(stderr, "\n");
1127 fprintf(stderr, "rec=");
1130 for (z = 0; z < rec->length; z++)
1131 fprintf(stderr, "%02X ", rec->data[z]);
1132 fprintf(stderr, "\n");
1136 if (!SSL_IS_DTLS(ssl)) {
1137 for (i = 7; i >= 0; i--) {
1146 for (z = 0; z < md_size; z++)
1147 fprintf(stderr, "%02X ", md[z]);
1148 fprintf(stderr, "\n");
1155 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1156 * record in |rec| by updating |rec->length| in constant time.
1158 * block_size: the block size of the cipher used to encrypt the record.
1160 * 0: (in non-constant time) if the record is publicly invalid.
1161 * 1: if the padding was valid
1164 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1165 unsigned block_size, unsigned mac_size)
1167 unsigned padding_length, good;
1168 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1171 * These lengths are all public so we can test them in non-constant time.
1173 if (overhead > rec->length)
1176 padding_length = rec->data[rec->length - 1];
1177 good = constant_time_ge(rec->length, padding_length + overhead);
1178 /* SSLv3 requires that the padding is minimal. */
1179 good &= constant_time_ge(block_size, padding_length + 1);
1180 rec->length -= good & (padding_length + 1);
1181 return constant_time_select_int(good, 1, -1);
1185 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1186 * record in |rec| in constant time and returns 1 if the padding is valid and
1187 * -1 otherwise. It also removes any explicit IV from the start of the record
1188 * without leaking any timing about whether there was enough space after the
1189 * padding was removed.
1191 * block_size: the block size of the cipher used to encrypt the record.
1193 * 0: (in non-constant time) if the record is publicly invalid.
1194 * 1: if the padding was valid
1197 int tls1_cbc_remove_padding(const SSL *s,
1199 unsigned block_size, unsigned mac_size)
1201 unsigned padding_length, good, to_check, i;
1202 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1203 /* Check if version requires explicit IV */
1204 if (SSL_USE_EXPLICIT_IV(s)) {
1206 * These lengths are all public so we can test them in non-constant
1209 if (overhead + block_size > rec->length)
1211 /* We can now safely skip explicit IV */
1212 rec->data += block_size;
1213 rec->input += block_size;
1214 rec->length -= block_size;
1215 rec->orig_len -= block_size;
1216 } else if (overhead > rec->length)
1219 padding_length = rec->data[rec->length - 1];
1221 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1222 /* padding is already verified */
1223 rec->length -= padding_length + 1;
1227 good = constant_time_ge(rec->length, overhead + padding_length);
1229 * The padding consists of a length byte at the end of the record and
1230 * then that many bytes of padding, all with the same value as the length
1231 * byte. Thus, with the length byte included, there are i+1 bytes of
1232 * padding. We can't check just |padding_length+1| bytes because that
1233 * leaks decrypted information. Therefore we always have to check the
1234 * maximum amount of padding possible. (Again, the length of the record
1235 * is public information so we can use it.)
1237 to_check = 255; /* maximum amount of padding. */
1238 if (to_check > rec->length - 1)
1239 to_check = rec->length - 1;
1241 for (i = 0; i < to_check; i++) {
1242 unsigned char mask = constant_time_ge_8(padding_length, i);
1243 unsigned char b = rec->data[rec->length - 1 - i];
1245 * The final |padding_length+1| bytes should all have the value
1246 * |padding_length|. Therefore the XOR should be zero.
1248 good &= ~(mask & (padding_length ^ b));
1252 * If any of the final |padding_length+1| bytes had the wrong value, one
1253 * or more of the lower eight bits of |good| will be cleared.
1255 good = constant_time_eq(0xff, good & 0xff);
1256 rec->length -= good & (padding_length + 1);
1258 return constant_time_select_int(good, 1, -1);
1262 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1263 * constant time (independent of the concrete value of rec->length, which may
1264 * vary within a 256-byte window).
1266 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1270 * rec->orig_len >= md_size
1271 * md_size <= EVP_MAX_MD_SIZE
1273 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1274 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1275 * a single or pair of cache-lines, then the variable memory accesses don't
1276 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1277 * not multi-core and are not considered vulnerable to cache-timing attacks.
1279 #define CBC_MAC_ROTATE_IN_PLACE
1281 void ssl3_cbc_copy_mac(unsigned char *out,
1282 const SSL3_RECORD *rec, unsigned md_size)
1284 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1285 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1286 unsigned char *rotated_mac;
1288 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1292 * mac_end is the index of |rec->data| just after the end of the MAC.
1294 unsigned mac_end = rec->length;
1295 unsigned mac_start = mac_end - md_size;
1297 * scan_start contains the number of bytes that we can ignore because the
1298 * MAC's position can only vary by 255 bytes.
1300 unsigned scan_start = 0;
1302 unsigned div_spoiler;
1303 unsigned rotate_offset;
1305 OPENSSL_assert(rec->orig_len >= md_size);
1306 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1308 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1309 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1312 /* This information is public so it's safe to branch based on it. */
1313 if (rec->orig_len > md_size + 255 + 1)
1314 scan_start = rec->orig_len - (md_size + 255 + 1);
1316 * div_spoiler contains a multiple of md_size that is used to cause the
1317 * modulo operation to be constant time. Without this, the time varies
1318 * based on the amount of padding when running on Intel chips at least.
1319 * The aim of right-shifting md_size is so that the compiler doesn't
1320 * figure out that it can remove div_spoiler as that would require it to
1321 * prove that md_size is always even, which I hope is beyond it.
1323 div_spoiler = md_size >> 1;
1324 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1325 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1327 memset(rotated_mac, 0, md_size);
1328 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1329 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1330 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1331 unsigned char b = rec->data[i];
1332 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1333 j &= constant_time_lt(j, md_size);
1336 /* Now rotate the MAC */
1337 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1339 for (i = 0; i < md_size; i++) {
1340 /* in case cache-line is 32 bytes, touch second line */
1341 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1342 out[j++] = rotated_mac[rotate_offset++];
1343 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1346 memset(out, 0, md_size);
1347 rotate_offset = md_size - rotate_offset;
1348 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1349 for (i = 0; i < md_size; i++) {
1350 for (j = 0; j < md_size; j++)
1351 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1353 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1358 int dtls1_process_record(SSL *s)
1364 unsigned int mac_size;
1365 unsigned char md[EVP_MAX_MD_SIZE];
1367 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1371 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1372 * and we have that many bytes in s->packet
1374 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1377 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1378 * at rr->length bytes, which need to be copied into rr->data by either
1379 * the decryption or by the decompression When the data is 'copied' into
1380 * the rr->data buffer, rr->input will be pointed at the new buffer
1384 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1385 * bytes of encrypted compressed stuff.
1388 /* check is not needed I believe */
1389 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1390 al = SSL_AD_RECORD_OVERFLOW;
1391 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1395 /* decrypt in place in 'rr->input' */
1396 rr->data = rr->input;
1397 rr->orig_len = rr->length;
1399 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1402 * 0: (in non-constant time) if the record is publically invalid.
1403 * 1: if the padding is valid
1404 * -1: if the padding is invalid
1407 /* For DTLS we simply ignore bad packets. */
1409 RECORD_LAYER_reset_packet_length(&s->rlayer);
1413 printf("dec %d\n", rr->length);
1416 for (z = 0; z < rr->length; z++)
1417 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1422 /* r->length is now the compressed data plus mac */
1423 if ((sess != NULL) &&
1424 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1425 /* s->read_hash != NULL => mac_size != -1 */
1426 unsigned char *mac = NULL;
1427 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1428 mac_size = EVP_MD_CTX_size(s->read_hash);
1429 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1432 * orig_len is the length of the record before any padding was
1433 * removed. This is public information, as is the MAC in use,
1434 * therefore we can safely process the record in a different amount
1435 * of time if it's too short to possibly contain a MAC.
1437 if (rr->orig_len < mac_size ||
1438 /* CBC records must have a padding length byte too. */
1439 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1440 rr->orig_len < mac_size + 1)) {
1441 al = SSL_AD_DECODE_ERROR;
1442 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1446 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1448 * We update the length so that the TLS header bytes can be
1449 * constructed correctly but we need to extract the MAC in
1450 * constant time from within the record, without leaking the
1451 * contents of the padding bytes.
1454 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1455 rr->length -= mac_size;
1458 * In this case there's no padding, so |rec->orig_len| equals
1459 * |rec->length| and we checked that there's enough bytes for
1462 rr->length -= mac_size;
1463 mac = &rr->data[rr->length];
1466 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1467 if (i < 0 || mac == NULL
1468 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1470 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1475 /* decryption failed, silently discard message */
1477 RECORD_LAYER_reset_packet_length(&s->rlayer);
1481 /* r->length is now just compressed */
1482 if (s->expand != NULL) {
1483 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1484 al = SSL_AD_RECORD_OVERFLOW;
1485 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1486 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1489 if (!ssl3_do_uncompress(s, rr)) {
1490 al = SSL_AD_DECOMPRESSION_FAILURE;
1491 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1496 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1497 al = SSL_AD_RECORD_OVERFLOW;
1498 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1504 * So at this point the following is true
1505 * ssl->s3->rrec.type is the type of record
1506 * ssl->s3->rrec.length == number of bytes in record
1507 * ssl->s3->rrec.off == offset to first valid byte
1508 * ssl->s3->rrec.data == where to take bytes from, increment
1512 /* we have pulled in a full packet so zero things */
1513 RECORD_LAYER_reset_packet_length(&s->rlayer);
1517 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1524 * retrieve a buffered record that belongs to the current epoch, ie,
1527 #define dtls1_get_processed_record(s) \
1528 dtls1_retrieve_buffered_record((s), \
1529 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1532 * Call this to get a new input record.
1533 * It will return <= 0 if more data is needed, normally due to an error
1534 * or non-blocking IO.
1535 * When it finishes, one packet has been decoded and can be found in
1536 * ssl->s3->rrec.type - is the type of record
1537 * ssl->s3->rrec.data, - data
1538 * ssl->s3->rrec.length, - number of bytes
1540 /* used only by dtls1_read_bytes */
1541 int dtls1_get_record(SSL *s)
1543 int ssl_major, ssl_minor;
1546 unsigned char *p = NULL;
1547 unsigned short version;
1548 DTLS1_BITMAP *bitmap;
1549 unsigned int is_next_epoch;
1551 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1554 * The epoch may have changed. If so, process all the pending records.
1555 * This is a non-blocking operation.
1557 if (dtls1_process_buffered_records(s) < 0)
1560 /* if we're renegotiating, then there may be buffered records */
1561 if (dtls1_get_processed_record(s))
1564 /* get something from the wire */
1566 /* check if we have the header */
1567 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1568 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1569 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1570 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1571 /* read timeout is handled by dtls1_read_bytes */
1573 return (n); /* error or non-blocking */
1575 /* this packet contained a partial record, dump it */
1576 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1577 RECORD_LAYER_reset_packet_length(&s->rlayer);
1581 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1583 p = RECORD_LAYER_get_packet(&s->rlayer);
1585 if (s->msg_callback)
1586 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1587 s, s->msg_callback_arg);
1589 /* Pull apart the header into the DTLS1_RECORD */
1593 version = (ssl_major << 8) | ssl_minor;
1595 /* sequence number is 64 bits, with top 2 bytes = epoch */
1598 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1603 /* Lets check version */
1604 if (!s->first_packet) {
1605 if (version != s->version) {
1606 /* unexpected version, silently discard */
1608 RECORD_LAYER_reset_packet_length(&s->rlayer);
1613 if ((version & 0xff00) != (s->version & 0xff00)) {
1614 /* wrong version, silently discard record */
1616 RECORD_LAYER_reset_packet_length(&s->rlayer);
1620 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1621 /* record too long, silently discard it */
1623 RECORD_LAYER_reset_packet_length(&s->rlayer);
1627 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1630 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1633 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1634 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1636 n = ssl3_read_n(s, i, i, 1, 1);
1637 /* this packet contained a partial record, dump it */
1640 RECORD_LAYER_reset_packet_length(&s->rlayer);
1645 * now n == rr->length, and s->packet_length ==
1646 * DTLS1_RT_HEADER_LENGTH + rr->length
1649 /* set state for later operations */
1650 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1652 /* match epochs. NULL means the packet is dropped on the floor */
1653 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1654 if (bitmap == NULL) {
1656 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1657 goto again; /* get another record */
1659 #ifndef OPENSSL_NO_SCTP
1660 /* Only do replay check if no SCTP bio */
1661 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1663 /* Check whether this is a repeat, or aged record. */
1664 if (!dtls1_record_replay_check(s, bitmap)) {
1666 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1667 goto again; /* get another record */
1669 #ifndef OPENSSL_NO_SCTP
1673 /* just read a 0 length packet */
1674 if (rr->length == 0)
1678 * If this record is from the next epoch (either HM or ALERT), and a
1679 * handshake is currently in progress, buffer it since it cannot be
1680 * processed at this time.
1682 if (is_next_epoch) {
1683 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1684 if (dtls1_buffer_record
1685 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1688 /* Mark receipt of record. */
1689 dtls1_record_bitmap_update(s, bitmap);
1692 RECORD_LAYER_reset_packet_length(&s->rlayer);
1696 if (!dtls1_process_record(s)) {
1698 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1699 goto again; /* get another record */
1701 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */