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