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