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