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