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