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)
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
424 && rr[num_recs-1].type == SSL3_RT_APPLICATION_DATA
425 && SSL_USE_EXPLICIT_IV(s)
426 && s->enc_read_ctx != NULL
427 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
428 & EVP_CIPH_FLAG_PIPELINE)
429 && ssl3_record_app_data_waiting(s));
433 * If in encrypt-then-mac mode calculate mac from encrypted record. All
434 * the details below are public so no timing details can leak.
436 if (SSL_USE_ETM(s) && s->read_hash) {
438 mac_size = EVP_MD_CTX_size(s->read_hash);
439 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
440 for (j = 0; j < num_recs; j++) {
441 if (rr[j].length < mac_size) {
442 al = SSL_AD_DECODE_ERROR;
443 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
446 rr[j].length -= mac_size;
447 mac = rr[j].data + rr[j].length;
448 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
449 if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
450 al = SSL_AD_BAD_RECORD_MAC;
451 SSLerr(SSL_F_SSL3_GET_RECORD,
452 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
458 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
461 * 0: (in non-constant time) if the record is publically invalid.
462 * 1: if the padding is valid
463 * -1: if the padding is invalid
466 al = SSL_AD_DECRYPTION_FAILED;
467 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
471 printf("dec %d\n", rr->length);
474 for (z = 0; z < rr->length; z++)
475 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
480 /* r->length is now the compressed data plus mac */
481 if ((sess != NULL) &&
482 (s->enc_read_ctx != NULL) &&
483 (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
484 /* s->read_hash != NULL => mac_size != -1 */
485 unsigned char *mac = NULL;
486 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
488 mac_size = EVP_MD_CTX_size(s->read_hash);
489 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
491 for (j=0; j < num_recs; j++) {
493 * orig_len is the length of the record before any padding was
494 * removed. This is public information, as is the MAC in use,
495 * therefore we can safely process the record in a different amount
496 * of time if it's too short to possibly contain a MAC.
498 if (rr[j].orig_len < mac_size ||
499 /* CBC records must have a padding length byte too. */
500 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
501 rr[j].orig_len < mac_size + 1)) {
502 al = SSL_AD_DECODE_ERROR;
503 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
507 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
509 * We update the length so that the TLS header bytes can be
510 * constructed correctly but we need to extract the MAC in
511 * constant time from within the record, without leaking the
512 * contents of the padding bytes.
515 ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
516 rr[j].length -= mac_size;
519 * In this case there's no padding, so |rec->orig_len| equals
520 * |rec->length| and we checked that there's enough bytes for
523 rr[j].length -= mac_size;
524 mac = &rr[j].data[rr[j].length];
527 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
528 if (i < 0 || mac == NULL
529 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
531 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
538 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
539 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
540 * failure is directly visible from the ciphertext anyway, we should
541 * not reveal which kind of error occurred -- this might become
542 * visible to an attacker (e.g. via a logfile)
544 al = SSL_AD_BAD_RECORD_MAC;
545 SSLerr(SSL_F_SSL3_GET_RECORD,
546 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
550 for (j = 0; j < num_recs; j++) {
551 /* rr[j].length is now just compressed */
552 if (s->expand != NULL) {
553 if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
554 al = SSL_AD_RECORD_OVERFLOW;
555 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
558 if (!ssl3_do_uncompress(s, &rr[j])) {
559 al = SSL_AD_DECOMPRESSION_FAILURE;
560 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
565 if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
566 al = SSL_AD_RECORD_OVERFLOW;
567 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
573 * So at this point the following is true
574 * rr[j].type is the type of record
575 * rr[j].length == number of bytes in record
576 * rr[j].off == offset to first valid byte
577 * rr[j].data == where to take bytes from, increment after use :-).
580 /* just read a 0 length packet */
581 if (rr[j].length == 0) {
583 empty_record_count++;
584 if (empty_record_count > MAX_EMPTY_RECORDS) {
585 al = SSL_AD_UNEXPECTED_MESSAGE;
586 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
591 if (curr_empty == num_recs) {
592 /* We have no data - do it all again */
598 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
602 ssl3_send_alert(s, SSL3_AL_FATAL, al);
607 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
609 #ifndef OPENSSL_NO_COMP
612 if (rr->comp == NULL) {
613 rr->comp = (unsigned char *)
614 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
616 if (rr->comp == NULL)
619 i = COMP_expand_block(ssl->expand, rr->comp,
620 SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
631 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
633 #ifndef OPENSSL_NO_COMP
636 i = COMP_compress_block(ssl->compress, wr->data,
637 SSL3_RT_MAX_COMPRESSED_LENGTH,
638 wr->input, (int)wr->length);
644 wr->input = wr->data;
650 * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
653 * 0: (in non-constant time) if the record is publically invalid (i.e. too
655 * 1: if the record's padding is valid / the encryption was successful.
656 * -1: if the record's padding is invalid or, if sending, an internal error
659 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
664 int bs, i, mac_size = 0;
665 const EVP_CIPHER *enc;
669 * We shouldn't ever be called with more than one record in the SSLv3 case
674 ds = s->enc_write_ctx;
675 if (s->enc_write_ctx == NULL)
678 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
680 ds = s->enc_read_ctx;
681 if (s->enc_read_ctx == NULL)
684 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
687 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
688 memmove(rec->data, rec->input, rec->length);
689 rec->input = rec->data;
692 bs = EVP_CIPHER_CTX_block_size(ds);
696 if ((bs != 1) && send) {
697 i = bs - ((int)l % bs);
699 /* we need to add 'i-1' padding bytes */
702 * the last of these zero bytes will be overwritten with the
705 memset(&rec->input[rec->length], 0, i);
707 rec->input[l - 1] = (i - 1);
711 if (l == 0 || l % bs != 0)
713 /* otherwise, rec->length >= bs */
716 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
719 if (EVP_MD_CTX_md(s->read_hash) != NULL)
720 mac_size = EVP_MD_CTX_size(s->read_hash);
721 if ((bs != 1) && !send)
722 return ssl3_cbc_remove_padding(rec, bs, mac_size);
728 * tls1_enc encrypts/decrypts |n_recs| in |recs|.
731 * 0: (in non-constant time) if the record is publically invalid (i.e. too
733 * 1: if the record's padding is valid / the encryption was successful.
734 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
735 * an internal error occurred.
737 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
740 size_t reclen[SSL_MAX_PIPELINES];
741 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
742 int bs, i, j, k, pad = 0, ret, mac_size = 0;
743 const EVP_CIPHER *enc;
747 if (EVP_MD_CTX_md(s->write_hash)) {
748 int n = EVP_MD_CTX_size(s->write_hash);
749 OPENSSL_assert(n >= 0);
751 ds = s->enc_write_ctx;
752 if (s->enc_write_ctx == NULL)
756 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
757 /* For TLSv1.1 and later explicit IV */
758 if (SSL_USE_EXPLICIT_IV(s)
759 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
760 ivlen = EVP_CIPHER_iv_length(enc);
764 for (ctr = 0; ctr < n_recs; ctr++) {
765 if (recs[ctr].data != recs[ctr].input) {
767 * we can't write into the input stream: Can this ever
770 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
772 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
773 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
780 if (EVP_MD_CTX_md(s->read_hash)) {
781 int n = EVP_MD_CTX_size(s->read_hash);
782 OPENSSL_assert(n >= 0);
784 ds = s->enc_read_ctx;
785 if (s->enc_read_ctx == NULL)
788 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
791 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
792 for (ctr = 0; ctr < n_recs; ctr++) {
793 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
794 recs[ctr].input = recs[ctr].data;
798 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
801 if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
802 & EVP_CIPH_FLAG_PIPELINE)) {
804 * We shouldn't have been called with pipeline data if the
805 * cipher doesn't support pipelining
807 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
811 for (ctr = 0; ctr < n_recs; ctr++) {
812 reclen[ctr] = recs[ctr].length;
814 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
815 & EVP_CIPH_FLAG_AEAD_CIPHER) {
818 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
819 : RECORD_LAYER_get_read_sequence(&s->rlayer);
821 if (SSL_IS_DTLS(s)) {
822 /* DTLS does not support pipelining */
823 unsigned char dtlsseq[9], *p = dtlsseq;
825 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
826 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
827 memcpy(p, &seq[2], 6);
828 memcpy(buf[ctr], dtlsseq, 8);
830 memcpy(buf[ctr], seq, 8);
831 for (i = 7; i >= 0; i--) { /* increment */
838 buf[ctr][8] = recs[ctr].type;
839 buf[ctr][9] = (unsigned char)(s->version >> 8);
840 buf[ctr][10] = (unsigned char)(s->version);
841 buf[ctr][11] = recs[ctr].length >> 8;
842 buf[ctr][12] = recs[ctr].length & 0xff;
843 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
844 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
850 recs[ctr].length += pad;
853 } else if ((bs != 1) && send) {
854 i = bs - ((int)reclen[ctr] % bs);
856 /* Add weird padding of upto 256 bytes */
858 /* we need to add 'i' padding bytes of value j */
860 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
861 recs[ctr].input[k] = j;
863 recs[ctr].length += i;
867 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
872 unsigned char *data[SSL_MAX_PIPELINES];
874 /* Set the output buffers */
875 for(ctr = 0; ctr < n_recs; ctr++) {
876 data[ctr] = recs[ctr].data;
878 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
879 n_recs, data) <= 0) {
880 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
882 /* Set the input buffers */
883 for(ctr = 0; ctr < n_recs; ctr++) {
884 data[ctr] = recs[ctr].input;
886 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
888 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
889 n_recs, reclen) <= 0) {
890 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
895 i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
896 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
897 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
900 return -1; /* AEAD can fail to verify MAC */
902 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
903 for (ctr = 0; ctr < n_recs; ctr++) {
904 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
905 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
906 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
908 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
909 for (ctr = 0; ctr < n_recs; ctr++) {
910 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
911 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
912 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
918 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
919 mac_size = EVP_MD_CTX_size(s->read_hash);
920 if ((bs != 1) && !send) {
922 for (ctr = 0; ctr < n_recs; ctr++) {
923 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
930 for (ctr = 0; ctr < n_recs; ctr++) {
931 recs[ctr].length -= pad;
938 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
940 unsigned char *mac_sec, *seq;
941 const EVP_MD_CTX *hash;
942 unsigned char *p, rec_char;
948 mac_sec = &(ssl->s3->write_mac_secret[0]);
949 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
950 hash = ssl->write_hash;
952 mac_sec = &(ssl->s3->read_mac_secret[0]);
953 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
954 hash = ssl->read_hash;
957 t = EVP_MD_CTX_size(hash);
961 npad = (48 / md_size) * md_size;
964 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
965 ssl3_cbc_record_digest_supported(hash)) {
967 * This is a CBC-encrypted record. We must avoid leaking any
968 * timing-side channel information about how many blocks of data we
969 * are hashing because that gives an attacker a timing-oracle.
973 * npad is, at most, 48 bytes and that's with MD5:
974 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
976 * With SHA-1 (the largest hash speced for SSLv3) the hash size
977 * goes up 4, but npad goes down by 8, resulting in a smaller
980 unsigned char header[75];
982 memcpy(header + j, mac_sec, md_size);
984 memcpy(header + j, ssl3_pad_1, npad);
986 memcpy(header + j, seq, 8);
988 header[j++] = rec->type;
989 header[j++] = rec->length >> 8;
990 header[j++] = rec->length & 0xff;
992 /* Final param == is SSLv3 */
993 if (ssl3_cbc_digest_record(hash,
996 rec->length + md_size, rec->orig_len,
997 mac_sec, md_size, 1) <= 0)
1000 unsigned int md_size_u;
1001 /* Chop the digest off the end :-) */
1002 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1007 rec_char = rec->type;
1009 s2n(rec->length, p);
1010 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1011 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1012 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1013 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1014 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1015 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1016 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1017 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1018 || 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_2, npad) <= 0
1021 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1022 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1023 EVP_MD_CTX_reset(md_ctx);
1026 md_size = md_size_u;
1028 EVP_MD_CTX_free(md_ctx);
1031 ssl3_record_sequence_update(seq);
1035 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1041 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1042 unsigned char header[13];
1043 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1044 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1048 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1049 hash = ssl->write_hash;
1051 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1052 hash = ssl->read_hash;
1055 t = EVP_MD_CTX_size(hash);
1056 OPENSSL_assert(t >= 0);
1059 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1063 hmac = EVP_MD_CTX_new();
1065 || !EVP_MD_CTX_copy(hmac, hash))
1070 if (SSL_IS_DTLS(ssl)) {
1071 unsigned char dtlsseq[8], *p = dtlsseq;
1073 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1074 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1075 memcpy(p, &seq[2], 6);
1077 memcpy(header, dtlsseq, 8);
1079 memcpy(header, seq, 8);
1081 header[8] = rec->type;
1082 header[9] = (unsigned char)(ssl->version >> 8);
1083 header[10] = (unsigned char)(ssl->version);
1084 header[11] = (rec->length) >> 8;
1085 header[12] = (rec->length) & 0xff;
1087 if (!send && !SSL_USE_ETM(ssl) &&
1088 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1089 ssl3_cbc_record_digest_supported(mac_ctx)) {
1091 * This is a CBC-encrypted record. We must avoid leaking any
1092 * timing-side channel information about how many blocks of data we
1093 * are hashing because that gives an attacker a timing-oracle.
1095 /* Final param == not SSLv3 */
1096 if (ssl3_cbc_digest_record(mac_ctx,
1099 rec->length + md_size, rec->orig_len,
1100 ssl->s3->read_mac_secret,
1101 ssl->s3->read_mac_secret_size, 0) <= 0) {
1102 EVP_MD_CTX_free(hmac);
1106 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1107 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1108 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1109 EVP_MD_CTX_free(hmac);
1112 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1113 tls_fips_digest_extra(ssl->enc_read_ctx,
1114 mac_ctx, rec->input,
1115 rec->length, rec->orig_len);
1118 EVP_MD_CTX_free(hmac);
1121 fprintf(stderr, "seq=");
1124 for (z = 0; z < 8; z++)
1125 fprintf(stderr, "%02X ", seq[z]);
1126 fprintf(stderr, "\n");
1128 fprintf(stderr, "rec=");
1131 for (z = 0; z < rec->length; z++)
1132 fprintf(stderr, "%02X ", rec->data[z]);
1133 fprintf(stderr, "\n");
1137 if (!SSL_IS_DTLS(ssl)) {
1138 for (i = 7; i >= 0; i--) {
1147 for (z = 0; z < md_size; z++)
1148 fprintf(stderr, "%02X ", md[z]);
1149 fprintf(stderr, "\n");
1156 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1157 * record in |rec| by updating |rec->length| in constant time.
1159 * block_size: the block size of the cipher used to encrypt the record.
1161 * 0: (in non-constant time) if the record is publicly invalid.
1162 * 1: if the padding was valid
1165 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1166 unsigned block_size, unsigned mac_size)
1168 unsigned padding_length, good;
1169 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1172 * These lengths are all public so we can test them in non-constant time.
1174 if (overhead > rec->length)
1177 padding_length = rec->data[rec->length - 1];
1178 good = constant_time_ge(rec->length, padding_length + overhead);
1179 /* SSLv3 requires that the padding is minimal. */
1180 good &= constant_time_ge(block_size, padding_length + 1);
1181 rec->length -= good & (padding_length + 1);
1182 return constant_time_select_int(good, 1, -1);
1186 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1187 * record in |rec| in constant time and returns 1 if the padding is valid and
1188 * -1 otherwise. It also removes any explicit IV from the start of the record
1189 * without leaking any timing about whether there was enough space after the
1190 * padding was removed.
1192 * block_size: the block size of the cipher used to encrypt the record.
1194 * 0: (in non-constant time) if the record is publicly invalid.
1195 * 1: if the padding was valid
1198 int tls1_cbc_remove_padding(const SSL *s,
1200 unsigned block_size, unsigned mac_size)
1202 unsigned padding_length, good, to_check, i;
1203 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1204 /* Check if version requires explicit IV */
1205 if (SSL_USE_EXPLICIT_IV(s)) {
1207 * These lengths are all public so we can test them in non-constant
1210 if (overhead + block_size > rec->length)
1212 /* We can now safely skip explicit IV */
1213 rec->data += block_size;
1214 rec->input += block_size;
1215 rec->length -= block_size;
1216 rec->orig_len -= block_size;
1217 } else if (overhead > rec->length)
1220 padding_length = rec->data[rec->length - 1];
1222 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1223 /* padding is already verified */
1224 rec->length -= padding_length + 1;
1228 good = constant_time_ge(rec->length, overhead + padding_length);
1230 * The padding consists of a length byte at the end of the record and
1231 * then that many bytes of padding, all with the same value as the length
1232 * byte. Thus, with the length byte included, there are i+1 bytes of
1233 * padding. We can't check just |padding_length+1| bytes because that
1234 * leaks decrypted information. Therefore we always have to check the
1235 * maximum amount of padding possible. (Again, the length of the record
1236 * is public information so we can use it.)
1238 to_check = 255; /* maximum amount of padding. */
1239 if (to_check > rec->length - 1)
1240 to_check = rec->length - 1;
1242 for (i = 0; i < to_check; i++) {
1243 unsigned char mask = constant_time_ge_8(padding_length, i);
1244 unsigned char b = rec->data[rec->length - 1 - i];
1246 * The final |padding_length+1| bytes should all have the value
1247 * |padding_length|. Therefore the XOR should be zero.
1249 good &= ~(mask & (padding_length ^ b));
1253 * If any of the final |padding_length+1| bytes had the wrong value, one
1254 * or more of the lower eight bits of |good| will be cleared.
1256 good = constant_time_eq(0xff, good & 0xff);
1257 rec->length -= good & (padding_length + 1);
1259 return constant_time_select_int(good, 1, -1);
1263 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1264 * constant time (independent of the concrete value of rec->length, which may
1265 * vary within a 256-byte window).
1267 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1271 * rec->orig_len >= md_size
1272 * md_size <= EVP_MAX_MD_SIZE
1274 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1275 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1276 * a single or pair of cache-lines, then the variable memory accesses don't
1277 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1278 * not multi-core and are not considered vulnerable to cache-timing attacks.
1280 #define CBC_MAC_ROTATE_IN_PLACE
1282 void ssl3_cbc_copy_mac(unsigned char *out,
1283 const SSL3_RECORD *rec, unsigned md_size)
1285 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1286 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1287 unsigned char *rotated_mac;
1289 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1293 * mac_end is the index of |rec->data| just after the end of the MAC.
1295 unsigned mac_end = rec->length;
1296 unsigned mac_start = mac_end - md_size;
1298 * scan_start contains the number of bytes that we can ignore because the
1299 * MAC's position can only vary by 255 bytes.
1301 unsigned scan_start = 0;
1303 unsigned div_spoiler;
1304 unsigned rotate_offset;
1306 OPENSSL_assert(rec->orig_len >= md_size);
1307 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1309 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1310 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1313 /* This information is public so it's safe to branch based on it. */
1314 if (rec->orig_len > md_size + 255 + 1)
1315 scan_start = rec->orig_len - (md_size + 255 + 1);
1317 * div_spoiler contains a multiple of md_size that is used to cause the
1318 * modulo operation to be constant time. Without this, the time varies
1319 * based on the amount of padding when running on Intel chips at least.
1320 * The aim of right-shifting md_size is so that the compiler doesn't
1321 * figure out that it can remove div_spoiler as that would require it to
1322 * prove that md_size is always even, which I hope is beyond it.
1324 div_spoiler = md_size >> 1;
1325 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1326 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1328 memset(rotated_mac, 0, md_size);
1329 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1330 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1331 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1332 unsigned char b = rec->data[i];
1333 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1334 j &= constant_time_lt(j, md_size);
1337 /* Now rotate the MAC */
1338 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1340 for (i = 0; i < md_size; i++) {
1341 /* in case cache-line is 32 bytes, touch second line */
1342 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1343 out[j++] = rotated_mac[rotate_offset++];
1344 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1347 memset(out, 0, md_size);
1348 rotate_offset = md_size - rotate_offset;
1349 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1350 for (i = 0; i < md_size; i++) {
1351 for (j = 0; j < md_size; j++)
1352 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1354 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1359 int dtls1_process_record(SSL *s)
1365 unsigned int mac_size;
1366 unsigned char md[EVP_MAX_MD_SIZE];
1368 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1372 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1373 * and we have that many bytes in s->packet
1375 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1378 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1379 * at rr->length bytes, which need to be copied into rr->data by either
1380 * the decryption or by the decompression When the data is 'copied' into
1381 * the rr->data buffer, rr->input will be pointed at the new buffer
1385 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1386 * bytes of encrypted compressed stuff.
1389 /* check is not needed I believe */
1390 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1391 al = SSL_AD_RECORD_OVERFLOW;
1392 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1396 /* decrypt in place in 'rr->input' */
1397 rr->data = rr->input;
1398 rr->orig_len = rr->length;
1400 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1403 * 0: (in non-constant time) if the record is publically invalid.
1404 * 1: if the padding is valid
1405 * -1: if the padding is invalid
1408 /* For DTLS we simply ignore bad packets. */
1410 RECORD_LAYER_reset_packet_length(&s->rlayer);
1414 printf("dec %d\n", rr->length);
1417 for (z = 0; z < rr->length; z++)
1418 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1423 /* r->length is now the compressed data plus mac */
1424 if ((sess != NULL) &&
1425 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1426 /* s->read_hash != NULL => mac_size != -1 */
1427 unsigned char *mac = NULL;
1428 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1429 mac_size = EVP_MD_CTX_size(s->read_hash);
1430 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1433 * orig_len is the length of the record before any padding was
1434 * removed. This is public information, as is the MAC in use,
1435 * therefore we can safely process the record in a different amount
1436 * of time if it's too short to possibly contain a MAC.
1438 if (rr->orig_len < mac_size ||
1439 /* CBC records must have a padding length byte too. */
1440 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1441 rr->orig_len < mac_size + 1)) {
1442 al = SSL_AD_DECODE_ERROR;
1443 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1447 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1449 * We update the length so that the TLS header bytes can be
1450 * constructed correctly but we need to extract the MAC in
1451 * constant time from within the record, without leaking the
1452 * contents of the padding bytes.
1455 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1456 rr->length -= mac_size;
1459 * In this case there's no padding, so |rec->orig_len| equals
1460 * |rec->length| and we checked that there's enough bytes for
1463 rr->length -= mac_size;
1464 mac = &rr->data[rr->length];
1467 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1468 if (i < 0 || mac == NULL
1469 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1471 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1476 /* decryption failed, silently discard message */
1478 RECORD_LAYER_reset_packet_length(&s->rlayer);
1482 /* r->length is now just compressed */
1483 if (s->expand != NULL) {
1484 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1485 al = SSL_AD_RECORD_OVERFLOW;
1486 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1487 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1490 if (!ssl3_do_uncompress(s, rr)) {
1491 al = SSL_AD_DECOMPRESSION_FAILURE;
1492 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1497 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1498 al = SSL_AD_RECORD_OVERFLOW;
1499 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1505 * So at this point the following is true
1506 * ssl->s3->rrec.type is the type of record
1507 * ssl->s3->rrec.length == number of bytes in record
1508 * ssl->s3->rrec.off == offset to first valid byte
1509 * ssl->s3->rrec.data == where to take bytes from, increment
1513 /* we have pulled in a full packet so zero things */
1514 RECORD_LAYER_reset_packet_length(&s->rlayer);
1518 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1525 * retrieve a buffered record that belongs to the current epoch, ie,
1528 #define dtls1_get_processed_record(s) \
1529 dtls1_retrieve_buffered_record((s), \
1530 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1533 * Call this to get a new input record.
1534 * It will return <= 0 if more data is needed, normally due to an error
1535 * or non-blocking IO.
1536 * When it finishes, one packet has been decoded and can be found in
1537 * ssl->s3->rrec.type - is the type of record
1538 * ssl->s3->rrec.data, - data
1539 * ssl->s3->rrec.length, - number of bytes
1541 /* used only by dtls1_read_bytes */
1542 int dtls1_get_record(SSL *s)
1544 int ssl_major, ssl_minor;
1547 unsigned char *p = NULL;
1548 unsigned short version;
1549 DTLS1_BITMAP *bitmap;
1550 unsigned int is_next_epoch;
1552 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1555 * The epoch may have changed. If so, process all the pending records.
1556 * This is a non-blocking operation.
1558 if (dtls1_process_buffered_records(s) < 0)
1561 /* if we're renegotiating, then there may be buffered records */
1562 if (dtls1_get_processed_record(s))
1565 /* get something from the wire */
1567 /* check if we have the header */
1568 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1569 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1570 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1571 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1572 /* read timeout is handled by dtls1_read_bytes */
1574 return (n); /* error or non-blocking */
1576 /* this packet contained a partial record, dump it */
1577 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1578 RECORD_LAYER_reset_packet_length(&s->rlayer);
1582 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1584 p = RECORD_LAYER_get_packet(&s->rlayer);
1586 if (s->msg_callback)
1587 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1588 s, s->msg_callback_arg);
1590 /* Pull apart the header into the DTLS1_RECORD */
1594 version = (ssl_major << 8) | ssl_minor;
1596 /* sequence number is 64 bits, with top 2 bytes = epoch */
1599 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1604 /* Lets check version */
1605 if (!s->first_packet) {
1606 if (version != s->version) {
1607 /* unexpected version, silently discard */
1609 RECORD_LAYER_reset_packet_length(&s->rlayer);
1614 if ((version & 0xff00) != (s->version & 0xff00)) {
1615 /* wrong version, silently discard record */
1617 RECORD_LAYER_reset_packet_length(&s->rlayer);
1621 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1622 /* record too long, silently discard it */
1624 RECORD_LAYER_reset_packet_length(&s->rlayer);
1628 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1631 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1634 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1635 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1637 n = ssl3_read_n(s, i, i, 1, 1);
1638 /* this packet contained a partial record, dump it */
1641 RECORD_LAYER_reset_packet_length(&s->rlayer);
1646 * now n == rr->length, and s->packet_length ==
1647 * DTLS1_RT_HEADER_LENGTH + rr->length
1650 /* set state for later operations */
1651 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1653 /* match epochs. NULL means the packet is dropped on the floor */
1654 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1655 if (bitmap == NULL) {
1657 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1658 goto again; /* get another record */
1660 #ifndef OPENSSL_NO_SCTP
1661 /* Only do replay check if no SCTP bio */
1662 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1664 /* Check whether this is a repeat, or aged record. */
1665 if (!dtls1_record_replay_check(s, bitmap)) {
1667 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1668 goto again; /* get another record */
1670 #ifndef OPENSSL_NO_SCTP
1674 /* just read a 0 length packet */
1675 if (rr->length == 0)
1679 * If this record is from the next epoch (either HM or ALERT), and a
1680 * handshake is currently in progress, buffer it since it cannot be
1681 * processed at this time.
1683 if (is_next_epoch) {
1684 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1685 if (dtls1_buffer_record
1686 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1689 /* Mark receipt of record. */
1690 dtls1_record_bitmap_update(s, bitmap);
1693 RECORD_LAYER_reset_packet_length(&s->rlayer);
1697 if (!dtls1_process_record(s)) {
1699 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1700 goto again; /* get another record */
1702 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */