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