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