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