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