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