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