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