3630cd900a7fa4021236b90a736e94a96ad14f97
[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             if (!tls_fips_digest_extra(ssl->enc_read_ctx,
1019                                        mac_ctx, rec->input,
1020                                        rec->length, rec->orig_len)) {
1021                 EVP_MD_CTX_free(hmac);
1022                 return -1;
1023         }
1024     }
1025
1026     EVP_MD_CTX_free(hmac);
1027
1028 #ifdef SSL_DEBUG
1029     fprintf(stderr, "seq=");
1030     {
1031         int z;
1032         for (z = 0; z < 8; z++)
1033             fprintf(stderr, "%02X ", seq[z]);
1034         fprintf(stderr, "\n");
1035     }
1036     fprintf(stderr, "rec=");
1037     {
1038         unsigned int z;
1039         for (z = 0; z < rec->length; z++)
1040             fprintf(stderr, "%02X ", rec->data[z]);
1041         fprintf(stderr, "\n");
1042     }
1043 #endif
1044
1045     if (!SSL_IS_DTLS(ssl)) {
1046         for (i = 7; i >= 0; i--) {
1047             ++seq[i];
1048             if (seq[i] != 0)
1049                 break;
1050         }
1051     }
1052 #ifdef SSL_DEBUG
1053     {
1054         unsigned int z;
1055         for (z = 0; z < md_size; z++)
1056             fprintf(stderr, "%02X ", md[z]);
1057         fprintf(stderr, "\n");
1058     }
1059 #endif
1060     return (md_size);
1061 }
1062
1063 /*-
1064  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1065  * record in |rec| by updating |rec->length| in constant time.
1066  *
1067  * block_size: the block size of the cipher used to encrypt the record.
1068  * returns:
1069  *   0: (in non-constant time) if the record is publicly invalid.
1070  *   1: if the padding was valid
1071  *  -1: otherwise.
1072  */
1073 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1074                             unsigned block_size, unsigned mac_size)
1075 {
1076     unsigned padding_length, good;
1077     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1078
1079     /*
1080      * These lengths are all public so we can test them in non-constant time.
1081      */
1082     if (overhead > rec->length)
1083         return 0;
1084
1085     padding_length = rec->data[rec->length - 1];
1086     good = constant_time_ge(rec->length, padding_length + overhead);
1087     /* SSLv3 requires that the padding is minimal. */
1088     good &= constant_time_ge(block_size, padding_length + 1);
1089     rec->length -= good & (padding_length + 1);
1090     return constant_time_select_int(good, 1, -1);
1091 }
1092
1093 /*-
1094  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1095  * record in |rec| in constant time and returns 1 if the padding is valid and
1096  * -1 otherwise. It also removes any explicit IV from the start of the record
1097  * without leaking any timing about whether there was enough space after the
1098  * padding was removed.
1099  *
1100  * block_size: the block size of the cipher used to encrypt the record.
1101  * returns:
1102  *   0: (in non-constant time) if the record is publicly invalid.
1103  *   1: if the padding was valid
1104  *  -1: otherwise.
1105  */
1106 int tls1_cbc_remove_padding(const SSL *s,
1107                             SSL3_RECORD *rec,
1108                             unsigned block_size, unsigned mac_size)
1109 {
1110     unsigned padding_length, good, to_check, i;
1111     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1112     /* Check if version requires explicit IV */
1113     if (SSL_USE_EXPLICIT_IV(s)) {
1114         /*
1115          * These lengths are all public so we can test them in non-constant
1116          * time.
1117          */
1118         if (overhead + block_size > rec->length)
1119             return 0;
1120         /* We can now safely skip explicit IV */
1121         rec->data += block_size;
1122         rec->input += block_size;
1123         rec->length -= block_size;
1124         rec->orig_len -= block_size;
1125     } else if (overhead > rec->length)
1126         return 0;
1127
1128     padding_length = rec->data[rec->length - 1];
1129
1130     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1131         /* padding is already verified */
1132         rec->length -= padding_length + 1;
1133         return 1;
1134     }
1135
1136     good = constant_time_ge(rec->length, overhead + padding_length);
1137     /*
1138      * The padding consists of a length byte at the end of the record and
1139      * then that many bytes of padding, all with the same value as the length
1140      * byte. Thus, with the length byte included, there are i+1 bytes of
1141      * padding. We can't check just |padding_length+1| bytes because that
1142      * leaks decrypted information. Therefore we always have to check the
1143      * maximum amount of padding possible. (Again, the length of the record
1144      * is public information so we can use it.)
1145      */
1146     to_check = 255;             /* maximum amount of padding. */
1147     if (to_check > rec->length - 1)
1148         to_check = rec->length - 1;
1149
1150     for (i = 0; i < to_check; i++) {
1151         unsigned char mask = constant_time_ge_8(padding_length, i);
1152         unsigned char b = rec->data[rec->length - 1 - i];
1153         /*
1154          * The final |padding_length+1| bytes should all have the value
1155          * |padding_length|. Therefore the XOR should be zero.
1156          */
1157         good &= ~(mask & (padding_length ^ b));
1158     }
1159
1160     /*
1161      * If any of the final |padding_length+1| bytes had the wrong value, one
1162      * or more of the lower eight bits of |good| will be cleared.
1163      */
1164     good = constant_time_eq(0xff, good & 0xff);
1165     rec->length -= good & (padding_length + 1);
1166
1167     return constant_time_select_int(good, 1, -1);
1168 }
1169
1170 /*-
1171  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1172  * constant time (independent of the concrete value of rec->length, which may
1173  * vary within a 256-byte window).
1174  *
1175  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1176  * this function.
1177  *
1178  * On entry:
1179  *   rec->orig_len >= md_size
1180  *   md_size <= EVP_MAX_MD_SIZE
1181  *
1182  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1183  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1184  * a single or pair of cache-lines, then the variable memory accesses don't
1185  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1186  * not multi-core and are not considered vulnerable to cache-timing attacks.
1187  */
1188 #define CBC_MAC_ROTATE_IN_PLACE
1189
1190 void ssl3_cbc_copy_mac(unsigned char *out,
1191                        const SSL3_RECORD *rec, unsigned md_size)
1192 {
1193 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1194     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1195     unsigned char *rotated_mac;
1196 #else
1197     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1198 #endif
1199
1200     /*
1201      * mac_end is the index of |rec->data| just after the end of the MAC.
1202      */
1203     unsigned mac_end = rec->length;
1204     unsigned mac_start = mac_end - md_size;
1205     /*
1206      * scan_start contains the number of bytes that we can ignore because the
1207      * MAC's position can only vary by 255 bytes.
1208      */
1209     unsigned scan_start = 0;
1210     unsigned i, j;
1211     unsigned div_spoiler;
1212     unsigned rotate_offset;
1213
1214     OPENSSL_assert(rec->orig_len >= md_size);
1215     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1216
1217 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1218     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1219 #endif
1220
1221     /* This information is public so it's safe to branch based on it. */
1222     if (rec->orig_len > md_size + 255 + 1)
1223         scan_start = rec->orig_len - (md_size + 255 + 1);
1224     /*
1225      * div_spoiler contains a multiple of md_size that is used to cause the
1226      * modulo operation to be constant time. Without this, the time varies
1227      * based on the amount of padding when running on Intel chips at least.
1228      * The aim of right-shifting md_size is so that the compiler doesn't
1229      * figure out that it can remove div_spoiler as that would require it to
1230      * prove that md_size is always even, which I hope is beyond it.
1231      */
1232     div_spoiler = md_size >> 1;
1233     div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1234     rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1235
1236     memset(rotated_mac, 0, md_size);
1237     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1238         unsigned char mac_started = constant_time_ge_8(i, mac_start);
1239         unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1240         unsigned char b = rec->data[i];
1241         rotated_mac[j++] |= b & mac_started & ~mac_ended;
1242         j &= constant_time_lt(j, md_size);
1243     }
1244
1245     /* Now rotate the MAC */
1246 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1247     j = 0;
1248     for (i = 0; i < md_size; i++) {
1249         /* in case cache-line is 32 bytes, touch second line */
1250         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1251         out[j++] = rotated_mac[rotate_offset++];
1252         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1253     }
1254 #else
1255     memset(out, 0, md_size);
1256     rotate_offset = md_size - rotate_offset;
1257     rotate_offset &= constant_time_lt(rotate_offset, md_size);
1258     for (i = 0; i < md_size; i++) {
1259         for (j = 0; j < md_size; j++)
1260             out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1261         rotate_offset++;
1262         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1263     }
1264 #endif
1265 }
1266
1267 int dtls1_process_record(SSL *s)
1268 {
1269     int i, al;
1270     int enc_err;
1271     SSL_SESSION *sess;
1272     SSL3_RECORD *rr;
1273     unsigned int mac_size;
1274     unsigned char md[EVP_MAX_MD_SIZE];
1275
1276     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1277     sess = s->session;
1278
1279     /*
1280      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1281      * and we have that many bytes in s->packet
1282      */
1283     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1284
1285     /*
1286      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1287      * at rr->length bytes, which need to be copied into rr->data by either
1288      * the decryption or by the decompression When the data is 'copied' into
1289      * the rr->data buffer, rr->input will be pointed at the new buffer
1290      */
1291
1292     /*
1293      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1294      * bytes of encrypted compressed stuff.
1295      */
1296
1297     /* check is not needed I believe */
1298     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1299         al = SSL_AD_RECORD_OVERFLOW;
1300         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1301         goto f_err;
1302     }
1303
1304     /* decrypt in place in 'rr->input' */
1305     rr->data = rr->input;
1306     rr->orig_len = rr->length;
1307
1308     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1309     /*-
1310      * enc_err is:
1311      *    0: (in non-constant time) if the record is publically invalid.
1312      *    1: if the padding is valid
1313      *   -1: if the padding is invalid
1314      */
1315     if (enc_err == 0) {
1316         /* For DTLS we simply ignore bad packets. */
1317         rr->length = 0;
1318         RECORD_LAYER_reset_packet_length(&s->rlayer);
1319         goto err;
1320     }
1321 #ifdef SSL_DEBUG
1322     printf("dec %d\n", rr->length);
1323     {
1324         unsigned int z;
1325         for (z = 0; z < rr->length; z++)
1326             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1327     }
1328     printf("\n");
1329 #endif
1330
1331     /* r->length is now the compressed data plus mac */
1332     if ((sess != NULL) &&
1333         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1334         /* s->read_hash != NULL => mac_size != -1 */
1335         unsigned char *mac = NULL;
1336         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1337         mac_size = EVP_MD_CTX_size(s->read_hash);
1338         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1339
1340         /*
1341          * orig_len is the length of the record before any padding was
1342          * removed. This is public information, as is the MAC in use,
1343          * therefore we can safely process the record in a different amount
1344          * of time if it's too short to possibly contain a MAC.
1345          */
1346         if (rr->orig_len < mac_size ||
1347             /* CBC records must have a padding length byte too. */
1348             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1349              rr->orig_len < mac_size + 1)) {
1350             al = SSL_AD_DECODE_ERROR;
1351             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1352             goto f_err;
1353         }
1354
1355         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1356             /*
1357              * We update the length so that the TLS header bytes can be
1358              * constructed correctly but we need to extract the MAC in
1359              * constant time from within the record, without leaking the
1360              * contents of the padding bytes.
1361              */
1362             mac = mac_tmp;
1363             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1364             rr->length -= mac_size;
1365         } else {
1366             /*
1367              * In this case there's no padding, so |rec->orig_len| equals
1368              * |rec->length| and we checked that there's enough bytes for
1369              * |mac_size| above.
1370              */
1371             rr->length -= mac_size;
1372             mac = &rr->data[rr->length];
1373         }
1374
1375         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1376         if (i < 0 || mac == NULL
1377             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1378             enc_err = -1;
1379         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1380             enc_err = -1;
1381     }
1382
1383     if (enc_err < 0) {
1384         /* decryption failed, silently discard message */
1385         rr->length = 0;
1386         RECORD_LAYER_reset_packet_length(&s->rlayer);
1387         goto err;
1388     }
1389
1390     /* r->length is now just compressed */
1391     if (s->expand != NULL) {
1392         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1393             al = SSL_AD_RECORD_OVERFLOW;
1394             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1395                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1396             goto f_err;
1397         }
1398         if (!ssl3_do_uncompress(s, rr)) {
1399             al = SSL_AD_DECOMPRESSION_FAILURE;
1400             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1401             goto f_err;
1402         }
1403     }
1404
1405     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1406         al = SSL_AD_RECORD_OVERFLOW;
1407         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1408         goto f_err;
1409     }
1410
1411     rr->off = 0;
1412     /*-
1413      * So at this point the following is true
1414      * ssl->s3->rrec.type   is the type of record
1415      * ssl->s3->rrec.length == number of bytes in record
1416      * ssl->s3->rrec.off    == offset to first valid byte
1417      * ssl->s3->rrec.data   == where to take bytes from, increment
1418      *                         after use :-).
1419      */
1420
1421     /* we have pulled in a full packet so zero things */
1422     RECORD_LAYER_reset_packet_length(&s->rlayer);
1423     return (1);
1424
1425  f_err:
1426     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1427  err:
1428     return (0);
1429 }
1430
1431
1432 /*
1433  * retrieve a buffered record that belongs to the current epoch, ie,
1434  * processed
1435  */
1436 #define dtls1_get_processed_record(s) \
1437                    dtls1_retrieve_buffered_record((s), \
1438                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1439
1440 /*-
1441  * Call this to get a new input record.
1442  * It will return <= 0 if more data is needed, normally due to an error
1443  * or non-blocking IO.
1444  * When it finishes, one packet has been decoded and can be found in
1445  * ssl->s3->rrec.type    - is the type of record
1446  * ssl->s3->rrec.data,   - data
1447  * ssl->s3->rrec.length, - number of bytes
1448  */
1449 /* used only by dtls1_read_bytes */
1450 int dtls1_get_record(SSL *s)
1451 {
1452     int ssl_major, ssl_minor;
1453     int i, n;
1454     SSL3_RECORD *rr;
1455     unsigned char *p = NULL;
1456     unsigned short version;
1457     DTLS1_BITMAP *bitmap;
1458     unsigned int is_next_epoch;
1459
1460     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1461
1462     /*
1463      * The epoch may have changed.  If so, process all the pending records.
1464      * This is a non-blocking operation.
1465      */
1466     if (dtls1_process_buffered_records(s) < 0)
1467         return -1;
1468
1469     /* if we're renegotiating, then there may be buffered records */
1470     if (dtls1_get_processed_record(s))
1471         return 1;
1472
1473     /* get something from the wire */
1474  again:
1475     /* check if we have the header */
1476     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1477         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1478         n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1479             SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1480         /* read timeout is handled by dtls1_read_bytes */
1481         if (n <= 0)
1482             return (n);         /* error or non-blocking */
1483
1484         /* this packet contained a partial record, dump it */
1485         if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1486             RECORD_LAYER_reset_packet_length(&s->rlayer);
1487             goto again;
1488         }
1489
1490         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1491
1492         p = RECORD_LAYER_get_packet(&s->rlayer);
1493
1494         if (s->msg_callback)
1495             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1496                             s, s->msg_callback_arg);
1497
1498         /* Pull apart the header into the DTLS1_RECORD */
1499         rr->type = *(p++);
1500         ssl_major = *(p++);
1501         ssl_minor = *(p++);
1502         version = (ssl_major << 8) | ssl_minor;
1503
1504         /* sequence number is 64 bits, with top 2 bytes = epoch */
1505         n2s(p, rr->epoch);
1506
1507         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1508         p += 6;
1509
1510         n2s(p, rr->length);
1511
1512         /* Lets check version */
1513         if (!s->first_packet) {
1514             if (version != s->version) {
1515                 /* unexpected version, silently discard */
1516                 rr->length = 0;
1517                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1518                 goto again;
1519             }
1520         }
1521
1522         if ((version & 0xff00) != (s->version & 0xff00)) {
1523             /* wrong version, silently discard record */
1524             rr->length = 0;
1525             RECORD_LAYER_reset_packet_length(&s->rlayer);
1526             goto again;
1527         }
1528
1529         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1530             /* record too long, silently discard it */
1531             rr->length = 0;
1532             RECORD_LAYER_reset_packet_length(&s->rlayer);
1533             goto again;
1534         }
1535
1536         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1537     }
1538
1539     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1540
1541     if (rr->length >
1542         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1543         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1544         i = rr->length;
1545         n = ssl3_read_n(s, i, i, 1, 1);
1546         /* this packet contained a partial record, dump it */
1547         if (n != i) {
1548             rr->length = 0;
1549             RECORD_LAYER_reset_packet_length(&s->rlayer);
1550             goto again;
1551         }
1552
1553         /*
1554          * now n == rr->length, and s->packet_length ==
1555          * DTLS1_RT_HEADER_LENGTH + rr->length
1556          */
1557     }
1558     /* set state for later operations */
1559     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1560
1561     /* match epochs.  NULL means the packet is dropped on the floor */
1562     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1563     if (bitmap == NULL) {
1564         rr->length = 0;
1565         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1566         goto again;             /* get another record */
1567     }
1568 #ifndef OPENSSL_NO_SCTP
1569     /* Only do replay check if no SCTP bio */
1570     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1571 #endif
1572         /* Check whether this is a repeat, or aged record. */
1573         if (!dtls1_record_replay_check(s, bitmap)) {
1574             rr->length = 0;
1575             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1576             goto again;         /* get another record */
1577         }
1578 #ifndef OPENSSL_NO_SCTP
1579     }
1580 #endif
1581
1582     /* just read a 0 length packet */
1583     if (rr->length == 0)
1584         goto again;
1585
1586     /*
1587      * If this record is from the next epoch (either HM or ALERT), and a
1588      * handshake is currently in progress, buffer it since it cannot be
1589      * processed at this time.
1590      */
1591     if (is_next_epoch) {
1592         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1593             if (dtls1_buffer_record
1594                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1595                 rr->seq_num) < 0)
1596                 return -1;
1597             /* Mark receipt of record. */
1598             dtls1_record_bitmap_update(s, bitmap);
1599         }
1600         rr->length = 0;
1601         RECORD_LAYER_reset_packet_length(&s->rlayer);
1602         goto again;
1603     }
1604
1605     if (!dtls1_process_record(s)) {
1606         rr->length = 0;
1607         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1608         goto again;             /* get another record */
1609     }
1610     dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
1611
1612     return (1);
1613
1614 }