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