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