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