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