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