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