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