ad240bc52d2a3e6b97759adbb3c60102f1505f23
[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              * Check whether this is a regular record or an SSLv2 style record.
163              * The latter can only be used in the first record of an initial
164              * ClientHello for old clients. Initial ClientHello means
165              * s->first_packet is set and s->server is true. The first record
166              * means we've not received any data so far (s->init_num == 0) and
167              * have had no empty records. We check s->read_hash and
168              * s->enc_read_ctx to ensure this does not apply during
169              * renegotiation.
170              */
171             if (s->first_packet && s->server
172                     && s->init_num == 0
173                     && RECORD_LAYER_get_empty_record_count(&s->rlayer) == 0
174                     && s->read_hash == NULL && s->enc_read_ctx == NULL
175                     && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
176                 /*
177                  *  SSLv2 style record
178                  *
179                  * |num_recs| here will actually always be 0 because
180                  * |num_recs > 0| only ever occurs when we are processing
181                  * multiple app data records - which we know isn't the case here
182                  * because it is an SSLv2ClientHello. We keep it using
183                  * |num_recs| for the sake of consistency
184                  */
185                 rr[num_recs].type = SSL3_RT_HANDSHAKE;
186                 rr[num_recs].rec_version = SSL2_VERSION;
187
188                 rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
189
190                 if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf)
191                                  - SSL2_RT_HEADER_LENGTH) {
192                     al = SSL_AD_RECORD_OVERFLOW;
193                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
194                     goto f_err;
195                 }
196
197                 if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
198                     al = SSL_AD_HANDSHAKE_FAILURE;
199                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
200                     goto f_err;
201                 }
202             } else {
203                 /* SSLv3+ style record */
204                 if (s->msg_callback)
205                     s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
206                                     s->msg_callback_arg);
207
208                 /* Pull apart the header into the SSL3_RECORD */
209                 rr[num_recs].type = *(p++);
210                 ssl_major = *(p++);
211                 ssl_minor = *(p++);
212                 version = (ssl_major << 8) | ssl_minor;
213                 rr[num_recs].rec_version = version;
214                 n2s(p, rr[num_recs].length);
215
216                 /* Lets check version */
217                 if (!s->first_packet && version != s->version) {
218                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
219                     if ((s->version & 0xFF00) == (version & 0xFF00)
220                         && !s->enc_write_ctx && !s->write_hash) {
221                         if (rr->type == SSL3_RT_ALERT) {
222                             /*
223                              * The record is using an incorrect version number,
224                              * but what we've got appears to be an alert. We
225                              * haven't read the body yet to check whether its a
226                              * fatal or not - but chances are it is. We probably
227                              * shouldn't send a fatal alert back. We'll just
228                              * end.
229                              */
230                              goto err;
231                         }
232                         /*
233                          * Send back error using their minor version number :-)
234                          */
235                         s->version = (unsigned short)version;
236                     }
237                     al = SSL_AD_PROTOCOL_VERSION;
238                     goto f_err;
239                 }
240
241                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
242                     if (s->first_packet) {
243                         /* Go back to start of packet, look at the five bytes
244                          * that we have. */
245                         p = RECORD_LAYER_get_packet(&s->rlayer);
246                         if (strncmp((char *)p, "GET ", 4) == 0 ||
247                             strncmp((char *)p, "POST ", 5) == 0 ||
248                             strncmp((char *)p, "HEAD ", 5) == 0 ||
249                             strncmp((char *)p, "PUT ", 4) == 0) {
250                             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
251                             goto err;
252                         } else if (strncmp((char *)p, "CONNE", 5) == 0) {
253                             SSLerr(SSL_F_SSL3_GET_RECORD,
254                                    SSL_R_HTTPS_PROXY_REQUEST);
255                             goto err;
256                         }
257                     }
258                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
259                     goto err;
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             i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
280                 - SSL3_RT_HEADER_LENGTH;
281         } else {
282             i = rr[num_recs].length;
283         }
284         if (i > 0) {
285             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
286
287             n = ssl3_read_n(s, i, i, 1, 0);
288             if (n <= 0)
289                 return (n);         /* 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     } while (num_recs < max_recs
339              && rr[num_recs-1].type == SSL3_RT_APPLICATION_DATA
340              && SSL_USE_EXPLICIT_IV(s)
341              && s->enc_read_ctx != NULL
342              && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
343                 & EVP_CIPH_FLAG_PIPELINE)
344              && ssl3_record_app_data_waiting(s));
345
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,
532                           (int)rr->length);
533     if (i < 0)
534         return 0;
535     else
536         rr->length = i;
537     rr->data = rr->comp;
538 #endif
539     return 1;
540 }
541
542 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
543 {
544 #ifndef OPENSSL_NO_COMP
545     int i;
546
547     i = COMP_compress_block(ssl->compress, wr->data,
548                             SSL3_RT_MAX_COMPRESSED_LENGTH,
549                             wr->input, (int)wr->length);
550     if (i < 0)
551         return (0);
552     else
553         wr->length = i;
554
555     wr->input = wr->data;
556 #endif
557     return (1);
558 }
559
560 /*-
561  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
562  *
563  * Returns:
564  *   0: (in non-constant time) if the record is publically invalid (i.e. too
565  *       short etc).
566  *   1: if the record's padding is valid / the encryption was successful.
567  *   -1: if the record's padding is invalid or, if sending, an internal error
568  *       occurred.
569  */
570 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
571 {
572     SSL3_RECORD *rec;
573     EVP_CIPHER_CTX *ds;
574     unsigned long l;
575     int bs, i, mac_size = 0;
576     const EVP_CIPHER *enc;
577
578     rec = inrecs;
579     /*
580      * We shouldn't ever be called with more than one record in the SSLv3 case
581      */
582     if (n_recs != 1)
583         return 0;
584     if (send) {
585         ds = s->enc_write_ctx;
586         if (s->enc_write_ctx == NULL)
587             enc = NULL;
588         else
589             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
590     } else {
591         ds = s->enc_read_ctx;
592         if (s->enc_read_ctx == NULL)
593             enc = NULL;
594         else
595             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
596     }
597
598     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
599         memmove(rec->data, rec->input, rec->length);
600         rec->input = rec->data;
601     } else {
602         l = rec->length;
603         bs = EVP_CIPHER_CTX_block_size(ds);
604
605         /* COMPRESS */
606
607         if ((bs != 1) && send) {
608             i = bs - ((int)l % bs);
609
610             /* we need to add 'i-1' padding bytes */
611             l += i;
612             /*
613              * the last of these zero bytes will be overwritten with the
614              * padding length.
615              */
616             memset(&rec->input[rec->length], 0, i);
617             rec->length += i;
618             rec->input[l - 1] = (i - 1);
619         }
620
621         if (!send) {
622             if (l == 0 || l % bs != 0)
623                 return 0;
624             /* otherwise, rec->length >= bs */
625         }
626
627         if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
628             return -1;
629
630         if (EVP_MD_CTX_md(s->read_hash) != NULL)
631             mac_size = EVP_MD_CTX_size(s->read_hash);
632         if ((bs != 1) && !send)
633             return ssl3_cbc_remove_padding(rec, bs, mac_size);
634     }
635     return (1);
636 }
637
638 /*-
639  * tls1_enc encrypts/decrypts |n_recs| in |recs|.
640  *
641  * Returns:
642  *   0: (in non-constant time) if the record is publically invalid (i.e. too
643  *       short etc).
644  *   1: if the record's padding is valid / the encryption was successful.
645  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
646  *       an internal error occurred.
647  */
648 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
649 {
650     EVP_CIPHER_CTX *ds;
651     size_t reclen[SSL_MAX_PIPELINES];
652     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
653     int bs, i, j, k, pad = 0, ret, mac_size = 0;
654     const EVP_CIPHER *enc;
655     unsigned int ctr;
656
657     if (send) {
658         if (EVP_MD_CTX_md(s->write_hash)) {
659             int n = EVP_MD_CTX_size(s->write_hash);
660             OPENSSL_assert(n >= 0);
661         }
662         ds = s->enc_write_ctx;
663         if (s->enc_write_ctx == NULL)
664             enc = NULL;
665         else {
666             int ivlen;
667             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
668             /* For TLSv1.1 and later explicit IV */
669             if (SSL_USE_EXPLICIT_IV(s)
670                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
671                 ivlen = EVP_CIPHER_iv_length(enc);
672             else
673                 ivlen = 0;
674             if (ivlen > 1) {
675                 for (ctr = 0; ctr < n_recs; ctr++) {
676                     if (recs[ctr].data != recs[ctr].input) {
677                         /*
678                          * we can't write into the input stream: Can this ever
679                          * happen?? (steve)
680                          */
681                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
682                         return -1;
683                     } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
684                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
685                         return -1;
686                     }
687                 }
688             }
689         }
690     } else {
691         if (EVP_MD_CTX_md(s->read_hash)) {
692             int n = EVP_MD_CTX_size(s->read_hash);
693             OPENSSL_assert(n >= 0);
694         }
695         ds = s->enc_read_ctx;
696         if (s->enc_read_ctx == NULL)
697             enc = NULL;
698         else
699             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
700     }
701
702     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
703         for (ctr = 0; ctr < n_recs; ctr++) {
704             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
705             recs[ctr].input = recs[ctr].data;
706         }
707         ret = 1;
708     } else {
709         bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
710
711         if (n_recs > 1) {
712             if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
713                                     & EVP_CIPH_FLAG_PIPELINE)) {
714                 /*
715                  * We shouldn't have been called with pipeline data if the
716                  * cipher doesn't support pipelining
717                  */
718                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
719                 return -1;
720             }
721         }
722         for (ctr = 0; ctr < n_recs; ctr++) {
723             reclen[ctr] = recs[ctr].length;
724
725             if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
726                     & EVP_CIPH_FLAG_AEAD_CIPHER) {
727                 unsigned char *seq;
728
729                 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
730                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
731
732                 if (SSL_IS_DTLS(s)) {
733                     /* DTLS does not support pipelining */
734                     unsigned char dtlsseq[9], *p = dtlsseq;
735
736                     s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
737                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
738                     memcpy(p, &seq[2], 6);
739                     memcpy(buf[ctr], dtlsseq, 8);
740                 } else {
741                     memcpy(buf[ctr], seq, 8);
742                     for (i = 7; i >= 0; i--) { /* increment */
743                         ++seq[i];
744                         if (seq[i] != 0)
745                             break;
746                     }
747                 }
748
749                 buf[ctr][8] = recs[ctr].type;
750                 buf[ctr][9] = (unsigned char)(s->version >> 8);
751                 buf[ctr][10] = (unsigned char)(s->version);
752                 buf[ctr][11] = recs[ctr].length >> 8;
753                 buf[ctr][12] = recs[ctr].length & 0xff;
754                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
755                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
756                 if (pad <= 0)
757                     return -1;
758
759                 if (send) {
760                     reclen[ctr] += pad;
761                     recs[ctr].length += pad;
762                 }
763
764             } else if ((bs != 1) && send) {
765                 i = bs - ((int)reclen[ctr] % bs);
766
767                 /* Add weird padding of upto 256 bytes */
768
769                 /* we need to add 'i' padding bytes of value j */
770                 j = i - 1;
771                 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
772                     recs[ctr].input[k] = j;
773                 reclen[ctr] += i;
774                 recs[ctr].length += i;
775             }
776
777             if (!send) {
778                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
779                     return 0;
780             }
781         }
782         if (n_recs > 1) {
783             unsigned char *data[SSL_MAX_PIPELINES];
784
785             /* Set the output buffers */
786             for (ctr = 0; ctr < n_recs; ctr++) {
787                 data[ctr] = recs[ctr].data;
788             }
789             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
790                                       n_recs, data) <= 0) {
791                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
792             }
793             /* Set the input buffers */
794             for (ctr = 0; ctr < n_recs; ctr++) {
795                 data[ctr] = recs[ctr].input;
796             }
797             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
798                                       n_recs, data) <= 0
799                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
800                                       n_recs, reclen) <= 0) {
801                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
802                 return -1;
803             }
804         }
805
806         i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
807         if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
808                 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
809             ? (i < 0)
810             : (i == 0))
811             return -1;          /* AEAD can fail to verify MAC */
812         if (send == 0) {
813             if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
814                 for (ctr = 0; ctr < n_recs; ctr++) {
815                     recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
816                     recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
817                     recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
818                 }
819             } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
820                 for (ctr = 0; ctr < n_recs; ctr++) {
821                     recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
822                     recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
823                     recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
824                 }
825             }
826         }
827
828         ret = 1;
829         if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
830             mac_size = EVP_MD_CTX_size(s->read_hash);
831         if ((bs != 1) && !send) {
832             int tmpret;
833             for (ctr = 0; ctr < n_recs; ctr++) {
834                 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
835                 if (tmpret == -1)
836                     return -1;
837                 ret &= tmpret;
838             }
839         }
840         if (pad && !send) {
841             for (ctr = 0; ctr < n_recs; ctr++) {
842                 recs[ctr].length -= pad;
843             }
844         }
845     }
846     return ret;
847 }
848
849 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
850 {
851     unsigned char *mac_sec, *seq;
852     const EVP_MD_CTX *hash;
853     unsigned char *p, rec_char;
854     size_t md_size;
855     int npad;
856     int t;
857
858     if (send) {
859         mac_sec = &(ssl->s3->write_mac_secret[0]);
860         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
861         hash = ssl->write_hash;
862     } else {
863         mac_sec = &(ssl->s3->read_mac_secret[0]);
864         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
865         hash = ssl->read_hash;
866     }
867
868     t = EVP_MD_CTX_size(hash);
869     if (t < 0)
870         return -1;
871     md_size = t;
872     npad = (48 / md_size) * md_size;
873
874     if (!send &&
875         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
876         ssl3_cbc_record_digest_supported(hash)) {
877         /*
878          * This is a CBC-encrypted record. We must avoid leaking any
879          * timing-side channel information about how many blocks of data we
880          * are hashing because that gives an attacker a timing-oracle.
881          */
882
883         /*-
884          * npad is, at most, 48 bytes and that's with MD5:
885          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
886          *
887          * With SHA-1 (the largest hash speced for SSLv3) the hash size
888          * goes up 4, but npad goes down by 8, resulting in a smaller
889          * total size.
890          */
891         unsigned char header[75];
892         unsigned j = 0;
893         memcpy(header + j, mac_sec, md_size);
894         j += md_size;
895         memcpy(header + j, ssl3_pad_1, npad);
896         j += npad;
897         memcpy(header + j, seq, 8);
898         j += 8;
899         header[j++] = rec->type;
900         header[j++] = rec->length >> 8;
901         header[j++] = rec->length & 0xff;
902
903         /* Final param == is SSLv3 */
904         if (ssl3_cbc_digest_record(hash,
905                                    md, &md_size,
906                                    header, rec->input,
907                                    rec->length + md_size, rec->orig_len,
908                                    mac_sec, md_size, 1) <= 0)
909             return -1;
910     } else {
911         unsigned int md_size_u;
912         /* Chop the digest off the end :-) */
913         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
914
915         if (md_ctx == NULL)
916             return -1;
917
918         rec_char = rec->type;
919         p = md;
920         s2n(rec->length, p);
921         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
922                 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
923                 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
924                 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
925                 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
926                 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
927                 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
928                 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
929                 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
930                 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
931                 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
932                 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
933                 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
934             EVP_MD_CTX_reset(md_ctx);
935             return -1;
936         }
937         md_size = md_size_u;
938
939         EVP_MD_CTX_free(md_ctx);
940     }
941
942     ssl3_record_sequence_update(seq);
943     return (md_size);
944 }
945
946 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
947 {
948     unsigned char *seq;
949     EVP_MD_CTX *hash;
950     size_t md_size;
951     int i;
952     EVP_MD_CTX *hmac = NULL, *mac_ctx;
953     unsigned char header[13];
954     int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
955                       : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
956     int t;
957
958     if (send) {
959         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
960         hash = ssl->write_hash;
961     } else {
962         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
963         hash = ssl->read_hash;
964     }
965
966     t = EVP_MD_CTX_size(hash);
967     OPENSSL_assert(t >= 0);
968     md_size = t;
969
970     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
971     if (stream_mac) {
972         mac_ctx = hash;
973     } else {
974         hmac = EVP_MD_CTX_new();
975         if (hmac == NULL
976                 || !EVP_MD_CTX_copy(hmac, hash))
977             return -1;
978         mac_ctx = hmac;
979     }
980
981     if (SSL_IS_DTLS(ssl)) {
982         unsigned char dtlsseq[8], *p = dtlsseq;
983
984         s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
985             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
986         memcpy(p, &seq[2], 6);
987
988         memcpy(header, dtlsseq, 8);
989     } else
990         memcpy(header, seq, 8);
991
992     header[8] = rec->type;
993     header[9] = (unsigned char)(ssl->version >> 8);
994     header[10] = (unsigned char)(ssl->version);
995     header[11] = (rec->length) >> 8;
996     header[12] = (rec->length) & 0xff;
997
998     if (!send && !SSL_USE_ETM(ssl) &&
999         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1000         ssl3_cbc_record_digest_supported(mac_ctx)) {
1001         /*
1002          * This is a CBC-encrypted record. We must avoid leaking any
1003          * timing-side channel information about how many blocks of data we
1004          * are hashing because that gives an attacker a timing-oracle.
1005          */
1006         /* Final param == not SSLv3 */
1007         if (ssl3_cbc_digest_record(mac_ctx,
1008                                    md, &md_size,
1009                                    header, rec->input,
1010                                    rec->length + md_size, rec->orig_len,
1011                                    ssl->s3->read_mac_secret,
1012                                    ssl->s3->read_mac_secret_size, 0) <= 0) {
1013             EVP_MD_CTX_free(hmac);
1014             return -1;
1015         }
1016     } else {
1017         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1018                 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1019                 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1020             EVP_MD_CTX_free(hmac);
1021             return -1;
1022         }
1023         if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1024             if (!tls_fips_digest_extra(ssl->enc_read_ctx,
1025                                        mac_ctx, rec->input,
1026                                        rec->length, rec->orig_len)) {
1027                 EVP_MD_CTX_free(hmac);
1028                 return -1;
1029         }
1030     }
1031
1032     EVP_MD_CTX_free(hmac);
1033
1034 #ifdef SSL_DEBUG
1035     fprintf(stderr, "seq=");
1036     {
1037         int z;
1038         for (z = 0; z < 8; z++)
1039             fprintf(stderr, "%02X ", seq[z]);
1040         fprintf(stderr, "\n");
1041     }
1042     fprintf(stderr, "rec=");
1043     {
1044         unsigned int z;
1045         for (z = 0; z < rec->length; z++)
1046             fprintf(stderr, "%02X ", rec->data[z]);
1047         fprintf(stderr, "\n");
1048     }
1049 #endif
1050
1051     if (!SSL_IS_DTLS(ssl)) {
1052         for (i = 7; i >= 0; i--) {
1053             ++seq[i];
1054             if (seq[i] != 0)
1055                 break;
1056         }
1057     }
1058 #ifdef SSL_DEBUG
1059     {
1060         unsigned int z;
1061         for (z = 0; z < md_size; z++)
1062             fprintf(stderr, "%02X ", md[z]);
1063         fprintf(stderr, "\n");
1064     }
1065 #endif
1066     return (md_size);
1067 }
1068
1069 /*-
1070  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1071  * record in |rec| by updating |rec->length| in constant time.
1072  *
1073  * block_size: the block size of the cipher used to encrypt the record.
1074  * returns:
1075  *   0: (in non-constant time) if the record is publicly invalid.
1076  *   1: if the padding was valid
1077  *  -1: otherwise.
1078  */
1079 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1080                             unsigned block_size, unsigned mac_size)
1081 {
1082     unsigned padding_length, good;
1083     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1084
1085     /*
1086      * These lengths are all public so we can test them in non-constant time.
1087      */
1088     if (overhead > rec->length)
1089         return 0;
1090
1091     padding_length = rec->data[rec->length - 1];
1092     good = constant_time_ge(rec->length, padding_length + overhead);
1093     /* SSLv3 requires that the padding is minimal. */
1094     good &= constant_time_ge(block_size, padding_length + 1);
1095     rec->length -= good & (padding_length + 1);
1096     return constant_time_select_int(good, 1, -1);
1097 }
1098
1099 /*-
1100  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1101  * record in |rec| in constant time and returns 1 if the padding is valid and
1102  * -1 otherwise. It also removes any explicit IV from the start of the record
1103  * without leaking any timing about whether there was enough space after the
1104  * padding was removed.
1105  *
1106  * block_size: the block size of the cipher used to encrypt the record.
1107  * returns:
1108  *   0: (in non-constant time) if the record is publicly invalid.
1109  *   1: if the padding was valid
1110  *  -1: otherwise.
1111  */
1112 int tls1_cbc_remove_padding(const SSL *s,
1113                             SSL3_RECORD *rec,
1114                             unsigned block_size, unsigned mac_size)
1115 {
1116     unsigned padding_length, good, to_check, i;
1117     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1118     /* Check if version requires explicit IV */
1119     if (SSL_USE_EXPLICIT_IV(s)) {
1120         /*
1121          * These lengths are all public so we can test them in non-constant
1122          * time.
1123          */
1124         if (overhead + block_size > rec->length)
1125             return 0;
1126         /* We can now safely skip explicit IV */
1127         rec->data += block_size;
1128         rec->input += block_size;
1129         rec->length -= block_size;
1130         rec->orig_len -= block_size;
1131     } else if (overhead > rec->length)
1132         return 0;
1133
1134     padding_length = rec->data[rec->length - 1];
1135
1136     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1137         /* padding is already verified */
1138         rec->length -= padding_length + 1;
1139         return 1;
1140     }
1141
1142     good = constant_time_ge(rec->length, overhead + padding_length);
1143     /*
1144      * The padding consists of a length byte at the end of the record and
1145      * then that many bytes of padding, all with the same value as the length
1146      * byte. Thus, with the length byte included, there are i+1 bytes of
1147      * padding. We can't check just |padding_length+1| bytes because that
1148      * leaks decrypted information. Therefore we always have to check the
1149      * maximum amount of padding possible. (Again, the length of the record
1150      * is public information so we can use it.)
1151      */
1152     to_check = 255;             /* maximum amount of padding. */
1153     if (to_check > rec->length - 1)
1154         to_check = rec->length - 1;
1155
1156     for (i = 0; i < to_check; i++) {
1157         unsigned char mask = constant_time_ge_8(padding_length, i);
1158         unsigned char b = rec->data[rec->length - 1 - i];
1159         /*
1160          * The final |padding_length+1| bytes should all have the value
1161          * |padding_length|. Therefore the XOR should be zero.
1162          */
1163         good &= ~(mask & (padding_length ^ b));
1164     }
1165
1166     /*
1167      * If any of the final |padding_length+1| bytes had the wrong value, one
1168      * or more of the lower eight bits of |good| will be cleared.
1169      */
1170     good = constant_time_eq(0xff, good & 0xff);
1171     rec->length -= good & (padding_length + 1);
1172
1173     return constant_time_select_int(good, 1, -1);
1174 }
1175
1176 /*-
1177  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1178  * constant time (independent of the concrete value of rec->length, which may
1179  * vary within a 256-byte window).
1180  *
1181  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1182  * this function.
1183  *
1184  * On entry:
1185  *   rec->orig_len >= md_size
1186  *   md_size <= EVP_MAX_MD_SIZE
1187  *
1188  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1189  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1190  * a single or pair of cache-lines, then the variable memory accesses don't
1191  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1192  * not multi-core and are not considered vulnerable to cache-timing attacks.
1193  */
1194 #define CBC_MAC_ROTATE_IN_PLACE
1195
1196 void ssl3_cbc_copy_mac(unsigned char *out,
1197                        const SSL3_RECORD *rec, unsigned md_size)
1198 {
1199 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1200     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1201     unsigned char *rotated_mac;
1202 #else
1203     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1204 #endif
1205
1206     /*
1207      * mac_end is the index of |rec->data| just after the end of the MAC.
1208      */
1209     unsigned mac_end = rec->length;
1210     unsigned mac_start = mac_end - md_size;
1211     /*
1212      * scan_start contains the number of bytes that we can ignore because the
1213      * MAC's position can only vary by 255 bytes.
1214      */
1215     unsigned scan_start = 0;
1216     unsigned i, j;
1217     unsigned div_spoiler;
1218     unsigned rotate_offset;
1219
1220     OPENSSL_assert(rec->orig_len >= md_size);
1221     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1222
1223 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1224     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1225 #endif
1226
1227     /* This information is public so it's safe to branch based on it. */
1228     if (rec->orig_len > md_size + 255 + 1)
1229         scan_start = rec->orig_len - (md_size + 255 + 1);
1230     /*
1231      * div_spoiler contains a multiple of md_size that is used to cause the
1232      * modulo operation to be constant time. Without this, the time varies
1233      * based on the amount of padding when running on Intel chips at least.
1234      * The aim of right-shifting md_size is so that the compiler doesn't
1235      * figure out that it can remove div_spoiler as that would require it to
1236      * prove that md_size is always even, which I hope is beyond it.
1237      */
1238     div_spoiler = md_size >> 1;
1239     div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1240     rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1241
1242     memset(rotated_mac, 0, md_size);
1243     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1244         unsigned char mac_started = constant_time_ge_8(i, mac_start);
1245         unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1246         unsigned char b = rec->data[i];
1247         rotated_mac[j++] |= b & mac_started & ~mac_ended;
1248         j &= constant_time_lt(j, md_size);
1249     }
1250
1251     /* Now rotate the MAC */
1252 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1253     j = 0;
1254     for (i = 0; i < md_size; i++) {
1255         /* in case cache-line is 32 bytes, touch second line */
1256         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1257         out[j++] = rotated_mac[rotate_offset++];
1258         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1259     }
1260 #else
1261     memset(out, 0, md_size);
1262     rotate_offset = md_size - rotate_offset;
1263     rotate_offset &= constant_time_lt(rotate_offset, md_size);
1264     for (i = 0; i < md_size; i++) {
1265         for (j = 0; j < md_size; j++)
1266             out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1267         rotate_offset++;
1268         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1269     }
1270 #endif
1271 }
1272
1273 int dtls1_process_record(SSL *s)
1274 {
1275     int i, al;
1276     int enc_err;
1277     SSL_SESSION *sess;
1278     SSL3_RECORD *rr;
1279     unsigned int mac_size;
1280     unsigned char md[EVP_MAX_MD_SIZE];
1281
1282     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1283     sess = s->session;
1284
1285     /*
1286      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1287      * and we have that many bytes in s->packet
1288      */
1289     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1290
1291     /*
1292      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1293      * at rr->length bytes, which need to be copied into rr->data by either
1294      * the decryption or by the decompression When the data is 'copied' into
1295      * the rr->data buffer, rr->input will be pointed at the new buffer
1296      */
1297
1298     /*
1299      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1300      * bytes of encrypted compressed stuff.
1301      */
1302
1303     /* check is not needed I believe */
1304     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1305         al = SSL_AD_RECORD_OVERFLOW;
1306         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1307         goto f_err;
1308     }
1309
1310     /* decrypt in place in 'rr->input' */
1311     rr->data = rr->input;
1312     rr->orig_len = rr->length;
1313
1314     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1315     /*-
1316      * enc_err is:
1317      *    0: (in non-constant time) if the record is publically invalid.
1318      *    1: if the padding is valid
1319      *   -1: if the padding is invalid
1320      */
1321     if (enc_err == 0) {
1322         /* For DTLS we simply ignore bad packets. */
1323         rr->length = 0;
1324         RECORD_LAYER_reset_packet_length(&s->rlayer);
1325         goto err;
1326     }
1327 #ifdef SSL_DEBUG
1328     printf("dec %d\n", rr->length);
1329     {
1330         unsigned int z;
1331         for (z = 0; z < rr->length; z++)
1332             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1333     }
1334     printf("\n");
1335 #endif
1336
1337     /* r->length is now the compressed data plus mac */
1338     if ((sess != NULL) &&
1339         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1340         /* s->read_hash != NULL => mac_size != -1 */
1341         unsigned char *mac = NULL;
1342         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1343         mac_size = EVP_MD_CTX_size(s->read_hash);
1344         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1345
1346         /*
1347          * orig_len is the length of the record before any padding was
1348          * removed. This is public information, as is the MAC in use,
1349          * therefore we can safely process the record in a different amount
1350          * of time if it's too short to possibly contain a MAC.
1351          */
1352         if (rr->orig_len < mac_size ||
1353             /* CBC records must have a padding length byte too. */
1354             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1355              rr->orig_len < mac_size + 1)) {
1356             al = SSL_AD_DECODE_ERROR;
1357             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1358             goto f_err;
1359         }
1360
1361         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1362             /*
1363              * We update the length so that the TLS header bytes can be
1364              * constructed correctly but we need to extract the MAC in
1365              * constant time from within the record, without leaking the
1366              * contents of the padding bytes.
1367              */
1368             mac = mac_tmp;
1369             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1370             rr->length -= mac_size;
1371         } else {
1372             /*
1373              * In this case there's no padding, so |rec->orig_len| equals
1374              * |rec->length| and we checked that there's enough bytes for
1375              * |mac_size| above.
1376              */
1377             rr->length -= mac_size;
1378             mac = &rr->data[rr->length];
1379         }
1380
1381         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1382         if (i < 0 || mac == NULL
1383             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1384             enc_err = -1;
1385         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1386             enc_err = -1;
1387     }
1388
1389     if (enc_err < 0) {
1390         /* decryption failed, silently discard message */
1391         rr->length = 0;
1392         RECORD_LAYER_reset_packet_length(&s->rlayer);
1393         goto err;
1394     }
1395
1396     /* r->length is now just compressed */
1397     if (s->expand != NULL) {
1398         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1399             al = SSL_AD_RECORD_OVERFLOW;
1400             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1401                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1402             goto f_err;
1403         }
1404         if (!ssl3_do_uncompress(s, rr)) {
1405             al = SSL_AD_DECOMPRESSION_FAILURE;
1406             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1407             goto f_err;
1408         }
1409     }
1410
1411     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1412         al = SSL_AD_RECORD_OVERFLOW;
1413         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1414         goto f_err;
1415     }
1416
1417     rr->off = 0;
1418     /*-
1419      * So at this point the following is true
1420      * ssl->s3->rrec.type   is the type of record
1421      * ssl->s3->rrec.length == number of bytes in record
1422      * ssl->s3->rrec.off    == offset to first valid byte
1423      * ssl->s3->rrec.data   == where to take bytes from, increment
1424      *                         after use :-).
1425      */
1426
1427     /* we have pulled in a full packet so zero things */
1428     RECORD_LAYER_reset_packet_length(&s->rlayer);
1429     return (1);
1430
1431  f_err:
1432     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1433  err:
1434     return (0);
1435 }
1436
1437
1438 /*
1439  * retrieve a buffered record that belongs to the current epoch, ie,
1440  * processed
1441  */
1442 #define dtls1_get_processed_record(s) \
1443                    dtls1_retrieve_buffered_record((s), \
1444                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1445
1446 /*-
1447  * Call this to get a new input record.
1448  * It will return <= 0 if more data is needed, normally due to an error
1449  * or non-blocking IO.
1450  * When it finishes, one packet has been decoded and can be found in
1451  * ssl->s3->rrec.type    - is the type of record
1452  * ssl->s3->rrec.data,   - data
1453  * ssl->s3->rrec.length, - number of bytes
1454  */
1455 /* used only by dtls1_read_bytes */
1456 int dtls1_get_record(SSL *s)
1457 {
1458     int ssl_major, ssl_minor;
1459     int i, n;
1460     SSL3_RECORD *rr;
1461     unsigned char *p = NULL;
1462     unsigned short version;
1463     DTLS1_BITMAP *bitmap;
1464     unsigned int is_next_epoch;
1465
1466     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1467
1468     /*
1469      * The epoch may have changed.  If so, process all the pending records.
1470      * This is a non-blocking operation.
1471      */
1472     if (dtls1_process_buffered_records(s) < 0)
1473         return -1;
1474
1475     /* if we're renegotiating, then there may be buffered records */
1476     if (dtls1_get_processed_record(s))
1477         return 1;
1478
1479     /* get something from the wire */
1480  again:
1481     /* check if we have the header */
1482     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1483         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1484         n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1485             SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1486         /* read timeout is handled by dtls1_read_bytes */
1487         if (n <= 0)
1488             return (n);         /* error or non-blocking */
1489
1490         /* this packet contained a partial record, dump it */
1491         if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1492             RECORD_LAYER_reset_packet_length(&s->rlayer);
1493             goto again;
1494         }
1495
1496         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1497
1498         p = RECORD_LAYER_get_packet(&s->rlayer);
1499
1500         if (s->msg_callback)
1501             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1502                             s, s->msg_callback_arg);
1503
1504         /* Pull apart the header into the DTLS1_RECORD */
1505         rr->type = *(p++);
1506         ssl_major = *(p++);
1507         ssl_minor = *(p++);
1508         version = (ssl_major << 8) | ssl_minor;
1509
1510         /* sequence number is 64 bits, with top 2 bytes = epoch */
1511         n2s(p, rr->epoch);
1512
1513         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1514         p += 6;
1515
1516         n2s(p, rr->length);
1517
1518         /* Lets check version */
1519         if (!s->first_packet) {
1520             if (version != s->version) {
1521                 /* unexpected version, silently discard */
1522                 rr->length = 0;
1523                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1524                 goto again;
1525             }
1526         }
1527
1528         if ((version & 0xff00) != (s->version & 0xff00)) {
1529             /* wrong version, silently discard record */
1530             rr->length = 0;
1531             RECORD_LAYER_reset_packet_length(&s->rlayer);
1532             goto again;
1533         }
1534
1535         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1536             /* record too long, silently discard it */
1537             rr->length = 0;
1538             RECORD_LAYER_reset_packet_length(&s->rlayer);
1539             goto again;
1540         }
1541
1542         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1543     }
1544
1545     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1546
1547     if (rr->length >
1548         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1549         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1550         i = rr->length;
1551         n = ssl3_read_n(s, i, i, 1, 1);
1552         /* this packet contained a partial record, dump it */
1553         if (n != i) {
1554             rr->length = 0;
1555             RECORD_LAYER_reset_packet_length(&s->rlayer);
1556             goto again;
1557         }
1558
1559         /*
1560          * now n == rr->length, and s->packet_length ==
1561          * DTLS1_RT_HEADER_LENGTH + rr->length
1562          */
1563     }
1564     /* set state for later operations */
1565     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1566
1567     /* match epochs.  NULL means the packet is dropped on the floor */
1568     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1569     if (bitmap == NULL) {
1570         rr->length = 0;
1571         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1572         goto again;             /* get another record */
1573     }
1574 #ifndef OPENSSL_NO_SCTP
1575     /* Only do replay check if no SCTP bio */
1576     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1577 #endif
1578         /* Check whether this is a repeat, or aged record. */
1579         if (!dtls1_record_replay_check(s, bitmap)) {
1580             rr->length = 0;
1581             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1582             goto again;         /* get another record */
1583         }
1584 #ifndef OPENSSL_NO_SCTP
1585     }
1586 #endif
1587
1588     /* just read a 0 length packet */
1589     if (rr->length == 0)
1590         goto again;
1591
1592     /*
1593      * If this record is from the next epoch (either HM or ALERT), and a
1594      * handshake is currently in progress, buffer it since it cannot be
1595      * processed at this time.
1596      */
1597     if (is_next_epoch) {
1598         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1599             if (dtls1_buffer_record
1600                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1601                 rr->seq_num) < 0)
1602                 return -1;
1603             /* Mark receipt of record. */
1604             dtls1_record_bitmap_update(s, bitmap);
1605         }
1606         rr->length = 0;
1607         RECORD_LAYER_reset_packet_length(&s->rlayer);
1608         goto again;
1609     }
1610
1611     if (!dtls1_process_record(s)) {
1612         rr->length = 0;
1613         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1614         goto again;             /* get another record */
1615     }
1616     dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
1617
1618     return (1);
1619
1620 }