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