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