Move Record layer methods code into a sub-directory
[openssl.git] / ssl / record / methods / tlsrecord.c
1 /*
2  * Copyright 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 <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include <openssl/rand.h>
15 #include "internal/e_os.h"
16 #include "internal/packet.h"
17 #include "../../ssl_local.h"
18 #include "../record_local.h"
19
20 /* Protocol version specific function pointers */
21 struct record_functions_st
22 {
23     int (*set_crypto_state)(OSSL_RECORD_LAYER *rl, int level,
24                             unsigned char *key, size_t keylen,
25                             unsigned char *iv, size_t ivlen,
26                             unsigned char *mackey, size_t mackeylen,
27                             const EVP_CIPHER *ciph,
28                             size_t taglen,
29                             /* TODO(RECLAYER): This probably should not be an int */
30                             int mactype,
31                             const EVP_MD *md,
32                             const SSL_COMP *comp,
33                             /* TODO(RECLAYER): Remove me */
34                             SSL_CONNECTION *s);
35     int (*cipher)(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
36                   int sending, SSL_MAC_BUF *macs, size_t macsize,
37                   /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s);
38     int (*mac)(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec, unsigned char *md,
39                int sending, /* TODO(RECLAYER): Remove me */SSL_CONNECTION *ssl);
40 };
41
42 struct ossl_record_layer_st
43 {
44     OSSL_LIB_CTX *libctx;
45     const char *propq;
46     int isdtls;
47     int version;
48     int role;
49     int direction;
50     BIO *bio;
51     /* Types match the equivalent structures in the SSL object */
52     uint64_t options;
53     /*
54      * TODO(RECLAYER): Should we take the opportunity to make this uint64_t
55      * even though upper layer continue to use uint32_t?
56      */
57     uint32_t mode;
58
59     /* read IO goes into here */
60     SSL3_BUFFER rbuf;
61     /* each decoded record goes in here */
62     SSL3_RECORD rrec[SSL_MAX_PIPELINES];
63
64     /* How many records have we got available in the rrec bufer */
65     size_t num_recs;
66
67     /* The record number in the rrec buffer that can be read next */
68     size_t curr_rec;
69
70     /* The number of records that have been released via tls_release_record */
71     size_t num_released;
72
73     /* Set to true if this is the first record in a connection */
74     unsigned int is_first_record;
75
76     /* where we are when reading */
77     int rstate;
78
79     /* used internally to point at a raw packet */
80     unsigned char *packet;
81     size_t packet_length;
82
83     int alert;
84
85     /*
86      * Read as many input bytes as possible (for
87      * non-blocking reads)
88      * TODO(RECLAYER): Why isn't this just an option?
89      */
90     int read_ahead;
91
92     /* The number of consecutive empty records we have received */
93     size_t empty_record_count;
94
95     /* cryptographic state */
96     EVP_CIPHER_CTX *enc_read_ctx;
97     /* TLSv1.3 static read IV */
98     unsigned char read_iv[EVP_MAX_IV_LENGTH];
99     /* used for mac generation */
100     EVP_MD_CTX *read_hash;
101     /* uncompress */
102     COMP_CTX *expand;
103
104     /* Function pointers for version specific functions */
105     /* Function pointers for version specific functions */
106     struct record_functions_st *funcs;
107 };
108
109 # define SSL_AD_NO_ALERT    -1
110
111 static void rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
112                          const char *fmt, ...)
113 {
114     va_list args;
115
116     va_start(args, fmt);
117     ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
118     va_end(args);
119
120     rl->alert = al;
121 }
122
123
124 # define RLAYERfatal(rl, al, r) RLAYERfatal_data((rl), (al), (r), NULL)
125 # define RLAYERfatal_data                                          \
126     (ERR_new(),                                                    \
127      ERR_set_debug(OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC),      \
128      rlayer_fatal)
129
130 static int tls_provider_set_tls_parameters(OSSL_RECORD_LAYER *rl,
131                                            EVP_CIPHER_CTX *ctx,
132                                            const EVP_CIPHER *ciph,
133                                            const EVP_MD *md,
134                                            SSL_CONNECTION *s)
135 {
136     /*
137      * Provided cipher, the TLS padding/MAC removal is performed provider
138      * side so we need to tell the ctx about our TLS version and mac size
139      */
140     OSSL_PARAM params[3], *pprm = params;
141     size_t macsize = 0;
142     int imacsize = -1;
143
144     if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
145                /*
146                 * We look at s->ext.use_etm instead of SSL_READ_ETM() or
147                 * SSL_WRITE_ETM() because this test applies to both reading
148                 * and writing.
149                 */
150             && !s->ext.use_etm)
151         imacsize = EVP_MD_get_size(md);
152     if (imacsize >= 0)
153         macsize = (size_t)imacsize;
154
155     *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
156                                        &rl->version);
157     *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
158                                           &macsize);
159     *pprm = OSSL_PARAM_construct_end();
160
161     if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
162         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
163         return 0;
164     }
165
166     return 1;
167 }
168
169 static int tls_fail_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
170                                      unsigned char *key, size_t keylen,
171                                      unsigned char *iv, size_t ivlen,
172                                      unsigned char *mackey, size_t mackeylen,
173                                      const EVP_CIPHER *ciph,
174                                      size_t taglen,
175                                      /* TODO(RECLAYER): This probably should not be an int */
176                                      int mactype,
177                                      const EVP_MD *md,
178                                      const SSL_COMP *comp,
179                                      /* TODO(RECLAYER): Remove me */
180                                      SSL_CONNECTION *s)
181 {
182     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
183     return 0;
184 }
185
186 static int tls_any_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
187                                     unsigned char *key, size_t keylen,
188                                     unsigned char *iv, size_t ivlen,
189                                     unsigned char *mackey, size_t mackeylen,
190                                     const EVP_CIPHER *ciph,
191                                     size_t taglen,
192                                     /* TODO(RECLAYER): This probably should not be an int */
193                                     int mactype,
194                                     const EVP_MD *md,
195                                     const SSL_COMP *comp,
196                                     /* TODO(RECLAYER): Remove me */
197                                     SSL_CONNECTION *s)
198 {
199     if (level != OSSL_RECORD_PROTECTION_LEVEL_NONE) {
200         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
201         return 0;
202     }
203
204     /* No crypto protection at the "NONE" level so nothing to be done */
205
206     return 1;
207 }
208
209 /* TODO(RECLAYER): Handle OPENSSL_NO_COMP */
210 static int tls1_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
211                                  unsigned char *key, size_t keylen,
212                                  unsigned char *iv, size_t ivlen,
213                                  unsigned char *mackey, size_t mackeylen,
214                                  const EVP_CIPHER *ciph,
215                                  size_t taglen,
216                                  /* TODO(RECLAYER): This probably should not be an int */
217                                  int mactype,
218                                  const EVP_MD *md,
219                                  const SSL_COMP *comp,
220                                  /* TODO(RECLAYER): Remove me */
221                                  SSL_CONNECTION *s)
222 {
223     EVP_CIPHER_CTX *ciph_ctx;
224     EVP_PKEY *mac_key;
225
226     if (level != OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
227         return 0;
228
229     if (s->ext.use_etm)
230         s->s3.flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
231     else
232         s->s3.flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
233
234     if (s->s3.tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
235         s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
236     else
237         s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
238
239     if (s->s3.tmp.new_cipher->algorithm2 & TLS1_TLSTREE)
240         s->mac_flags |= SSL_MAC_FLAG_READ_MAC_TLSTREE;
241     else
242         s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_TLSTREE;
243
244     if ((rl->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL) {
245         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
246         return 0;
247     }
248
249     ciph_ctx = rl->enc_read_ctx;
250
251     rl->read_hash = EVP_MD_CTX_new();
252     if (rl->read_hash == NULL) {
253         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
254         return 0;
255     }
256 #ifndef OPENSSL_NO_COMP
257     if (comp != NULL) {
258         rl->expand = COMP_CTX_new(comp->method);
259         if (rl->expand == NULL) {
260             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
261                         SSL_R_COMPRESSION_LIBRARY_ERROR);
262             return 0;
263         }
264     }
265 #endif
266     /*
267      * this is done by dtls1_reset_seq_numbers for DTLS
268      */
269     if (!rl->isdtls)
270         RECORD_LAYER_reset_read_sequence(&s->rlayer);
271
272     /*
273      * If we have an AEAD Cipher, then there is no separate MAC, so we can skip
274      * setting up the MAC key.
275      */
276     if (!(EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
277         if (mactype == EVP_PKEY_HMAC) {
278             mac_key = EVP_PKEY_new_raw_private_key_ex(rl->libctx, "HMAC",
279                                                       rl->propq, mackey,
280                                                       mackeylen);
281         } else {
282             /*
283              * If its not HMAC then the only other types of MAC we support are
284              * the GOST MACs, so we need to use the old style way of creating
285              * a MAC key.
286              */
287             mac_key = EVP_PKEY_new_mac_key(mactype, NULL, mackey,
288                                            (int)mackeylen);
289         }
290         if (mac_key == NULL
291             || EVP_DigestSignInit_ex(rl->read_hash, NULL, EVP_MD_get0_name(md),
292                                      rl->libctx, rl->propq, mac_key,
293                                      NULL) <= 0) {
294             EVP_PKEY_free(mac_key);
295             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
296             return 0;
297         }
298         EVP_PKEY_free(mac_key);
299     }
300
301     if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_GCM_MODE) {
302         if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, key, NULL)
303                 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
304                                         (int)ivlen, iv)) {
305             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
306             return 0;
307         }
308     } else if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
309         if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, NULL, NULL)
310                 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, 12,
311                                         NULL)
312                 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
313                                         (int)taglen, NULL)
314                 || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_CCM_SET_IV_FIXED,
315                                         (int)ivlen, iv)
316                    /*
317                     * TODO(RECLAYER): Why do we defer setting the key until here?
318                     * why not in the initial EVP_DecryptInit_ex() call?
319                     */
320                 || !EVP_DecryptInit_ex(ciph_ctx, NULL, NULL, key, NULL)) {
321             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
322             return 0;
323         }
324     } else {
325         if (!EVP_DecryptInit_ex(ciph_ctx, ciph, NULL, key, iv)) {
326             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
327             return 0;
328         }
329     }
330     /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
331     if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
332         && mackeylen != 0
333         && !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
334                                 (int)mackeylen, mackey)) {
335         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
336         return 0;
337     }
338     if (EVP_CIPHER_get0_provider(ciph) != NULL
339             && !tls_provider_set_tls_parameters(rl, ciph_ctx, ciph, md, s)) {
340         /* SSLfatal already called */
341         return 0;
342     }
343
344     return 1;
345 }
346
347 static int tls_any_cipher(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
348                           int sending, SSL_MAC_BUF *macs, size_t macsize,
349                           /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
350 {
351     size_t ctr;
352
353     for (ctr = 0; ctr < n_recs; ctr++) {
354         memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
355         recs[ctr].input = recs[ctr].data;
356     }
357
358     return 1;
359 }
360
361
362 #define MAX_PADDING 256
363 /*-
364  * tls1_cipher encrypts/decrypts |n_recs| in |recs|. Calls SSLfatal on internal
365  * error, but not otherwise. It is the responsibility of the caller to report
366  * a bad_record_mac - if appropriate (DTLS just drops the record).
367  *
368  * Returns:
369  *    0: if the record is publicly invalid, or an internal error, or AEAD
370  *       decryption failed, or Encrypt-then-mac decryption failed.
371  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
372  */
373 static int tls1_cipher(OSSL_RECORD_LAYER *rl, SSL3_RECORD *recs, size_t n_recs,
374                        int sending, SSL_MAC_BUF *macs, size_t macsize,
375                        /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
376 {
377     EVP_CIPHER_CTX *ds;
378     size_t reclen[SSL_MAX_PIPELINES];
379     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
380     int i, pad = 0, tmpr, provided;
381     size_t bs, ctr, padnum, loop;
382     unsigned char padval;
383     const EVP_CIPHER *enc;
384     int tlstree_enc = sending ? (s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
385                               : (s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
386     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
387
388     if (n_recs == 0) {
389         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
390         return 0;
391     }
392
393     if (sending) {
394         int ivlen;
395
396         if (EVP_MD_CTX_get0_md(s->write_hash)) {
397             int n = EVP_MD_CTX_get_size(s->write_hash);
398             if (!ossl_assert(n >= 0)) {
399                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
400                 return 0;
401             }
402         }
403         ds = s->enc_write_ctx;
404         if (!ossl_assert(s->enc_write_ctx)) {
405             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
406             return 0;
407         }
408
409         enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
410         /* For TLSv1.1 and later explicit IV */
411         if (SSL_USE_EXPLICIT_IV(s)
412             && EVP_CIPHER_get_mode(enc) == EVP_CIPH_CBC_MODE)
413             ivlen = EVP_CIPHER_get_iv_length(enc);
414         else
415             ivlen = 0;
416         if (ivlen > 1) {
417             for (ctr = 0; ctr < n_recs; ctr++) {
418                 if (recs[ctr].data != recs[ctr].input) {
419                     /*
420                         * we can't write into the input stream: Can this ever
421                         * happen?? (steve)
422                         */
423                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
424                     return 0;
425                 } else if (RAND_bytes_ex(sctx->libctx, recs[ctr].input,
426                                             ivlen, 0) <= 0) {
427                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
428                     return 0;
429                 }
430             }
431         }
432     } else {
433         if (EVP_MD_CTX_get0_md(rl->read_hash)) {
434             int n = EVP_MD_CTX_get_size(rl->read_hash);
435             if (!ossl_assert(n >= 0)) {
436                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
437                 return 0;
438             }
439         }
440         ds = rl->enc_read_ctx;
441         if (!ossl_assert(rl->enc_read_ctx)) {
442             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
443             return 0;
444         }
445
446         enc = EVP_CIPHER_CTX_get0_cipher(rl->enc_read_ctx);
447     }
448
449     if ((s->session == NULL) || (enc == NULL)) {
450         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
451         return 0;
452     }
453
454     provided = (EVP_CIPHER_get0_provider(enc) != NULL);
455
456     bs = EVP_CIPHER_get_block_size(EVP_CIPHER_CTX_get0_cipher(ds));
457
458     if (n_recs > 1) {
459         if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
460                 & EVP_CIPH_FLAG_PIPELINE) == 0) {
461             /*
462                 * We shouldn't have been called with pipeline data if the
463                 * cipher doesn't support pipelining
464                 */
465             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
466             return 0;
467         }
468     }
469     for (ctr = 0; ctr < n_recs; ctr++) {
470         reclen[ctr] = recs[ctr].length;
471
472         if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
473                     & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
474             unsigned char *seq;
475
476             seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
477                 : RECORD_LAYER_get_read_sequence(&s->rlayer);
478
479             if (SSL_CONNECTION_IS_DTLS(s)) {
480                 /* DTLS does not support pipelining */
481                 unsigned char dtlsseq[8], *p = dtlsseq;
482
483                 s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
484                     DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
485                 memcpy(p, &seq[2], 6);
486                 memcpy(buf[ctr], dtlsseq, 8);
487             } else {
488                 memcpy(buf[ctr], seq, 8);
489                 for (i = 7; i >= 0; i--) { /* increment */
490                     ++seq[i];
491                     if (seq[i] != 0)
492                         break;
493                 }
494             }
495
496             buf[ctr][8] = recs[ctr].type;
497             buf[ctr][9] = (unsigned char)(rl->version >> 8);
498             buf[ctr][10] = (unsigned char)(rl->version);
499             buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
500             buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
501             pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
502                                         EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
503             if (pad <= 0) {
504                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
505                 return 0;
506             }
507
508             if (sending) {
509                 reclen[ctr] += pad;
510                 recs[ctr].length += pad;
511             }
512
513         } else if ((bs != 1) && sending && !provided) {
514             /*
515                 * We only do this for legacy ciphers. Provided ciphers add the
516                 * padding on the provider side.
517                 */
518             padnum = bs - (reclen[ctr] % bs);
519
520             /* Add weird padding of up to 256 bytes */
521
522             if (padnum > MAX_PADDING) {
523                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
524                 return 0;
525             }
526             /* we need to add 'padnum' padding bytes of value padval */
527             padval = (unsigned char)(padnum - 1);
528             for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
529                 recs[ctr].input[loop] = padval;
530             reclen[ctr] += padnum;
531             recs[ctr].length += padnum;
532         }
533
534         if (!sending) {
535             if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
536                 /* Publicly invalid */
537                 return 0;
538             }
539         }
540     }
541     if (n_recs > 1) {
542         unsigned char *data[SSL_MAX_PIPELINES];
543
544         /* Set the output buffers */
545         for (ctr = 0; ctr < n_recs; ctr++) {
546             data[ctr] = recs[ctr].data;
547         }
548         if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
549                                 (int)n_recs, data) <= 0) {
550             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
551             return 0;
552         }
553         /* Set the input buffers */
554         for (ctr = 0; ctr < n_recs; ctr++) {
555             data[ctr] = recs[ctr].input;
556         }
557         if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
558                                 (int)n_recs, data) <= 0
559             || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
560                                     (int)n_recs, reclen) <= 0) {
561             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
562             return 0;
563         }
564     }
565
566     if (!SSL_CONNECTION_IS_DTLS(s) && tlstree_enc) {
567         unsigned char *seq;
568         int decrement_seq = 0;
569
570         /*
571             * When sending, seq is incremented after MAC calculation.
572             * So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
573             * Otherwise we have to decrease it in the implementation
574             */
575         if (sending && !SSL_WRITE_ETM(s))
576             decrement_seq = 1;
577
578         seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
579                         : RECORD_LAYER_get_read_sequence(&s->rlayer);
580         if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq, seq) <= 0) {
581             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
582             return 0;
583         }
584     }
585
586     if (provided) {
587         int outlen;
588
589         /* Provided cipher - we do not support pipelining on this path */
590         if (n_recs > 1)  {
591             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
592             return 0;
593         }
594
595         if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
596                                 (unsigned int)reclen[0]))
597             return 0;
598         recs[0].length = outlen;
599
600         /*
601             * The length returned from EVP_CipherUpdate above is the actual
602             * payload length. We need to adjust the data/input ptr to skip over
603             * any explicit IV
604             */
605         if (!sending) {
606             if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
607                     recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
608                     recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
609             } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
610                     recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
611                     recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
612             } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
613                 recs[0].data += bs;
614                 recs[0].input += bs;
615                 recs[0].orig_len -= bs;
616             }
617
618             /* Now get a pointer to the MAC (if applicable) */
619             if (macs != NULL) {
620                 OSSL_PARAM params[2], *p = params;
621
622                 /* Get the MAC */
623                 macs[0].alloced = 0;
624
625                 *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
626                                                         (void **)&macs[0].mac,
627                                                         macsize);
628                 *p = OSSL_PARAM_construct_end();
629
630                 if (!EVP_CIPHER_CTX_get_params(ds, params)) {
631                     /* Shouldn't normally happen */
632                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
633                                 ERR_R_INTERNAL_ERROR);
634                     return 0;
635                 }
636             }
637         }
638     } else {
639         /* Legacy cipher */
640
641         tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
642                             (unsigned int)reclen[0]);
643         if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
644                 & EVP_CIPH_FLAG_CUSTOM_CIPHER) != 0
645             ? (tmpr < 0)
646             : (tmpr == 0)) {
647             /* AEAD can fail to verify MAC */
648             return 0;
649         }
650
651         if (!sending) {
652             for (ctr = 0; ctr < n_recs; ctr++) {
653                 /* Adjust the record to remove the explicit IV/MAC/Tag */
654                 if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
655                     recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
656                     recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
657                     recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
658                 } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
659                     recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
660                     recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
661                     recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
662                 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
663                     if (recs[ctr].length < bs)
664                         return 0;
665                     recs[ctr].data += bs;
666                     recs[ctr].input += bs;
667                     recs[ctr].length -= bs;
668                     recs[ctr].orig_len -= bs;
669                 }
670
671                 /*
672                     * If using Mac-then-encrypt, then this will succeed but
673                     * with a random MAC if padding is invalid
674                     */
675                 if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
676                                         recs[ctr].orig_len,
677                                         recs[ctr].data,
678                                         (macs != NULL) ? &macs[ctr].mac : NULL,
679                                         (macs != NULL) ? &macs[ctr].alloced
680                                                     : NULL,
681                                         bs,
682                                         pad ? (size_t)pad : macsize,
683                                         (EVP_CIPHER_get_flags(enc)
684                                         & EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
685                                         sctx->libctx))
686                     return 0;
687             }
688         }
689     }
690     return 1;
691 }
692
693 static int tls1_mac(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec, unsigned char *md,
694                     int sending, SSL_CONNECTION *ssl)
695 {
696     unsigned char *seq;
697     EVP_MD_CTX *hash;
698     size_t md_size;
699     int i;
700     EVP_MD_CTX *hmac = NULL, *mac_ctx;
701     unsigned char header[13];
702     int stream_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
703                              : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM);
704     int tlstree_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
705                               : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
706     int t;
707     int ret = 0;
708
709     if (sending) {
710         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
711         hash = ssl->write_hash;
712     } else {
713         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
714         hash = rl->read_hash;
715     }
716
717     t = EVP_MD_CTX_get_size(hash);
718     if (!ossl_assert(t >= 0))
719         return 0;
720     md_size = t;
721
722     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
723     if (stream_mac) {
724         mac_ctx = hash;
725     } else {
726         hmac = EVP_MD_CTX_new();
727         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
728             goto end;
729         }
730         mac_ctx = hmac;
731     }
732
733     if (!rl->isdtls
734             && tlstree_mac
735             && EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0) {
736         goto end;
737     }
738
739     if (rl->isdtls) {
740         unsigned char dtlsseq[8], *p = dtlsseq;
741
742         s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
743             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
744         memcpy(p, &seq[2], 6);
745
746         memcpy(header, dtlsseq, 8);
747     } else
748         memcpy(header, seq, 8);
749
750     header[8] = rec->type;
751     header[9] = (unsigned char)(ssl->version >> 8);
752     header[10] = (unsigned char)(ssl->version);
753     header[11] = (unsigned char)(rec->length >> 8);
754     header[12] = (unsigned char)(rec->length & 0xff);
755
756     if (!sending && !SSL_READ_ETM(ssl)
757         && EVP_CIPHER_CTX_get_mode(rl->enc_read_ctx) == EVP_CIPH_CBC_MODE
758         && ssl3_cbc_record_digest_supported(mac_ctx)) {
759         OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
760
761         *p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
762                                            &rec->orig_len);
763         *p++ = OSSL_PARAM_construct_end();
764
765         if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_get_pkey_ctx(mac_ctx),
766                                      tls_hmac_params)) {
767             goto end;
768         }
769     }
770
771     if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
772         || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
773         || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
774         goto end;
775     }
776
777     OSSL_TRACE_BEGIN(TLS) {
778         BIO_printf(trc_out, "seq:\n");
779         BIO_dump_indent(trc_out, seq, 8, 4);
780         BIO_printf(trc_out, "rec:\n");
781         BIO_dump_indent(trc_out, rec->data, rec->length, 4);
782     } OSSL_TRACE_END(TLS);
783
784     if (!SSL_CONNECTION_IS_DTLS(ssl)) {
785         for (i = 7; i >= 0; i--) {
786             ++seq[i];
787             if (seq[i] != 0)
788                 break;
789         }
790     }
791     OSSL_TRACE_BEGIN(TLS) {
792         BIO_printf(trc_out, "md:\n");
793         BIO_dump_indent(trc_out, md, md_size, 4);
794     } OSSL_TRACE_END(TLS);
795     ret = 1;
796  end:
797     EVP_MD_CTX_free(hmac);
798     return ret;
799 }
800
801
802 struct record_functions_st tls_any_funcs = {
803     tls_any_set_crypto_state,
804     tls_any_cipher,
805     NULL
806 };
807
808 struct record_functions_st tls_1_3_funcs = {
809     tls_fail_set_crypto_state,
810     NULL,
811     NULL
812 };
813
814 struct record_functions_st tls_1_2_funcs = {
815     tls1_set_crypto_state,
816     tls1_cipher,
817     tls1_mac
818 };
819
820 struct record_functions_st tls_1_1_funcs = {
821     tls1_set_crypto_state,
822     tls1_cipher,
823     tls1_mac
824 };
825
826 struct record_functions_st tls_1_0_funcs = {
827     tls1_set_crypto_state,
828     tls1_cipher,
829     tls1_mac
830 };
831
832 struct record_functions_st ssl_3_0_funcs = {
833     tls_fail_set_crypto_state,
834     NULL,
835     NULL
836 };
837
838 static int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio);
839
840 static int rlayer_allow_compression(OSSL_RECORD_LAYER *rl)
841 {
842     if (rl->options & SSL_OP_NO_COMPRESSION)
843         return 0;
844 #if 0
845     /* TODO(RECLAYER): Implement ssl_security inside the record layer */
846     return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
847 #else
848     return 1;
849 #endif
850 }
851
852 static int rlayer_setup_read_buffer(OSSL_RECORD_LAYER *rl)
853 {
854     unsigned char *p;
855     size_t len, align = 0, headerlen;
856     SSL3_BUFFER *b;
857
858     b = &rl->rbuf;
859
860     if (rl->isdtls)
861         headerlen = DTLS1_RT_HEADER_LENGTH;
862     else
863         headerlen = SSL3_RT_HEADER_LENGTH;
864
865 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
866     align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
867 #endif
868
869     if (b->buf == NULL) {
870         len = SSL3_RT_MAX_PLAIN_LENGTH
871             + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
872 #ifndef OPENSSL_NO_COMP
873         if (rlayer_allow_compression(rl))
874             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
875 #endif
876         if (b->default_len > len)
877             len = b->default_len;
878         if ((p = OPENSSL_malloc(len)) == NULL) {
879             /*
880              * We've got a malloc failure, and we're still initialising buffers.
881              * We assume we're so doomed that we won't even be able to send an
882              * alert.
883              */
884             RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
885             return 0;
886         }
887         b->buf = p;
888         b->len = len;
889     }
890
891     return 1;
892 }
893
894 static int rlayer_release_read_buffer(OSSL_RECORD_LAYER *rl)
895 {
896     SSL3_BUFFER *b;
897
898     b = &rl->rbuf;
899     if (rl->options & SSL_OP_CLEANSE_PLAINTEXT)
900         OPENSSL_cleanse(b->buf, b->len);
901     OPENSSL_free(b->buf);
902     b->buf = NULL;
903     return 1;
904 }
905
906 static void tls_reset_packet_length(OSSL_RECORD_LAYER *rl)
907 {
908     rl->packet_length = 0;
909 }
910
911 /*
912  * Return values are as per SSL_read()
913  */
914 static int tls_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
915                       int clearold, size_t *readbytes)
916 {
917     /*
918      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
919      * packet by another n bytes. The packet will be in the sub-array of
920      * s->rlayer.rbuf.buf specified by s->rlayer.packet and
921      * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
922      * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
923      * if clearold == 1, move the packet to the start of the buffer; if
924      * clearold == 0 then leave any old packets where they were
925      */
926     size_t len, left, align = 0;
927     unsigned char *pkt;
928     SSL3_BUFFER *rb;
929
930     if (n == 0)
931         return OSSL_RECORD_RETURN_NON_FATAL_ERR;
932
933     rb = &rl->rbuf;
934     if (rb->buf == NULL) {
935         if (!rlayer_setup_read_buffer(rl)) {
936             /* RLAYERfatal() already called */
937             return OSSL_RECORD_RETURN_FATAL;
938         }
939     }
940
941     left = rb->left;
942 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
943     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
944     align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
945 #endif
946
947     if (!extend) {
948         /* start with empty packet ... */
949         if (left == 0) {
950             rb->offset = align;
951         } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
952             /*
953              * check if next packet length is large enough to justify payload
954              * alignment...
955              */
956             pkt = rb->buf + rb->offset;
957             if (pkt[0] == SSL3_RT_APPLICATION_DATA
958                     && (pkt[3] << 8 | pkt[4]) >= 128) {
959                 /*
960                  * Note that even if packet is corrupted and its length field
961                  * is insane, we can only be led to wrong decision about
962                  * whether memmove will occur or not. Header values has no
963                  * effect on memmove arguments and therefore no buffer
964                  * overrun can be triggered.
965                  */
966                 memmove(rb->buf + align, pkt, left);
967                 rb->offset = align;
968             }
969         }
970         rl->packet = rb->buf + rb->offset;
971         rl->packet_length = 0;
972         /* ... now we can act as if 'extend' was set */
973     }
974
975     len = rl->packet_length;
976     pkt = rb->buf + align;
977     /*
978      * Move any available bytes to front of buffer: 'len' bytes already
979      * pointed to by 'packet', 'left' extra ones at the end
980      */
981     if (rl->packet != pkt && clearold == 1) {
982         memmove(pkt, rl->packet, len + left);
983         rl->packet = pkt;
984         rb->offset = len + align;
985     }
986
987     /*
988      * For DTLS/UDP reads should not span multiple packets because the read
989      * operation returns the whole packet at once (as long as it fits into
990      * the buffer).
991      */
992     if (rl->isdtls) {
993         if (left == 0 && extend)
994             return 0;
995         if (left > 0 && n > left)
996             n = left;
997     }
998
999     /* if there is enough in the buffer from a previous read, take some */
1000     if (left >= n) {
1001         rl->packet_length += n;
1002         rb->left = left - n;
1003         rb->offset += n;
1004         *readbytes = n;
1005         return OSSL_RECORD_RETURN_SUCCESS;
1006     }
1007
1008     /* else we need to read more data */
1009
1010     if (n > rb->len - rb->offset) {
1011         /* does not happen */
1012         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1013         return OSSL_RECORD_RETURN_FATAL;
1014     }
1015
1016     /*
1017      * Ktls always reads full records.
1018      * Also, we always act like read_ahead is set for DTLS.
1019      */
1020     if (!BIO_get_ktls_recv(s->rbio) && !rl->read_ahead
1021             && !rl->isdtls) {
1022         /* ignore max parameter */
1023         max = n;
1024     } else {
1025         if (max < n)
1026             max = n;
1027         if (max > rb->len - rb->offset)
1028             max = rb->len - rb->offset;
1029     }
1030
1031     while (left < n) {
1032         size_t bioread = 0;
1033         int ret;
1034
1035         /*
1036          * Now we have len+left bytes at the front of s->s3.rbuf.buf and
1037          * need to read in more until we have len+n (up to len+max if
1038          * possible)
1039          */
1040
1041         clear_sys_error();
1042         if (rl->bio != NULL) {
1043             ret = BIO_read(rl->bio, pkt + len + left, max - left);
1044             if (ret > 0) {
1045                 bioread = ret;
1046                 ret = OSSL_RECORD_RETURN_SUCCESS;
1047             } else if (BIO_should_retry(rl->bio)) {
1048                 ret = OSSL_RECORD_RETURN_RETRY;
1049             } else if (BIO_eof(rl->bio)) {
1050                 ret = OSSL_RECORD_RETURN_EOF;
1051             } else {
1052                 ret = OSSL_RECORD_RETURN_FATAL;
1053             }
1054         } else {
1055             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
1056             ret = OSSL_RECORD_RETURN_FATAL;
1057         }
1058
1059         if (ret <= OSSL_RECORD_RETURN_RETRY) {
1060             rb->left = left;
1061             if (rl->mode & SSL_MODE_RELEASE_BUFFERS && !rl->isdtls)
1062                 if (len + left == 0)
1063                     rlayer_release_read_buffer(rl);
1064             return ret;
1065         }
1066         left += bioread;
1067         /*
1068          * reads should *never* span multiple packets for DTLS because the
1069          * underlying transport protocol is message oriented as opposed to
1070          * byte oriented as in the TLS case.
1071          */
1072         if (rl->isdtls) {
1073             if (n > left)
1074                 n = left;       /* makes the while condition false */
1075         }
1076     }
1077
1078     /* done reading, now the book-keeping */
1079     rb->offset += n;
1080     rb->left = left - n;
1081     rl->packet_length += n;
1082     *readbytes = n;
1083     return OSSL_RECORD_RETURN_SUCCESS;
1084 }
1085
1086 /*
1087  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
1088  * for us in the buffer.
1089  */
1090 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
1091 {
1092     SSL3_BUFFER *rbuf;
1093     size_t left, len;
1094     unsigned char *p;
1095
1096     rbuf = &rl->rbuf;
1097
1098     p = SSL3_BUFFER_get_buf(rbuf);
1099     if (p == NULL)
1100         return 0;
1101
1102     left = SSL3_BUFFER_get_left(rbuf);
1103
1104     if (left < SSL3_RT_HEADER_LENGTH)
1105         return 0;
1106
1107     p += SSL3_BUFFER_get_offset(rbuf);
1108
1109     /*
1110      * We only check the type and record length, we will sanity check version
1111      * etc later
1112      */
1113     if (*p != SSL3_RT_APPLICATION_DATA)
1114         return 0;
1115
1116     p += 3;
1117     n2s(p, len);
1118
1119     if (left < SSL3_RT_HEADER_LENGTH + len)
1120         return 0;
1121
1122     return 1;
1123 }
1124
1125 /*
1126  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
1127  * will be processed per call to ssl3_get_record. Without this limit an
1128  * attacker could send empty records at a faster rate than we can process and
1129  * cause ssl3_get_record to loop forever.
1130  */
1131 #define MAX_EMPTY_RECORDS 32
1132
1133 #define SSL2_RT_HEADER_LENGTH   2
1134
1135 /*-
1136  * Call this to buffer new input records in rl->rrec.
1137  * It will return a OSSL_RECORD_RETURN_* value.
1138  * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
1139  * records have been decoded. For each record 'i':
1140  * rrec[i].type    - is the type of record
1141  * rrec[i].data,   - data
1142  * rrec[i].length, - number of bytes
1143  * Multiple records will only be returned if the record types are all
1144  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
1145  * |max_pipelines|
1146  */
1147 static int tls_get_more_records(OSSL_RECORD_LAYER *rl, 
1148                                 /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
1149 {
1150     int enc_err, rret;
1151     int i;
1152     size_t more, n;
1153     SSL3_RECORD *rr, *thisrr;
1154     SSL3_BUFFER *rbuf;
1155     SSL_SESSION *sess;
1156     unsigned char *p;
1157     unsigned char md[EVP_MAX_MD_SIZE];
1158     unsigned int version;
1159     size_t mac_size = 0;
1160     int imac_size;
1161     size_t num_recs = 0, max_recs, j;
1162     PACKET pkt, sslv2pkt;
1163     int using_ktls;
1164     SSL_MAC_BUF *macbufs = NULL;
1165     int ret = OSSL_RECORD_RETURN_FATAL;
1166     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1167
1168     rr = rl->rrec;
1169     rbuf = &rl->rbuf;
1170
1171     max_recs = s->max_pipelines;
1172     if (max_recs == 0)
1173         max_recs = 1;
1174     sess = s->session;
1175
1176     /*
1177      * KTLS reads full records. If there is any data left,
1178      * then it is from before enabling ktls.
1179      */
1180     using_ktls = BIO_get_ktls_recv(rl->bio) && SSL3_BUFFER_get_left(rbuf) == 0;
1181
1182     do {
1183         thisrr = &rr[num_recs];
1184
1185         /* check if we have the header */
1186         if ((rl->rstate != SSL_ST_READ_BODY) ||
1187             (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
1188             size_t sslv2len;
1189             unsigned int type;
1190
1191             rret = tls_read_n(rl, SSL3_RT_HEADER_LENGTH,
1192                               SSL3_BUFFER_get_len(rbuf), 0,
1193                               num_recs == 0 ? 1 : 0, &n);
1194
1195             if (rret < OSSL_RECORD_RETURN_SUCCESS) {
1196 #ifndef OPENSSL_NO_KTLS
1197                 if (!BIO_get_ktls_recv(rl->bio) || rret == 0)
1198                     return rret;     /* error or non-blocking */
1199                 switch (errno) {
1200                 case EBADMSG:
1201                     RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1202                                 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1203                     break;
1204                 case EMSGSIZE:
1205                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1206                                 SSL_R_PACKET_LENGTH_TOO_LONG);
1207                     break;
1208                 case EINVAL:
1209                     RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1210                                 SSL_R_WRONG_VERSION_NUMBER);
1211                     break;
1212                 default:
1213                     break;
1214                 }
1215 #endif
1216                 return rret;
1217             }
1218             rl->rstate = SSL_ST_READ_BODY;
1219
1220             p = rl->packet;
1221             if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
1222                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1223                 return OSSL_RECORD_RETURN_FATAL;
1224             }
1225             sslv2pkt = pkt;
1226             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
1227                     || !PACKET_get_1(&sslv2pkt, &type)) {
1228                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
1229                 return OSSL_RECORD_RETURN_FATAL;
1230             }
1231             /*
1232              * The first record received by the server may be a V2ClientHello.
1233              */
1234             if (rl->role == OSSL_RECORD_ROLE_SERVER
1235                     && rl->is_first_record
1236                     && (sslv2len & 0x8000) != 0
1237                     && (type == SSL2_MT_CLIENT_HELLO)) {
1238                 /*
1239                  *  SSLv2 style record
1240                  *
1241                  * |num_recs| here will actually always be 0 because
1242                  * |num_recs > 0| only ever occurs when we are processing
1243                  * multiple app data records - which we know isn't the case here
1244                  * because it is an SSLv2ClientHello. We keep it using
1245                  * |num_recs| for the sake of consistency
1246                  */
1247                 thisrr->type = SSL3_RT_HANDSHAKE;
1248                 thisrr->rec_version = SSL2_VERSION;
1249
1250                 thisrr->length = sslv2len & 0x7fff;
1251
1252                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
1253                     - SSL2_RT_HEADER_LENGTH) {
1254                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1255                                 SSL_R_PACKET_LENGTH_TOO_LONG);
1256                     return OSSL_RECORD_RETURN_FATAL;
1257                 }
1258
1259                 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
1260                     RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1261                     return OSSL_RECORD_RETURN_FATAL;
1262                 }
1263             } else {
1264                 /* SSLv3+ style record */
1265
1266                 /* Pull apart the header into the SSL3_RECORD */
1267                 if (!PACKET_get_1(&pkt, &type)
1268                         || !PACKET_get_net_2(&pkt, &version)
1269                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
1270                     if (s->msg_callback)
1271                         s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, ssl,
1272                                         s->msg_callback_arg);
1273                     RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
1274                     return OSSL_RECORD_RETURN_FATAL;
1275                 }
1276                 thisrr->type = type;
1277                 thisrr->rec_version = version;
1278
1279                 if (s->msg_callback)
1280                     s->msg_callback(0, version, SSL3_RT_HEADER, p, 5, ssl,
1281                                     s->msg_callback_arg);
1282
1283                 /*
1284                  * Lets check version. In TLSv1.3 we only check this field
1285                  * when encryption is occurring (see later check). For the
1286                  * ServerHello after an HRR we haven't actually selected TLSv1.3
1287                  * yet, but we still treat it as TLSv1.3, so we must check for
1288                  * that explicitly
1289                  */
1290                 if (!s->first_packet && !SSL_CONNECTION_IS_TLS13(s)
1291                         && s->hello_retry_request != SSL_HRR_PENDING
1292                         && version != (unsigned int)s->version) {
1293                     if ((s->version & 0xFF00) == (version & 0xFF00)
1294                         && !s->enc_write_ctx && !s->write_hash) {
1295                         if (thisrr->type == SSL3_RT_ALERT) {
1296                             /*
1297                              * The record is using an incorrect version number,
1298                              * but what we've got appears to be an alert. We
1299                              * haven't read the body yet to check whether its a
1300                              * fatal or not - but chances are it is. We probably
1301                              * shouldn't send a fatal alert back. We'll just
1302                              * end.
1303                              */
1304                             RLAYERfatal(rl, SSL_AD_NO_ALERT,
1305                                         SSL_R_WRONG_VERSION_NUMBER);
1306                             return OSSL_RECORD_RETURN_FATAL;
1307                         }
1308                         /*
1309                          * Send back error using their minor version number :-)
1310                          */
1311                         s->version = (unsigned short)version;
1312                     }
1313                     RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1314                                 SSL_R_WRONG_VERSION_NUMBER);
1315                     return OSSL_RECORD_RETURN_FATAL;
1316                 }
1317
1318                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
1319                     if (rl->is_first_record) {
1320                         /* Go back to start of packet, look at the five bytes
1321                          * that we have. */
1322                         p = rl->packet;
1323                         if (HAS_PREFIX((char *)p, "GET ") ||
1324                             HAS_PREFIX((char *)p, "POST ") ||
1325                             HAS_PREFIX((char *)p, "HEAD ") ||
1326                             HAS_PREFIX((char *)p, "PUT ")) {
1327                             RLAYERfatal(rl, SSL_AD_NO_ALERT, SSL_R_HTTP_REQUEST);
1328                             return OSSL_RECORD_RETURN_FATAL;
1329                         } else if (HAS_PREFIX((char *)p, "CONNE")) {
1330                             RLAYERfatal(rl, SSL_AD_NO_ALERT,
1331                                         SSL_R_HTTPS_PROXY_REQUEST);
1332                             return OSSL_RECORD_RETURN_FATAL;
1333                         }
1334
1335                         /* Doesn't look like TLS - don't send an alert */
1336                         RLAYERfatal(rl, SSL_AD_NO_ALERT,
1337                                     SSL_R_WRONG_VERSION_NUMBER);
1338                         return OSSL_RECORD_RETURN_FATAL;
1339                     } else {
1340                         RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
1341                                     SSL_R_WRONG_VERSION_NUMBER);
1342                         return OSSL_RECORD_RETURN_FATAL;
1343                     }
1344                 }
1345
1346                 if (SSL_CONNECTION_IS_TLS13(s)
1347                         && s->enc_read_ctx != NULL
1348                         && !using_ktls) {
1349                     if (thisrr->type != SSL3_RT_APPLICATION_DATA
1350                             && (thisrr->type != SSL3_RT_CHANGE_CIPHER_SPEC
1351                                 || !SSL_IS_FIRST_HANDSHAKE(s))
1352                             && (thisrr->type != SSL3_RT_ALERT
1353                                 || s->statem.enc_read_state
1354                                    != ENC_READ_STATE_ALLOW_PLAIN_ALERTS)) {
1355                         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1356                                     SSL_R_BAD_RECORD_TYPE);
1357                         return OSSL_RECORD_RETURN_FATAL;
1358                     }
1359                     if (thisrr->rec_version != TLS1_2_VERSION) {
1360                         RLAYERfatal(rl, SSL_AD_DECODE_ERROR,
1361                                     SSL_R_WRONG_VERSION_NUMBER);
1362                         return OSSL_RECORD_RETURN_FATAL;
1363                     }
1364                 }
1365
1366                 if (thisrr->length >
1367                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
1368                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1369                                 SSL_R_PACKET_LENGTH_TOO_LONG);
1370                     return OSSL_RECORD_RETURN_FATAL;
1371                 }
1372             }
1373
1374             /* now rl->rstate == SSL_ST_READ_BODY */
1375         }
1376
1377         if (SSL_CONNECTION_IS_TLS13(s)) {
1378             size_t len = SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH;
1379
1380             /* KTLS strips the inner record type. */
1381             if (using_ktls)
1382                 len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
1383
1384             if (thisrr->length > len) {
1385                 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1386                             SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1387                 return OSSL_RECORD_RETURN_FATAL;
1388             }
1389         } else {
1390             size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
1391
1392 #ifndef OPENSSL_NO_COMP
1393             /*
1394              * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
1395              * does not include the compression overhead anyway.
1396              */
1397             if (s->expand == NULL)
1398                 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1399 #endif
1400
1401             /* KTLS may use all of the buffer */
1402             if (using_ktls)
1403                 len = SSL3_BUFFER_get_left(rbuf);
1404
1405             if (thisrr->length > len) {
1406                 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1407                             SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1408                 return OSSL_RECORD_RETURN_FATAL;
1409             }
1410         }
1411
1412         /*
1413          * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
1414          * how much more data we need to read for the rest of the record
1415          */
1416         if (thisrr->rec_version == SSL2_VERSION) {
1417             more = thisrr->length + SSL2_RT_HEADER_LENGTH
1418                 - SSL3_RT_HEADER_LENGTH;
1419         } else {
1420             more = thisrr->length;
1421         }
1422
1423         if (more > 0) {
1424             /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
1425
1426             rret = tls_read_n(rl, more, more, 1, 0, &n);
1427             if (rret < OSSL_RECORD_RETURN_SUCCESS)
1428                 return rret;     /* error or non-blocking io */
1429         }
1430
1431         /* set state for later operations */
1432         rl->rstate = SSL_ST_READ_HEADER;
1433
1434         /*
1435          * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
1436          * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
1437          * + thisrr->length and we have that many bytes in rl->packet
1438          */
1439         if (thisrr->rec_version == SSL2_VERSION)
1440             thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
1441         else
1442             thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
1443
1444         /*
1445          * ok, we can now read from 'rl->packet' data into 'thisrr'.
1446          * thisrr->input points at thisrr->length bytes, which need to be copied
1447          * into thisrr->data by either the decryption or by the decompression.
1448          * When the data is 'copied' into the thisrr->data buffer,
1449          * thisrr->input will be updated to point at the new buffer
1450          */
1451
1452         /*
1453          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
1454          * thisrr->length bytes of encrypted compressed stuff.
1455          */
1456
1457         /* decrypt in place in 'thisrr->input' */
1458         thisrr->data = thisrr->input;
1459         thisrr->orig_len = thisrr->length;
1460
1461         /* Mark this record as not read by upper layers yet */
1462         thisrr->read = 0;
1463
1464         num_recs++;
1465
1466         /* we have pulled in a full packet so zero things */
1467         tls_reset_packet_length(rl);
1468         rl->is_first_record = 0;
1469     } while (num_recs < max_recs
1470              && thisrr->type == SSL3_RT_APPLICATION_DATA
1471              && SSL_USE_EXPLICIT_IV(s)
1472              && rl->enc_read_ctx != NULL
1473              && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_read_ctx))
1474                  & EVP_CIPH_FLAG_PIPELINE) != 0
1475              && tls_record_app_data_waiting(rl));
1476
1477     if (num_recs == 1
1478             && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1479             && (SSL_CONNECTION_IS_TLS13(s) || s->hello_retry_request != SSL_HRR_NONE)
1480             && SSL_IS_FIRST_HANDSHAKE(s)) {
1481         /*
1482          * CCS messages must be exactly 1 byte long, containing the value 0x01
1483          */
1484         if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
1485             RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
1486                         SSL_R_INVALID_CCS_MESSAGE);
1487             return OSSL_RECORD_RETURN_FATAL;
1488         }
1489         /*
1490          * CCS messages are ignored in TLSv1.3. We treat it like an empty
1491          * handshake record
1492          */
1493         thisrr->type = SSL3_RT_HANDSHAKE;
1494         if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
1495             RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1496                         SSL_R_UNEXPECTED_CCS_MESSAGE);
1497             return OSSL_RECORD_RETURN_FATAL;
1498         }
1499         thisrr->read = 1;
1500         rl->num_recs = 0;
1501         rl->curr_rec = 0;
1502         rl->num_released = 0;
1503
1504         return OSSL_RECORD_RETURN_SUCCESS;
1505     }
1506
1507     if (using_ktls)
1508         goto skip_decryption;
1509
1510     if (rl->read_hash != NULL) {
1511         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->read_hash);
1512
1513         if (tmpmd != NULL) {
1514             imac_size = EVP_MD_get_size(tmpmd);
1515             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
1516                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
1517                     return OSSL_RECORD_RETURN_FATAL;
1518             }
1519             mac_size = (size_t)imac_size;
1520         }
1521     }
1522
1523     /*
1524      * If in encrypt-then-mac mode calculate mac from encrypted record. All
1525      * the details below are public so no timing details can leak.
1526      */
1527     if (SSL_READ_ETM(s) && rl->read_hash) {
1528         unsigned char *mac;
1529
1530         for (j = 0; j < num_recs; j++) {
1531             thisrr = &rr[j];
1532
1533             if (thisrr->length < mac_size) {
1534                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1535                 return OSSL_RECORD_RETURN_FATAL;
1536             }
1537             thisrr->length -= mac_size;
1538             mac = thisrr->data + thisrr->length;
1539             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */, s);
1540             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
1541                 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1542                             SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1543                 return OSSL_RECORD_RETURN_FATAL;
1544             }
1545         }
1546         /*
1547          * We've handled the mac now - there is no MAC inside the encrypted
1548          * record
1549          */
1550         mac_size = 0;
1551     }
1552
1553     if (mac_size > 0) {
1554         macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
1555         if (macbufs == NULL) {
1556             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1557             return OSSL_RECORD_RETURN_FATAL;
1558         }
1559     }
1560
1561     /*
1562      * TODO(RECLAYER): Only call rl functions once TLSv1.3/SSLv3 is moved to new
1563      * record layer code
1564      */
1565     if (!SSL_CONNECTION_IS_TLS13(s))
1566         enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size, s);
1567     else
1568         enc_err = ssl->method->ssl3_enc->enc(s, rr, num_recs, 0, macbufs, mac_size);
1569
1570     /*-
1571      * enc_err is:
1572      *    0: if the record is publicly invalid, or an internal error, or AEAD
1573      *       decryption failed, or ETM decryption failed.
1574      *    1: Success or MTE decryption failed (MAC will be randomised)
1575      */
1576     if (enc_err == 0) {
1577         if (ossl_statem_in_error(s)) {
1578             /* SSLfatal() already got called */
1579             goto end;
1580         }
1581         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
1582             /*
1583              * Valid early_data that we cannot decrypt will fail here. We treat
1584              * it like an empty record.
1585              */
1586
1587             thisrr = &rr[0];
1588
1589             if (!ossl_early_data_count_ok(s, thisrr->length,
1590                                      EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1591                 /* SSLfatal() already called */
1592                 goto end;
1593             }
1594
1595             thisrr->length = 0;
1596             thisrr->read = 1;
1597             rl->num_recs = 0;
1598             rl->curr_rec = 0;
1599             rl->num_released = 0;
1600             RECORD_LAYER_reset_read_sequence(&s->rlayer);
1601             ret = 1;
1602             goto end;
1603         }
1604         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1605                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1606         goto end;
1607     }
1608     OSSL_TRACE_BEGIN(TLS) {
1609         BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
1610         BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
1611     } OSSL_TRACE_END(TLS);
1612
1613     /* r->length is now the compressed data plus mac */
1614     if ((sess != NULL)
1615             && (rl->enc_read_ctx != NULL)
1616             && (!SSL_READ_ETM(s) && EVP_MD_CTX_get0_md(rl->read_hash) != NULL)) {
1617         /* rl->read_hash != NULL => mac_size != -1 */
1618
1619         for (j = 0; j < num_recs; j++) {
1620             SSL_MAC_BUF *thismb = &macbufs[j];
1621             thisrr = &rr[j];
1622
1623             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */, s);
1624             if (i == 0 || thismb == NULL || thismb->mac == NULL
1625                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
1626                 enc_err = 0;
1627             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1628                 enc_err = 0;
1629         }
1630     }
1631
1632     if (enc_err == 0) {
1633         if (ossl_statem_in_error(s)) {
1634             /* We already called SSLfatal() */
1635             goto end;
1636         }
1637         /*
1638          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
1639          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
1640          * failure is directly visible from the ciphertext anyway, we should
1641          * not reveal which kind of error occurred -- this might become
1642          * visible to an attacker (e.g. via a logfile)
1643          */
1644         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
1645                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1646         goto end;
1647     }
1648
1649  skip_decryption:
1650
1651     for (j = 0; j < num_recs; j++) {
1652         thisrr = &rr[j];
1653
1654         /* thisrr->length is now just compressed */
1655         if (s->expand != NULL) {
1656             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1657                 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1658                             SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1659                 goto end;
1660             }
1661             if (!ssl3_do_uncompress(s, thisrr)) {
1662                 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1663                             SSL_R_BAD_DECOMPRESSION);
1664                 goto end;
1665             }
1666         }
1667
1668         if (SSL_CONNECTION_IS_TLS13(s)
1669                 && s->enc_read_ctx != NULL
1670                 && thisrr->type != SSL3_RT_ALERT) {
1671             /*
1672              * The following logic are irrelevant in KTLS: the kernel provides
1673              * unprotected record and thus record type represent the actual
1674              * content type, and padding is already removed and thisrr->type and
1675              * thisrr->length should have the correct values.
1676              */
1677             if (!using_ktls) {
1678                 size_t end;
1679
1680                 if (thisrr->length == 0
1681                         || thisrr->type != SSL3_RT_APPLICATION_DATA) {
1682                     RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
1683                                 SSL_R_BAD_RECORD_TYPE);
1684                     goto end;
1685                 }
1686
1687                 /* Strip trailing padding */
1688                 for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
1689                      end--)
1690                     continue;
1691
1692                 thisrr->length = end;
1693                 thisrr->type = thisrr->data[end];
1694             }
1695             if (thisrr->type != SSL3_RT_APPLICATION_DATA
1696                     && thisrr->type != SSL3_RT_ALERT
1697                     && thisrr->type != SSL3_RT_HANDSHAKE) {
1698                 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1699                 goto end;
1700             }
1701             if (s->msg_callback)
1702                 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
1703                                 &thisrr->type, 1, ssl, s->msg_callback_arg);
1704         }
1705
1706         /*
1707          * TLSv1.3 alert and handshake records are required to be non-zero in
1708          * length.
1709          */
1710         if (SSL_CONNECTION_IS_TLS13(s)
1711                 && (thisrr->type == SSL3_RT_HANDSHAKE
1712                     || thisrr->type == SSL3_RT_ALERT)
1713                 && thisrr->length == 0) {
1714             RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1715             goto end;
1716         }
1717
1718         /*
1719          * Usually thisrr->length is the length of a single record, but when
1720          * KTLS handles the decryption, thisrr->length may be larger than
1721          * SSL3_RT_MAX_PLAIN_LENGTH because the kernel may have coalesced
1722          * multiple records.
1723          * Therefore we have to rely on KTLS to check the plaintext length
1724          * limit in the kernel.
1725          */
1726         if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH && !using_ktls) {
1727             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1728             goto end;
1729         }
1730
1731         /*
1732          * Check if the received packet overflows the current
1733          * Max Fragment Length setting.
1734          * Note: USE_MAX_FRAGMENT_LENGTH_EXT and KTLS are mutually exclusive.
1735          */
1736         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1737                 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
1738             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1739             goto end;
1740         }
1741
1742         thisrr->off = 0;
1743         /*-
1744          * So at this point the following is true
1745          * thisrr->type   is the type of record
1746          * thisrr->length == number of bytes in record
1747          * thisrr->off    == offset to first valid byte
1748          * thisrr->data   == where to take bytes from, increment after use :-).
1749          */
1750
1751         /* just read a 0 length packet */
1752         if (thisrr->length == 0) {
1753             if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
1754                 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
1755                 goto end;
1756             }
1757         } else {
1758             rl->empty_record_count = 0;
1759         }
1760     }
1761
1762     if (s->early_data_state == SSL_EARLY_DATA_READING) {
1763         thisrr = &rr[0];
1764         if (thisrr->type == SSL3_RT_APPLICATION_DATA
1765                 && !ossl_early_data_count_ok(s, thisrr->length, 0, 0)) {
1766             /* SSLfatal already called */
1767             goto end;
1768         }
1769     }
1770
1771     rl->num_recs = num_recs;
1772     rl->curr_rec = 0;
1773     rl->num_released = 0;
1774     ret = OSSL_RECORD_RETURN_SUCCESS;
1775  end:
1776     if (macbufs != NULL) {
1777         for (j = 0; j < num_recs; j++) {
1778             if (macbufs[j].alloced)
1779                 OPENSSL_free(macbufs[j].mac);
1780         }
1781         OPENSSL_free(macbufs);
1782     }
1783     return ret;
1784 }
1785
1786 static int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,
1787                            int *rversion, int *type, unsigned char **data,
1788                            size_t *datalen, uint16_t *epoch,
1789                            unsigned char *seq_num,
1790                            /* TODO(RECLAYER): Remove me */ SSL_CONNECTION *s)
1791 {
1792     SSL3_RECORD *rec;
1793
1794     /*
1795      * tls_get_more_records() can return success without actually reading
1796      * anything useful (i.e. if empty records are read). We loop here until
1797      * we have something useful. tls_get_more_records() will eventually fail if
1798      * too many sequential empty records are read.
1799      */
1800     while (rl->curr_rec >= rl->num_recs) {
1801         int ret;
1802
1803         if (rl->num_released != rl->num_recs) {
1804             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1805             return OSSL_RECORD_RETURN_FATAL;
1806         }
1807
1808         ret = tls_get_more_records(rl, s);
1809
1810         if (ret != OSSL_RECORD_RETURN_SUCCESS)
1811             return ret;
1812     }
1813
1814     /*
1815      * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1816      * points to the next one to read.
1817      */
1818     rec = &rl->rrec[rl->curr_rec++];
1819
1820     *rechandle = rec;
1821     *rversion = rec->rec_version;
1822     *type = rec->type;
1823     *data = rec->data;
1824     *datalen = rec->length;
1825
1826     return OSSL_RECORD_RETURN_SUCCESS;
1827 }
1828
1829 static int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1830 {
1831     if (!ossl_assert(rl->num_released < rl->curr_rec)
1832             || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1833         /* Should not happen */
1834         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1835         return OSSL_RECORD_RETURN_FATAL;
1836     }
1837
1838     rl->num_released++;
1839
1840     return OSSL_RECORD_RETURN_SUCCESS;
1841 }
1842
1843 static OSSL_RECORD_LAYER *tls_new_record_layer(OSSL_LIB_CTX *libctx,
1844                                                const char *propq, int vers,
1845                                                int role, int direction,
1846                                                int level, unsigned char *key,
1847                                                size_t keylen,
1848                                                unsigned char *iv,
1849                                                size_t ivlen,
1850                                                unsigned char *mackey,
1851                                                size_t mackeylen,
1852                                                const EVP_CIPHER *ciph,
1853                                                size_t taglen,
1854                                                /* TODO(RECLAYER): This probably should not be an int */
1855                                                int mactype,
1856                                                const EVP_MD *md,
1857                                                const SSL_COMP *comp,
1858                                                BIO *transport, BIO_ADDR *local,
1859                                                BIO_ADDR *peer,
1860                                                const OSSL_PARAM *settings,
1861                                                const OSSL_PARAM *options,
1862                                                /* TODO(RECLAYER): Remove me */
1863                                                SSL_CONNECTION *s)
1864 {
1865     OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1866     const OSSL_PARAM *p;
1867
1868     if (rl == NULL) {
1869         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1870         return NULL;
1871     }
1872
1873     if (transport != NULL && !BIO_up_ref(transport)) {
1874         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1875         goto err;
1876     }
1877
1878     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1879     if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1880         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1881         goto err;
1882     }
1883
1884     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1885     if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1886         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1887         goto err;
1888     }
1889
1890
1891     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1892     if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1893         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1894         goto err;
1895     }
1896
1897     rl->libctx = libctx;
1898     rl->propq = propq;
1899
1900     rl->version = vers;
1901     rl->role = role;
1902     rl->direction = direction;
1903
1904     if (level == 0)
1905         rl->is_first_record = 1;
1906
1907     if (!tls_set1_bio(rl, transport))
1908         goto err;
1909
1910     switch (vers) {
1911     case TLS_ANY_VERSION:
1912         rl->funcs = &tls_any_funcs;
1913         break;
1914     case TLS1_3_VERSION:
1915         rl->funcs = &tls_1_3_funcs;
1916         break;
1917     case TLS1_2_VERSION:
1918         rl->funcs = &tls_1_2_funcs;
1919         break;
1920     case TLS1_1_VERSION:
1921         rl->funcs = &tls_1_1_funcs;
1922         break;
1923     case TLS1_VERSION:
1924         rl->funcs = &tls_1_0_funcs;
1925         break;
1926     case SSL3_VERSION:
1927         rl->funcs = &ssl_3_0_funcs;
1928         break;
1929     default:
1930         /* Should not happen */
1931         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1932         goto err;
1933     }
1934
1935     if (!rl->funcs->set_crypto_state(rl, level, key, keylen, iv, ivlen,
1936                                      mackey, mackeylen, ciph, taglen,
1937                                      mactype, md, comp, s)) {
1938         /* RLAYERfatal already called */
1939         goto err;
1940     }
1941
1942     return rl;
1943  err:
1944     OPENSSL_free(rl);
1945     return NULL;
1946 }
1947
1948 static OSSL_RECORD_LAYER *dtls_new_record_layer(OSSL_LIB_CTX *libctx,
1949                                                 const char *propq, int vers,
1950                                                 int role, int direction,
1951                                                 int level, unsigned char *key,
1952                                                 size_t keylen,
1953                                                 unsigned char *iv,
1954                                                 size_t ivlen,
1955                                                 unsigned char *mackey,
1956                                                 size_t mackeylen,
1957                                                 const EVP_CIPHER *ciph,
1958                                                 size_t taglen,
1959                                                 /* TODO(RECLAYER): This probably should not be an int */
1960                                                 int mactype,
1961                                                 const EVP_MD *md,
1962                                                 const SSL_COMP *comp,
1963                                                 BIO *transport, BIO_ADDR *local,
1964                                                 BIO_ADDR *peer,
1965                                                 const OSSL_PARAM *settings,
1966                                                 const OSSL_PARAM *options,
1967                                                 /* TODO(RECLAYER): Remove me */
1968                                                 SSL_CONNECTION *s)
1969 {
1970     OSSL_RECORD_LAYER *rl = tls_new_record_layer(libctx, propq, vers, role,
1971                                                  direction, level, key, keylen,
1972                                                  iv, ivlen, mackey, mackeylen,
1973                                                  ciph, taglen, mactype, md,
1974                                                  comp, transport, local, peer,
1975                                                  settings, options, s);
1976
1977     if (rl == NULL)
1978         return NULL;
1979
1980     rl->isdtls = 1;
1981
1982     return rl;
1983 }
1984
1985 static void tls_free(OSSL_RECORD_LAYER *rl)
1986 {
1987     BIO_free(rl->bio);
1988     OPENSSL_free(rl);
1989 }
1990
1991 static int tls_reset(OSSL_RECORD_LAYER *rl)
1992 {
1993     memset(rl, 0, sizeof(*rl));
1994     return 1;
1995 }
1996
1997 static int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1998 {
1999     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;;
2000 }
2001
2002 static int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
2003 {
2004     return rl->curr_rec < rl->num_recs;
2005 }
2006
2007 static size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
2008 {
2009     return 0;
2010 }
2011
2012 static int tls_write_pending(OSSL_RECORD_LAYER *rl)
2013 {
2014     return 0;
2015 }
2016
2017 static size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
2018 {
2019     return 0;
2020 }
2021
2022 static size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
2023 {
2024     return 0;
2025 }
2026
2027 static int tls_write_records(OSSL_RECORD_LAYER *rl,
2028                              OSSL_RECORD_TEMPLATE **templates, size_t numtempl,
2029                              size_t allowance, size_t *sent)
2030 {
2031     return 0;
2032 }
2033
2034 static int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
2035                                    size_t *sent)
2036 {
2037     return 0;
2038 }
2039
2040
2041 static int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
2042 {
2043     return rl->alert;
2044 }
2045
2046 static int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
2047 {
2048     if (bio != NULL && !BIO_up_ref(bio))
2049         return 0;
2050     BIO_free(rl->bio);
2051     rl->bio = bio;
2052
2053     return 1;
2054 }
2055
2056 static SSL3_BUFFER *tls_get0_rbuf(OSSL_RECORD_LAYER *rl)
2057 {
2058     return &rl->rbuf;
2059 }
2060
2061 static unsigned char *tls_get0_packet(OSSL_RECORD_LAYER *rl)
2062 {
2063     return rl->packet;
2064 }
2065
2066 static void tls_set0_packet(OSSL_RECORD_LAYER *rl, unsigned char *packet,
2067                             size_t packetlen)
2068 {
2069     rl->packet = packet;
2070     rl->packet_length = packetlen;
2071 }
2072
2073 static size_t tls_get_packet_length(OSSL_RECORD_LAYER *rl)
2074 {
2075     return rl->packet_length;
2076 }
2077
2078 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2079     tls_new_record_layer,
2080     tls_free,
2081     tls_reset,
2082     tls_unprocessed_read_pending,
2083     tls_processed_read_pending,
2084     tls_app_data_pending,
2085     tls_write_pending,
2086     tls_get_max_record_len,
2087     tls_get_max_records,
2088     tls_write_records,
2089     tls_retry_write_records,
2090     tls_read_record,
2091     tls_release_record,
2092     tls_get_alert_code,
2093     tls_set1_bio,
2094
2095     /*
2096      * TODO(RECLAYER): Remove these. These function pointers are temporary hacks
2097      * during the record layer refactoring. They need to be removed before the
2098      * refactor is complete.
2099      */
2100     tls_read_n,
2101     tls_get0_rbuf,
2102     tls_get0_packet,
2103     tls_set0_packet,
2104     tls_get_packet_length,
2105     tls_reset_packet_length
2106 };
2107
2108 const OSSL_RECORD_METHOD ossl_dtls_record_method = {
2109     dtls_new_record_layer,
2110     tls_free,
2111     tls_reset,
2112     tls_unprocessed_read_pending,
2113     tls_processed_read_pending,
2114     tls_app_data_pending,
2115     tls_write_pending,
2116     tls_get_max_record_len,
2117     tls_get_max_records,
2118     tls_write_records,
2119     tls_retry_write_records,
2120     tls_read_record,
2121     tls_release_record,
2122     tls_get_alert_code,
2123     tls_set1_bio,
2124
2125     /*
2126      * TODO(RECLAYER): Remove these. These function pointers are temporary hacks
2127      * during the record layer refactoring. They need to be removed before the
2128      * refactor is complete.
2129      */
2130     tls_read_n,
2131     tls_get0_rbuf,
2132     tls_get0_packet,
2133     tls_set0_packet,
2134     tls_get_packet_length,
2135     tls_reset_packet_length
2136 };