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