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 |numpipes| 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 numpipes, int send)
663 int bs, i, mac_size = 0;
664 const EVP_CIPHER *enc;
668 ds = s->enc_write_ctx;
669 if (s->enc_write_ctx == NULL)
672 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
674 ds = s->enc_read_ctx;
675 if (s->enc_read_ctx == NULL)
678 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
681 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
682 memmove(rec->data, rec->input, rec->length);
683 rec->input = rec->data;
686 bs = EVP_CIPHER_CTX_block_size(ds);
690 if ((bs != 1) && send) {
691 i = bs - ((int)l % bs);
693 /* we need to add 'i-1' padding bytes */
696 * the last of these zero bytes will be overwritten with the
699 memset(&rec->input[rec->length], 0, i);
701 rec->input[l - 1] = (i - 1);
705 if (l == 0 || l % bs != 0)
707 /* otherwise, rec->length >= bs */
710 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
713 if (EVP_MD_CTX_md(s->read_hash) != NULL)
714 mac_size = EVP_MD_CTX_size(s->read_hash);
715 if ((bs != 1) && !send)
716 return ssl3_cbc_remove_padding(rec, bs, mac_size);
722 * tls1_enc encrypts/decrypts |numpipes| in |recs|.
725 * 0: (in non-constant time) if the record is publically invalid (i.e. too
727 * 1: if the record's padding is valid / the encryption was successful.
728 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
729 * an internal error occurred.
731 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int numpipes, int send)
734 size_t reclen[SSL_MAX_PIPELINES];
735 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
736 int bs, i, j, k, pad = 0, ret, mac_size = 0;
737 const EVP_CIPHER *enc;
741 if (EVP_MD_CTX_md(s->write_hash)) {
742 int n = EVP_MD_CTX_size(s->write_hash);
743 OPENSSL_assert(n >= 0);
745 ds = s->enc_write_ctx;
746 if (s->enc_write_ctx == NULL)
750 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
751 /* For TLSv1.1 and later explicit IV */
752 if (SSL_USE_EXPLICIT_IV(s)
753 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
754 ivlen = EVP_CIPHER_iv_length(enc);
758 for (ctr = 0; ctr < numpipes; ctr++) {
759 if (recs[ctr].data != recs[ctr].input) {
761 * we can't write into the input stream: Can this ever
764 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
766 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
767 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
774 if (EVP_MD_CTX_md(s->read_hash)) {
775 int n = EVP_MD_CTX_size(s->read_hash);
776 OPENSSL_assert(n >= 0);
778 ds = s->enc_read_ctx;
779 if (s->enc_read_ctx == NULL)
782 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
785 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
786 for (ctr = 0; ctr < numpipes; ctr++) {
787 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
788 recs[ctr].input = recs[ctr].data;
792 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
795 if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
796 & EVP_CIPH_FLAG_PIPELINE)) {
798 * We shouldn't have been called with pipeline data if the
799 * cipher doesn't support pipelining
801 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
805 for (ctr = 0; ctr < numpipes; ctr++) {
806 reclen[ctr] = recs[ctr].length;
808 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
809 & EVP_CIPH_FLAG_AEAD_CIPHER) {
812 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
813 : RECORD_LAYER_get_read_sequence(&s->rlayer);
815 if (SSL_IS_DTLS(s)) {
816 /* DTLS does not support pipelining */
817 unsigned char dtlsseq[9], *p = dtlsseq;
819 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
820 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
821 memcpy(p, &seq[2], 6);
822 memcpy(buf[ctr], dtlsseq, 8);
824 memcpy(buf[ctr], seq, 8);
825 for (i = 7; i >= 0; i--) { /* increment */
832 buf[ctr][8] = recs[ctr].type;
833 buf[ctr][9] = (unsigned char)(s->version >> 8);
834 buf[ctr][10] = (unsigned char)(s->version);
835 buf[ctr][11] = recs[ctr].length >> 8;
836 buf[ctr][12] = recs[ctr].length & 0xff;
837 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
838 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
844 recs[ctr].length += pad;
847 } else if ((bs != 1) && send) {
848 i = bs - ((int)reclen[ctr] % bs);
850 /* Add weird padding of upto 256 bytes */
852 /* we need to add 'i' padding bytes of value j */
854 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
855 recs[ctr].input[k] = j;
857 recs[ctr].length += i;
861 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
866 unsigned char *data[SSL_MAX_PIPELINES];
868 /* Set the output buffers */
869 for(ctr = 0; ctr < numpipes; ctr++) {
870 data[ctr] = recs[ctr].data;
872 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
873 numpipes, data) <= 0) {
874 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
876 /* Set the input buffers */
877 for(ctr = 0; ctr < numpipes; ctr++) {
878 data[ctr] = recs[ctr].input;
880 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
882 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
883 numpipes, reclen) <= 0) {
884 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
889 i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
890 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
891 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
894 return -1; /* AEAD can fail to verify MAC */
896 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
897 for (ctr = 0; ctr < numpipes; ctr++) {
898 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
899 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
900 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
902 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
903 for (ctr = 0; ctr < numpipes; ctr++) {
904 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
905 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
906 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
912 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
913 mac_size = EVP_MD_CTX_size(s->read_hash);
914 if ((bs != 1) && !send) {
916 for (ctr = 0; ctr < numpipes; ctr++) {
917 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
924 for (ctr = 0; ctr < numpipes; ctr++) {
925 recs[ctr].length -= pad;
932 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
934 unsigned char *mac_sec, *seq;
935 const EVP_MD_CTX *hash;
936 unsigned char *p, rec_char;
942 mac_sec = &(ssl->s3->write_mac_secret[0]);
943 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
944 hash = ssl->write_hash;
946 mac_sec = &(ssl->s3->read_mac_secret[0]);
947 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
948 hash = ssl->read_hash;
951 t = EVP_MD_CTX_size(hash);
955 npad = (48 / md_size) * md_size;
958 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
959 ssl3_cbc_record_digest_supported(hash)) {
961 * This is a CBC-encrypted record. We must avoid leaking any
962 * timing-side channel information about how many blocks of data we
963 * are hashing because that gives an attacker a timing-oracle.
967 * npad is, at most, 48 bytes and that's with MD5:
968 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
970 * With SHA-1 (the largest hash speced for SSLv3) the hash size
971 * goes up 4, but npad goes down by 8, resulting in a smaller
974 unsigned char header[75];
976 memcpy(header + j, mac_sec, md_size);
978 memcpy(header + j, ssl3_pad_1, npad);
980 memcpy(header + j, seq, 8);
982 header[j++] = rec->type;
983 header[j++] = rec->length >> 8;
984 header[j++] = rec->length & 0xff;
986 /* Final param == is SSLv3 */
987 if (ssl3_cbc_digest_record(hash,
990 rec->length + md_size, rec->orig_len,
991 mac_sec, md_size, 1) <= 0)
994 unsigned int md_size_u;
995 /* Chop the digest off the end :-) */
996 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1001 rec_char = rec->type;
1003 s2n(rec->length, p);
1004 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1005 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1006 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1007 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1008 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1009 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1010 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1011 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1012 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1013 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1014 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1015 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1016 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1017 EVP_MD_CTX_reset(md_ctx);
1020 md_size = md_size_u;
1022 EVP_MD_CTX_free(md_ctx);
1025 ssl3_record_sequence_update(seq);
1029 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1035 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1036 unsigned char header[13];
1037 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1038 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1042 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1043 hash = ssl->write_hash;
1045 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1046 hash = ssl->read_hash;
1049 t = EVP_MD_CTX_size(hash);
1050 OPENSSL_assert(t >= 0);
1053 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1057 hmac = EVP_MD_CTX_new();
1059 || !EVP_MD_CTX_copy(hmac, hash))
1064 if (SSL_IS_DTLS(ssl)) {
1065 unsigned char dtlsseq[8], *p = dtlsseq;
1067 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1068 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1069 memcpy(p, &seq[2], 6);
1071 memcpy(header, dtlsseq, 8);
1073 memcpy(header, seq, 8);
1075 header[8] = rec->type;
1076 header[9] = (unsigned char)(ssl->version >> 8);
1077 header[10] = (unsigned char)(ssl->version);
1078 header[11] = (rec->length) >> 8;
1079 header[12] = (rec->length) & 0xff;
1081 if (!send && !SSL_USE_ETM(ssl) &&
1082 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1083 ssl3_cbc_record_digest_supported(mac_ctx)) {
1085 * This is a CBC-encrypted record. We must avoid leaking any
1086 * timing-side channel information about how many blocks of data we
1087 * are hashing because that gives an attacker a timing-oracle.
1089 /* Final param == not SSLv3 */
1090 if (ssl3_cbc_digest_record(mac_ctx,
1093 rec->length + md_size, rec->orig_len,
1094 ssl->s3->read_mac_secret,
1095 ssl->s3->read_mac_secret_size, 0) <= 0) {
1096 EVP_MD_CTX_free(hmac);
1100 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1101 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1102 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1103 EVP_MD_CTX_free(hmac);
1106 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1107 tls_fips_digest_extra(ssl->enc_read_ctx,
1108 mac_ctx, rec->input,
1109 rec->length, rec->orig_len);
1112 EVP_MD_CTX_free(hmac);
1115 fprintf(stderr, "seq=");
1118 for (z = 0; z < 8; z++)
1119 fprintf(stderr, "%02X ", seq[z]);
1120 fprintf(stderr, "\n");
1122 fprintf(stderr, "rec=");
1125 for (z = 0; z < rec->length; z++)
1126 fprintf(stderr, "%02X ", rec->data[z]);
1127 fprintf(stderr, "\n");
1131 if (!SSL_IS_DTLS(ssl)) {
1132 for (i = 7; i >= 0; i--) {
1141 for (z = 0; z < md_size; z++)
1142 fprintf(stderr, "%02X ", md[z]);
1143 fprintf(stderr, "\n");
1150 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1151 * record in |rec| by updating |rec->length| in constant time.
1153 * block_size: the block size of the cipher used to encrypt the record.
1155 * 0: (in non-constant time) if the record is publicly invalid.
1156 * 1: if the padding was valid
1159 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1160 unsigned block_size, unsigned mac_size)
1162 unsigned padding_length, good;
1163 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1166 * These lengths are all public so we can test them in non-constant time.
1168 if (overhead > rec->length)
1171 padding_length = rec->data[rec->length - 1];
1172 good = constant_time_ge(rec->length, padding_length + overhead);
1173 /* SSLv3 requires that the padding is minimal. */
1174 good &= constant_time_ge(block_size, padding_length + 1);
1175 rec->length -= good & (padding_length + 1);
1176 return constant_time_select_int(good, 1, -1);
1180 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1181 * record in |rec| in constant time and returns 1 if the padding is valid and
1182 * -1 otherwise. It also removes any explicit IV from the start of the record
1183 * without leaking any timing about whether there was enough space after the
1184 * padding was removed.
1186 * block_size: the block size of the cipher used to encrypt the record.
1188 * 0: (in non-constant time) if the record is publicly invalid.
1189 * 1: if the padding was valid
1192 int tls1_cbc_remove_padding(const SSL *s,
1194 unsigned block_size, unsigned mac_size)
1196 unsigned padding_length, good, to_check, i;
1197 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1198 /* Check if version requires explicit IV */
1199 if (SSL_USE_EXPLICIT_IV(s)) {
1201 * These lengths are all public so we can test them in non-constant
1204 if (overhead + block_size > rec->length)
1206 /* We can now safely skip explicit IV */
1207 rec->data += block_size;
1208 rec->input += block_size;
1209 rec->length -= block_size;
1210 rec->orig_len -= block_size;
1211 } else if (overhead > rec->length)
1214 padding_length = rec->data[rec->length - 1];
1216 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1217 /* padding is already verified */
1218 rec->length -= padding_length + 1;
1222 good = constant_time_ge(rec->length, overhead + padding_length);
1224 * The padding consists of a length byte at the end of the record and
1225 * then that many bytes of padding, all with the same value as the length
1226 * byte. Thus, with the length byte included, there are i+1 bytes of
1227 * padding. We can't check just |padding_length+1| bytes because that
1228 * leaks decrypted information. Therefore we always have to check the
1229 * maximum amount of padding possible. (Again, the length of the record
1230 * is public information so we can use it.)
1232 to_check = 255; /* maximum amount of padding. */
1233 if (to_check > rec->length - 1)
1234 to_check = rec->length - 1;
1236 for (i = 0; i < to_check; i++) {
1237 unsigned char mask = constant_time_ge_8(padding_length, i);
1238 unsigned char b = rec->data[rec->length - 1 - i];
1240 * The final |padding_length+1| bytes should all have the value
1241 * |padding_length|. Therefore the XOR should be zero.
1243 good &= ~(mask & (padding_length ^ b));
1247 * If any of the final |padding_length+1| bytes had the wrong value, one
1248 * or more of the lower eight bits of |good| will be cleared.
1250 good = constant_time_eq(0xff, good & 0xff);
1251 rec->length -= good & (padding_length + 1);
1253 return constant_time_select_int(good, 1, -1);
1257 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1258 * constant time (independent of the concrete value of rec->length, which may
1259 * vary within a 256-byte window).
1261 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1265 * rec->orig_len >= md_size
1266 * md_size <= EVP_MAX_MD_SIZE
1268 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1269 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1270 * a single or pair of cache-lines, then the variable memory accesses don't
1271 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1272 * not multi-core and are not considered vulnerable to cache-timing attacks.
1274 #define CBC_MAC_ROTATE_IN_PLACE
1276 void ssl3_cbc_copy_mac(unsigned char *out,
1277 const SSL3_RECORD *rec, unsigned md_size)
1279 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1280 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1281 unsigned char *rotated_mac;
1283 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1287 * mac_end is the index of |rec->data| just after the end of the MAC.
1289 unsigned mac_end = rec->length;
1290 unsigned mac_start = mac_end - md_size;
1292 * scan_start contains the number of bytes that we can ignore because the
1293 * MAC's position can only vary by 255 bytes.
1295 unsigned scan_start = 0;
1297 unsigned div_spoiler;
1298 unsigned rotate_offset;
1300 OPENSSL_assert(rec->orig_len >= md_size);
1301 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1303 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1304 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1307 /* This information is public so it's safe to branch based on it. */
1308 if (rec->orig_len > md_size + 255 + 1)
1309 scan_start = rec->orig_len - (md_size + 255 + 1);
1311 * div_spoiler contains a multiple of md_size that is used to cause the
1312 * modulo operation to be constant time. Without this, the time varies
1313 * based on the amount of padding when running on Intel chips at least.
1314 * The aim of right-shifting md_size is so that the compiler doesn't
1315 * figure out that it can remove div_spoiler as that would require it to
1316 * prove that md_size is always even, which I hope is beyond it.
1318 div_spoiler = md_size >> 1;
1319 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1320 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1322 memset(rotated_mac, 0, md_size);
1323 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1324 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1325 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1326 unsigned char b = rec->data[i];
1327 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1328 j &= constant_time_lt(j, md_size);
1331 /* Now rotate the MAC */
1332 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1334 for (i = 0; i < md_size; i++) {
1335 /* in case cache-line is 32 bytes, touch second line */
1336 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1337 out[j++] = rotated_mac[rotate_offset++];
1338 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1341 memset(out, 0, md_size);
1342 rotate_offset = md_size - rotate_offset;
1343 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1344 for (i = 0; i < md_size; i++) {
1345 for (j = 0; j < md_size; j++)
1346 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1348 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1353 int dtls1_process_record(SSL *s)
1359 unsigned int mac_size;
1360 unsigned char md[EVP_MAX_MD_SIZE];
1362 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1366 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1367 * and we have that many bytes in s->packet
1369 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1372 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1373 * at rr->length bytes, which need to be copied into rr->data by either
1374 * the decryption or by the decompression When the data is 'copied' into
1375 * the rr->data buffer, rr->input will be pointed at the new buffer
1379 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1380 * bytes of encrypted compressed stuff.
1383 /* check is not needed I believe */
1384 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1385 al = SSL_AD_RECORD_OVERFLOW;
1386 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1390 /* decrypt in place in 'rr->input' */
1391 rr->data = rr->input;
1392 rr->orig_len = rr->length;
1394 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1397 * 0: (in non-constant time) if the record is publically invalid.
1398 * 1: if the padding is valid
1399 * -1: if the padding is invalid
1402 /* For DTLS we simply ignore bad packets. */
1404 RECORD_LAYER_reset_packet_length(&s->rlayer);
1408 printf("dec %d\n", rr->length);
1411 for (z = 0; z < rr->length; z++)
1412 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1417 /* r->length is now the compressed data plus mac */
1418 if ((sess != NULL) &&
1419 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1420 /* s->read_hash != NULL => mac_size != -1 */
1421 unsigned char *mac = NULL;
1422 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1423 mac_size = EVP_MD_CTX_size(s->read_hash);
1424 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1427 * orig_len is the length of the record before any padding was
1428 * removed. This is public information, as is the MAC in use,
1429 * therefore we can safely process the record in a different amount
1430 * of time if it's too short to possibly contain a MAC.
1432 if (rr->orig_len < mac_size ||
1433 /* CBC records must have a padding length byte too. */
1434 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1435 rr->orig_len < mac_size + 1)) {
1436 al = SSL_AD_DECODE_ERROR;
1437 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1441 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1443 * We update the length so that the TLS header bytes can be
1444 * constructed correctly but we need to extract the MAC in
1445 * constant time from within the record, without leaking the
1446 * contents of the padding bytes.
1449 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1450 rr->length -= mac_size;
1453 * In this case there's no padding, so |rec->orig_len| equals
1454 * |rec->length| and we checked that there's enough bytes for
1457 rr->length -= mac_size;
1458 mac = &rr->data[rr->length];
1461 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1462 if (i < 0 || mac == NULL
1463 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1465 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1470 /* decryption failed, silently discard message */
1472 RECORD_LAYER_reset_packet_length(&s->rlayer);
1476 /* r->length is now just compressed */
1477 if (s->expand != NULL) {
1478 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1479 al = SSL_AD_RECORD_OVERFLOW;
1480 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1481 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1484 if (!ssl3_do_uncompress(s, rr)) {
1485 al = SSL_AD_DECOMPRESSION_FAILURE;
1486 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1491 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1492 al = SSL_AD_RECORD_OVERFLOW;
1493 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1499 * So at this point the following is true
1500 * ssl->s3->rrec.type is the type of record
1501 * ssl->s3->rrec.length == number of bytes in record
1502 * ssl->s3->rrec.off == offset to first valid byte
1503 * ssl->s3->rrec.data == where to take bytes from, increment
1507 /* we have pulled in a full packet so zero things */
1508 RECORD_LAYER_reset_packet_length(&s->rlayer);
1512 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1519 * retrieve a buffered record that belongs to the current epoch, ie,
1522 #define dtls1_get_processed_record(s) \
1523 dtls1_retrieve_buffered_record((s), \
1524 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1527 * Call this to get a new input record.
1528 * It will return <= 0 if more data is needed, normally due to an error
1529 * or non-blocking IO.
1530 * When it finishes, one packet has been decoded and can be found in
1531 * ssl->s3->rrec.type - is the type of record
1532 * ssl->s3->rrec.data, - data
1533 * ssl->s3->rrec.length, - number of bytes
1535 /* used only by dtls1_read_bytes */
1536 int dtls1_get_record(SSL *s)
1538 int ssl_major, ssl_minor;
1541 unsigned char *p = NULL;
1542 unsigned short version;
1543 DTLS1_BITMAP *bitmap;
1544 unsigned int is_next_epoch;
1546 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1549 * The epoch may have changed. If so, process all the pending records.
1550 * This is a non-blocking operation.
1552 if (dtls1_process_buffered_records(s) < 0)
1555 /* if we're renegotiating, then there may be buffered records */
1556 if (dtls1_get_processed_record(s))
1559 /* get something from the wire */
1561 /* check if we have the header */
1562 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1563 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1564 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1565 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1566 /* read timeout is handled by dtls1_read_bytes */
1568 return (n); /* error or non-blocking */
1570 /* this packet contained a partial record, dump it */
1571 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1572 RECORD_LAYER_reset_packet_length(&s->rlayer);
1576 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1578 p = RECORD_LAYER_get_packet(&s->rlayer);
1580 if (s->msg_callback)
1581 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1582 s, s->msg_callback_arg);
1584 /* Pull apart the header into the DTLS1_RECORD */
1588 version = (ssl_major << 8) | ssl_minor;
1590 /* sequence number is 64 bits, with top 2 bytes = epoch */
1593 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1598 /* Lets check version */
1599 if (!s->first_packet) {
1600 if (version != s->version) {
1601 /* unexpected version, silently discard */
1603 RECORD_LAYER_reset_packet_length(&s->rlayer);
1608 if ((version & 0xff00) != (s->version & 0xff00)) {
1609 /* wrong version, silently discard record */
1611 RECORD_LAYER_reset_packet_length(&s->rlayer);
1615 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1616 /* record too long, silently discard it */
1618 RECORD_LAYER_reset_packet_length(&s->rlayer);
1622 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1625 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1628 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1629 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1631 n = ssl3_read_n(s, i, i, 1, 1);
1632 /* this packet contained a partial record, dump it */
1635 RECORD_LAYER_reset_packet_length(&s->rlayer);
1640 * now n == rr->length, and s->packet_length ==
1641 * DTLS1_RT_HEADER_LENGTH + rr->length
1644 /* set state for later operations */
1645 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1647 /* match epochs. NULL means the packet is dropped on the floor */
1648 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1649 if (bitmap == NULL) {
1651 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1652 goto again; /* get another record */
1654 #ifndef OPENSSL_NO_SCTP
1655 /* Only do replay check if no SCTP bio */
1656 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1658 /* Check whether this is a repeat, or aged record. */
1659 if (!dtls1_record_replay_check(s, bitmap)) {
1661 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1662 goto again; /* get another record */
1664 #ifndef OPENSSL_NO_SCTP
1668 /* just read a 0 length packet */
1669 if (rr->length == 0)
1673 * If this record is from the next epoch (either HM or ALERT), and a
1674 * handshake is currently in progress, buffer it since it cannot be
1675 * processed at this time.
1677 if (is_next_epoch) {
1678 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1679 if (dtls1_buffer_record
1680 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1683 /* Mark receipt of record. */
1684 dtls1_record_bitmap_update(s, bitmap);
1687 RECORD_LAYER_reset_packet_length(&s->rlayer);
1691 if (!dtls1_process_record(s)) {
1693 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1694 goto again; /* get another record */
1696 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */