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 int SSL3_RECORD_setup(SSL3_RECORD *r, unsigned int num_recs)
164 for (i = 0; i < num_recs; i++) {
165 if (r[i].comp == NULL)
166 r[i].comp = (unsigned char *)
167 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
168 if (r[i].comp == NULL) {
170 SSL3_RECORD_release(r, i);
178 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
180 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
185 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
186 * for us in the buffer.
188 static int have_whole_app_data_record_waiting(SSL *s)
194 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
196 p = SSL3_BUFFER_get_buf(rbuf);
200 left = SSL3_BUFFER_get_left(rbuf);
202 if (left < SSL3_RT_HEADER_LENGTH)
205 p += SSL3_BUFFER_get_offset(rbuf);
208 * We only check the type and record length, we will sanity check version
211 if (*p != SSL3_RT_APPLICATION_DATA)
217 if (left < SSL3_RT_HEADER_LENGTH + len)
224 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
225 * will be processed per call to ssl3_get_record. Without this limit an
226 * attacker could send empty records at a faster rate than we can process and
227 * cause ssl3_get_record to loop forever.
229 #define MAX_EMPTY_RECORDS 32
231 #define SSL2_RT_HEADER_LENGTH 2
233 * Call this to get new input records.
234 * It will return <= 0 if more data is needed, normally due to an error
235 * or non-blocking IO.
236 * When it finishes, |numrpipes| records have been decoded. For each record 'i':
237 * rr[i].type - is the type of record
239 * rr[i].length, - number of bytes
240 * Multiple records will only be returned if the record types are all
241 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
244 /* used only by ssl3_read_bytes */
245 int ssl3_get_record(SSL *s)
247 int ssl_major, ssl_minor, al;
248 int enc_err, n, i, ret = -1;
253 unsigned char md[EVP_MAX_MD_SIZE];
256 unsigned empty_record_count = 0, curr_empty = 0;
257 unsigned int num_recs = 0;
258 unsigned int max_recs;
261 rr = RECORD_LAYER_get_rrec(&s->rlayer);
262 rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
263 max_recs = s->max_pipelines;
270 /* check if we have the header */
271 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
272 (RECORD_LAYER_get_packet_length(&s->rlayer)
273 < SSL3_RT_HEADER_LENGTH)) {
274 n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
275 SSL3_BUFFER_get_len(rbuf), 0, num_recs == 0 ? 1 : 0);
277 return (n); /* error or non-blocking */
278 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
280 p = RECORD_LAYER_get_packet(&s->rlayer);
283 * Check whether this is a regular record or an SSLv2 style record.
284 * The latter is only used in an initial ClientHello for old
285 * clients. We check s->read_hash and s->enc_read_ctx to ensure this
286 * does not apply during renegotiation
288 if (s->first_packet && s->server && !s->read_hash
290 && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
291 /* SSLv2 style record */
292 rr[num_recs].type = SSL3_RT_HANDSHAKE;
293 rr[num_recs].rec_version = SSL2_VERSION;
295 rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
297 if (rr[num_recs].length > SSL3_BUFFER_get_len(&rbuf[num_recs])
298 - SSL2_RT_HEADER_LENGTH) {
299 al = SSL_AD_RECORD_OVERFLOW;
300 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
304 if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
305 al = SSL_AD_HANDSHAKE_FAILURE;
306 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
310 /* SSLv3+ style record */
312 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
313 s->msg_callback_arg);
315 /* Pull apart the header into the SSL3_RECORD */
316 rr[num_recs].type = *(p++);
319 version = (ssl_major << 8) | ssl_minor;
320 rr[num_recs].rec_version = version;
321 n2s(p, rr[num_recs].length);
323 /* Lets check version */
324 if (!s->first_packet && version != s->version) {
325 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
326 if ((s->version & 0xFF00) == (version & 0xFF00)
327 && !s->enc_write_ctx && !s->write_hash) {
328 if (rr->type == SSL3_RT_ALERT) {
330 * The record is using an incorrect version number,
331 * but what we've got appears to be an alert. We
332 * haven't read the body yet to check whether its a
333 * fatal or not - but chances are it is. We probably
334 * shouldn't send a fatal alert back. We'll just
340 * Send back error using their minor version number :-)
342 s->version = (unsigned short)version;
344 al = SSL_AD_PROTOCOL_VERSION;
348 if ((version >> 8) != SSL3_VERSION_MAJOR) {
349 if (s->first_packet) {
350 /* Go back to start of packet, look at the five bytes
352 p = RECORD_LAYER_get_packet(&s->rlayer);
353 if (strncmp((char *)p, "GET ", 4) == 0 ||
354 strncmp((char *)p, "POST ", 5) == 0 ||
355 strncmp((char *)p, "HEAD ", 5) == 0 ||
356 strncmp((char *)p, "PUT ", 4) == 0) {
357 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
359 } else if (strncmp((char *)p, "CONNE", 5) == 0) {
360 SSLerr(SSL_F_SSL3_GET_RECORD,
361 SSL_R_HTTPS_PROXY_REQUEST);
365 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
369 if (rr[num_recs].length >
370 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
371 al = SSL_AD_RECORD_OVERFLOW;
372 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
377 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
381 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
382 * Calculate how much more data we need to read for the rest of the
385 if (rr[num_recs].rec_version == SSL2_VERSION) {
386 i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
387 - SSL3_RT_HEADER_LENGTH;
389 i = rr[num_recs].length;
392 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
394 n = ssl3_read_n(s, i, i, 1, 0);
396 return (n); /* error or non-blocking io */
399 /* set state for later operations */
400 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
403 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
404 * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
405 * and we have that many bytes in s->packet
407 if(rr[num_recs].rec_version == SSL2_VERSION) {
409 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
412 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
416 * ok, we can now read from 's->packet' data into 'rr' rr->input points
417 * at rr->length bytes, which need to be copied into rr->data by either
418 * the decryption or by the decompression When the data is 'copied' into
419 * the rr->data buffer, rr->input will be pointed at the new buffer
423 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
424 * bytes of encrypted compressed stuff.
427 /* check is not needed I believe */
428 if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
429 al = SSL_AD_RECORD_OVERFLOW;
430 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
434 /* decrypt in place in 'rr->input' */
435 rr[num_recs].data = rr[num_recs].input;
436 rr[num_recs].orig_len = rr[num_recs].length;
439 /* we have pulled in a full packet so zero things */
440 RECORD_LAYER_reset_packet_length(&s->rlayer);
441 } while (num_recs < max_recs && rr->type == SSL3_RT_APPLICATION_DATA
442 && SSL_USE_EXPLICIT_IV(s)
443 && s->enc_read_ctx != NULL
444 && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
445 & EVP_CIPH_FLAG_PIPELINE)
446 && have_whole_app_data_record_waiting(s));
450 * If in encrypt-then-mac mode calculate mac from encrypted record. All
451 * the details below are public so no timing details can leak.
453 if (SSL_USE_ETM(s) && s->read_hash) {
455 mac_size = EVP_MD_CTX_size(s->read_hash);
456 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
457 for (j = 0; j < num_recs; j++) {
458 if (rr[j].length < mac_size) {
459 al = SSL_AD_DECODE_ERROR;
460 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
463 rr[j].length -= mac_size;
464 mac = rr[j].data + rr[j].length;
465 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
466 if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
467 al = SSL_AD_BAD_RECORD_MAC;
468 SSLerr(SSL_F_SSL3_GET_RECORD,
469 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
475 enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
478 * 0: (in non-constant time) if the record is publically invalid.
479 * 1: if the padding is valid
480 * -1: if the padding is invalid
483 al = SSL_AD_DECRYPTION_FAILED;
484 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
488 printf("dec %d\n", rr->length);
491 for (z = 0; z < rr->length; z++)
492 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
497 /* r->length is now the compressed data plus mac */
498 if ((sess != NULL) &&
499 (s->enc_read_ctx != NULL) &&
500 (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
501 /* s->read_hash != NULL => mac_size != -1 */
502 unsigned char *mac = NULL;
503 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
505 mac_size = EVP_MD_CTX_size(s->read_hash);
506 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
508 for (j=0; j < num_recs; j++) {
510 * orig_len is the length of the record before any padding was
511 * removed. This is public information, as is the MAC in use,
512 * therefore we can safely process the record in a different amount
513 * of time if it's too short to possibly contain a MAC.
515 if (rr[j].orig_len < mac_size ||
516 /* CBC records must have a padding length byte too. */
517 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
518 rr[j].orig_len < mac_size + 1)) {
519 al = SSL_AD_DECODE_ERROR;
520 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
524 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
526 * We update the length so that the TLS header bytes can be
527 * constructed correctly but we need to extract the MAC in
528 * constant time from within the record, without leaking the
529 * contents of the padding bytes.
532 ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
533 rr[j].length -= mac_size;
536 * In this case there's no padding, so |rec->orig_len| equals
537 * |rec->length| and we checked that there's enough bytes for
540 rr[j].length -= mac_size;
541 mac = &rr[j].data[rr[j].length];
544 i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
545 if (i < 0 || mac == NULL
546 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
548 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
555 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
556 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
557 * failure is directly visible from the ciphertext anyway, we should
558 * not reveal which kind of error occurred -- this might become
559 * visible to an attacker (e.g. via a logfile)
561 al = SSL_AD_BAD_RECORD_MAC;
562 SSLerr(SSL_F_SSL3_GET_RECORD,
563 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
567 for (j = 0; j < num_recs; j++) {
568 /* rr[j].length is now just compressed */
569 if (s->expand != NULL) {
570 if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
571 al = SSL_AD_RECORD_OVERFLOW;
572 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
575 if (!ssl3_do_uncompress(s, &rr[j])) {
576 al = SSL_AD_DECOMPRESSION_FAILURE;
577 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
582 if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
583 al = SSL_AD_RECORD_OVERFLOW;
584 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
590 * So at this point the following is true
591 * rr[j].type is the type of record
592 * rr[j].length == number of bytes in record
593 * rr[j].off == offset to first valid byte
594 * rr[j].data == where to take bytes from, increment after use :-).
597 /* just read a 0 length packet */
598 if (rr[j].length == 0) {
600 empty_record_count++;
601 if (empty_record_count > MAX_EMPTY_RECORDS) {
602 al = SSL_AD_UNEXPECTED_MESSAGE;
603 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
608 if (curr_empty == num_recs) {
609 /* We have no data - do it all again */
615 RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
619 ssl3_send_alert(s, SSL3_AL_FATAL, al);
624 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
626 #ifndef OPENSSL_NO_COMP
629 i = COMP_expand_block(ssl->expand, rr->comp,
630 SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
641 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
643 #ifndef OPENSSL_NO_COMP
646 i = COMP_compress_block(ssl->compress, wr->data,
647 SSL3_RT_MAX_COMPRESSED_LENGTH,
648 wr->input, (int)wr->length);
654 wr->input = wr->data;
660 * ssl3_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
663 * 0: (in non-constant time) if the record is publically invalid (i.e. too
665 * 1: if the record's padding is valid / the encryption was successful.
666 * -1: if the record's padding is invalid or, if sending, an internal error
669 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int numpipes, int send)
674 int bs, i, mac_size = 0;
675 const EVP_CIPHER *enc;
679 ds = s->enc_write_ctx;
680 if (s->enc_write_ctx == NULL)
683 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
685 ds = s->enc_read_ctx;
686 if (s->enc_read_ctx == NULL)
689 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
692 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
693 memmove(rec->data, rec->input, rec->length);
694 rec->input = rec->data;
697 bs = EVP_CIPHER_CTX_block_size(ds);
701 if ((bs != 1) && send) {
702 i = bs - ((int)l % bs);
704 /* we need to add 'i-1' padding bytes */
707 * the last of these zero bytes will be overwritten with the
710 memset(&rec->input[rec->length], 0, i);
712 rec->input[l - 1] = (i - 1);
716 if (l == 0 || l % bs != 0)
718 /* otherwise, rec->length >= bs */
721 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
724 if (EVP_MD_CTX_md(s->read_hash) != NULL)
725 mac_size = EVP_MD_CTX_size(s->read_hash);
726 if ((bs != 1) && !send)
727 return ssl3_cbc_remove_padding(rec, bs, mac_size);
733 * tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
736 * 0: (in non-constant time) if the record is publically invalid (i.e. too
738 * 1: if the record's padding is valid / the encryption was successful.
739 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
740 * an internal error occurred.
742 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int numpipes, int send)
745 size_t reclen[SSL_MAX_PIPELINES];
746 unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
747 int bs, i, j, k, pad = 0, ret, mac_size = 0;
748 const EVP_CIPHER *enc;
752 if (EVP_MD_CTX_md(s->write_hash)) {
753 int n = EVP_MD_CTX_size(s->write_hash);
754 OPENSSL_assert(n >= 0);
756 ds = s->enc_write_ctx;
757 if (s->enc_write_ctx == NULL)
761 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
762 /* For TLSv1.1 and later explicit IV */
763 if (SSL_USE_EXPLICIT_IV(s)
764 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
765 ivlen = EVP_CIPHER_iv_length(enc);
769 for (ctr = 0; ctr < numpipes; ctr++) {
770 if (recs[ctr].data != recs[ctr].input) {
772 * we can't write into the input stream: Can this ever
775 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
777 } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
778 SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
785 if (EVP_MD_CTX_md(s->read_hash)) {
786 int n = EVP_MD_CTX_size(s->read_hash);
787 OPENSSL_assert(n >= 0);
789 ds = s->enc_read_ctx;
790 if (s->enc_read_ctx == NULL)
793 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
796 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
797 for (ctr = 0; ctr < numpipes; ctr++) {
798 memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
799 recs[ctr].input = recs[ctr].data;
803 bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
806 if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
807 & EVP_CIPH_FLAG_PIPELINE)) {
809 * We shouldn't have been called with pipeline data if the
810 * cipher doesn't support pipelining
812 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
816 for (ctr = 0; ctr < numpipes; ctr++) {
817 reclen[ctr] = recs[ctr].length;
819 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
820 & EVP_CIPH_FLAG_AEAD_CIPHER) {
823 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
824 : RECORD_LAYER_get_read_sequence(&s->rlayer);
826 if (SSL_IS_DTLS(s)) {
827 /* DTLS does not support pipelining */
828 unsigned char dtlsseq[9], *p = dtlsseq;
830 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
831 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
832 memcpy(p, &seq[2], 6);
833 memcpy(buf[ctr], dtlsseq, 8);
835 memcpy(buf[ctr], seq, 8);
836 for (i = 7; i >= 0; i--) { /* increment */
843 buf[ctr][8] = recs[ctr].type;
844 buf[ctr][9] = (unsigned char)(s->version >> 8);
845 buf[ctr][10] = (unsigned char)(s->version);
846 buf[ctr][11] = recs[ctr].length >> 8;
847 buf[ctr][12] = recs[ctr].length & 0xff;
848 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
849 EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
855 recs[ctr].length += pad;
858 } else if ((bs != 1) && send) {
859 i = bs - ((int)reclen[ctr] % bs);
861 /* Add weird padding of upto 256 bytes */
863 /* we need to add 'i' padding bytes of value j */
865 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
866 recs[ctr].input[k] = j;
868 recs[ctr].length += i;
872 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
877 unsigned char *data[SSL_MAX_PIPELINES];
879 /* Set the output buffers */
880 for(ctr = 0; ctr < numpipes; ctr++) {
881 data[ctr] = recs[ctr].data;
883 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
884 numpipes, data) <= 0) {
885 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
887 /* Set the input buffers */
888 for(ctr = 0; ctr < numpipes; ctr++) {
889 data[ctr] = recs[ctr].input;
891 if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
893 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
894 numpipes, reclen) <= 0) {
895 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
900 i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
901 if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
902 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
905 return -1; /* AEAD can fail to verify MAC */
907 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
908 for (ctr = 0; ctr < numpipes; ctr++) {
909 recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
910 recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
911 recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
913 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
914 for (ctr = 0; ctr < numpipes; ctr++) {
915 recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
916 recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
917 recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
923 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
924 mac_size = EVP_MD_CTX_size(s->read_hash);
925 if ((bs != 1) && !send) {
927 for (ctr = 0; ctr < numpipes; ctr++) {
928 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
935 for (ctr = 0; ctr < numpipes; ctr++) {
936 recs[ctr].length -= pad;
943 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
945 unsigned char *mac_sec, *seq;
946 const EVP_MD_CTX *hash;
947 unsigned char *p, rec_char;
953 mac_sec = &(ssl->s3->write_mac_secret[0]);
954 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
955 hash = ssl->write_hash;
957 mac_sec = &(ssl->s3->read_mac_secret[0]);
958 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
959 hash = ssl->read_hash;
962 t = EVP_MD_CTX_size(hash);
966 npad = (48 / md_size) * md_size;
969 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
970 ssl3_cbc_record_digest_supported(hash)) {
972 * This is a CBC-encrypted record. We must avoid leaking any
973 * timing-side channel information about how many blocks of data we
974 * are hashing because that gives an attacker a timing-oracle.
978 * npad is, at most, 48 bytes and that's with MD5:
979 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
981 * With SHA-1 (the largest hash speced for SSLv3) the hash size
982 * goes up 4, but npad goes down by 8, resulting in a smaller
985 unsigned char header[75];
987 memcpy(header + j, mac_sec, md_size);
989 memcpy(header + j, ssl3_pad_1, npad);
991 memcpy(header + j, seq, 8);
993 header[j++] = rec->type;
994 header[j++] = rec->length >> 8;
995 header[j++] = rec->length & 0xff;
997 /* Final param == is SSLv3 */
998 if (ssl3_cbc_digest_record(hash,
1001 rec->length + md_size, rec->orig_len,
1002 mac_sec, md_size, 1) <= 0)
1005 unsigned int md_size_u;
1006 /* Chop the digest off the end :-) */
1007 EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1012 rec_char = rec->type;
1014 s2n(rec->length, p);
1015 if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1016 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1017 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1018 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1019 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1020 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1021 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1022 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1023 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1024 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1025 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1026 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1027 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1028 EVP_MD_CTX_reset(md_ctx);
1031 md_size = md_size_u;
1033 EVP_MD_CTX_free(md_ctx);
1036 ssl3_record_sequence_update(seq);
1040 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1046 EVP_MD_CTX *hmac = NULL, *mac_ctx;
1047 unsigned char header[13];
1048 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1049 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1053 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1054 hash = ssl->write_hash;
1056 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1057 hash = ssl->read_hash;
1060 t = EVP_MD_CTX_size(hash);
1061 OPENSSL_assert(t >= 0);
1064 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1068 hmac = EVP_MD_CTX_new();
1070 || !EVP_MD_CTX_copy(hmac, hash))
1075 if (SSL_IS_DTLS(ssl)) {
1076 unsigned char dtlsseq[8], *p = dtlsseq;
1078 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1079 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1080 memcpy(p, &seq[2], 6);
1082 memcpy(header, dtlsseq, 8);
1084 memcpy(header, seq, 8);
1086 header[8] = rec->type;
1087 header[9] = (unsigned char)(ssl->version >> 8);
1088 header[10] = (unsigned char)(ssl->version);
1089 header[11] = (rec->length) >> 8;
1090 header[12] = (rec->length) & 0xff;
1092 if (!send && !SSL_USE_ETM(ssl) &&
1093 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1094 ssl3_cbc_record_digest_supported(mac_ctx)) {
1096 * This is a CBC-encrypted record. We must avoid leaking any
1097 * timing-side channel information about how many blocks of data we
1098 * are hashing because that gives an attacker a timing-oracle.
1100 /* Final param == not SSLv3 */
1101 if (ssl3_cbc_digest_record(mac_ctx,
1104 rec->length + md_size, rec->orig_len,
1105 ssl->s3->read_mac_secret,
1106 ssl->s3->read_mac_secret_size, 0) <= 0) {
1107 EVP_MD_CTX_free(hmac);
1111 if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1112 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1113 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1114 EVP_MD_CTX_free(hmac);
1117 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1118 tls_fips_digest_extra(ssl->enc_read_ctx,
1119 mac_ctx, rec->input,
1120 rec->length, rec->orig_len);
1123 EVP_MD_CTX_free(hmac);
1126 fprintf(stderr, "seq=");
1129 for (z = 0; z < 8; z++)
1130 fprintf(stderr, "%02X ", seq[z]);
1131 fprintf(stderr, "\n");
1133 fprintf(stderr, "rec=");
1136 for (z = 0; z < rec->length; z++)
1137 fprintf(stderr, "%02X ", rec->data[z]);
1138 fprintf(stderr, "\n");
1142 if (!SSL_IS_DTLS(ssl)) {
1143 for (i = 7; i >= 0; i--) {
1152 for (z = 0; z < md_size; z++)
1153 fprintf(stderr, "%02X ", md[z]);
1154 fprintf(stderr, "\n");
1161 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1162 * record in |rec| by updating |rec->length| in constant time.
1164 * block_size: the block size of the cipher used to encrypt the record.
1166 * 0: (in non-constant time) if the record is publicly invalid.
1167 * 1: if the padding was valid
1170 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1171 unsigned block_size, unsigned mac_size)
1173 unsigned padding_length, good;
1174 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1177 * These lengths are all public so we can test them in non-constant time.
1179 if (overhead > rec->length)
1182 padding_length = rec->data[rec->length - 1];
1183 good = constant_time_ge(rec->length, padding_length + overhead);
1184 /* SSLv3 requires that the padding is minimal. */
1185 good &= constant_time_ge(block_size, padding_length + 1);
1186 rec->length -= good & (padding_length + 1);
1187 return constant_time_select_int(good, 1, -1);
1191 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1192 * record in |rec| in constant time and returns 1 if the padding is valid and
1193 * -1 otherwise. It also removes any explicit IV from the start of the record
1194 * without leaking any timing about whether there was enough space after the
1195 * padding was removed.
1197 * block_size: the block size of the cipher used to encrypt the record.
1199 * 0: (in non-constant time) if the record is publicly invalid.
1200 * 1: if the padding was valid
1203 int tls1_cbc_remove_padding(const SSL *s,
1205 unsigned block_size, unsigned mac_size)
1207 unsigned padding_length, good, to_check, i;
1208 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1209 /* Check if version requires explicit IV */
1210 if (SSL_USE_EXPLICIT_IV(s)) {
1212 * These lengths are all public so we can test them in non-constant
1215 if (overhead + block_size > rec->length)
1217 /* We can now safely skip explicit IV */
1218 rec->data += block_size;
1219 rec->input += block_size;
1220 rec->length -= block_size;
1221 rec->orig_len -= block_size;
1222 } else if (overhead > rec->length)
1225 padding_length = rec->data[rec->length - 1];
1227 if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1228 /* padding is already verified */
1229 rec->length -= padding_length + 1;
1233 good = constant_time_ge(rec->length, overhead + padding_length);
1235 * The padding consists of a length byte at the end of the record and
1236 * then that many bytes of padding, all with the same value as the length
1237 * byte. Thus, with the length byte included, there are i+1 bytes of
1238 * padding. We can't check just |padding_length+1| bytes because that
1239 * leaks decrypted information. Therefore we always have to check the
1240 * maximum amount of padding possible. (Again, the length of the record
1241 * is public information so we can use it.)
1243 to_check = 255; /* maximum amount of padding. */
1244 if (to_check > rec->length - 1)
1245 to_check = rec->length - 1;
1247 for (i = 0; i < to_check; i++) {
1248 unsigned char mask = constant_time_ge_8(padding_length, i);
1249 unsigned char b = rec->data[rec->length - 1 - i];
1251 * The final |padding_length+1| bytes should all have the value
1252 * |padding_length|. Therefore the XOR should be zero.
1254 good &= ~(mask & (padding_length ^ b));
1258 * If any of the final |padding_length+1| bytes had the wrong value, one
1259 * or more of the lower eight bits of |good| will be cleared.
1261 good = constant_time_eq(0xff, good & 0xff);
1262 rec->length -= good & (padding_length + 1);
1264 return constant_time_select_int(good, 1, -1);
1268 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1269 * constant time (independent of the concrete value of rec->length, which may
1270 * vary within a 256-byte window).
1272 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1276 * rec->orig_len >= md_size
1277 * md_size <= EVP_MAX_MD_SIZE
1279 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1280 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1281 * a single or pair of cache-lines, then the variable memory accesses don't
1282 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1283 * not multi-core and are not considered vulnerable to cache-timing attacks.
1285 #define CBC_MAC_ROTATE_IN_PLACE
1287 void ssl3_cbc_copy_mac(unsigned char *out,
1288 const SSL3_RECORD *rec, unsigned md_size)
1290 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1291 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1292 unsigned char *rotated_mac;
1294 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1298 * mac_end is the index of |rec->data| just after the end of the MAC.
1300 unsigned mac_end = rec->length;
1301 unsigned mac_start = mac_end - md_size;
1303 * scan_start contains the number of bytes that we can ignore because the
1304 * MAC's position can only vary by 255 bytes.
1306 unsigned scan_start = 0;
1308 unsigned div_spoiler;
1309 unsigned rotate_offset;
1311 OPENSSL_assert(rec->orig_len >= md_size);
1312 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1314 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1315 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1318 /* This information is public so it's safe to branch based on it. */
1319 if (rec->orig_len > md_size + 255 + 1)
1320 scan_start = rec->orig_len - (md_size + 255 + 1);
1322 * div_spoiler contains a multiple of md_size that is used to cause the
1323 * modulo operation to be constant time. Without this, the time varies
1324 * based on the amount of padding when running on Intel chips at least.
1325 * The aim of right-shifting md_size is so that the compiler doesn't
1326 * figure out that it can remove div_spoiler as that would require it to
1327 * prove that md_size is always even, which I hope is beyond it.
1329 div_spoiler = md_size >> 1;
1330 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1331 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1333 memset(rotated_mac, 0, md_size);
1334 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1335 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1336 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1337 unsigned char b = rec->data[i];
1338 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1339 j &= constant_time_lt(j, md_size);
1342 /* Now rotate the MAC */
1343 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1345 for (i = 0; i < md_size; i++) {
1346 /* in case cache-line is 32 bytes, touch second line */
1347 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1348 out[j++] = rotated_mac[rotate_offset++];
1349 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1352 memset(out, 0, md_size);
1353 rotate_offset = md_size - rotate_offset;
1354 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1355 for (i = 0; i < md_size; i++) {
1356 for (j = 0; j < md_size; j++)
1357 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1359 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1364 int dtls1_process_record(SSL *s)
1370 unsigned int mac_size;
1371 unsigned char md[EVP_MAX_MD_SIZE];
1373 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1377 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1378 * and we have that many bytes in s->packet
1380 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1383 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1384 * at rr->length bytes, which need to be copied into rr->data by either
1385 * the decryption or by the decompression When the data is 'copied' into
1386 * the rr->data buffer, rr->input will be pointed at the new buffer
1390 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1391 * bytes of encrypted compressed stuff.
1394 /* check is not needed I believe */
1395 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1396 al = SSL_AD_RECORD_OVERFLOW;
1397 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1401 /* decrypt in place in 'rr->input' */
1402 rr->data = rr->input;
1403 rr->orig_len = rr->length;
1405 enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1408 * 0: (in non-constant time) if the record is publically invalid.
1409 * 1: if the padding is valid
1410 * -1: if the padding is invalid
1413 /* For DTLS we simply ignore bad packets. */
1415 RECORD_LAYER_reset_packet_length(&s->rlayer);
1419 printf("dec %d\n", rr->length);
1422 for (z = 0; z < rr->length; z++)
1423 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1428 /* r->length is now the compressed data plus mac */
1429 if ((sess != NULL) &&
1430 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1431 /* s->read_hash != NULL => mac_size != -1 */
1432 unsigned char *mac = NULL;
1433 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1434 mac_size = EVP_MD_CTX_size(s->read_hash);
1435 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1438 * orig_len is the length of the record before any padding was
1439 * removed. This is public information, as is the MAC in use,
1440 * therefore we can safely process the record in a different amount
1441 * of time if it's too short to possibly contain a MAC.
1443 if (rr->orig_len < mac_size ||
1444 /* CBC records must have a padding length byte too. */
1445 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1446 rr->orig_len < mac_size + 1)) {
1447 al = SSL_AD_DECODE_ERROR;
1448 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1452 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1454 * We update the length so that the TLS header bytes can be
1455 * constructed correctly but we need to extract the MAC in
1456 * constant time from within the record, without leaking the
1457 * contents of the padding bytes.
1460 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1461 rr->length -= mac_size;
1464 * In this case there's no padding, so |rec->orig_len| equals
1465 * |rec->length| and we checked that there's enough bytes for
1468 rr->length -= mac_size;
1469 mac = &rr->data[rr->length];
1472 i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1473 if (i < 0 || mac == NULL
1474 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1476 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1481 /* decryption failed, silently discard message */
1483 RECORD_LAYER_reset_packet_length(&s->rlayer);
1487 /* r->length is now just compressed */
1488 if (s->expand != NULL) {
1489 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1490 al = SSL_AD_RECORD_OVERFLOW;
1491 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1492 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1495 if (!ssl3_do_uncompress(s, rr)) {
1496 al = SSL_AD_DECOMPRESSION_FAILURE;
1497 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1502 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1503 al = SSL_AD_RECORD_OVERFLOW;
1504 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1510 * So at this point the following is true
1511 * ssl->s3->rrec.type is the type of record
1512 * ssl->s3->rrec.length == number of bytes in record
1513 * ssl->s3->rrec.off == offset to first valid byte
1514 * ssl->s3->rrec.data == where to take bytes from, increment
1518 /* we have pulled in a full packet so zero things */
1519 RECORD_LAYER_reset_packet_length(&s->rlayer);
1523 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1530 * retrieve a buffered record that belongs to the current epoch, ie,
1533 #define dtls1_get_processed_record(s) \
1534 dtls1_retrieve_buffered_record((s), \
1535 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1538 * Call this to get a new input record.
1539 * It will return <= 0 if more data is needed, normally due to an error
1540 * or non-blocking IO.
1541 * When it finishes, one packet has been decoded and can be found in
1542 * ssl->s3->rrec.type - is the type of record
1543 * ssl->s3->rrec.data, - data
1544 * ssl->s3->rrec.length, - number of bytes
1546 /* used only by dtls1_read_bytes */
1547 int dtls1_get_record(SSL *s)
1549 int ssl_major, ssl_minor;
1552 unsigned char *p = NULL;
1553 unsigned short version;
1554 DTLS1_BITMAP *bitmap;
1555 unsigned int is_next_epoch;
1557 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1560 * The epoch may have changed. If so, process all the pending records.
1561 * This is a non-blocking operation.
1563 if (dtls1_process_buffered_records(s) < 0)
1566 /* if we're renegotiating, then there may be buffered records */
1567 if (dtls1_get_processed_record(s))
1570 /* get something from the wire */
1572 /* check if we have the header */
1573 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1574 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1575 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1576 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1577 /* read timeout is handled by dtls1_read_bytes */
1579 return (n); /* error or non-blocking */
1581 /* this packet contained a partial record, dump it */
1582 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1583 RECORD_LAYER_reset_packet_length(&s->rlayer);
1587 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1589 p = RECORD_LAYER_get_packet(&s->rlayer);
1591 if (s->msg_callback)
1592 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1593 s, s->msg_callback_arg);
1595 /* Pull apart the header into the DTLS1_RECORD */
1599 version = (ssl_major << 8) | ssl_minor;
1601 /* sequence number is 64 bits, with top 2 bytes = epoch */
1604 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1609 /* Lets check version */
1610 if (!s->first_packet) {
1611 if (version != s->version) {
1612 /* unexpected version, silently discard */
1614 RECORD_LAYER_reset_packet_length(&s->rlayer);
1619 if ((version & 0xff00) != (s->version & 0xff00)) {
1620 /* wrong version, silently discard record */
1622 RECORD_LAYER_reset_packet_length(&s->rlayer);
1626 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1627 /* record too long, silently discard it */
1629 RECORD_LAYER_reset_packet_length(&s->rlayer);
1633 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1636 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1639 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1640 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1642 n = ssl3_read_n(s, i, i, 1, 1);
1643 /* this packet contained a partial record, dump it */
1646 RECORD_LAYER_reset_packet_length(&s->rlayer);
1651 * now n == rr->length, and s->packet_length ==
1652 * DTLS1_RT_HEADER_LENGTH + rr->length
1655 /* set state for later operations */
1656 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1658 /* match epochs. NULL means the packet is dropped on the floor */
1659 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1660 if (bitmap == NULL) {
1662 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1663 goto again; /* get another record */
1665 #ifndef OPENSSL_NO_SCTP
1666 /* Only do replay check if no SCTP bio */
1667 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1669 /* Check whether this is a repeat, or aged record. */
1670 if (!dtls1_record_replay_check(s, bitmap)) {
1672 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1673 goto again; /* get another record */
1675 #ifndef OPENSSL_NO_SCTP
1679 /* just read a 0 length packet */
1680 if (rr->length == 0)
1684 * If this record is from the next epoch (either HM or ALERT), and a
1685 * handshake is currently in progress, buffer it since it cannot be
1686 * processed at this time.
1688 if (is_next_epoch) {
1689 if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1690 if (dtls1_buffer_record
1691 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1694 /* Mark receipt of record. */
1695 dtls1_record_bitmap_update(s, bitmap);
1698 RECORD_LAYER_reset_packet_length(&s->rlayer);
1702 if (!dtls1_process_record(s)) {
1704 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1705 goto again; /* get another record */
1707 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */