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)) {
276 * |num_recs| here will actually always be 0 because
277 * |num_recs > 0| only ever occurs when we are processing
278 * multiple app data records - which we know isn't the case here
279 * because it is an SSLv2ClientHello. We keep it using
280 * |num_recs| for the sake of consistency
282 rr[num_recs].type = SSL3_RT_HANDSHAKE;
283 rr[num_recs].rec_version = SSL2_VERSION;
285 rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
287 if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf)
288 - SSL2_RT_HEADER_LENGTH) {
289 al = SSL_AD_RECORD_OVERFLOW;
290 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
294 if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
295 al = SSL_AD_HANDSHAKE_FAILURE;
296 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
300 /* SSLv3+ style record */
302 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
303 s->msg_callback_arg);
305 /* Pull apart the header into the SSL3_RECORD */
306 rr[num_recs].type = *(p++);
309 version = (ssl_major << 8) | ssl_minor;
310 rr[num_recs].rec_version = version;
311 n2s(p, rr[num_recs].length);
313 /* Lets check version */
314 if (!s->first_packet && version != s->version) {
315 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
316 if ((s->version & 0xFF00) == (version & 0xFF00)
317 && !s->enc_write_ctx && !s->write_hash) {
318 if (rr->type == SSL3_RT_ALERT) {
320 * The record is using an incorrect version number,
321 * but what we've got appears to be an alert. We
322 * haven't read the body yet to check whether its a
323 * fatal or not - but chances are it is. We probably
324 * shouldn't send a fatal alert back. We'll just
330 * Send back error using their minor version number :-)
332 s->version = (unsigned short)version;
334 al = SSL_AD_PROTOCOL_VERSION;
338 if ((version >> 8) != SSL3_VERSION_MAJOR) {
339 if (s->first_packet) {
340 /* Go back to start of packet, look at the five bytes
342 p = RECORD_LAYER_get_packet(&s->rlayer);
343 if (strncmp((char *)p, "GET ", 4) == 0 ||
344 strncmp((char *)p, "POST ", 5) == 0 ||
345 strncmp((char *)p, "HEAD ", 5) == 0 ||
346 strncmp((char *)p, "PUT ", 4) == 0) {
347 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
349 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
350 SSLerr(SSL_F_SSL3_GET_RECORD,
351 SSL_R_HTTPS_PROXY_REQUEST);
355 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
359 if (rr[num_recs].length >
360 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
361 al = SSL_AD_RECORD_OVERFLOW;
362 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
367 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
371 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
372 * Calculate how much more data we need to read for the rest of the
375 if (rr[num_recs].rec_version == SSL2_VERSION) {
376 i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
377 - SSL3_RT_HEADER_LENGTH;
379 i = rr[num_recs].length;
382 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
384 n = ssl3_read_n(s, i, i, 1, 0);
386 return (n); /* error or non-blocking io */
389 /* set state for later operations */
390 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
393 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
394 * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
395 * and we have that many bytes in s->packet
397 if(rr[num_recs].rec_version == SSL2_VERSION) {
399 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
402 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
406 * ok, we can now read from 's->packet' data into 'rr' rr->input points
407 * at rr->length bytes, which need to be copied into rr->data by either
408 * the decryption or by the decompression When the data is 'copied' into
409 * the rr->data buffer, rr->input will be pointed at the new buffer
413 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
414 * bytes of encrypted compressed stuff.
417 /* check is not needed I believe */
418 if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
419 al = SSL_AD_RECORD_OVERFLOW;
420 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
424 /* decrypt in place in 'rr->input' */
425 rr[num_recs].data = rr[num_recs].input;
426 rr[num_recs].orig_len = rr[num_recs].length;
429 /* we have pulled in a full packet so zero things */
430 RECORD_LAYER_reset_packet_length(&s->rlayer);
431 } while (num_recs < max_recs
432 && rr[num_recs-1].type == SSL3_RT_APPLICATION_DATA
433 && SSL_USE_EXPLICIT_IV(s)
434 && s->enc_read_ctx != NULL
435 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
436 & EVP_CIPH_FLAG_PIPELINE)
437 && ssl3_record_app_data_waiting(s));
441 * If in encrypt-then-mac mode calculate mac from encrypted record. All
442 * the details below are public so no timing details can leak.
444 if (SSL_USE_ETM(s) && s->read_hash) {
446 mac_size = EVP_MD_CTX_size(s->read_hash);
447 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
448 for (j = 0; j < num_recs; j++) {
449 if (rr[j].length < mac_size) {
450 al = SSL_AD_DECODE_ERROR;
451 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
454 rr[j].length -= mac_size;
455 mac = rr[j].data + rr[j].length;
456 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
457 if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
458 al = SSL_AD_BAD_RECORD_MAC;
459 SSLerr(SSL_F_SSL3_GET_RECORD,
460 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
466 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
469 * 0: (in non-constant time) if the record is publically invalid.
470 * 1: if the padding is valid
471 * -1: if the padding is invalid
474 al = SSL_AD_DECRYPTION_FAILED;
475 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
479 printf("dec %d\n", rr->length);
482 for (z = 0; z < rr->length; z++)
483 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
488 /* r->length is now the compressed data plus mac */
489 if ((sess != NULL) &&
490 (s->enc_read_ctx != NULL) &&
491 (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
492 /* s->read_hash != NULL => mac_size != -1 */
493 unsigned char *mac = NULL;
494 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
496 mac_size = EVP_MD_CTX_size(s->read_hash);
497 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
499 for (j=0; j < num_recs; j++) {
501 * orig_len is the length of the record before any padding was
502 * removed. This is public information, as is the MAC in use,
503 * therefore we can safely process the record in a different amount
504 * of time if it's too short to possibly contain a MAC.
506 if (rr[j].orig_len < mac_size ||
507 /* CBC records must have a padding length byte too. */
508 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
509 rr[j].orig_len < mac_size + 1)) {
510 al = SSL_AD_DECODE_ERROR;
511 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
515 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
517 * We update the length so that the TLS header bytes can be
518 * constructed correctly but we need to extract the MAC in
519 * constant time from within the record, without leaking the
520 * contents of the padding bytes.
523 ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
524 rr[j].length -= mac_size;
527 * In this case there's no padding, so |rec->orig_len| equals
528 * |rec->length| and we checked that there's enough bytes for
531 rr[j].length -= mac_size;
532 mac = &rr[j].data[rr[j].length];
535 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
536 if (i < 0 || mac == NULL
537 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
539 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
546 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
547 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
548 * failure is directly visible from the ciphertext anyway, we should
549 * not reveal which kind of error occurred -- this might become
550 * visible to an attacker (e.g. via a logfile)
552 al = SSL_AD_BAD_RECORD_MAC;
553 SSLerr(SSL_F_SSL3_GET_RECORD,
554 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
558 for (j = 0; j < num_recs; j++) {
559 /* rr[j].length is now just compressed */
560 if (s->expand != NULL) {
561 if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
562 al = SSL_AD_RECORD_OVERFLOW;
563 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
566 if (!ssl3_do_uncompress(s, &rr[j])) {
567 al = SSL_AD_DECOMPRESSION_FAILURE;
568 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
573 if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
574 al = SSL_AD_RECORD_OVERFLOW;
575 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
581 * So at this point the following is true
582 * rr[j].type is the type of record
583 * rr[j].length == number of bytes in record
584 * rr[j].off == offset to first valid byte
585 * rr[j].data == where to take bytes from, increment after use :-).
588 /* just read a 0 length packet */
589 if (rr[j].length == 0) {
591 empty_record_count++;
592 if (empty_record_count > MAX_EMPTY_RECORDS) {
593 al = SSL_AD_UNEXPECTED_MESSAGE;
594 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
599 if (curr_empty == num_recs) {
600 /* We have no data - do it all again */
606 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
610 ssl3_send_alert(s, SSL3_AL_FATAL, al);
615 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
617 #ifndef OPENSSL_NO_COMP
620 if (rr->comp == NULL) {
621 rr->comp = (unsigned char *)
622 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
624 if (rr->comp == NULL)
627 i = COMP_expand_block(ssl->expand, rr->comp,
628 SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
639 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
641 #ifndef OPENSSL_NO_COMP
644 i = COMP_compress_block(ssl->compress, wr->data,
645 SSL3_RT_MAX_COMPRESSED_LENGTH,
646 wr->input, (int)wr->length);
652 wr->input = wr->data;
658 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
661 * 0: (in non-constant time) if the record is publically invalid (i.e. too
663 * 1: if the record's padding is valid / the encryption was successful.
664 * -1: if the record's padding is invalid or, if sending, an internal error
667 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
672 int bs, i, mac_size = 0;
673 const EVP_CIPHER *enc;
677 * We shouldn't ever be called with more than one record in the SSLv3 case
682 ds = s->enc_write_ctx;
683 if (s->enc_write_ctx == NULL)
686 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
688 ds = s->enc_read_ctx;
689 if (s->enc_read_ctx == NULL)
692 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
695 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
696 memmove(rec->data, rec->input, rec->length);
697 rec->input = rec->data;
700 bs = EVP_CIPHER_CTX_block_size(ds);
704 if ((bs != 1) && send) {
705 i = bs - ((int)l % bs);
707 /* we need to add 'i-1' padding bytes */
710 * the last of these zero bytes will be overwritten with the
713 memset(&rec->input[rec->length], 0, i);
715 rec->input[l - 1] = (i - 1);
719 if (l == 0 || l % bs != 0)
721 /* otherwise, rec->length >= bs */
724 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
727 if (EVP_MD_CTX_md(s->read_hash) != NULL)
728 mac_size = EVP_MD_CTX_size(s->read_hash);
729 if ((bs != 1) && !send)
730 return ssl3_cbc_remove_padding(rec, bs, mac_size);
736 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
739 * 0: (in non-constant time) if the record is publically invalid (i.e. too
741 * 1: if the record's padding is valid / the encryption was successful.
742 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
743 * an internal error occurred.
745 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
748 size_t reclen[SSL_MAX_PIPELINES];
749 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
750 int bs, i, j, k, pad = 0, ret, mac_size = 0;
751 const EVP_CIPHER *enc;
755 if (EVP_MD_CTX_md(s->write_hash)) {
756 int n = EVP_MD_CTX_size(s->write_hash);
757 OPENSSL_assert(n >= 0);
759 ds = s->enc_write_ctx;
760 if (s->enc_write_ctx == NULL)
764 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
765 /* For TLSv1.1 and later explicit IV */
766 if (SSL_USE_EXPLICIT_IV(s)
767 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
768 ivlen = EVP_CIPHER_iv_length(enc);
772 for (ctr = 0; ctr < n_recs; ctr++) {
773 if (recs[ctr].data != recs[ctr].input) {
775 * we can't write into the input stream: Can this ever
778 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
780 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
781 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
788 if (EVP_MD_CTX_md(s->read_hash)) {
789 int n = EVP_MD_CTX_size(s->read_hash);
790 OPENSSL_assert(n >= 0);
792 ds = s->enc_read_ctx;
793 if (s->enc_read_ctx == NULL)
796 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
799 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
800 for (ctr = 0; ctr < n_recs; ctr++) {
801 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
802 recs[ctr].input = recs[ctr].data;
806 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
809 if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
810 & EVP_CIPH_FLAG_PIPELINE)) {
812 * We shouldn't have been called with pipeline data if the
813 * cipher doesn't support pipelining
815 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
819 for (ctr = 0; ctr < n_recs; ctr++) {
820 reclen[ctr] = recs[ctr].length;
822 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
823 & EVP_CIPH_FLAG_AEAD_CIPHER) {
826 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
827 : RECORD_LAYER_get_read_sequence(&s->rlayer);
829 if (SSL_IS_DTLS(s)) {
830 /* DTLS does not support pipelining */
831 unsigned char dtlsseq[9], *p = dtlsseq;
833 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
834 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
835 memcpy(p, &seq[2], 6);
836 memcpy(buf[ctr], dtlsseq, 8);
838 memcpy(buf[ctr], seq, 8);
839 for (i = 7; i >= 0; i--) { /* increment */
846 buf[ctr][8] = recs[ctr].type;
847 buf[ctr][9] = (unsigned char)(s->version >> 8);
848 buf[ctr][10] = (unsigned char)(s->version);
849 buf[ctr][11] = recs[ctr].length >> 8;
850 buf[ctr][12] = recs[ctr].length & 0xff;
851 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
852 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
858 recs[ctr].length += pad;
861 } else if ((bs != 1) && send) {
862 i = bs - ((int)reclen[ctr] % bs);
864 /* Add weird padding of upto 256 bytes */
866 /* we need to add 'i' padding bytes of value j */
868 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
869 recs[ctr].input[k] = j;
871 recs[ctr].length += i;
875 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
880 unsigned char *data[SSL_MAX_PIPELINES];
882 /* Set the output buffers */
883 for(ctr = 0; ctr < n_recs; ctr++) {
884 data[ctr] = recs[ctr].data;
886 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
887 n_recs, data) <= 0) {
888 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
890 /* Set the input buffers */
891 for(ctr = 0; ctr < n_recs; ctr++) {
892 data[ctr] = recs[ctr].input;
894 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
896 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
897 n_recs, reclen) <= 0) {
898 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
903 i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
904 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
905 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
908 return -1; /* AEAD can fail to verify MAC */
910 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
911 for (ctr = 0; ctr < n_recs; ctr++) {
912 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
913 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
914 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
916 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
917 for (ctr = 0; ctr < n_recs; ctr++) {
918 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
919 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
920 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
926 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
927 mac_size = EVP_MD_CTX_size(s->read_hash);
928 if ((bs != 1) && !send) {
930 for (ctr = 0; ctr < n_recs; ctr++) {
931 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
938 for (ctr = 0; ctr < n_recs; ctr++) {
939 recs[ctr].length -= pad;
946 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
948 unsigned char *mac_sec, *seq;
949 const EVP_MD_CTX *hash;
950 unsigned char *p, rec_char;
956 mac_sec = &(ssl->s3->write_mac_secret[0]);
957 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
958 hash = ssl->write_hash;
960 mac_sec = &(ssl->s3->read_mac_secret[0]);
961 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
962 hash = ssl->read_hash;
965 t = EVP_MD_CTX_size(hash);
969 npad = (48 / md_size) * md_size;
972 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
973 ssl3_cbc_record_digest_supported(hash)) {
975 * This is a CBC-encrypted record. We must avoid leaking any
976 * timing-side channel information about how many blocks of data we
977 * are hashing because that gives an attacker a timing-oracle.
981 * npad is, at most, 48 bytes and that's with MD5:
982 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
984 * With SHA-1 (the largest hash speced for SSLv3) the hash size
985 * goes up 4, but npad goes down by 8, resulting in a smaller
988 unsigned char header[75];
990 memcpy(header + j, mac_sec, md_size);
992 memcpy(header + j, ssl3_pad_1, npad);
994 memcpy(header + j, seq, 8);
996 header[j++] = rec->type;
997 header[j++] = rec->length >> 8;
998 header[j++] = rec->length & 0xff;
1000 /* Final param == is SSLv3 */
1001 if (ssl3_cbc_digest_record(hash,
1004 rec->length + md_size, rec->orig_len,
1005 mac_sec, md_size, 1) <= 0)
1008 unsigned int md_size_u;
1009 /* Chop the digest off the end :-) */
1010 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1015 rec_char = rec->type;
1017 s2n(rec->length, p);
1018 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1019 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1020 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1021 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1022 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1023 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1024 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1025 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1026 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1027 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1028 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1029 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1030 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1031 EVP_MD_CTX_reset(md_ctx);
1034 md_size = md_size_u;
1036 EVP_MD_CTX_free(md_ctx);
1039 ssl3_record_sequence_update(seq);
1043 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1049 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1050 unsigned char header[13];
1051 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1052 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1056 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1057 hash = ssl->write_hash;
1059 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1060 hash = ssl->read_hash;
1063 t = EVP_MD_CTX_size(hash);
1064 OPENSSL_assert(t >= 0);
1067 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1071 hmac = EVP_MD_CTX_new();
1073 || !EVP_MD_CTX_copy(hmac, hash))
1078 if (SSL_IS_DTLS(ssl)) {
1079 unsigned char dtlsseq[8], *p = dtlsseq;
1081 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1082 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1083 memcpy(p, &seq[2], 6);
1085 memcpy(header, dtlsseq, 8);
1087 memcpy(header, seq, 8);
1089 header[8] = rec->type;
1090 header[9] = (unsigned char)(ssl->version >> 8);
1091 header[10] = (unsigned char)(ssl->version);
1092 header[11] = (rec->length) >> 8;
1093 header[12] = (rec->length) & 0xff;
1095 if (!send && !SSL_USE_ETM(ssl) &&
1096 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1097 ssl3_cbc_record_digest_supported(mac_ctx)) {
1099 * This is a CBC-encrypted record. We must avoid leaking any
1100 * timing-side channel information about how many blocks of data we
1101 * are hashing because that gives an attacker a timing-oracle.
1103 /* Final param == not SSLv3 */
1104 if (ssl3_cbc_digest_record(mac_ctx,
1107 rec->length + md_size, rec->orig_len,
1108 ssl->s3->read_mac_secret,
1109 ssl->s3->read_mac_secret_size, 0) <= 0) {
1110 EVP_MD_CTX_free(hmac);
1114 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1115 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1116 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1117 EVP_MD_CTX_free(hmac);
1120 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1121 tls_fips_digest_extra(ssl->enc_read_ctx,
1122 mac_ctx, rec->input,
1123 rec->length, rec->orig_len);
1126 EVP_MD_CTX_free(hmac);
1129 fprintf(stderr, "seq=");
1132 for (z = 0; z < 8; z++)
1133 fprintf(stderr, "%02X ", seq[z]);
1134 fprintf(stderr, "\n");
1136 fprintf(stderr, "rec=");
1139 for (z = 0; z < rec->length; z++)
1140 fprintf(stderr, "%02X ", rec->data[z]);
1141 fprintf(stderr, "\n");
1145 if (!SSL_IS_DTLS(ssl)) {
1146 for (i = 7; i >= 0; i--) {
1155 for (z = 0; z < md_size; z++)
1156 fprintf(stderr, "%02X ", md[z]);
1157 fprintf(stderr, "\n");
1164 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1165 * record in |rec| by updating |rec->length| in constant time.
1167 * block_size: the block size of the cipher used to encrypt the record.
1169 * 0: (in non-constant time) if the record is publicly invalid.
1170 * 1: if the padding was valid
1173 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1174 unsigned block_size, unsigned mac_size)
1176 unsigned padding_length, good;
1177 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1180 * These lengths are all public so we can test them in non-constant time.
1182 if (overhead > rec->length)
1185 padding_length = rec->data[rec->length - 1];
1186 good = constant_time_ge(rec->length, padding_length + overhead);
1187 /* SSLv3 requires that the padding is minimal. */
1188 good &= constant_time_ge(block_size, padding_length + 1);
1189 rec->length -= good & (padding_length + 1);
1190 return constant_time_select_int(good, 1, -1);
1194 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1195 * record in |rec| in constant time and returns 1 if the padding is valid and
1196 * -1 otherwise. It also removes any explicit IV from the start of the record
1197 * without leaking any timing about whether there was enough space after the
1198 * padding was removed.
1200 * block_size: the block size of the cipher used to encrypt the record.
1202 * 0: (in non-constant time) if the record is publicly invalid.
1203 * 1: if the padding was valid
1206 int tls1_cbc_remove_padding(const SSL *s,
1208 unsigned block_size, unsigned mac_size)
1210 unsigned padding_length, good, to_check, i;
1211 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1212 /* Check if version requires explicit IV */
1213 if (SSL_USE_EXPLICIT_IV(s)) {
1215 * These lengths are all public so we can test them in non-constant
1218 if (overhead + block_size > rec->length)
1220 /* We can now safely skip explicit IV */
1221 rec->data += block_size;
1222 rec->input += block_size;
1223 rec->length -= block_size;
1224 rec->orig_len -= block_size;
1225 } else if (overhead > rec->length)
1228 padding_length = rec->data[rec->length - 1];
1230 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1231 /* padding is already verified */
1232 rec->length -= padding_length + 1;
1236 good = constant_time_ge(rec->length, overhead + padding_length);
1238 * The padding consists of a length byte at the end of the record and
1239 * then that many bytes of padding, all with the same value as the length
1240 * byte. Thus, with the length byte included, there are i+1 bytes of
1241 * padding. We can't check just |padding_length+1| bytes because that
1242 * leaks decrypted information. Therefore we always have to check the
1243 * maximum amount of padding possible. (Again, the length of the record
1244 * is public information so we can use it.)
1246 to_check = 255; /* maximum amount of padding. */
1247 if (to_check > rec->length - 1)
1248 to_check = rec->length - 1;
1250 for (i = 0; i < to_check; i++) {
1251 unsigned char mask = constant_time_ge_8(padding_length, i);
1252 unsigned char b = rec->data[rec->length - 1 - i];
1254 * The final |padding_length+1| bytes should all have the value
1255 * |padding_length|. Therefore the XOR should be zero.
1257 good &= ~(mask & (padding_length ^ b));
1261 * If any of the final |padding_length+1| bytes had the wrong value, one
1262 * or more of the lower eight bits of |good| will be cleared.
1264 good = constant_time_eq(0xff, good & 0xff);
1265 rec->length -= good & (padding_length + 1);
1267 return constant_time_select_int(good, 1, -1);
1271 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1272 * constant time (independent of the concrete value of rec->length, which may
1273 * vary within a 256-byte window).
1275 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1279 * rec->orig_len >= md_size
1280 * md_size <= EVP_MAX_MD_SIZE
1282 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1283 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1284 * a single or pair of cache-lines, then the variable memory accesses don't
1285 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1286 * not multi-core and are not considered vulnerable to cache-timing attacks.
1288 #define CBC_MAC_ROTATE_IN_PLACE
1290 void ssl3_cbc_copy_mac(unsigned char *out,
1291 const SSL3_RECORD *rec, unsigned md_size)
1293 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1294 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1295 unsigned char *rotated_mac;
1297 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1301 * mac_end is the index of |rec->data| just after the end of the MAC.
1303 unsigned mac_end = rec->length;
1304 unsigned mac_start = mac_end - md_size;
1306 * scan_start contains the number of bytes that we can ignore because the
1307 * MAC's position can only vary by 255 bytes.
1309 unsigned scan_start = 0;
1311 unsigned div_spoiler;
1312 unsigned rotate_offset;
1314 OPENSSL_assert(rec->orig_len >= md_size);
1315 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1317 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1318 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1321 /* This information is public so it's safe to branch based on it. */
1322 if (rec->orig_len > md_size + 255 + 1)
1323 scan_start = rec->orig_len - (md_size + 255 + 1);
1325 * div_spoiler contains a multiple of md_size that is used to cause the
1326 * modulo operation to be constant time. Without this, the time varies
1327 * based on the amount of padding when running on Intel chips at least.
1328 * The aim of right-shifting md_size is so that the compiler doesn't
1329 * figure out that it can remove div_spoiler as that would require it to
1330 * prove that md_size is always even, which I hope is beyond it.
1332 div_spoiler = md_size >> 1;
1333 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1334 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1336 memset(rotated_mac, 0, md_size);
1337 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1338 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1339 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1340 unsigned char b = rec->data[i];
1341 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1342 j &= constant_time_lt(j, md_size);
1345 /* Now rotate the MAC */
1346 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1348 for (i = 0; i < md_size; i++) {
1349 /* in case cache-line is 32 bytes, touch second line */
1350 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1351 out[j++] = rotated_mac[rotate_offset++];
1352 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1355 memset(out, 0, md_size);
1356 rotate_offset = md_size - rotate_offset;
1357 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1358 for (i = 0; i < md_size; i++) {
1359 for (j = 0; j < md_size; j++)
1360 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1362 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1367 int dtls1_process_record(SSL *s)
1373 unsigned int mac_size;
1374 unsigned char md[EVP_MAX_MD_SIZE];
1376 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1380 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1381 * and we have that many bytes in s->packet
1383 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1386 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1387 * at rr->length bytes, which need to be copied into rr->data by either
1388 * the decryption or by the decompression When the data is 'copied' into
1389 * the rr->data buffer, rr->input will be pointed at the new buffer
1393 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1394 * bytes of encrypted compressed stuff.
1397 /* check is not needed I believe */
1398 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1399 al = SSL_AD_RECORD_OVERFLOW;
1400 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1404 /* decrypt in place in 'rr->input' */
1405 rr->data = rr->input;
1406 rr->orig_len = rr->length;
1408 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1411 * 0: (in non-constant time) if the record is publically invalid.
1412 * 1: if the padding is valid
1413 * -1: if the padding is invalid
1416 /* For DTLS we simply ignore bad packets. */
1418 RECORD_LAYER_reset_packet_length(&s->rlayer);
1422 printf("dec %d\n", rr->length);
1425 for (z = 0; z < rr->length; z++)
1426 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1431 /* r->length is now the compressed data plus mac */
1432 if ((sess != NULL) &&
1433 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1434 /* s->read_hash != NULL => mac_size != -1 */
1435 unsigned char *mac = NULL;
1436 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1437 mac_size = EVP_MD_CTX_size(s->read_hash);
1438 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1441 * orig_len is the length of the record before any padding was
1442 * removed. This is public information, as is the MAC in use,
1443 * therefore we can safely process the record in a different amount
1444 * of time if it's too short to possibly contain a MAC.
1446 if (rr->orig_len < mac_size ||
1447 /* CBC records must have a padding length byte too. */
1448 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1449 rr->orig_len < mac_size + 1)) {
1450 al = SSL_AD_DECODE_ERROR;
1451 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1455 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1457 * We update the length so that the TLS header bytes can be
1458 * constructed correctly but we need to extract the MAC in
1459 * constant time from within the record, without leaking the
1460 * contents of the padding bytes.
1463 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1464 rr->length -= mac_size;
1467 * In this case there's no padding, so |rec->orig_len| equals
1468 * |rec->length| and we checked that there's enough bytes for
1471 rr->length -= mac_size;
1472 mac = &rr->data[rr->length];
1475 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1476 if (i < 0 || mac == NULL
1477 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1479 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1484 /* decryption failed, silently discard message */
1486 RECORD_LAYER_reset_packet_length(&s->rlayer);
1490 /* r->length is now just compressed */
1491 if (s->expand != NULL) {
1492 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1493 al = SSL_AD_RECORD_OVERFLOW;
1494 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1495 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1498 if (!ssl3_do_uncompress(s, rr)) {
1499 al = SSL_AD_DECOMPRESSION_FAILURE;
1500 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1505 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1506 al = SSL_AD_RECORD_OVERFLOW;
1507 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1513 * So at this point the following is true
1514 * ssl->s3->rrec.type is the type of record
1515 * ssl->s3->rrec.length == number of bytes in record
1516 * ssl->s3->rrec.off == offset to first valid byte
1517 * ssl->s3->rrec.data == where to take bytes from, increment
1521 /* we have pulled in a full packet so zero things */
1522 RECORD_LAYER_reset_packet_length(&s->rlayer);
1526 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1533 * retrieve a buffered record that belongs to the current epoch, ie,
1536 #define dtls1_get_processed_record(s) \
1537 dtls1_retrieve_buffered_record((s), \
1538 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1541 * Call this to get a new input record.
1542 * It will return <= 0 if more data is needed, normally due to an error
1543 * or non-blocking IO.
1544 * When it finishes, one packet has been decoded and can be found in
1545 * ssl->s3->rrec.type - is the type of record
1546 * ssl->s3->rrec.data, - data
1547 * ssl->s3->rrec.length, - number of bytes
1549 /* used only by dtls1_read_bytes */
1550 int dtls1_get_record(SSL *s)
1552 int ssl_major, ssl_minor;
1555 unsigned char *p = NULL;
1556 unsigned short version;
1557 DTLS1_BITMAP *bitmap;
1558 unsigned int is_next_epoch;
1560 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1563 * The epoch may have changed. If so, process all the pending records.
1564 * This is a non-blocking operation.
1566 if (dtls1_process_buffered_records(s) < 0)
1569 /* if we're renegotiating, then there may be buffered records */
1570 if (dtls1_get_processed_record(s))
1573 /* get something from the wire */
1575 /* check if we have the header */
1576 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1577 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1578 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1579 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1580 /* read timeout is handled by dtls1_read_bytes */
1582 return (n); /* error or non-blocking */
1584 /* this packet contained a partial record, dump it */
1585 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1586 RECORD_LAYER_reset_packet_length(&s->rlayer);
1590 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1592 p = RECORD_LAYER_get_packet(&s->rlayer);
1594 if (s->msg_callback)
1595 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1596 s, s->msg_callback_arg);
1598 /* Pull apart the header into the DTLS1_RECORD */
1602 version = (ssl_major << 8) | ssl_minor;
1604 /* sequence number is 64 bits, with top 2 bytes = epoch */
1607 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1612 /* Lets check version */
1613 if (!s->first_packet) {
1614 if (version != s->version) {
1615 /* unexpected version, silently discard */
1617 RECORD_LAYER_reset_packet_length(&s->rlayer);
1622 if ((version & 0xff00) != (s->version & 0xff00)) {
1623 /* wrong version, silently discard record */
1625 RECORD_LAYER_reset_packet_length(&s->rlayer);
1629 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1630 /* record too long, silently discard it */
1632 RECORD_LAYER_reset_packet_length(&s->rlayer);
1636 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1639 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1642 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1643 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1645 n = ssl3_read_n(s, i, i, 1, 1);
1646 /* this packet contained a partial record, dump it */
1649 RECORD_LAYER_reset_packet_length(&s->rlayer);
1654 * now n == rr->length, and s->packet_length ==
1655 * DTLS1_RT_HEADER_LENGTH + rr->length
1658 /* set state for later operations */
1659 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1661 /* match epochs. NULL means the packet is dropped on the floor */
1662 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1663 if (bitmap == NULL) {
1665 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1666 goto again; /* get another record */
1668 #ifndef OPENSSL_NO_SCTP
1669 /* Only do replay check if no SCTP bio */
1670 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1672 /* Check whether this is a repeat, or aged record. */
1673 if (!dtls1_record_replay_check(s, bitmap)) {
1675 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1676 goto again; /* get another record */
1678 #ifndef OPENSSL_NO_SCTP
1682 /* just read a 0 length packet */
1683 if (rr->length == 0)
1687 * If this record is from the next epoch (either HM or ALERT), and a
1688 * handshake is currently in progress, buffer it since it cannot be
1689 * processed at this time.
1691 if (is_next_epoch) {
1692 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1693 if (dtls1_buffer_record
1694 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1697 /* Mark receipt of record. */
1698 dtls1_record_bitmap_update(s, bitmap);
1701 RECORD_LAYER_reset_packet_length(&s->rlayer);
1705 if (!dtls1_process_record(s)) {
1707 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1708 goto again; /* get another record */
1710 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */