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