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