]> git.ipfire.org Git - thirdparty/openssl.git/blob - ssl/record/ssl3_record.c
Server side version negotiation rewrite
[thirdparty/openssl.git] / ssl / record / ssl3_record.c
1 /* ssl/record/ssl3_record.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58 /* ====================================================================
59 * Copyright (c) 1998-2015 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112 #include "../ssl_locl.h"
113 #include "internal/constant_time_locl.h"
114 #include <openssl/rand.h>
115 #include "record_locl.h"
116
117 static const unsigned char ssl3_pad_1[48] = {
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,
123 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
124 };
125
126 static const unsigned char ssl3_pad_2[48] = {
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,
132 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
133 };
134
135 void SSL3_RECORD_clear(SSL3_RECORD *r)
136 {
137 memset(r->seq_num, 0, sizeof(r->seq_num));
138 }
139
140 void SSL3_RECORD_release(SSL3_RECORD *r)
141 {
142 OPENSSL_free(r->comp);
143 r->comp = NULL;
144 }
145
146 int SSL3_RECORD_setup(SSL3_RECORD *r)
147 {
148 if (r->comp == NULL)
149 r->comp = (unsigned char *)
150 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
151 if (r->comp == NULL)
152 return 0;
153 return 1;
154 }
155
156 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
157 {
158 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
159 }
160
161 /*
162 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
163 * will be processed per call to ssl3_get_record. Without this limit an
164 * attacker could send empty records at a faster rate than we can process and
165 * cause ssl3_get_record to loop forever.
166 */
167 #define MAX_EMPTY_RECORDS 32
168
169 #define SSL2_RT_HEADER_LENGTH 2
170 /*-
171 * Call this to get a new input record.
172 * It will return <= 0 if more data is needed, normally due to an error
173 * or non-blocking IO.
174 * When it finishes, one packet has been decoded and can be found in
175 * ssl->s3->rrec.type - is the type of record
176 * ssl->s3->rrec.data, - data
177 * ssl->s3->rrec.length, - number of bytes
178 */
179 /* used only by ssl3_read_bytes */
180 int ssl3_get_record(SSL *s)
181 {
182 int ssl_major, ssl_minor, al;
183 int enc_err, n, i, ret = -1;
184 SSL3_RECORD *rr;
185 SSL_SESSION *sess;
186 unsigned char *p;
187 unsigned char md[EVP_MAX_MD_SIZE];
188 short version;
189 unsigned mac_size;
190 size_t extra;
191 unsigned empty_record_count = 0;
192
193 rr = RECORD_LAYER_get_rrec(&s->rlayer);
194 sess = s->session;
195
196 if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
197 extra = SSL3_RT_MAX_EXTRA;
198 else
199 extra = 0;
200 if (extra && !s->s3->init_extra) {
201 /*
202 * An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
203 * ssl3_setup_buffers() was done
204 */
205 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
206 return -1;
207 }
208
209 again:
210 /* check if we have the header */
211 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
212 (RECORD_LAYER_get_packet_length(&s->rlayer) < SSL3_RT_HEADER_LENGTH)) {
213 n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
214 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
215 if (n <= 0)
216 return (n); /* error or non-blocking */
217 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
218
219 p = RECORD_LAYER_get_packet(&s->rlayer);
220
221 /*
222 * Check whether this is a regular record or an SSLv2 style record. The
223 * latter is only used in an initial ClientHello for old clients.
224 */
225 if (s->first_packet && s->server && !s->read_hash && !s->enc_read_ctx
226 && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
227 /* SSLv2 style record */
228 if (s->msg_callback)
229 s->msg_callback(0, SSL2_VERSION, 0, p + 2,
230 RECORD_LAYER_get_packet_length(&s->rlayer) - 2,
231 s, s->msg_callback_arg);
232
233 rr->type = SSL3_RT_HANDSHAKE;
234 rr->rec_version = SSL2_VERSION;
235
236 rr->length = ((p[0] & 0x7f) << 8) | p[1];
237
238 if (rr->length > SSL3_BUFFER_get_len(&s->rlayer.rbuf)
239 - SSL2_RT_HEADER_LENGTH) {
240 al = SSL_AD_RECORD_OVERFLOW;
241 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
242 goto f_err;
243 }
244
245 if (rr->length < MIN_SSL2_RECORD_LEN) {
246 al = SSL_AD_HANDSHAKE_FAILURE;
247 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
248 goto f_err;
249 }
250 } else {
251 /* SSLv3+ style record */
252 if (s->msg_callback)
253 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
254 s->msg_callback_arg);
255
256 /* Pull apart the header into the SSL3_RECORD */
257 rr->type = *(p++);
258 ssl_major = *(p++);
259 ssl_minor = *(p++);
260 version = (ssl_major << 8) | ssl_minor;
261 rr->rec_version = version;
262 n2s(p, rr->length);
263
264 /* Lets check version */
265 if (!s->first_packet) {
266 if (version != s->version) {
267 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
268 if ((s->version & 0xFF00) == (version & 0xFF00)
269 && !s->enc_write_ctx && !s->write_hash)
270 /*
271 * Send back error using their minor version number :-)
272 */
273 s->version = (unsigned short)version;
274 al = SSL_AD_PROTOCOL_VERSION;
275 goto f_err;
276 }
277 }
278
279 if ((version >> 8) != SSL3_VERSION_MAJOR) {
280 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
281 goto err;
282 }
283
284 if (rr->length >
285 SSL3_BUFFER_get_len(&s->rlayer.rbuf)
286 - SSL3_RT_HEADER_LENGTH) {
287 al = SSL_AD_RECORD_OVERFLOW;
288 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
289 goto f_err;
290 }
291 }
292
293 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
294 }
295
296 /*
297 * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
298 * Calculate how much more data we need to read for the rest of the record
299 */
300 if (rr->rec_version == SSL2_VERSION) {
301 i = rr->length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH;
302 } else {
303 i = rr->length;
304 }
305 if (i > 0) {
306 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
307
308 n = ssl3_read_n(s, i, i, 1);
309 if (n <= 0)
310 return (n); /* error or non-blocking io */
311 /*
312 * now n == rr->length, and
313 * s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length
314 * or
315 * s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
316 * (if SSLv2 packet)
317 */
318 } else {
319 n = 0;
320 }
321
322 /* set state for later operations */
323 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
324
325 /*
326 * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
327 * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
328 * and we have that many bytes in s->packet
329 */
330 if(rr->rec_version == SSL2_VERSION) {
331 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
332 } else {
333 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
334 }
335
336 /*
337 * ok, we can now read from 's->packet' data into 'rr' rr->input points
338 * at rr->length bytes, which need to be copied into rr->data by either
339 * the decryption or by the decompression When the data is 'copied' into
340 * the rr->data buffer, rr->input will be pointed at the new buffer
341 */
342
343 /*
344 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
345 * bytes of encrypted compressed stuff.
346 */
347
348 /* check is not needed I believe */
349 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
350 al = SSL_AD_RECORD_OVERFLOW;
351 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
352 goto f_err;
353 }
354
355 /* decrypt in place in 'rr->input' */
356 rr->data = rr->input;
357 rr->orig_len = rr->length;
358 /*
359 * If in encrypt-then-mac mode calculate mac from encrypted record. All
360 * the details below are public so no timing details can leak.
361 */
362 if (SSL_USE_ETM(s) && s->read_hash) {
363 unsigned char *mac;
364 mac_size = EVP_MD_CTX_size(s->read_hash);
365 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
366 if (rr->length < mac_size) {
367 al = SSL_AD_DECODE_ERROR;
368 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
369 goto f_err;
370 }
371 rr->length -= mac_size;
372 mac = rr->data + rr->length;
373 i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
374 if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
375 al = SSL_AD_BAD_RECORD_MAC;
376 SSLerr(SSL_F_SSL3_GET_RECORD,
377 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
378 goto f_err;
379 }
380 }
381
382 enc_err = s->method->ssl3_enc->enc(s, 0);
383 /*-
384 * enc_err is:
385 * 0: (in non-constant time) if the record is publically invalid.
386 * 1: if the padding is valid
387 * -1: if the padding is invalid
388 */
389 if (enc_err == 0) {
390 al = SSL_AD_DECRYPTION_FAILED;
391 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
392 goto f_err;
393 }
394 #ifdef TLS_DEBUG
395 printf("dec %d\n", rr->length);
396 {
397 unsigned int z;
398 for (z = 0; z < rr->length; z++)
399 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
400 }
401 printf("\n");
402 #endif
403
404 /* r->length is now the compressed data plus mac */
405 if ((sess != NULL) &&
406 (s->enc_read_ctx != NULL) &&
407 (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
408 /* s->read_hash != NULL => mac_size != -1 */
409 unsigned char *mac = NULL;
410 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
411 mac_size = EVP_MD_CTX_size(s->read_hash);
412 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
413
414 /*
415 * orig_len is the length of the record before any padding was
416 * removed. This is public information, as is the MAC in use,
417 * therefore we can safely process the record in a different amount
418 * of time if it's too short to possibly contain a MAC.
419 */
420 if (rr->orig_len < mac_size ||
421 /* CBC records must have a padding length byte too. */
422 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
423 rr->orig_len < mac_size + 1)) {
424 al = SSL_AD_DECODE_ERROR;
425 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
426 goto f_err;
427 }
428
429 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
430 /*
431 * We update the length so that the TLS header bytes can be
432 * constructed correctly but we need to extract the MAC in
433 * constant time from within the record, without leaking the
434 * contents of the padding bytes.
435 */
436 mac = mac_tmp;
437 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
438 rr->length -= mac_size;
439 } else {
440 /*
441 * In this case there's no padding, so |rec->orig_len| equals
442 * |rec->length| and we checked that there's enough bytes for
443 * |mac_size| above.
444 */
445 rr->length -= mac_size;
446 mac = &rr->data[rr->length];
447 }
448
449 i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
450 if (i < 0 || mac == NULL
451 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
452 enc_err = -1;
453 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
454 enc_err = -1;
455 }
456
457 if (enc_err < 0) {
458 /*
459 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
460 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
461 * failure is directly visible from the ciphertext anyway, we should
462 * not reveal which kind of error occurred -- this might become
463 * visible to an attacker (e.g. via a logfile)
464 */
465 al = SSL_AD_BAD_RECORD_MAC;
466 SSLerr(SSL_F_SSL3_GET_RECORD,
467 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
468 goto f_err;
469 }
470
471 /* r->length is now just compressed */
472 if (s->expand != NULL) {
473 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
474 al = SSL_AD_RECORD_OVERFLOW;
475 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
476 goto f_err;
477 }
478 if (!ssl3_do_uncompress(s)) {
479 al = SSL_AD_DECOMPRESSION_FAILURE;
480 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
481 goto f_err;
482 }
483 }
484
485 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
486 al = SSL_AD_RECORD_OVERFLOW;
487 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
488 goto f_err;
489 }
490
491 rr->off = 0;
492 /*-
493 * So at this point the following is true
494 * ssl->s3->rrec.type is the type of record
495 * ssl->s3->rrec.length == number of bytes in record
496 * ssl->s3->rrec.off == offset to first valid byte
497 * ssl->s3->rrec.data == where to take bytes from, increment
498 * after use :-).
499 */
500
501 /* we have pulled in a full packet so zero things */
502 RECORD_LAYER_reset_packet_length(&s->rlayer);
503
504 /* just read a 0 length packet */
505 if (rr->length == 0) {
506 empty_record_count++;
507 if (empty_record_count > MAX_EMPTY_RECORDS) {
508 al = SSL_AD_UNEXPECTED_MESSAGE;
509 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
510 goto f_err;
511 }
512 goto again;
513 }
514
515 return (1);
516
517 f_err:
518 ssl3_send_alert(s, SSL3_AL_FATAL, al);
519 err:
520 return (ret);
521 }
522
523 int ssl3_do_uncompress(SSL *ssl)
524 {
525 #ifndef OPENSSL_NO_COMP
526 int i;
527 SSL3_RECORD *rr;
528
529 rr = RECORD_LAYER_get_rrec(&ssl->rlayer);
530 i = COMP_expand_block(ssl->expand, rr->comp,
531 SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
532 (int)rr->length);
533 if (i < 0)
534 return (0);
535 else
536 rr->length = i;
537 rr->data = rr->comp;
538 #endif
539 return (1);
540 }
541
542 int ssl3_do_compress(SSL *ssl)
543 {
544 #ifndef OPENSSL_NO_COMP
545 int i;
546 SSL3_RECORD *wr;
547
548 wr = RECORD_LAYER_get_wrec(&ssl->rlayer);
549 i = COMP_compress_block(ssl->compress, wr->data,
550 SSL3_RT_MAX_COMPRESSED_LENGTH,
551 wr->input, (int)wr->length);
552 if (i < 0)
553 return (0);
554 else
555 wr->length = i;
556
557 wr->input = wr->data;
558 #endif
559 return (1);
560 }
561
562 /*-
563 * ssl3_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
564 *
565 * Returns:
566 * 0: (in non-constant time) if the record is publically invalid (i.e. too
567 * short etc).
568 * 1: if the record's padding is valid / the encryption was successful.
569 * -1: if the record's padding is invalid or, if sending, an internal error
570 * occurred.
571 */
572 int ssl3_enc(SSL *s, int send)
573 {
574 SSL3_RECORD *rec;
575 EVP_CIPHER_CTX *ds;
576 unsigned long l;
577 int bs, i, mac_size = 0;
578 const EVP_CIPHER *enc;
579
580 if (send) {
581 ds = s->enc_write_ctx;
582 rec = RECORD_LAYER_get_wrec(&s->rlayer);
583 if (s->enc_write_ctx == NULL)
584 enc = NULL;
585 else
586 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
587 } else {
588 ds = s->enc_read_ctx;
589 rec = RECORD_LAYER_get_rrec(&s->rlayer);
590 if (s->enc_read_ctx == NULL)
591 enc = NULL;
592 else
593 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
594 }
595
596 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
597 memmove(rec->data, rec->input, rec->length);
598 rec->input = rec->data;
599 } else {
600 l = rec->length;
601 bs = EVP_CIPHER_block_size(ds->cipher);
602
603 /* COMPRESS */
604
605 if ((bs != 1) && send) {
606 i = bs - ((int)l % bs);
607
608 /* we need to add 'i-1' padding bytes */
609 l += i;
610 /*
611 * the last of these zero bytes will be overwritten with the
612 * padding length.
613 */
614 memset(&rec->input[rec->length], 0, i);
615 rec->length += i;
616 rec->input[l - 1] = (i - 1);
617 }
618
619 if (!send) {
620 if (l == 0 || l % bs != 0)
621 return 0;
622 /* otherwise, rec->length >= bs */
623 }
624
625 if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
626 return -1;
627
628 if (EVP_MD_CTX_md(s->read_hash) != NULL)
629 mac_size = EVP_MD_CTX_size(s->read_hash);
630 if ((bs != 1) && !send)
631 return ssl3_cbc_remove_padding(s, rec, bs, mac_size);
632 }
633 return (1);
634 }
635
636 /*-
637 * tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
638 *
639 * Returns:
640 * 0: (in non-constant time) if the record is publically invalid (i.e. too
641 * short etc).
642 * 1: if the record's padding is valid / the encryption was successful.
643 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
644 * an internal error occurred.
645 */
646 int tls1_enc(SSL *s, int send)
647 {
648 SSL3_RECORD *rec;
649 EVP_CIPHER_CTX *ds;
650 unsigned long l;
651 int bs, i, j, k, pad = 0, ret, mac_size = 0;
652 const EVP_CIPHER *enc;
653
654 if (send) {
655 if (EVP_MD_CTX_md(s->write_hash)) {
656 int n = EVP_MD_CTX_size(s->write_hash);
657 OPENSSL_assert(n >= 0);
658 }
659 ds = s->enc_write_ctx;
660 rec = RECORD_LAYER_get_wrec(&s->rlayer);
661 if (s->enc_write_ctx == NULL)
662 enc = NULL;
663 else {
664 int ivlen;
665 enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
666 /* For TLSv1.1 and later explicit IV */
667 if (SSL_USE_EXPLICIT_IV(s)
668 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
669 ivlen = EVP_CIPHER_iv_length(enc);
670 else
671 ivlen = 0;
672 if (ivlen > 1) {
673 if (rec->data != rec->input)
674 /*
675 * we can't write into the input stream: Can this ever
676 * happen?? (steve)
677 */
678 fprintf(stderr,
679 "%s:%d: rec->data != rec->input\n",
680 __FILE__, __LINE__);
681 else if (RAND_bytes(rec->input, ivlen) <= 0)
682 return -1;
683 }
684 }
685 } else {
686 if (EVP_MD_CTX_md(s->read_hash)) {
687 int n = EVP_MD_CTX_size(s->read_hash);
688 OPENSSL_assert(n >= 0);
689 }
690 ds = s->enc_read_ctx;
691 rec = RECORD_LAYER_get_rrec(&s->rlayer);
692 if (s->enc_read_ctx == NULL)
693 enc = NULL;
694 else
695 enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
696 }
697
698 if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
699 memmove(rec->data, rec->input, rec->length);
700 rec->input = rec->data;
701 ret = 1;
702 } else {
703 l = rec->length;
704 bs = EVP_CIPHER_block_size(ds->cipher);
705
706 if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
707 unsigned char buf[EVP_AEAD_TLS1_AAD_LEN], *seq;
708
709 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
710 : RECORD_LAYER_get_read_sequence(&s->rlayer);
711
712 if (SSL_IS_DTLS(s)) {
713 unsigned char dtlsseq[9], *p = dtlsseq;
714
715 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
716 DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
717 memcpy(p, &seq[2], 6);
718 memcpy(buf, dtlsseq, 8);
719 } else {
720 memcpy(buf, seq, 8);
721 for (i = 7; i >= 0; i--) { /* increment */
722 ++seq[i];
723 if (seq[i] != 0)
724 break;
725 }
726 }
727
728 buf[8] = rec->type;
729 buf[9] = (unsigned char)(s->version >> 8);
730 buf[10] = (unsigned char)(s->version);
731 buf[11] = rec->length >> 8;
732 buf[12] = rec->length & 0xff;
733 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
734 EVP_AEAD_TLS1_AAD_LEN, buf);
735 if (pad <= 0)
736 return -1;
737 if (send) {
738 l += pad;
739 rec->length += pad;
740 }
741 } else if ((bs != 1) && send) {
742 i = bs - ((int)l % bs);
743
744 /* Add weird padding of upto 256 bytes */
745
746 /* we need to add 'i' padding bytes of value j */
747 j = i - 1;
748 if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
749 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
750 j++;
751 }
752 for (k = (int)l; k < (int)(l + i); k++)
753 rec->input[k] = j;
754 l += i;
755 rec->length += i;
756 }
757
758 if (!send) {
759 if (l == 0 || l % bs != 0)
760 return 0;
761 }
762
763 i = EVP_Cipher(ds, rec->data, rec->input, l);
764 if ((EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
765 ? (i < 0)
766 : (i == 0))
767 return -1; /* AEAD can fail to verify MAC */
768 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
769 rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
770 rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
771 rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
772 }
773
774 ret = 1;
775 if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
776 mac_size = EVP_MD_CTX_size(s->read_hash);
777 if ((bs != 1) && !send)
778 ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
779 if (pad && !send)
780 rec->length -= pad;
781 }
782 return ret;
783 }
784
785 int n_ssl3_mac(SSL *ssl, unsigned char *md, int send)
786 {
787 SSL3_RECORD *rec;
788 unsigned char *mac_sec, *seq;
789 EVP_MD_CTX md_ctx;
790 const EVP_MD_CTX *hash;
791 unsigned char *p, rec_char;
792 size_t md_size;
793 int npad;
794 int t;
795
796 if (send) {
797 rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
798 mac_sec = &(ssl->s3->write_mac_secret[0]);
799 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
800 hash = ssl->write_hash;
801 } else {
802 rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
803 mac_sec = &(ssl->s3->read_mac_secret[0]);
804 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
805 hash = ssl->read_hash;
806 }
807
808 t = EVP_MD_CTX_size(hash);
809 if (t < 0)
810 return -1;
811 md_size = t;
812 npad = (48 / md_size) * md_size;
813
814 if (!send &&
815 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
816 ssl3_cbc_record_digest_supported(hash)) {
817 /*
818 * This is a CBC-encrypted record. We must avoid leaking any
819 * timing-side channel information about how many blocks of data we
820 * are hashing because that gives an attacker a timing-oracle.
821 */
822
823 /*-
824 * npad is, at most, 48 bytes and that's with MD5:
825 * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
826 *
827 * With SHA-1 (the largest hash speced for SSLv3) the hash size
828 * goes up 4, but npad goes down by 8, resulting in a smaller
829 * total size.
830 */
831 unsigned char header[75];
832 unsigned j = 0;
833 memcpy(header + j, mac_sec, md_size);
834 j += md_size;
835 memcpy(header + j, ssl3_pad_1, npad);
836 j += npad;
837 memcpy(header + j, seq, 8);
838 j += 8;
839 header[j++] = rec->type;
840 header[j++] = rec->length >> 8;
841 header[j++] = rec->length & 0xff;
842
843 /* Final param == is SSLv3 */
844 ssl3_cbc_digest_record(hash,
845 md, &md_size,
846 header, rec->input,
847 rec->length + md_size, rec->orig_len,
848 mac_sec, md_size, 1);
849 } else {
850 unsigned int md_size_u;
851 /* Chop the digest off the end :-) */
852 EVP_MD_CTX_init(&md_ctx);
853
854 EVP_MD_CTX_copy_ex(&md_ctx, hash);
855 EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
856 EVP_DigestUpdate(&md_ctx, ssl3_pad_1, npad);
857 EVP_DigestUpdate(&md_ctx, seq, 8);
858 rec_char = rec->type;
859 EVP_DigestUpdate(&md_ctx, &rec_char, 1);
860 p = md;
861 s2n(rec->length, p);
862 EVP_DigestUpdate(&md_ctx, md, 2);
863 EVP_DigestUpdate(&md_ctx, rec->input, rec->length);
864 EVP_DigestFinal_ex(&md_ctx, md, NULL);
865
866 EVP_MD_CTX_copy_ex(&md_ctx, hash);
867 EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
868 EVP_DigestUpdate(&md_ctx, ssl3_pad_2, npad);
869 EVP_DigestUpdate(&md_ctx, md, md_size);
870 EVP_DigestFinal_ex(&md_ctx, md, &md_size_u);
871 md_size = md_size_u;
872
873 EVP_MD_CTX_cleanup(&md_ctx);
874 }
875
876 ssl3_record_sequence_update(seq);
877 return (md_size);
878 }
879
880 int tls1_mac(SSL *ssl, unsigned char *md, int send)
881 {
882 SSL3_RECORD *rec;
883 unsigned char *seq;
884 EVP_MD_CTX *hash;
885 size_t md_size;
886 int i;
887 EVP_MD_CTX hmac, *mac_ctx;
888 unsigned char header[13];
889 int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
890 : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
891 int t;
892
893 if (send) {
894 rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
895 seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
896 hash = ssl->write_hash;
897 } else {
898 rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
899 seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
900 hash = ssl->read_hash;
901 }
902
903 t = EVP_MD_CTX_size(hash);
904 OPENSSL_assert(t >= 0);
905 md_size = t;
906
907 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
908 if (stream_mac) {
909 mac_ctx = hash;
910 } else {
911 if (!EVP_MD_CTX_copy(&hmac, hash))
912 return -1;
913 mac_ctx = &hmac;
914 }
915
916 if (SSL_IS_DTLS(ssl)) {
917 unsigned char dtlsseq[8], *p = dtlsseq;
918
919 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
920 DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
921 memcpy(p, &seq[2], 6);
922
923 memcpy(header, dtlsseq, 8);
924 } else
925 memcpy(header, seq, 8);
926
927 header[8] = rec->type;
928 header[9] = (unsigned char)(ssl->version >> 8);
929 header[10] = (unsigned char)(ssl->version);
930 header[11] = (rec->length) >> 8;
931 header[12] = (rec->length) & 0xff;
932
933 if (!send && !SSL_USE_ETM(ssl) &&
934 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
935 ssl3_cbc_record_digest_supported(mac_ctx)) {
936 /*
937 * This is a CBC-encrypted record. We must avoid leaking any
938 * timing-side channel information about how many blocks of data we
939 * are hashing because that gives an attacker a timing-oracle.
940 */
941 /* Final param == not SSLv3 */
942 ssl3_cbc_digest_record(mac_ctx,
943 md, &md_size,
944 header, rec->input,
945 rec->length + md_size, rec->orig_len,
946 ssl->s3->read_mac_secret,
947 ssl->s3->read_mac_secret_size, 0);
948 } else {
949 EVP_DigestSignUpdate(mac_ctx, header, sizeof(header));
950 EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length);
951 t = EVP_DigestSignFinal(mac_ctx, md, &md_size);
952 OPENSSL_assert(t > 0);
953 if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
954 tls_fips_digest_extra(ssl->enc_read_ctx,
955 mac_ctx, rec->input,
956 rec->length, rec->orig_len);
957 }
958
959 if (!stream_mac)
960 EVP_MD_CTX_cleanup(&hmac);
961 #ifdef TLS_DEBUG
962 fprintf(stderr, "seq=");
963 {
964 int z;
965 for (z = 0; z < 8; z++)
966 fprintf(stderr, "%02X ", seq[z]);
967 fprintf(stderr, "\n");
968 }
969 fprintf(stderr, "rec=");
970 {
971 unsigned int z;
972 for (z = 0; z < rec->length; z++)
973 fprintf(stderr, "%02X ", rec->data[z]);
974 fprintf(stderr, "\n");
975 }
976 #endif
977
978 if (!SSL_IS_DTLS(ssl)) {
979 for (i = 7; i >= 0; i--) {
980 ++seq[i];
981 if (seq[i] != 0)
982 break;
983 }
984 }
985 #ifdef TLS_DEBUG
986 {
987 unsigned int z;
988 for (z = 0; z < md_size; z++)
989 fprintf(stderr, "%02X ", md[z]);
990 fprintf(stderr, "\n");
991 }
992 #endif
993 return (md_size);
994 }
995
996 /*-
997 * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
998 * record in |rec| by updating |rec->length| in constant time.
999 *
1000 * block_size: the block size of the cipher used to encrypt the record.
1001 * returns:
1002 * 0: (in non-constant time) if the record is publicly invalid.
1003 * 1: if the padding was valid
1004 * -1: otherwise.
1005 */
1006 int ssl3_cbc_remove_padding(const SSL *s,
1007 SSL3_RECORD *rec,
1008 unsigned block_size, unsigned mac_size)
1009 {
1010 unsigned padding_length, good;
1011 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1012
1013 /*
1014 * These lengths are all public so we can test them in non-constant time.
1015 */
1016 if (overhead > rec->length)
1017 return 0;
1018
1019 padding_length = rec->data[rec->length - 1];
1020 good = constant_time_ge(rec->length, padding_length + overhead);
1021 /* SSLv3 requires that the padding is minimal. */
1022 good &= constant_time_ge(block_size, padding_length + 1);
1023 rec->length -= good & (padding_length + 1);
1024 return constant_time_select_int(good, 1, -1);
1025 }
1026
1027 /*-
1028 * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1029 * record in |rec| in constant time and returns 1 if the padding is valid and
1030 * -1 otherwise. It also removes any explicit IV from the start of the record
1031 * without leaking any timing about whether there was enough space after the
1032 * padding was removed.
1033 *
1034 * block_size: the block size of the cipher used to encrypt the record.
1035 * returns:
1036 * 0: (in non-constant time) if the record is publicly invalid.
1037 * 1: if the padding was valid
1038 * -1: otherwise.
1039 */
1040 int tls1_cbc_remove_padding(const SSL *s,
1041 SSL3_RECORD *rec,
1042 unsigned block_size, unsigned mac_size)
1043 {
1044 unsigned padding_length, good, to_check, i;
1045 const unsigned overhead = 1 /* padding length byte */ + mac_size;
1046 /* Check if version requires explicit IV */
1047 if (SSL_USE_EXPLICIT_IV(s)) {
1048 /*
1049 * These lengths are all public so we can test them in non-constant
1050 * time.
1051 */
1052 if (overhead + block_size > rec->length)
1053 return 0;
1054 /* We can now safely skip explicit IV */
1055 rec->data += block_size;
1056 rec->input += block_size;
1057 rec->length -= block_size;
1058 rec->orig_len -= block_size;
1059 } else if (overhead > rec->length)
1060 return 0;
1061
1062 padding_length = rec->data[rec->length - 1];
1063
1064 /*
1065 * NB: if compression is in operation the first packet may not be of even
1066 * length so the padding bug check cannot be performed. This bug
1067 * workaround has been around since SSLeay so hopefully it is either
1068 * fixed now or no buggy implementation supports compression [steve]
1069 */
1070 if ((s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) && !s->expand) {
1071 /* First packet is even in size, so check */
1072 if ((memcmp(RECORD_LAYER_get_read_sequence(&s->rlayer),
1073 "\0\0\0\0\0\0\0\0", 8) == 0) &&
1074 !(padding_length & 1)) {
1075 s->s3->flags |= TLS1_FLAGS_TLS_PADDING_BUG;
1076 }
1077 if ((s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) && padding_length > 0) {
1078 padding_length--;
1079 }
1080 }
1081
1082 if (EVP_CIPHER_flags(s->enc_read_ctx->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1083 /* padding is already verified */
1084 rec->length -= padding_length + 1;
1085 return 1;
1086 }
1087
1088 good = constant_time_ge(rec->length, overhead + padding_length);
1089 /*
1090 * The padding consists of a length byte at the end of the record and
1091 * then that many bytes of padding, all with the same value as the length
1092 * byte. Thus, with the length byte included, there are i+1 bytes of
1093 * padding. We can't check just |padding_length+1| bytes because that
1094 * leaks decrypted information. Therefore we always have to check the
1095 * maximum amount of padding possible. (Again, the length of the record
1096 * is public information so we can use it.)
1097 */
1098 to_check = 255; /* maximum amount of padding. */
1099 if (to_check > rec->length - 1)
1100 to_check = rec->length - 1;
1101
1102 for (i = 0; i < to_check; i++) {
1103 unsigned char mask = constant_time_ge_8(padding_length, i);
1104 unsigned char b = rec->data[rec->length - 1 - i];
1105 /*
1106 * The final |padding_length+1| bytes should all have the value
1107 * |padding_length|. Therefore the XOR should be zero.
1108 */
1109 good &= ~(mask & (padding_length ^ b));
1110 }
1111
1112 /*
1113 * If any of the final |padding_length+1| bytes had the wrong value, one
1114 * or more of the lower eight bits of |good| will be cleared.
1115 */
1116 good = constant_time_eq(0xff, good & 0xff);
1117 rec->length -= good & (padding_length + 1);
1118
1119 return constant_time_select_int(good, 1, -1);
1120 }
1121
1122 /*-
1123 * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1124 * constant time (independent of the concrete value of rec->length, which may
1125 * vary within a 256-byte window).
1126 *
1127 * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1128 * this function.
1129 *
1130 * On entry:
1131 * rec->orig_len >= md_size
1132 * md_size <= EVP_MAX_MD_SIZE
1133 *
1134 * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1135 * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1136 * a single or pair of cache-lines, then the variable memory accesses don't
1137 * actually affect the timing. CPUs with smaller cache-lines [if any] are
1138 * not multi-core and are not considered vulnerable to cache-timing attacks.
1139 */
1140 #define CBC_MAC_ROTATE_IN_PLACE
1141
1142 void ssl3_cbc_copy_mac(unsigned char *out,
1143 const SSL3_RECORD *rec, unsigned md_size)
1144 {
1145 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1146 unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1147 unsigned char *rotated_mac;
1148 #else
1149 unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1150 #endif
1151
1152 /*
1153 * mac_end is the index of |rec->data| just after the end of the MAC.
1154 */
1155 unsigned mac_end = rec->length;
1156 unsigned mac_start = mac_end - md_size;
1157 /*
1158 * scan_start contains the number of bytes that we can ignore because the
1159 * MAC's position can only vary by 255 bytes.
1160 */
1161 unsigned scan_start = 0;
1162 unsigned i, j;
1163 unsigned div_spoiler;
1164 unsigned rotate_offset;
1165
1166 OPENSSL_assert(rec->orig_len >= md_size);
1167 OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1168
1169 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1170 rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1171 #endif
1172
1173 /* This information is public so it's safe to branch based on it. */
1174 if (rec->orig_len > md_size + 255 + 1)
1175 scan_start = rec->orig_len - (md_size + 255 + 1);
1176 /*
1177 * div_spoiler contains a multiple of md_size that is used to cause the
1178 * modulo operation to be constant time. Without this, the time varies
1179 * based on the amount of padding when running on Intel chips at least.
1180 * The aim of right-shifting md_size is so that the compiler doesn't
1181 * figure out that it can remove div_spoiler as that would require it to
1182 * prove that md_size is always even, which I hope is beyond it.
1183 */
1184 div_spoiler = md_size >> 1;
1185 div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1186 rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1187
1188 memset(rotated_mac, 0, md_size);
1189 for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1190 unsigned char mac_started = constant_time_ge_8(i, mac_start);
1191 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1192 unsigned char b = rec->data[i];
1193 rotated_mac[j++] |= b & mac_started & ~mac_ended;
1194 j &= constant_time_lt(j, md_size);
1195 }
1196
1197 /* Now rotate the MAC */
1198 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1199 j = 0;
1200 for (i = 0; i < md_size; i++) {
1201 /* in case cache-line is 32 bytes, touch second line */
1202 ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1203 out[j++] = rotated_mac[rotate_offset++];
1204 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1205 }
1206 #else
1207 memset(out, 0, md_size);
1208 rotate_offset = md_size - rotate_offset;
1209 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1210 for (i = 0; i < md_size; i++) {
1211 for (j = 0; j < md_size; j++)
1212 out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1213 rotate_offset++;
1214 rotate_offset &= constant_time_lt(rotate_offset, md_size);
1215 }
1216 #endif
1217 }
1218
1219 int dtls1_process_record(SSL *s)
1220 {
1221 int i, al;
1222 int enc_err;
1223 SSL_SESSION *sess;
1224 SSL3_RECORD *rr;
1225 unsigned int mac_size;
1226 unsigned char md[EVP_MAX_MD_SIZE];
1227
1228 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1229 sess = s->session;
1230
1231 /*
1232 * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1233 * and we have that many bytes in s->packet
1234 */
1235 rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1236
1237 /*
1238 * ok, we can now read from 's->packet' data into 'rr' rr->input points
1239 * at rr->length bytes, which need to be copied into rr->data by either
1240 * the decryption or by the decompression When the data is 'copied' into
1241 * the rr->data buffer, rr->input will be pointed at the new buffer
1242 */
1243
1244 /*
1245 * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1246 * bytes of encrypted compressed stuff.
1247 */
1248
1249 /* check is not needed I believe */
1250 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1251 al = SSL_AD_RECORD_OVERFLOW;
1252 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1253 goto f_err;
1254 }
1255
1256 /* decrypt in place in 'rr->input' */
1257 rr->data = rr->input;
1258 rr->orig_len = rr->length;
1259
1260 enc_err = s->method->ssl3_enc->enc(s, 0);
1261 /*-
1262 * enc_err is:
1263 * 0: (in non-constant time) if the record is publically invalid.
1264 * 1: if the padding is valid
1265 * -1: if the padding is invalid
1266 */
1267 if (enc_err == 0) {
1268 /* For DTLS we simply ignore bad packets. */
1269 rr->length = 0;
1270 RECORD_LAYER_reset_packet_length(&s->rlayer);
1271 goto err;
1272 }
1273 #ifdef TLS_DEBUG
1274 printf("dec %d\n", rr->length);
1275 {
1276 unsigned int z;
1277 for (z = 0; z < rr->length; z++)
1278 printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1279 }
1280 printf("\n");
1281 #endif
1282
1283 /* r->length is now the compressed data plus mac */
1284 if ((sess != NULL) &&
1285 (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1286 /* s->read_hash != NULL => mac_size != -1 */
1287 unsigned char *mac = NULL;
1288 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1289 mac_size = EVP_MD_CTX_size(s->read_hash);
1290 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1291
1292 /*
1293 * orig_len is the length of the record before any padding was
1294 * removed. This is public information, as is the MAC in use,
1295 * therefore we can safely process the record in a different amount
1296 * of time if it's too short to possibly contain a MAC.
1297 */
1298 if (rr->orig_len < mac_size ||
1299 /* CBC records must have a padding length byte too. */
1300 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1301 rr->orig_len < mac_size + 1)) {
1302 al = SSL_AD_DECODE_ERROR;
1303 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1304 goto f_err;
1305 }
1306
1307 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1308 /*
1309 * We update the length so that the TLS header bytes can be
1310 * constructed correctly but we need to extract the MAC in
1311 * constant time from within the record, without leaking the
1312 * contents of the padding bytes.
1313 */
1314 mac = mac_tmp;
1315 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1316 rr->length -= mac_size;
1317 } else {
1318 /*
1319 * In this case there's no padding, so |rec->orig_len| equals
1320 * |rec->length| and we checked that there's enough bytes for
1321 * |mac_size| above.
1322 */
1323 rr->length -= mac_size;
1324 mac = &rr->data[rr->length];
1325 }
1326
1327 i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
1328 if (i < 0 || mac == NULL
1329 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1330 enc_err = -1;
1331 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1332 enc_err = -1;
1333 }
1334
1335 if (enc_err < 0) {
1336 /* decryption failed, silently discard message */
1337 rr->length = 0;
1338 RECORD_LAYER_reset_packet_length(&s->rlayer);
1339 goto err;
1340 }
1341
1342 /* r->length is now just compressed */
1343 if (s->expand != NULL) {
1344 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1345 al = SSL_AD_RECORD_OVERFLOW;
1346 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1347 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1348 goto f_err;
1349 }
1350 if (!ssl3_do_uncompress(s)) {
1351 al = SSL_AD_DECOMPRESSION_FAILURE;
1352 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1353 goto f_err;
1354 }
1355 }
1356
1357 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1358 al = SSL_AD_RECORD_OVERFLOW;
1359 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1360 goto f_err;
1361 }
1362
1363 rr->off = 0;
1364 /*-
1365 * So at this point the following is true
1366 * ssl->s3->rrec.type is the type of record
1367 * ssl->s3->rrec.length == number of bytes in record
1368 * ssl->s3->rrec.off == offset to first valid byte
1369 * ssl->s3->rrec.data == where to take bytes from, increment
1370 * after use :-).
1371 */
1372
1373 /* we have pulled in a full packet so zero things */
1374 RECORD_LAYER_reset_packet_length(&s->rlayer);
1375 return (1);
1376
1377 f_err:
1378 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1379 err:
1380 return (0);
1381 }
1382
1383
1384 /*
1385 * retrieve a buffered record that belongs to the current epoch, ie,
1386 * processed
1387 */
1388 #define dtls1_get_processed_record(s) \
1389 dtls1_retrieve_buffered_record((s), \
1390 &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1391
1392 /*-
1393 * Call this to get a new input record.
1394 * It will return <= 0 if more data is needed, normally due to an error
1395 * or non-blocking IO.
1396 * When it finishes, one packet has been decoded and can be found in
1397 * ssl->s3->rrec.type - is the type of record
1398 * ssl->s3->rrec.data, - data
1399 * ssl->s3->rrec.length, - number of bytes
1400 */
1401 /* used only by dtls1_read_bytes */
1402 int dtls1_get_record(SSL *s)
1403 {
1404 int ssl_major, ssl_minor;
1405 int i, n;
1406 SSL3_RECORD *rr;
1407 unsigned char *p = NULL;
1408 unsigned short version;
1409 DTLS1_BITMAP *bitmap;
1410 unsigned int is_next_epoch;
1411
1412 rr = RECORD_LAYER_get_rrec(&s->rlayer);
1413
1414 /*
1415 * The epoch may have changed. If so, process all the pending records.
1416 * This is a non-blocking operation.
1417 */
1418 if (dtls1_process_buffered_records(s) < 0)
1419 return -1;
1420
1421 /* if we're renegotiating, then there may be buffered records */
1422 if (dtls1_get_processed_record(s))
1423 return 1;
1424
1425 /* get something from the wire */
1426 again:
1427 /* check if we have the header */
1428 if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1429 (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1430 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1431 SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
1432 /* read timeout is handled by dtls1_read_bytes */
1433 if (n <= 0)
1434 return (n); /* error or non-blocking */
1435
1436 /* this packet contained a partial record, dump it */
1437 if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1438 RECORD_LAYER_reset_packet_length(&s->rlayer);
1439 goto again;
1440 }
1441
1442 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1443
1444 p = RECORD_LAYER_get_packet(&s->rlayer);
1445
1446 if (s->msg_callback)
1447 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1448 s, s->msg_callback_arg);
1449
1450 /* Pull apart the header into the DTLS1_RECORD */
1451 rr->type = *(p++);
1452 ssl_major = *(p++);
1453 ssl_minor = *(p++);
1454 version = (ssl_major << 8) | ssl_minor;
1455
1456 /* sequence number is 64 bits, with top 2 bytes = epoch */
1457 n2s(p, rr->epoch);
1458
1459 memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1460 p += 6;
1461
1462 n2s(p, rr->length);
1463
1464 /* Lets check version */
1465 if (!s->first_packet) {
1466 if (version != s->version) {
1467 /* unexpected version, silently discard */
1468 rr->length = 0;
1469 RECORD_LAYER_reset_packet_length(&s->rlayer);
1470 goto again;
1471 }
1472 }
1473
1474 if ((version & 0xff00) != (s->version & 0xff00)) {
1475 /* wrong version, silently discard record */
1476 rr->length = 0;
1477 RECORD_LAYER_reset_packet_length(&s->rlayer);
1478 goto again;
1479 }
1480
1481 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1482 /* record too long, silently discard it */
1483 rr->length = 0;
1484 RECORD_LAYER_reset_packet_length(&s->rlayer);
1485 goto again;
1486 }
1487
1488 /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1489 }
1490
1491 /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1492
1493 if (rr->length >
1494 RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1495 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1496 i = rr->length;
1497 n = ssl3_read_n(s, i, i, 1);
1498 /* this packet contained a partial record, dump it */
1499 if (n != i) {
1500 rr->length = 0;
1501 RECORD_LAYER_reset_packet_length(&s->rlayer);
1502 goto again;
1503 }
1504
1505 /*
1506 * now n == rr->length, and s->packet_length ==
1507 * DTLS1_RT_HEADER_LENGTH + rr->length
1508 */
1509 }
1510 /* set state for later operations */
1511 RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1512
1513 /* match epochs. NULL means the packet is dropped on the floor */
1514 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1515 if (bitmap == NULL) {
1516 rr->length = 0;
1517 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1518 goto again; /* get another record */
1519 }
1520 #ifndef OPENSSL_NO_SCTP
1521 /* Only do replay check if no SCTP bio */
1522 if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1523 #endif
1524 /*
1525 * Check whether this is a repeat, or aged record. Don't check if
1526 * we're listening and this message is a ClientHello. They can look
1527 * as if they're replayed, since they arrive from different
1528 * connections and would be dropped unnecessarily.
1529 */
1530 if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
1531 RECORD_LAYER_get_packet_length(&s->rlayer)
1532 > DTLS1_RT_HEADER_LENGTH &&
1533 RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]
1534 == SSL3_MT_CLIENT_HELLO) &&
1535 !dtls1_record_replay_check(s, bitmap)) {
1536 rr->length = 0;
1537 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1538 goto again; /* get another record */
1539 }
1540 #ifndef OPENSSL_NO_SCTP
1541 }
1542 #endif
1543
1544 /* just read a 0 length packet */
1545 if (rr->length == 0)
1546 goto again;
1547
1548 /*
1549 * If this record is from the next epoch (either HM or ALERT), and a
1550 * handshake is currently in progress, buffer it since it cannot be
1551 * processed at this time. However, do not buffer anything while
1552 * listening.
1553 */
1554 if (is_next_epoch) {
1555 if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
1556 if (dtls1_buffer_record
1557 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1558 rr->seq_num) < 0)
1559 return -1;
1560 /* Mark receipt of record. */
1561 dtls1_record_bitmap_update(s, bitmap);
1562 }
1563 rr->length = 0;
1564 RECORD_LAYER_reset_packet_length(&s->rlayer);
1565 goto again;
1566 }
1567
1568 if (!dtls1_process_record(s)) {
1569 rr->length = 0;
1570 RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1571 goto again; /* get another record */
1572 }
1573 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
1574
1575 return (1);
1576
1577 }
1578