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