94f140fd68ea33e25d4a89c4aaf9f459dfd0198a
[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     size_t 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, rret, ret = -1;
129     int i;
130     size_t more, n;
131     SSL3_RECORD *rr;
132     SSL3_BUFFER *rbuf;
133     SSL_SESSION *sess;
134     unsigned char *p;
135     unsigned char md[EVP_MAX_MD_SIZE];
136     short version;
137     unsigned mac_size;
138     unsigned int num_recs = 0;
139     unsigned int max_recs;
140     unsigned int j;
141
142     rr = RECORD_LAYER_get_rrec(&s->rlayer);
143     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
144     max_recs = s->max_pipelines;
145     if (max_recs == 0)
146         max_recs = 1;
147     sess = s->session;
148
149     do {
150         /* check if we have the header */
151         if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
152             (RECORD_LAYER_get_packet_length(&s->rlayer)
153              < SSL3_RT_HEADER_LENGTH)) {
154             rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
155                                SSL3_BUFFER_get_len(rbuf), 0,
156                                num_recs == 0 ? 1 : 0, &n);
157             if (rret <= 0)
158                 return rret;     /* error or non-blocking */
159             RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
160
161             p = RECORD_LAYER_get_packet(&s->rlayer);
162
163             /*
164              * The first record received by the server may be a V2ClientHello.
165              */
166             if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
167                 && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
168                 /*
169                  *  SSLv2 style record
170                  *
171                  * |num_recs| here will actually always be 0 because
172                  * |num_recs > 0| only ever occurs when we are processing
173                  * multiple app data records - which we know isn't the case here
174                  * because it is an SSLv2ClientHello. We keep it using
175                  * |num_recs| for the sake of consistency
176                  */
177                 rr[num_recs].type = SSL3_RT_HANDSHAKE;
178                 rr[num_recs].rec_version = SSL2_VERSION;
179
180                 rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
181
182                 if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf)
183                     - SSL2_RT_HEADER_LENGTH) {
184                     al = SSL_AD_RECORD_OVERFLOW;
185                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
186                     goto f_err;
187                 }
188
189                 if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
190                     al = SSL_AD_HANDSHAKE_FAILURE;
191                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
192                     goto f_err;
193                 }
194             } else {
195                 /* SSLv3+ style record */
196                 if (s->msg_callback)
197                     s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
198                                     s->msg_callback_arg);
199
200                 /* Pull apart the header into the SSL3_RECORD */
201                 rr[num_recs].type = *(p++);
202                 ssl_major = *(p++);
203                 ssl_minor = *(p++);
204                 version = (ssl_major << 8) | ssl_minor;
205                 rr[num_recs].rec_version = version;
206                 n2s(p, rr[num_recs].length);
207
208                 /* Lets check version */
209                 if (!s->first_packet && version != s->version) {
210                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
211                     if ((s->version & 0xFF00) == (version & 0xFF00)
212                         && !s->enc_write_ctx && !s->write_hash) {
213                         if (rr->type == SSL3_RT_ALERT) {
214                             /*
215                              * The record is using an incorrect version number,
216                              * but what we've got appears to be an alert. We
217                              * haven't read the body yet to check whether its a
218                              * fatal or not - but chances are it is. We probably
219                              * shouldn't send a fatal alert back. We'll just
220                              * end.
221                              */
222                             goto err;
223                         }
224                         /*
225                          * Send back error using their minor version number :-)
226                          */
227                         s->version = (unsigned short)version;
228                     }
229                     al = SSL_AD_PROTOCOL_VERSION;
230                     goto f_err;
231                 }
232
233                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
234                     if (RECORD_LAYER_is_first_record(&s->rlayer)) {
235                         /* Go back to start of packet, look at the five bytes
236                          * that we have. */
237                         p = RECORD_LAYER_get_packet(&s->rlayer);
238                         if (strncmp((char *)p, "GET ", 4) == 0 ||
239                             strncmp((char *)p, "POST ", 5) == 0 ||
240                             strncmp((char *)p, "HEAD ", 5) == 0 ||
241                             strncmp((char *)p, "PUT ", 4) == 0) {
242                             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
243                             goto err;
244                         } else if (strncmp((char *)p, "CONNE", 5) == 0) {
245                             SSLerr(SSL_F_SSL3_GET_RECORD,
246                                    SSL_R_HTTPS_PROXY_REQUEST);
247                             goto err;
248                         }
249
250                         /* Doesn't look like TLS - don't send an alert */
251                         SSLerr(SSL_F_SSL3_GET_RECORD,
252                                SSL_R_WRONG_VERSION_NUMBER);
253                         goto err;
254                     } else {
255                         SSLerr(SSL_F_SSL3_GET_RECORD,
256                                SSL_R_WRONG_VERSION_NUMBER);
257                         al = SSL_AD_PROTOCOL_VERSION;
258                         goto f_err;
259                     }
260                 }
261
262                 if (rr[num_recs].length >
263                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
264                     al = SSL_AD_RECORD_OVERFLOW;
265                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
266                     goto f_err;
267                 }
268             }
269
270             /* now s->rlayer.rstate == SSL_ST_READ_BODY */
271         }
272
273         /*
274          * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
275          * Calculate how much more data we need to read for the rest of the
276          * record
277          */
278         if (rr[num_recs].rec_version == SSL2_VERSION) {
279             more = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
280                 - SSL3_RT_HEADER_LENGTH;
281         } else {
282             more = rr[num_recs].length;
283         }
284         if (more > 0) {
285             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
286
287             rret = ssl3_read_n(s, more, more, 1, 0, &n);
288             if (rret <= 0)
289                 return rret;     /* error or non-blocking io */
290         }
291
292         /* set state for later operations */
293         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
294
295         /*
296          * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
297          * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
298          * and we have that many bytes in s->packet
299          */
300         if (rr[num_recs].rec_version == SSL2_VERSION) {
301             rr[num_recs].input =
302                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
303         } else {
304             rr[num_recs].input =
305                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
306         }
307
308         /*
309          * ok, we can now read from 's->packet' data into 'rr' rr->input points
310          * at rr->length bytes, which need to be copied into rr->data by either
311          * the decryption or by the decompression When the data is 'copied' into
312          * the rr->data buffer, rr->input will be pointed at the new buffer
313          */
314
315         /*
316          * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
317          * bytes of encrypted compressed stuff.
318          */
319
320         /* check is not needed I believe */
321         if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
322             al = SSL_AD_RECORD_OVERFLOW;
323             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
324             goto f_err;
325         }
326
327         /* decrypt in place in 'rr->input' */
328         rr[num_recs].data = rr[num_recs].input;
329         rr[num_recs].orig_len = rr[num_recs].length;
330
331         /* Mark this record as not read by upper layers yet */
332         rr[num_recs].read = 0;
333
334         num_recs++;
335
336         /* we have pulled in a full packet so zero things */
337         RECORD_LAYER_reset_packet_length(&s->rlayer);
338         RECORD_LAYER_clear_first_record(&s->rlayer);
339     } while (num_recs < max_recs
340              && rr[num_recs - 1].type == SSL3_RT_APPLICATION_DATA
341              && SSL_USE_EXPLICIT_IV(s)
342              && s->enc_read_ctx != NULL
343              && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
344                  & EVP_CIPH_FLAG_PIPELINE)
345              && ssl3_record_app_data_waiting(s));
346
347     /*
348      * If in encrypt-then-mac mode calculate mac from encrypted record. All
349      * the details below are public so no timing details can leak.
350      */
351     if (SSL_USE_ETM(s) && s->read_hash) {
352         unsigned char *mac;
353         mac_size = EVP_MD_CTX_size(s->read_hash);
354         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
355         for (j = 0; j < num_recs; j++) {
356             if (rr[j].length < mac_size) {
357                 al = SSL_AD_DECODE_ERROR;
358                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
359                 goto f_err;
360             }
361             rr[j].length -= mac_size;
362             mac = rr[j].data + rr[j].length;
363             i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
364             if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
365                 al = SSL_AD_BAD_RECORD_MAC;
366                 SSLerr(SSL_F_SSL3_GET_RECORD,
367                        SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
368                 goto f_err;
369             }
370         }
371     }
372
373     enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
374     /*-
375      * enc_err is:
376      *    0: (in non-constant time) if the record is publically invalid.
377      *    1: if the padding is valid
378      *    -1: if the padding is invalid
379      */
380     if (enc_err == 0) {
381         al = SSL_AD_DECRYPTION_FAILED;
382         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
383         goto f_err;
384     }
385 #ifdef SSL_DEBUG
386     printf("dec %d\n", rr->length);
387     {
388         unsigned int z;
389         for (z = 0; z < rr->length; z++)
390             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
391     }
392     printf("\n");
393 #endif
394
395     /* r->length is now the compressed data plus mac */
396     if ((sess != NULL) &&
397         (s->enc_read_ctx != NULL) &&
398         (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
399         /* s->read_hash != NULL => mac_size != -1 */
400         unsigned char *mac = NULL;
401         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
402
403         mac_size = EVP_MD_CTX_size(s->read_hash);
404         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
405
406         for (j = 0; j < num_recs; j++) {
407             /*
408              * orig_len is the length of the record before any padding was
409              * removed. This is public information, as is the MAC in use,
410              * therefore we can safely process the record in a different amount
411              * of time if it's too short to possibly contain a MAC.
412              */
413             if (rr[j].orig_len < mac_size ||
414                 /* CBC records must have a padding length byte too. */
415                 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
416                  rr[j].orig_len < mac_size + 1)) {
417                 al = SSL_AD_DECODE_ERROR;
418                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
419                 goto f_err;
420             }
421
422             if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
423                 /*
424                  * We update the length so that the TLS header bytes can be
425                  * constructed correctly but we need to extract the MAC in
426                  * constant time from within the record, without leaking the
427                  * contents of the padding bytes.
428                  */
429                 mac = mac_tmp;
430                 ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
431                 rr[j].length -= mac_size;
432             } else {
433                 /*
434                  * In this case there's no padding, so |rec->orig_len| equals
435                  * |rec->length| and we checked that there's enough bytes for
436                  * |mac_size| above.
437                  */
438                 rr[j].length -= mac_size;
439                 mac = &rr[j].data[rr[j].length];
440             }
441
442             i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
443             if (i < 0 || mac == NULL
444                 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
445                 enc_err = -1;
446             if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
447                 enc_err = -1;
448         }
449     }
450
451     if (enc_err < 0) {
452         /*
453          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
454          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
455          * failure is directly visible from the ciphertext anyway, we should
456          * not reveal which kind of error occurred -- this might become
457          * visible to an attacker (e.g. via a logfile)
458          */
459         al = SSL_AD_BAD_RECORD_MAC;
460         SSLerr(SSL_F_SSL3_GET_RECORD,
461                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
462         goto f_err;
463     }
464
465     for (j = 0; j < num_recs; j++) {
466         /* rr[j].length is now just compressed */
467         if (s->expand != NULL) {
468             if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
469                 al = SSL_AD_RECORD_OVERFLOW;
470                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
471                 goto f_err;
472             }
473             if (!ssl3_do_uncompress(s, &rr[j])) {
474                 al = SSL_AD_DECOMPRESSION_FAILURE;
475                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
476                 goto f_err;
477             }
478         }
479
480         if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
481             al = SSL_AD_RECORD_OVERFLOW;
482             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
483             goto f_err;
484         }
485
486         rr[j].off = 0;
487         /*-
488          * So at this point the following is true
489          * rr[j].type   is the type of record
490          * rr[j].length == number of bytes in record
491          * rr[j].off    == offset to first valid byte
492          * rr[j].data   == where to take bytes from, increment after use :-).
493          */
494
495         /* just read a 0 length packet */
496         if (rr[j].length == 0) {
497             RECORD_LAYER_inc_empty_record_count(&s->rlayer);
498             if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
499                 > MAX_EMPTY_RECORDS) {
500                 al = SSL_AD_UNEXPECTED_MESSAGE;
501                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
502                 goto f_err;
503             }
504         } else {
505             RECORD_LAYER_reset_empty_record_count(&s->rlayer);
506         }
507     }
508
509     RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
510     return 1;
511
512  f_err:
513     ssl3_send_alert(s, SSL3_AL_FATAL, al);
514  err:
515     return ret;
516 }
517
518 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
519 {
520 #ifndef OPENSSL_NO_COMP
521     int i;
522
523     if (rr->comp == NULL) {
524         rr->comp = (unsigned char *)
525             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
526     }
527     if (rr->comp == NULL)
528         return 0;
529
530     i = COMP_expand_block(ssl->expand, rr->comp,
531                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (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 || !EVP_MD_CTX_copy(hmac, hash))
981             return -1;
982         mac_ctx = hmac;
983     }
984
985     if (SSL_IS_DTLS(ssl)) {
986         unsigned char dtlsseq[8], *p = dtlsseq;
987
988         s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
989             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
990         memcpy(p, &seq[2], 6);
991
992         memcpy(header, dtlsseq, 8);
993     } else
994         memcpy(header, seq, 8);
995
996     header[8] = rec->type;
997     header[9] = (unsigned char)(ssl->version >> 8);
998     header[10] = (unsigned char)(ssl->version);
999     header[11] = (rec->length) >> 8;
1000     header[12] = (rec->length) & 0xff;
1001
1002     if (!send && !SSL_USE_ETM(ssl) &&
1003         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1004         ssl3_cbc_record_digest_supported(mac_ctx)) {
1005         /*
1006          * This is a CBC-encrypted record. We must avoid leaking any
1007          * timing-side channel information about how many blocks of data we
1008          * are hashing because that gives an attacker a timing-oracle.
1009          */
1010         /* Final param == not SSLv3 */
1011         if (ssl3_cbc_digest_record(mac_ctx,
1012                                    md, &md_size,
1013                                    header, rec->input,
1014                                    rec->length + md_size, rec->orig_len,
1015                                    ssl->s3->read_mac_secret,
1016                                    ssl->s3->read_mac_secret_size, 0) <= 0) {
1017             EVP_MD_CTX_free(hmac);
1018             return -1;
1019         }
1020     } else {
1021         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1022             || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1023             || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1024             EVP_MD_CTX_free(hmac);
1025             return -1;
1026         }
1027         if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1028             if (!tls_fips_digest_extra(ssl->enc_read_ctx,
1029                                        mac_ctx, rec->input,
1030                                        rec->length, rec->orig_len)) {
1031                 EVP_MD_CTX_free(hmac);
1032                 return -1;
1033             }
1034     }
1035
1036     EVP_MD_CTX_free(hmac);
1037
1038 #ifdef SSL_DEBUG
1039     fprintf(stderr, "seq=");
1040     {
1041         int z;
1042         for (z = 0; z < 8; z++)
1043             fprintf(stderr, "%02X ", seq[z]);
1044         fprintf(stderr, "\n");
1045     }
1046     fprintf(stderr, "rec=");
1047     {
1048         unsigned int z;
1049         for (z = 0; z < rec->length; z++)
1050             fprintf(stderr, "%02X ", rec->data[z]);
1051         fprintf(stderr, "\n");
1052     }
1053 #endif
1054
1055     if (!SSL_IS_DTLS(ssl)) {
1056         for (i = 7; i >= 0; i--) {
1057             ++seq[i];
1058             if (seq[i] != 0)
1059                 break;
1060         }
1061     }
1062 #ifdef SSL_DEBUG
1063     {
1064         unsigned int z;
1065         for (z = 0; z < md_size; z++)
1066             fprintf(stderr, "%02X ", md[z]);
1067         fprintf(stderr, "\n");
1068     }
1069 #endif
1070     return (md_size);
1071 }
1072
1073 /*-
1074  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1075  * record in |rec| by updating |rec->length| in constant time.
1076  *
1077  * block_size: the block size of the cipher used to encrypt the record.
1078  * returns:
1079  *   0: (in non-constant time) if the record is publicly invalid.
1080  *   1: if the padding was valid
1081  *  -1: otherwise.
1082  */
1083 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1084                             unsigned block_size, unsigned mac_size)
1085 {
1086     unsigned padding_length, good;
1087     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1088
1089     /*
1090      * These lengths are all public so we can test them in non-constant time.
1091      */
1092     if (overhead > rec->length)
1093         return 0;
1094
1095     padding_length = rec->data[rec->length - 1];
1096     good = constant_time_ge(rec->length, padding_length + overhead);
1097     /* SSLv3 requires that the padding is minimal. */
1098     good &= constant_time_ge(block_size, padding_length + 1);
1099     rec->length -= good & (padding_length + 1);
1100     return constant_time_select_int(good, 1, -1);
1101 }
1102
1103 /*-
1104  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1105  * record in |rec| in constant time and returns 1 if the padding is valid and
1106  * -1 otherwise. It also removes any explicit IV from the start of the record
1107  * without leaking any timing about whether there was enough space after the
1108  * padding was removed.
1109  *
1110  * block_size: the block size of the cipher used to encrypt the record.
1111  * returns:
1112  *   0: (in non-constant time) if the record is publicly invalid.
1113  *   1: if the padding was valid
1114  *  -1: otherwise.
1115  */
1116 int tls1_cbc_remove_padding(const SSL *s,
1117                             SSL3_RECORD *rec,
1118                             unsigned block_size, unsigned mac_size)
1119 {
1120     unsigned padding_length, good, to_check, i;
1121     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1122     /* Check if version requires explicit IV */
1123     if (SSL_USE_EXPLICIT_IV(s)) {
1124         /*
1125          * These lengths are all public so we can test them in non-constant
1126          * time.
1127          */
1128         if (overhead + block_size > rec->length)
1129             return 0;
1130         /* We can now safely skip explicit IV */
1131         rec->data += block_size;
1132         rec->input += block_size;
1133         rec->length -= block_size;
1134         rec->orig_len -= block_size;
1135     } else if (overhead > rec->length)
1136         return 0;
1137
1138     padding_length = rec->data[rec->length - 1];
1139
1140     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1141         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, DTLS1_BITMAP *bitmap)
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     if (SSL_USE_ETM(s) && s->read_hash) {
1320         unsigned char *mac;
1321         mac_size = EVP_MD_CTX_size(s->read_hash);
1322         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1323         if (rr->orig_len < mac_size) {
1324             al = SSL_AD_DECODE_ERROR;
1325             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1326             goto f_err;
1327         }
1328         rr->length -= mac_size;
1329         mac = rr->data + rr->length;
1330         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1331         if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1332             al = SSL_AD_BAD_RECORD_MAC;
1333             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1334                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1335             goto f_err;
1336         }
1337     }
1338
1339     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1340     /*-
1341      * enc_err is:
1342      *    0: (in non-constant time) if the record is publically invalid.
1343      *    1: if the padding is valid
1344      *   -1: if the padding is invalid
1345      */
1346     if (enc_err == 0) {
1347         /* For DTLS we simply ignore bad packets. */
1348         rr->length = 0;
1349         RECORD_LAYER_reset_packet_length(&s->rlayer);
1350         goto err;
1351     }
1352 #ifdef SSL_DEBUG
1353     printf("dec %d\n", rr->length);
1354     {
1355         unsigned int z;
1356         for (z = 0; z < rr->length; z++)
1357             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1358     }
1359     printf("\n");
1360 #endif
1361
1362     /* r->length is now the compressed data plus mac */
1363     if ((sess != NULL) && !SSL_USE_ETM(s) &&
1364         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1365         /* s->read_hash != NULL => mac_size != -1 */
1366         unsigned char *mac = NULL;
1367         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1368         mac_size = EVP_MD_CTX_size(s->read_hash);
1369         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1370
1371         /*
1372          * orig_len is the length of the record before any padding was
1373          * removed. This is public information, as is the MAC in use,
1374          * therefore we can safely process the record in a different amount
1375          * of time if it's too short to possibly contain a MAC.
1376          */
1377         if (rr->orig_len < mac_size ||
1378             /* CBC records must have a padding length byte too. */
1379             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1380              rr->orig_len < mac_size + 1)) {
1381             al = SSL_AD_DECODE_ERROR;
1382             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1383             goto f_err;
1384         }
1385
1386         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1387             /*
1388              * We update the length so that the TLS header bytes can be
1389              * constructed correctly but we need to extract the MAC in
1390              * constant time from within the record, without leaking the
1391              * contents of the padding bytes.
1392              */
1393             mac = mac_tmp;
1394             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1395             rr->length -= mac_size;
1396         } else {
1397             /*
1398              * In this case there's no padding, so |rec->orig_len| equals
1399              * |rec->length| and we checked that there's enough bytes for
1400              * |mac_size| above.
1401              */
1402             rr->length -= mac_size;
1403             mac = &rr->data[rr->length];
1404         }
1405
1406         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1407         if (i < 0 || mac == NULL
1408             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1409             enc_err = -1;
1410         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1411             enc_err = -1;
1412     }
1413
1414     if (enc_err < 0) {
1415         /* decryption failed, silently discard message */
1416         rr->length = 0;
1417         RECORD_LAYER_reset_packet_length(&s->rlayer);
1418         goto err;
1419     }
1420
1421     /* r->length is now just compressed */
1422     if (s->expand != NULL) {
1423         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1424             al = SSL_AD_RECORD_OVERFLOW;
1425             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1426                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1427             goto f_err;
1428         }
1429         if (!ssl3_do_uncompress(s, rr)) {
1430             al = SSL_AD_DECOMPRESSION_FAILURE;
1431             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1432             goto f_err;
1433         }
1434     }
1435
1436     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1437         al = SSL_AD_RECORD_OVERFLOW;
1438         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1439         goto f_err;
1440     }
1441
1442     rr->off = 0;
1443     /*-
1444      * So at this point the following is true
1445      * ssl->s3->rrec.type   is the type of record
1446      * ssl->s3->rrec.length == number of bytes in record
1447      * ssl->s3->rrec.off    == offset to first valid byte
1448      * ssl->s3->rrec.data   == where to take bytes from, increment
1449      *                         after use :-).
1450      */
1451
1452     /* we have pulled in a full packet so zero things */
1453     RECORD_LAYER_reset_packet_length(&s->rlayer);
1454
1455     /* Mark receipt of record. */
1456     dtls1_record_bitmap_update(s, bitmap);
1457
1458     return (1);
1459
1460  f_err:
1461     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1462  err:
1463     return (0);
1464 }
1465
1466 /*
1467  * retrieve a buffered record that belongs to the current epoch, ie,
1468  * processed
1469  */
1470 #define dtls1_get_processed_record(s) \
1471                    dtls1_retrieve_buffered_record((s), \
1472                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1473
1474 /*-
1475  * Call this to get a new input record.
1476  * It will return <= 0 if more data is needed, normally due to an error
1477  * or non-blocking IO.
1478  * When it finishes, one packet has been decoded and can be found in
1479  * ssl->s3->rrec.type    - is the type of record
1480  * ssl->s3->rrec.data,   - data
1481  * ssl->s3->rrec.length, - number of bytes
1482  */
1483 /* used only by dtls1_read_bytes */
1484 int dtls1_get_record(SSL *s)
1485 {
1486     int ssl_major, ssl_minor;
1487     int rret;
1488     size_t more, n;
1489     SSL3_RECORD *rr;
1490     unsigned char *p = NULL;
1491     unsigned short version;
1492     DTLS1_BITMAP *bitmap;
1493     unsigned int is_next_epoch;
1494
1495     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1496
1497  again:
1498     /*
1499      * The epoch may have changed.  If so, process all the pending records.
1500      * This is a non-blocking operation.
1501      */
1502     if (!dtls1_process_buffered_records(s))
1503         return -1;
1504
1505     /* if we're renegotiating, then there may be buffered records */
1506     if (dtls1_get_processed_record(s))
1507         return 1;
1508
1509     /* get something from the wire */
1510
1511     /* check if we have the header */
1512     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1513         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1514         rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1515                            SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1516         /* read timeout is handled by dtls1_read_bytes */
1517         if (rret <= 0)
1518             return rret;         /* error or non-blocking */
1519
1520         /* this packet contained a partial record, dump it */
1521         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1522             DTLS1_RT_HEADER_LENGTH) {
1523             RECORD_LAYER_reset_packet_length(&s->rlayer);
1524             goto again;
1525         }
1526
1527         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1528
1529         p = RECORD_LAYER_get_packet(&s->rlayer);
1530
1531         if (s->msg_callback)
1532             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1533                             s, s->msg_callback_arg);
1534
1535         /* Pull apart the header into the DTLS1_RECORD */
1536         rr->type = *(p++);
1537         ssl_major = *(p++);
1538         ssl_minor = *(p++);
1539         version = (ssl_major << 8) | ssl_minor;
1540
1541         /* sequence number is 64 bits, with top 2 bytes = epoch */
1542         n2s(p, rr->epoch);
1543
1544         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1545         p += 6;
1546
1547         n2s(p, rr->length);
1548
1549         /* Lets check version */
1550         if (!s->first_packet) {
1551             if (version != s->version) {
1552                 /* unexpected version, silently discard */
1553                 rr->length = 0;
1554                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1555                 goto again;
1556             }
1557         }
1558
1559         if ((version & 0xff00) != (s->version & 0xff00)) {
1560             /* wrong version, silently discard record */
1561             rr->length = 0;
1562             RECORD_LAYER_reset_packet_length(&s->rlayer);
1563             goto again;
1564         }
1565
1566         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1567             /* record too long, silently discard it */
1568             rr->length = 0;
1569             RECORD_LAYER_reset_packet_length(&s->rlayer);
1570             goto again;
1571         }
1572
1573         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1574     }
1575
1576     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1577
1578     if (rr->length >
1579         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1580         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1581         more = rr->length;
1582         rret = ssl3_read_n(s, more, more, 1, 1, &n);
1583         /* this packet contained a partial record, dump it */
1584         if (rret <= 0 || n != more) {
1585             rr->length = 0;
1586             RECORD_LAYER_reset_packet_length(&s->rlayer);
1587             goto again;
1588         }
1589
1590         /*
1591          * now n == rr->length, and s->packet_length ==
1592          * DTLS1_RT_HEADER_LENGTH + rr->length
1593          */
1594     }
1595     /* set state for later operations */
1596     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1597
1598     /* match epochs.  NULL means the packet is dropped on the floor */
1599     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1600     if (bitmap == NULL) {
1601         rr->length = 0;
1602         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1603         goto again;             /* get another record */
1604     }
1605 #ifndef OPENSSL_NO_SCTP
1606     /* Only do replay check if no SCTP bio */
1607     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1608 #endif
1609         /* Check whether this is a repeat, or aged record. */
1610         /*
1611          * TODO: Does it make sense to have replay protection in epoch 0 where
1612          * we have no integrity negotiated yet?
1613          */
1614         if (!dtls1_record_replay_check(s, bitmap)) {
1615             rr->length = 0;
1616             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1617             goto again;         /* get another record */
1618         }
1619 #ifndef OPENSSL_NO_SCTP
1620     }
1621 #endif
1622
1623     /* just read a 0 length packet */
1624     if (rr->length == 0)
1625         goto again;
1626
1627     /*
1628      * If this record is from the next epoch (either HM or ALERT), and a
1629      * handshake is currently in progress, buffer it since it cannot be
1630      * processed at this time.
1631      */
1632     if (is_next_epoch) {
1633         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1634             if (dtls1_buffer_record
1635                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1636                  rr->seq_num) < 0)
1637                 return -1;
1638         }
1639         rr->length = 0;
1640         RECORD_LAYER_reset_packet_length(&s->rlayer);
1641         goto again;
1642     }
1643
1644     if (!dtls1_process_record(s, bitmap)) {
1645         rr->length = 0;
1646         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1647         goto again;             /* get another record */
1648     }
1649
1650     return (1);
1651
1652 }