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