xref: /openssl/ssl/record/rec_layer_s3.c (revision efc84eac)
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdio.h>
11 #include <limits.h>
12 #include <errno.h>
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
20 
21 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
22         !(      defined(AES_ASM) &&     ( \
23                 defined(__x86_64)       || defined(__x86_64__)  || \
24                 defined(_M_AMD64)       || defined(_M_X64)      ) \
25         )
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
28 #endif
29 
RECORD_LAYER_init(RECORD_LAYER * rl,SSL_CONNECTION * s)30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
31 {
32     rl->s = s;
33 }
34 
RECORD_LAYER_clear(RECORD_LAYER * rl)35 void RECORD_LAYER_clear(RECORD_LAYER *rl)
36 {
37     rl->wnum = 0;
38     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
39     rl->handshake_fragment_len = 0;
40     rl->wpend_tot = 0;
41     rl->wpend_type = 0;
42     rl->wpend_ret = 0;
43     rl->wpend_buf = NULL;
44 
45     ssl3_release_write_buffer(rl->s);
46 
47     RECORD_LAYER_reset_write_sequence(rl);
48 
49     if (rl->rrlmethod != NULL)
50         rl->rrlmethod->free(rl->rrl); /* Ignore return value */
51     BIO_free(rl->rrlnext);
52     rl->rrlmethod = NULL;
53     rl->rrlnext = NULL;
54 
55     if (rl->d)
56         DTLS_RECORD_LAYER_clear(rl);
57 }
58 
RECORD_LAYER_release(RECORD_LAYER * rl)59 void RECORD_LAYER_release(RECORD_LAYER *rl)
60 {
61     if (rl->numwpipes > 0)
62         ssl3_release_write_buffer(rl->s);
63 }
64 
65 /* Checks if we have unprocessed read ahead data pending */
RECORD_LAYER_read_pending(const RECORD_LAYER * rl)66 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
67 {
68     return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
69 }
70 
71 /* Checks if we have decrypted unread record data pending */
RECORD_LAYER_processed_read_pending(const RECORD_LAYER * rl)72 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
73 {
74     return (rl->curr_rec < rl->num_recs)
75            || rl->rrlmethod->processed_read_pending(rl->rrl);
76 }
77 
RECORD_LAYER_write_pending(const RECORD_LAYER * rl)78 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
79 {
80     return (rl->numwpipes > 0)
81         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
82 }
83 
RECORD_LAYER_reset_write_sequence(RECORD_LAYER * rl)84 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
85 {
86     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
87 }
88 
ssl3_pending(const SSL * s)89 size_t ssl3_pending(const SSL *s)
90 {
91     size_t i, num = 0;
92     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
93 
94     if (sc == NULL)
95         return 0;
96 
97     if (SSL_CONNECTION_IS_DTLS(sc)) {
98         TLS_RECORD *rdata;
99         pitem *item, *iter;
100 
101         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
102         while ((item = pqueue_next(&iter)) != NULL) {
103             rdata = item->data;
104             num += rdata->length;
105         }
106     }
107 
108     for (i = 0; i < sc->rlayer.num_recs; i++) {
109         if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
110             return num;
111         num += sc->rlayer.tlsrecs[i].length;
112     }
113 
114     num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
115 
116     return num;
117 }
118 
SSL_CTX_set_default_read_buffer_len(SSL_CTX * ctx,size_t len)119 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
120 {
121     ctx->default_read_buf_len = len;
122 }
123 
SSL_set_default_read_buffer_len(SSL * s,size_t len)124 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
125 {
126     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
127 
128     if (sc == NULL)
129         return;
130     sc->rlayer.default_read_buf_len = len;
131 }
132 
SSL_rstate_string_long(const SSL * s)133 const char *SSL_rstate_string_long(const SSL *s)
134 {
135     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
136     const char *lng;
137 
138     if (sc == NULL)
139         return NULL;
140 
141     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
142         return "unknown";
143 
144     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
145 
146     return lng;
147 }
148 
SSL_rstate_string(const SSL * s)149 const char *SSL_rstate_string(const SSL *s)
150 {
151     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
152     const char *shrt;
153 
154     if (sc == NULL)
155         return NULL;
156 
157     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
158         return "unknown";
159 
160     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
161 
162     return shrt;
163 }
164 
165 /*
166  * Call this to write data in records of type 'type' It will return <= 0 if
167  * not all data has been sent or non-blocking IO.
168  */
ssl3_write_bytes(SSL * ssl,int type,const void * buf_,size_t len,size_t * written)169 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
170                      size_t *written)
171 {
172     const unsigned char *buf = buf_;
173     size_t tot;
174     size_t n, max_send_fragment, split_send_fragment, maxpipes;
175 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
176     size_t nw;
177 #endif
178     SSL3_BUFFER *wb;
179     int i;
180     size_t tmpwrit;
181     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
182 
183     if (s == NULL)
184         return -1;
185 
186     wb = &s->rlayer.wbuf[0];
187     s->rwstate = SSL_NOTHING;
188     tot = s->rlayer.wnum;
189     /*
190      * ensure that if we end up with a smaller value of data to write out
191      * than the original len from a write which didn't complete for
192      * non-blocking I/O and also somehow ended up avoiding the check for
193      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
194      * possible to end up with (len-tot) as a large number that will then
195      * promptly send beyond the end of the users buffer ... so we trap and
196      * report the error in a way the user will notice
197      */
198     if ((len < s->rlayer.wnum)
199         || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
200         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
201         return -1;
202     }
203 
204     if (s->early_data_state == SSL_EARLY_DATA_WRITING
205             && !ossl_early_data_count_ok(s, len, 0, 1)) {
206         /* SSLfatal() already called */
207         return -1;
208     }
209 
210     s->rlayer.wnum = 0;
211 
212     /*
213      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
214      * into init unless we have writes pending - in which case we should finish
215      * doing that first.
216      */
217     if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
218                           || s->ext.extra_tickets_expected > 0))
219         ossl_statem_set_in_init(s, 1);
220 
221     /*
222      * When writing early data on the server side we could be "in_init" in
223      * between receiving the EoED and the CF - but we don't want to handle those
224      * messages yet.
225      */
226     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
227             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
228         i = s->handshake_func(ssl);
229         /* SSLfatal() already called */
230         if (i < 0)
231             return i;
232         if (i == 0) {
233             return -1;
234         }
235     }
236 
237     /*
238      * first check if there is a SSL3_BUFFER still being written out.  This
239      * will happen with non blocking IO
240      */
241     if (wb->left != 0) {
242         /* SSLfatal() already called if appropriate */
243         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
244                                &tmpwrit);
245         if (i <= 0) {
246             /* XXX should we ssl3_release_write_buffer if i<0? */
247             s->rlayer.wnum = tot;
248             return i;
249         }
250         tot += tmpwrit;               /* this might be last fragment */
251     }
252 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
253     /*
254      * Depending on platform multi-block can deliver several *times*
255      * better performance. Downside is that it has to allocate
256      * jumbo buffer to accommodate up to 8 records, but the
257      * compromise is considered worthy.
258      */
259     if (type == SSL3_RT_APPLICATION_DATA
260             && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
261             && s->compress == NULL
262             && s->msg_callback == NULL
263             && !SSL_WRITE_ETM(s)
264             && SSL_USE_EXPLICIT_IV(s)
265             && !BIO_get_ktls_send(s->wbio)
266             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
267                 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
268         unsigned char aad[13];
269         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
270         size_t packlen;
271         int packleni;
272 
273         /* minimize address aliasing conflicts */
274         if ((max_send_fragment & 0xfff) == 0)
275             max_send_fragment -= 512;
276 
277         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
278             ssl3_release_write_buffer(s);
279 
280             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
281                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
282                                           (int)max_send_fragment, NULL);
283 
284             if (len >= 8 * max_send_fragment)
285                 packlen *= 8;
286             else
287                 packlen *= 4;
288 
289             if (!ssl3_setup_write_buffer(s, 1, packlen)) {
290                 /* SSLfatal() already called */
291                 return -1;
292             }
293         } else if (tot == len) { /* done? */
294             /* free jumbo buffer */
295             ssl3_release_write_buffer(s);
296             *written = tot;
297             return 1;
298         }
299 
300         n = (len - tot);
301         for (;;) {
302             if (n < 4 * max_send_fragment) {
303                 /* free jumbo buffer */
304                 ssl3_release_write_buffer(s);
305                 break;
306             }
307 
308             if (s->s3.alert_dispatch) {
309                 i = ssl->method->ssl_dispatch_alert(ssl);
310                 if (i <= 0) {
311                     /* SSLfatal() already called if appropriate */
312                     s->rlayer.wnum = tot;
313                     return i;
314                 }
315             }
316 
317             if (n >= 8 * max_send_fragment)
318                 nw = max_send_fragment * (mb_param.interleave = 8);
319             else
320                 nw = max_send_fragment * (mb_param.interleave = 4);
321 
322             memcpy(aad, s->rlayer.write_sequence, 8);
323             aad[8] = type;
324             aad[9] = (unsigned char)(s->version >> 8);
325             aad[10] = (unsigned char)(s->version);
326             aad[11] = 0;
327             aad[12] = 0;
328             mb_param.out = NULL;
329             mb_param.inp = aad;
330             mb_param.len = nw;
331 
332             packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
333                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
334                                           sizeof(mb_param), &mb_param);
335             packlen = (size_t)packleni;
336             if (packleni <= 0 || packlen > wb->len) { /* never happens */
337                 /* free jumbo buffer */
338                 ssl3_release_write_buffer(s);
339                 break;
340             }
341 
342             mb_param.out = wb->buf;
343             mb_param.inp = &buf[tot];
344             mb_param.len = nw;
345 
346             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
347                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
348                                     sizeof(mb_param), &mb_param) <= 0)
349                 return -1;
350 
351             s->rlayer.write_sequence[7] += mb_param.interleave;
352             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
353                 int j = 6;
354                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
355             }
356 
357             wb->offset = 0;
358             wb->left = packlen;
359 
360             s->rlayer.wpend_tot = nw;
361             s->rlayer.wpend_buf = &buf[tot];
362             s->rlayer.wpend_type = type;
363             s->rlayer.wpend_ret = nw;
364 
365             i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
366             if (i <= 0) {
367                 /* SSLfatal() already called if appropriate */
368                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
369                     /* free jumbo buffer */
370                     ssl3_release_write_buffer(s);
371                 }
372                 s->rlayer.wnum = tot;
373                 return i;
374             }
375             if (tmpwrit == n) {
376                 /* free jumbo buffer */
377                 ssl3_release_write_buffer(s);
378                 *written = tot + tmpwrit;
379                 return 1;
380             }
381             n -= tmpwrit;
382             tot += tmpwrit;
383         }
384     } else
385 #endif  /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
386     if (tot == len) {           /* done? */
387         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
388             ssl3_release_write_buffer(s);
389 
390         *written = tot;
391         return 1;
392     }
393 
394     n = (len - tot);
395 
396     max_send_fragment = ssl_get_max_send_fragment(s);
397     split_send_fragment = ssl_get_split_send_fragment(s);
398     /*
399      * If max_pipelines is 0 then this means "undefined" and we default to
400      * 1 pipeline. Similarly if the cipher does not support pipelined
401      * processing then we also only use 1 pipeline, or if we're not using
402      * explicit IVs
403      */
404     maxpipes = s->max_pipelines;
405     if (maxpipes > SSL_MAX_PIPELINES) {
406         /*
407          * We should have prevented this when we set max_pipelines so we
408          * shouldn't get here
409          */
410         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
411         return -1;
412     }
413     if (maxpipes == 0
414         || s->enc_write_ctx == NULL
415         || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
416             & EVP_CIPH_FLAG_PIPELINE) == 0
417         || !SSL_USE_EXPLICIT_IV(s))
418         maxpipes = 1;
419     if (max_send_fragment == 0
420             || split_send_fragment == 0
421             || split_send_fragment > max_send_fragment) {
422         /*
423          * We should have prevented this when we set/get the split and max send
424          * fragments so we shouldn't get here
425          */
426         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
427         return -1;
428     }
429 
430     for (;;) {
431         size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
432         size_t numpipes, j;
433 
434         if (n == 0)
435             numpipes = 1;
436         else
437             numpipes = ((n - 1) / split_send_fragment) + 1;
438         if (numpipes > maxpipes)
439             numpipes = maxpipes;
440 
441         if (n / numpipes >= max_send_fragment) {
442             /*
443              * We have enough data to completely fill all available
444              * pipelines
445              */
446             for (j = 0; j < numpipes; j++) {
447                 pipelens[j] = max_send_fragment;
448             }
449         } else {
450             /* We can partially fill all available pipelines */
451             tmppipelen = n / numpipes;
452             remain = n % numpipes;
453             for (j = 0; j < numpipes; j++) {
454                 pipelens[j] = tmppipelen;
455                 if (j < remain)
456                     pipelens[j]++;
457             }
458         }
459 
460         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
461                           &tmpwrit);
462         if (i <= 0) {
463             /* SSLfatal() already called if appropriate */
464             /* XXX should we ssl3_release_write_buffer if i<0? */
465             s->rlayer.wnum = tot;
466             return i;
467         }
468 
469         if (tmpwrit == n ||
470             (type == SSL3_RT_APPLICATION_DATA &&
471              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
472             /*
473              * next chunk of data should get another prepended empty fragment
474              * in ciphersuites with known-IV weakness:
475              */
476             s->s3.empty_fragment_done = 0;
477 
478             if (tmpwrit == n
479                     && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
480                     && !SSL_CONNECTION_IS_DTLS(s))
481                 ssl3_release_write_buffer(s);
482 
483             *written = tot + tmpwrit;
484             return 1;
485         }
486 
487         n -= tmpwrit;
488         tot += tmpwrit;
489     }
490 }
491 
do_ssl3_write(SSL_CONNECTION * s,int type,const unsigned char * buf,size_t * pipelens,size_t numpipes,int create_empty_fragment,size_t * written)492 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
493                   size_t *pipelens, size_t numpipes,
494                   int create_empty_fragment, size_t *written)
495 {
496     WPACKET pkt[SSL_MAX_PIPELINES];
497     SSL3_RECORD wr[SSL_MAX_PIPELINES];
498     WPACKET *thispkt;
499     SSL3_RECORD *thiswr;
500     unsigned char *recordstart;
501     int i, mac_size, clear = 0;
502     size_t prefix_len = 0;
503     int eivlen = 0;
504     size_t align = 0;
505     SSL3_BUFFER *wb;
506     SSL_SESSION *sess;
507     size_t totlen = 0, len, wpinited = 0;
508     size_t j;
509     int using_ktls;
510     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
511 
512     for (j = 0; j < numpipes; j++)
513         totlen += pipelens[j];
514     /*
515      * first check if there is a SSL3_BUFFER still being written out.  This
516      * will happen with non blocking IO
517      */
518     if (RECORD_LAYER_write_pending(&s->rlayer)) {
519         /* Calls SSLfatal() as required */
520         return ssl3_write_pending(s, type, buf, totlen, written);
521     }
522 
523     /* If we have an alert to send, lets send it */
524     if (s->s3.alert_dispatch) {
525         i = ssl->method->ssl_dispatch_alert(ssl);
526         if (i <= 0) {
527             /* SSLfatal() already called if appropriate */
528             return i;
529         }
530         /* if it went, fall through and send more stuff */
531     }
532 
533     if (s->rlayer.numwpipes < numpipes) {
534         if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
535             /* SSLfatal() already called */
536             return -1;
537         }
538     }
539 
540     if (totlen == 0 && !create_empty_fragment)
541         return 0;
542 
543     sess = s->session;
544 
545     if ((sess == NULL)
546             || (s->enc_write_ctx == NULL)
547             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
548         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
549         mac_size = 0;
550     } else {
551         mac_size = EVP_MD_CTX_get_size(s->write_hash);
552         if (mac_size < 0) {
553             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
554             goto err;
555         }
556     }
557 
558     /*
559      * 'create_empty_fragment' is true only when this function calls itself
560      */
561     if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
562         /*
563          * countermeasure against known-IV weakness in CBC ciphersuites (see
564          * http://www.openssl.org/~bodo/tls-cbc.txt)
565          */
566 
567         if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
568             /*
569              * recursive function call with 'create_empty_fragment' set; this
570              * prepares and buffers the data for an empty fragment (these
571              * 'prefix_len' bytes are sent out later together with the actual
572              * payload)
573              */
574             size_t tmppipelen = 0;
575             int ret;
576 
577             ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
578             if (ret <= 0) {
579                 /* SSLfatal() already called if appropriate */
580                 goto err;
581             }
582 
583             if (prefix_len >
584                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
585                 /* insufficient space */
586                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
587                 goto err;
588             }
589         }
590 
591         s->s3.empty_fragment_done = 1;
592     }
593 
594     using_ktls = BIO_get_ktls_send(s->wbio);
595     if (using_ktls) {
596         /*
597          * ktls doesn't modify the buffer, but to avoid a warning we need to
598          * discard the const qualifier.
599          * This doesn't leak memory because the buffers have been released when
600          * switching to ktls.
601          */
602         SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
603         SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
604         SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
605         goto wpacket_init_complete;
606     }
607 
608     if (create_empty_fragment) {
609         wb = &s->rlayer.wbuf[0];
610 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
611         /*
612          * extra fragment would be couple of cipher blocks, which would be
613          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
614          * payload, then we can just pretend we simply have two headers.
615          */
616         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
617         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
618 #endif
619         SSL3_BUFFER_set_offset(wb, align);
620         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
621                                      SSL3_BUFFER_get_len(wb), 0)
622                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
623             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
624             goto err;
625         }
626         wpinited = 1;
627     } else if (prefix_len) {
628         wb = &s->rlayer.wbuf[0];
629         if (!WPACKET_init_static_len(&pkt[0],
630                                      SSL3_BUFFER_get_buf(wb),
631                                      SSL3_BUFFER_get_len(wb), 0)
632                 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
633                                                     + prefix_len, NULL)) {
634             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
635             goto err;
636         }
637         wpinited = 1;
638     } else {
639         for (j = 0; j < numpipes; j++) {
640             thispkt = &pkt[j];
641 
642             wb = &s->rlayer.wbuf[j];
643 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
644             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
645             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
646 #endif
647             SSL3_BUFFER_set_offset(wb, align);
648             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
649                                          SSL3_BUFFER_get_len(wb), 0)
650                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
651                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
652                 goto err;
653             }
654             wpinited++;
655         }
656     }
657 
658     /* Explicit IV length, block ciphers appropriate version flag */
659     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
660         && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
661         int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
662         if (mode == EVP_CIPH_CBC_MODE) {
663             eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
664             if (eivlen < 0) {
665                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
666                 goto err;
667 	    }
668             if (eivlen <= 1)
669                 eivlen = 0;
670         } else if (mode == EVP_CIPH_GCM_MODE) {
671             /* Need explicit part of IV for GCM mode */
672             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
673         } else if (mode == EVP_CIPH_CCM_MODE) {
674             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
675         }
676     }
677 
678  wpacket_init_complete:
679 
680     totlen = 0;
681     /* Clear our SSL3_RECORD structures */
682     memset(wr, 0, sizeof(wr));
683     for (j = 0; j < numpipes; j++) {
684         unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
685                                                               : s->version;
686         unsigned char *compressdata = NULL;
687         size_t maxcomplen;
688         unsigned int rectype;
689 
690         thispkt = &pkt[j];
691         thiswr = &wr[j];
692 
693         /*
694          * In TLSv1.3, once encrypting, we always use application data for the
695          * record type
696          */
697         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
698                 && s->enc_write_ctx != NULL
699                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
700                     || type != SSL3_RT_ALERT))
701             rectype = SSL3_RT_APPLICATION_DATA;
702         else
703             rectype = type;
704         SSL3_RECORD_set_type(thiswr, rectype);
705 
706         /*
707          * Some servers hang if initial client hello is larger than 256 bytes
708          * and record version number > TLS 1.0
709          */
710         if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
711                 && !s->renegotiate
712                 && TLS1_get_version(ssl) > TLS1_VERSION
713                 && s->hello_retry_request == SSL_HRR_NONE)
714             version = TLS1_VERSION;
715         SSL3_RECORD_set_rec_version(thiswr, version);
716 
717         maxcomplen = pipelens[j];
718         if (s->compress != NULL)
719             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
720 
721         /*
722          * When using offload kernel will write the header.
723          * Otherwise write the header now
724          */
725         if (!using_ktls
726                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
727                 || !WPACKET_put_bytes_u16(thispkt, version)
728                 || !WPACKET_start_sub_packet_u16(thispkt)
729                 || (eivlen > 0
730                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
731                 || (maxcomplen > 0
732                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
733                                               &compressdata)))) {
734             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
735             goto err;
736         }
737 
738         /* lets setup the record stuff. */
739         SSL3_RECORD_set_data(thiswr, compressdata);
740         SSL3_RECORD_set_length(thiswr, pipelens[j]);
741         SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
742         totlen += pipelens[j];
743 
744         /*
745          * we now 'read' from thiswr->input, thiswr->length bytes into
746          * thiswr->data
747          */
748 
749         /* first we compress */
750         if (s->compress != NULL) {
751             if (!ssl3_do_compress(s, thiswr)
752                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
753                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
754                 goto err;
755             }
756         } else {
757             if (using_ktls) {
758                 SSL3_RECORD_reset_data(&wr[j]);
759             } else {
760                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
761                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
762                     goto err;
763                 }
764                 SSL3_RECORD_reset_input(&wr[j]);
765             }
766         }
767 
768         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
769                 && !using_ktls
770                 && s->enc_write_ctx != NULL
771                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
772                     || type != SSL3_RT_ALERT)) {
773             size_t rlen, max_send_fragment;
774 
775             if (!WPACKET_put_bytes_u8(thispkt, type)) {
776                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
777                 goto err;
778             }
779             SSL3_RECORD_add_length(thiswr, 1);
780 
781             /* Add TLS1.3 padding */
782             max_send_fragment = ssl_get_max_send_fragment(s);
783             rlen = SSL3_RECORD_get_length(thiswr);
784             if (rlen < max_send_fragment) {
785                 size_t padding = 0;
786                 size_t max_padding = max_send_fragment - rlen;
787                 if (s->record_padding_cb != NULL) {
788                     padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
789                 } else if (s->block_padding > 0) {
790                     size_t mask = s->block_padding - 1;
791                     size_t remainder;
792 
793                     /* optimize for power of 2 */
794                     if ((s->block_padding & mask) == 0)
795                         remainder = rlen & mask;
796                     else
797                         remainder = rlen % s->block_padding;
798                     /* don't want to add a block of padding if we don't have to */
799                     if (remainder == 0)
800                         padding = 0;
801                     else
802                         padding = s->block_padding - remainder;
803                 }
804                 if (padding > 0) {
805                     /* do not allow the record to exceed max plaintext length */
806                     if (padding > max_padding)
807                         padding = max_padding;
808                     if (!WPACKET_memset(thispkt, 0, padding)) {
809                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
810                                  ERR_R_INTERNAL_ERROR);
811                         goto err;
812                     }
813                     SSL3_RECORD_add_length(thiswr, padding);
814                 }
815             }
816         }
817 
818         /*
819          * we should still have the output to thiswr->data and the input from
820          * wr->input. Length should be thiswr->length. thiswr->data still points
821          * in the wb->buf
822          */
823 
824         if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
825             unsigned char *mac;
826 
827             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
828                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
829                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
830                 goto err;
831             }
832         }
833 
834         /*
835          * Reserve some bytes for any growth that may occur during encryption.
836          * This will be at most one cipher block or the tag length if using
837          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
838          */
839         if (!using_ktls) {
840             if (!WPACKET_reserve_bytes(thispkt,
841                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
842                                         NULL)
843                 /*
844                  * We also need next the amount of bytes written to this
845                  * sub-packet
846                  */
847                 || !WPACKET_get_length(thispkt, &len)) {
848             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
849             goto err;
850             }
851 
852             /* Get a pointer to the start of this record excluding header */
853             recordstart = WPACKET_get_curr(thispkt) - len;
854             SSL3_RECORD_set_data(thiswr, recordstart);
855             SSL3_RECORD_reset_input(thiswr);
856             SSL3_RECORD_set_length(thiswr, len);
857         }
858     }
859 
860     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
861         /*
862          * We haven't actually negotiated the version yet, but we're trying to
863          * send early data - so we need to use the tls13enc function.
864          */
865         if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
866             if (!ossl_statem_in_error(s)) {
867                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
868             }
869             goto err;
870         }
871     } else {
872         if (!using_ktls) {
873             if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
874                                          mac_size) < 1) {
875                 if (!ossl_statem_in_error(s)) {
876                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
877                 }
878                 goto err;
879             }
880         }
881     }
882 
883     for (j = 0; j < numpipes; j++) {
884         size_t origlen;
885 
886         thispkt = &pkt[j];
887         thiswr = &wr[j];
888 
889         if (using_ktls)
890             goto mac_done;
891 
892         /* Allocate bytes for the encryption overhead */
893         if (!WPACKET_get_length(thispkt, &origlen)
894                    /* Encryption should never shrink the data! */
895                 || origlen > thiswr->length
896                 || (thiswr->length > origlen
897                     && !WPACKET_allocate_bytes(thispkt,
898                                                thiswr->length - origlen,
899                                                NULL))) {
900             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
901             goto err;
902         }
903         if (SSL_WRITE_ETM(s) && mac_size != 0) {
904             unsigned char *mac;
905 
906             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
907                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
908                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
909                 goto err;
910             }
911             SSL3_RECORD_add_length(thiswr, mac_size);
912         }
913 
914         if (!WPACKET_get_length(thispkt, &len)
915                 || !WPACKET_close(thispkt)) {
916             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
917             goto err;
918         }
919 
920         if (s->msg_callback) {
921             recordstart = WPACKET_get_curr(thispkt) - len
922                           - SSL3_RT_HEADER_LENGTH;
923             s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
924                             SSL3_RT_HEADER_LENGTH, ssl,
925                             s->msg_callback_arg);
926 
927             if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
928                 unsigned char ctype = type;
929 
930                 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
931                                 &ctype, 1, ssl, s->msg_callback_arg);
932             }
933         }
934 
935         if (!WPACKET_finish(thispkt)) {
936             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
937             goto err;
938         }
939 
940         /* header is added by the kernel when using offload */
941         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
942 
943         if (create_empty_fragment) {
944             /*
945              * we are in a recursive call; just return the length, don't write
946              * out anything here
947              */
948             if (j > 0) {
949                 /* We should never be pipelining an empty fragment!! */
950                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
951                 goto err;
952             }
953             *written = SSL3_RECORD_get_length(thiswr);
954             return 1;
955         }
956 
957  mac_done:
958         /*
959          * we should now have thiswr->data pointing to the encrypted data, which
960          * is thiswr->length long
961          */
962         SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
963                                              * debugging */
964 
965         /* now let's set up wb */
966         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
967                              prefix_len + SSL3_RECORD_get_length(thiswr));
968     }
969 
970     /*
971      * memorize arguments so that ssl3_write_pending can detect bad write
972      * retries later
973      */
974     s->rlayer.wpend_tot = totlen;
975     s->rlayer.wpend_buf = buf;
976     s->rlayer.wpend_type = type;
977     s->rlayer.wpend_ret = totlen;
978 
979     /* we now just need to write the buffer */
980     return ssl3_write_pending(s, type, buf, totlen, written);
981  err:
982     for (j = 0; j < wpinited; j++)
983         WPACKET_cleanup(&pkt[j]);
984     return -1;
985 }
986 
987 /* if SSL3_BUFFER_get_left() != 0, we need to call this
988  *
989  * Return values are as per SSL_write()
990  */
ssl3_write_pending(SSL_CONNECTION * s,int type,const unsigned char * buf,size_t len,size_t * written)991 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
992                        size_t len, size_t *written)
993 {
994     int i;
995     SSL3_BUFFER *wb = s->rlayer.wbuf;
996     size_t currbuf = 0;
997     size_t tmpwrit = 0;
998 
999     if ((s->rlayer.wpend_tot > len)
1000         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1001             && (s->rlayer.wpend_buf != buf))
1002         || (s->rlayer.wpend_type != type)) {
1003         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1004         return -1;
1005     }
1006 
1007     for (;;) {
1008         /* Loop until we find a buffer we haven't written out yet */
1009         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1010             && currbuf < s->rlayer.numwpipes - 1) {
1011             currbuf++;
1012             continue;
1013         }
1014         clear_sys_error();
1015         if (s->wbio != NULL) {
1016             s->rwstate = SSL_WRITING;
1017 
1018             /*
1019              * To prevent coalescing of control and data messages,
1020              * such as in buffer_write, we flush the BIO
1021              */
1022             if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1023                 i = BIO_flush(s->wbio);
1024                 if (i <= 0)
1025                     return i;
1026                 BIO_set_ktls_ctrl_msg(s->wbio, type);
1027             }
1028             i = BIO_write(s->wbio, (char *)
1029                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
1030                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1031                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1032             if (i >= 0)
1033                 tmpwrit = i;
1034         } else {
1035             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1036             i = -1;
1037         }
1038 
1039         /*
1040          * When an empty fragment is sent on a connection using KTLS,
1041          * it is sent as a write of zero bytes.  If this zero byte
1042          * write succeeds, i will be 0 rather than a non-zero value.
1043          * Treat i == 0 as success rather than an error for zero byte
1044          * writes to permit this case.
1045          */
1046         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1047             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1048             SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1049             if (currbuf + 1 < s->rlayer.numwpipes)
1050                 continue;
1051             s->rwstate = SSL_NOTHING;
1052             *written = s->rlayer.wpend_ret;
1053             return 1;
1054         } else if (i <= 0) {
1055             if (SSL_CONNECTION_IS_DTLS(s)) {
1056                 /*
1057                  * For DTLS, just drop it. That's kind of the whole point in
1058                  * using a datagram service
1059                  */
1060                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1061             }
1062             return i;
1063         }
1064         SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1065         SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1066     }
1067 }
1068 
ossl_tls_handle_rlayer_return(SSL_CONNECTION * s,int ret,char * file,int line)1069 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1070                                   int line)
1071 {
1072     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1073 
1074     if (ret == OSSL_RECORD_RETURN_RETRY) {
1075         s->rwstate = SSL_READING;
1076         ret = -1;
1077     } else {
1078         s->rwstate = SSL_NOTHING;
1079         if (ret == OSSL_RECORD_RETURN_EOF) {
1080             if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1081                 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1082                 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1083             } else {
1084                 ERR_new();
1085                 ERR_set_debug(file, line, 0);
1086                 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1087                                   SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1088             }
1089         } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1090             int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
1091 
1092             if (al != SSL_AD_NO_ALERT) {
1093                 ERR_new();
1094                 ERR_set_debug(file, line, 0);
1095                 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
1096             }
1097             /*
1098              * else some failure but there is no alert code. We don't log an
1099              * error for this. The record layer should have logged an error
1100              * already or, if not, its due to some sys call error which will be
1101              * reported via SSL_ERROR_SYSCALL and errno.
1102              */
1103         }
1104         /*
1105          * The record layer distinguishes the cases of EOF, non-fatal
1106          * err and retry. Upper layers do not.
1107          * If we got a retry or success then *ret is already correct,
1108          * otherwise we need to convert the return value.
1109          */
1110         if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1111             ret = 0;
1112         else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1113             ret = -1;
1114     }
1115 
1116     return ret;
1117 }
1118 
ssl_release_record(SSL_CONNECTION * s,TLS_RECORD * rr)1119 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1120 {
1121     if (rr->rechandle != NULL) {
1122         /* The record layer allocated the buffers for this record */
1123         s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
1124     } else {
1125         /* We allocated the buffers for this record (only happens with DTLS) */
1126         OPENSSL_free(rr->data);
1127     }
1128     s->rlayer.curr_rec++;
1129 }
1130 
1131 /*-
1132  * Return up to 'len' payload bytes received in 'type' records.
1133  * 'type' is one of the following:
1134  *
1135  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1136  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1137  *   -  0 (during a shutdown, no data has to be returned)
1138  *
1139  * If we don't have stored data to work from, read a SSL/TLS record first
1140  * (possibly multiple records if we still don't have anything to return).
1141  *
1142  * This function must handle any surprises the peer may have for us, such as
1143  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1144  * messages are treated as if they were handshake messages *if* the |recvd_type|
1145  * argument is non NULL.
1146  * Also if record payloads contain fragments too small to process, we store
1147  * them until there is enough for the respective protocol (the record protocol
1148  * may use arbitrary fragmentation and even interleaving):
1149  *     Change cipher spec protocol
1150  *             just 1 byte needed, no need for keeping anything stored
1151  *     Alert protocol
1152  *             2 bytes needed (AlertLevel, AlertDescription)
1153  *     Handshake protocol
1154  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1155  *             to detect unexpected Client Hello and Hello Request messages
1156  *             here, anything else is handled by higher layers
1157  *     Application data protocol
1158  *             none of our business
1159  */
ssl3_read_bytes(SSL * ssl,int type,int * recvd_type,unsigned char * buf,size_t len,int peek,size_t * readbytes)1160 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1161                     size_t len, int peek, size_t *readbytes)
1162 {
1163     int i, j, ret;
1164     size_t n, curr_rec, totalbytes;
1165     TLS_RECORD *rr;
1166     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1167     int is_tls13;
1168     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1169 
1170     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1171 
1172     if ((type != 0
1173             && (type != SSL3_RT_APPLICATION_DATA)
1174             && (type != SSL3_RT_HANDSHAKE))
1175         || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1176         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1177         return -1;
1178     }
1179 
1180     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1181         /* (partially) satisfy request from storage */
1182     {
1183         unsigned char *src = s->rlayer.handshake_fragment;
1184         unsigned char *dst = buf;
1185         unsigned int k;
1186 
1187         /* peek == 0 */
1188         n = 0;
1189         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1190             *dst++ = *src++;
1191             len--;
1192             s->rlayer.handshake_fragment_len--;
1193             n++;
1194         }
1195         /* move any remaining fragment bytes: */
1196         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1197             s->rlayer.handshake_fragment[k] = *src++;
1198 
1199         if (recvd_type != NULL)
1200             *recvd_type = SSL3_RT_HANDSHAKE;
1201 
1202         *readbytes = n;
1203         return 1;
1204     }
1205 
1206     /*
1207      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1208      */
1209 
1210     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1211         /* type == SSL3_RT_APPLICATION_DATA */
1212         i = s->handshake_func(ssl);
1213         /* SSLfatal() already called */
1214         if (i < 0)
1215             return i;
1216         if (i == 0)
1217             return -1;
1218     }
1219  start:
1220     s->rwstate = SSL_NOTHING;
1221 
1222     /*-
1223      * For each record 'i' up to |num_recs]
1224      * rr[i].type     - is the type of record
1225      * rr[i].data,    - data
1226      * rr[i].off,     - offset into 'data' for next read
1227      * rr[i].length,  - number of bytes.
1228      */
1229     /* get new records if necessary */
1230     if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1231         s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1232         do {
1233             rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1234 
1235             ret = HANDLE_RLAYER_RETURN(s,
1236                     s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
1237                                                      &rr->rechandle,
1238                                                      &rr->version, &rr->type,
1239                                                      &rr->data, &rr->length,
1240                                                      NULL, NULL));
1241             if (ret <= 0) {
1242                 /* SSLfatal() already called if appropriate */
1243                 return ret;
1244             }
1245             rr->off = 0;
1246             s->rlayer.num_recs++;
1247         } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
1248                  && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1249     }
1250     rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1251 
1252     if (s->rlayer.handshake_fragment_len > 0
1253             && rr->type != SSL3_RT_HANDSHAKE
1254             && SSL_CONNECTION_IS_TLS13(s)) {
1255         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1256                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1257         return -1;
1258     }
1259 
1260     /*
1261      * Reset the count of consecutive warning alerts if we've got a non-empty
1262      * record that isn't an alert.
1263      */
1264     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1265         s->rlayer.alert_count = 0;
1266 
1267     /* we now have a packet which can be read and processed */
1268 
1269     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1270                                   * reset by ssl3_get_finished */
1271         && (rr->type != SSL3_RT_HANDSHAKE)) {
1272         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1273                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1274         return -1;
1275     }
1276 
1277     /*
1278      * If the other end has shut down, throw anything we read away (even in
1279      * 'peek' mode)
1280      */
1281     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1282         s->rlayer.curr_rec++;
1283         s->rwstate = SSL_NOTHING;
1284         return 0;
1285     }
1286 
1287     if (type == rr->type
1288         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1289             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1290             && !is_tls13)) {
1291         /*
1292          * SSL3_RT_APPLICATION_DATA or
1293          * SSL3_RT_HANDSHAKE or
1294          * SSL3_RT_CHANGE_CIPHER_SPEC
1295          */
1296         /*
1297          * make sure that we are not getting application data when we are
1298          * doing a handshake for the first time
1299          */
1300         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1301             && s->enc_read_ctx == NULL) {
1302             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1303             return -1;
1304         }
1305 
1306         if (type == SSL3_RT_HANDSHAKE
1307             && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1308             && s->rlayer.handshake_fragment_len > 0) {
1309             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1310             return -1;
1311         }
1312 
1313         if (recvd_type != NULL)
1314             *recvd_type = rr->type;
1315 
1316         if (len == 0) {
1317             /*
1318              * Skip a zero length record. This ensures multiple calls to
1319              * SSL_read() with a zero length buffer will eventually cause
1320              * SSL_pending() to report data as being available.
1321              */
1322             if (rr->length == 0)
1323                 ssl_release_record(s, rr);
1324 
1325             return 0;
1326         }
1327 
1328         totalbytes = 0;
1329         curr_rec = s->rlayer.curr_rec;
1330         do {
1331             if (len - totalbytes > rr->length)
1332                 n = rr->length;
1333             else
1334                 n = len - totalbytes;
1335 
1336             memcpy(buf, &(rr->data[rr->off]), n);
1337             buf += n;
1338             if (peek) {
1339                 /* Mark any zero length record as consumed CVE-2016-6305 */
1340                 if (rr->length == 0)
1341                     ssl_release_record(s, rr);
1342             } else {
1343                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1344                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
1345                 rr->length -= n;
1346                 rr->off += n;
1347                 if (rr->length == 0)
1348                     ssl_release_record(s, rr);
1349             }
1350             if (rr->length == 0
1351                 || (peek && n == rr->length)) {
1352                 rr++;
1353                 curr_rec++;
1354             }
1355             totalbytes += n;
1356         } while (type == SSL3_RT_APPLICATION_DATA
1357                     && curr_rec < s->rlayer.num_recs
1358                     && totalbytes < len);
1359         if (totalbytes == 0) {
1360             /* We must have read empty records. Get more data */
1361             goto start;
1362         }
1363         *readbytes = totalbytes;
1364         return 1;
1365     }
1366 
1367     /*
1368      * If we get here, then type != rr->type; if we have a handshake message,
1369      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1370      * were actually expecting a CCS).
1371      */
1372 
1373     /*
1374      * Lets just double check that we've not got an SSLv2 record
1375      */
1376     if (rr->version == SSL2_VERSION) {
1377         /*
1378          * Should never happen. ssl3_get_record() should only give us an SSLv2
1379          * record back if this is the first packet and we are looking for an
1380          * initial ClientHello. Therefore |type| should always be equal to
1381          * |rr->type|. If not then something has gone horribly wrong
1382          */
1383         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1384         return -1;
1385     }
1386 
1387     if (ssl->method->version == TLS_ANY_VERSION
1388         && (s->server || rr->type != SSL3_RT_ALERT)) {
1389         /*
1390          * If we've got this far and still haven't decided on what version
1391          * we're using then this must be a client side alert we're dealing
1392          * with. We shouldn't be receiving anything other than a ClientHello
1393          * if we are a server.
1394          */
1395         s->version = rr->version;
1396         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1397         return -1;
1398     }
1399 
1400     /*-
1401      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1402      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1403      */
1404 
1405     if (rr->type == SSL3_RT_ALERT) {
1406         unsigned int alert_level, alert_descr;
1407         unsigned char *alert_bytes = rr->data
1408                                      + rr->off;
1409         PACKET alert;
1410 
1411         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1412                 || !PACKET_get_1(&alert, &alert_level)
1413                 || !PACKET_get_1(&alert, &alert_descr)
1414                 || PACKET_remaining(&alert) != 0) {
1415             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1416             return -1;
1417         }
1418 
1419         if (s->msg_callback)
1420             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1421                             s->msg_callback_arg);
1422 
1423         if (s->info_callback != NULL)
1424             cb = s->info_callback;
1425         else if (ssl->ctx->info_callback != NULL)
1426             cb = ssl->ctx->info_callback;
1427 
1428         if (cb != NULL) {
1429             j = (alert_level << 8) | alert_descr;
1430             cb(ssl, SSL_CB_READ_ALERT, j);
1431         }
1432 
1433         if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1434                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1435             s->s3.warn_alert = alert_descr;
1436             ssl_release_record(s, rr);
1437 
1438             s->rlayer.alert_count++;
1439             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1440                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1441                          SSL_R_TOO_MANY_WARN_ALERTS);
1442                 return -1;
1443             }
1444         }
1445 
1446         /*
1447          * Apart from close_notify the only other warning alert in TLSv1.3
1448          * is user_cancelled - which we just ignore.
1449          */
1450         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1451             goto start;
1452         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1453                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1454             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1455             return 0;
1456         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1457             s->rwstate = SSL_NOTHING;
1458             s->s3.fatal_alert = alert_descr;
1459             SSLfatal_data(s, SSL_AD_NO_ALERT,
1460                           SSL_AD_REASON_OFFSET + alert_descr,
1461                           "SSL alert number %d", alert_descr);
1462             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1463             ssl_release_record(s, rr);
1464             SSL_CTX_remove_session(s->session_ctx, s->session);
1465             return 0;
1466         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1467             /*
1468              * This is a warning but we receive it if we requested
1469              * renegotiation and the peer denied it. Terminate with a fatal
1470              * alert because if application tried to renegotiate it
1471              * presumably had a good reason and expects it to succeed. In
1472              * future we might have a renegotiation where we don't care if
1473              * the peer refused it where we carry on.
1474              */
1475             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1476             return -1;
1477         } else if (alert_level == SSL3_AL_WARNING) {
1478             /* We ignore any other warning alert in TLSv1.2 and below */
1479             goto start;
1480         }
1481 
1482         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1483         return -1;
1484     }
1485 
1486     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1487         if (rr->type == SSL3_RT_HANDSHAKE) {
1488             BIO *rbio;
1489 
1490             /*
1491              * We ignore any handshake messages sent to us unless they are
1492              * TLSv1.3 in which case we want to process them. For all other
1493              * handshake messages we can't do anything reasonable with them
1494              * because we are unable to write any response due to having already
1495              * sent close_notify.
1496              */
1497             if (!SSL_CONNECTION_IS_TLS13(s)) {
1498                 ssl_release_record(s, rr);
1499 
1500                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1501                     goto start;
1502 
1503                 s->rwstate = SSL_READING;
1504                 rbio = SSL_get_rbio(ssl);
1505                 BIO_clear_retry_flags(rbio);
1506                 BIO_set_retry_read(rbio);
1507                 return -1;
1508             }
1509         } else {
1510             /*
1511              * The peer is continuing to send application data, but we have
1512              * already sent close_notify. If this was expected we should have
1513              * been called via SSL_read() and this would have been handled
1514              * above.
1515              * No alert sent because we already sent close_notify
1516              */
1517             ssl_release_record(s, rr);
1518             SSLfatal(s, SSL_AD_NO_ALERT,
1519                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1520             return -1;
1521         }
1522     }
1523 
1524     /*
1525      * For handshake data we have 'fragment' storage, so fill that so that we
1526      * can process the header at a fixed place. This is done after the
1527      * "SHUTDOWN" code above to avoid filling the fragment storage with data
1528      * that we're just going to discard.
1529      */
1530     if (rr->type == SSL3_RT_HANDSHAKE) {
1531         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1532         unsigned char *dest = s->rlayer.handshake_fragment;
1533         size_t *dest_len = &s->rlayer.handshake_fragment_len;
1534 
1535         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1536         if (rr->length < n)
1537             n = rr->length; /* available bytes */
1538 
1539         /* now move 'n' bytes: */
1540         memcpy(dest + *dest_len, rr->data + rr->off, n);
1541         rr->off += n;
1542         rr->length -= n;
1543         *dest_len += n;
1544         if (rr->length == 0)
1545             ssl_release_record(s, rr);
1546 
1547         if (*dest_len < dest_maxlen)
1548             goto start;     /* fragment was too small */
1549     }
1550 
1551     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1552         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1553         return -1;
1554     }
1555 
1556     /*
1557      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1558      * protocol violation)
1559      */
1560     if ((s->rlayer.handshake_fragment_len >= 4)
1561             && !ossl_statem_get_in_handshake(s)) {
1562         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1563 
1564         /* We found handshake data, so we're going back into init */
1565         ossl_statem_set_in_init(s, 1);
1566 
1567         i = s->handshake_func(ssl);
1568         /* SSLfatal() already called if appropriate */
1569         if (i < 0)
1570             return i;
1571         if (i == 0) {
1572             return -1;
1573         }
1574 
1575         /*
1576          * If we were actually trying to read early data and we found a
1577          * handshake message, then we don't want to continue to try and read
1578          * the application data any more. It won't be "early" now.
1579          */
1580         if (ined)
1581             return -1;
1582 
1583         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1584             if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1585                 BIO *bio;
1586                 /*
1587                  * In the case where we try to read application data, but we
1588                  * trigger an SSL handshake, we return -1 with the retry
1589                  * option set.  Otherwise renegotiation may cause nasty
1590                  * problems in the blocking world
1591                  */
1592                 s->rwstate = SSL_READING;
1593                 bio = SSL_get_rbio(ssl);
1594                 BIO_clear_retry_flags(bio);
1595                 BIO_set_retry_read(bio);
1596                 return -1;
1597             }
1598         }
1599         goto start;
1600     }
1601 
1602     switch (rr->type) {
1603     default:
1604         /*
1605          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1606          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1607          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1608          * no progress is being made and the peer continually sends unrecognised
1609          * record types, using up resources processing them.
1610          */
1611         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1612         return -1;
1613     case SSL3_RT_CHANGE_CIPHER_SPEC:
1614     case SSL3_RT_ALERT:
1615     case SSL3_RT_HANDSHAKE:
1616         /*
1617          * we already handled all of these, with the possible exception of
1618          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1619          * that should not happen when type != rr->type
1620          */
1621         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1622         return -1;
1623     case SSL3_RT_APPLICATION_DATA:
1624         /*
1625          * At this point, we were expecting handshake data, but have
1626          * application data.  If the library was running inside ssl3_read()
1627          * (i.e. in_read_app_data is set) and it makes sense to read
1628          * application data at this point (session renegotiation not yet
1629          * started), we will indulge it.
1630          */
1631         if (ossl_statem_app_data_allowed(s)) {
1632             s->s3.in_read_app_data = 2;
1633             return -1;
1634         } else if (ossl_statem_skip_early_data(s)) {
1635             /*
1636              * This can happen after a client sends a CH followed by early_data,
1637              * but the server responds with a HelloRetryRequest. The server
1638              * reads the next record from the client expecting to find a
1639              * plaintext ClientHello but gets a record which appears to be
1640              * application data. The trial decrypt "works" because null
1641              * decryption was applied. We just skip it and move on to the next
1642              * record.
1643              */
1644             if (!ossl_early_data_count_ok(s, rr->length,
1645                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1646                 /* SSLfatal() already called */
1647                 return -1;
1648             }
1649             ssl_release_record(s, rr);
1650             goto start;
1651         } else {
1652             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1653             return -1;
1654         }
1655     }
1656 }
1657 
ssl3_record_sequence_update(unsigned char * seq)1658 void ssl3_record_sequence_update(unsigned char *seq)
1659 {
1660     int i;
1661 
1662     for (i = 7; i >= 0; i--) {
1663         ++seq[i];
1664         if (seq[i] != 0)
1665             break;
1666     }
1667 }
1668 
1669 /*
1670  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1671  * format and false otherwise.
1672  */
RECORD_LAYER_is_sslv2_record(RECORD_LAYER * rl)1673 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1674 {
1675     if (SSL_CONNECTION_IS_DTLS(rl->s))
1676         return 0;
1677     return rl->tlsrecs[0].version == SSL2_VERSION;
1678 }
1679 
1680 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
rlayer_msg_callback_wrapper(int write_p,int version,int content_type,const void * buf,size_t len,void * cbarg)1681 static void rlayer_msg_callback_wrapper(int write_p, int version,
1682                                         int content_type, const void *buf,
1683                                         size_t len, void *cbarg)
1684 {
1685     SSL_CONNECTION *s = cbarg;
1686     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1687 
1688     if (s->msg_callback != NULL)
1689         s->msg_callback(write_p, version, content_type, buf, len, ssl,
1690                         s->msg_callback_arg);
1691 }
1692 
1693 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
rlayer_security_wrapper(void * cbarg,int op,int bits,int nid,void * other)1694 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1695                                    void *other)
1696 {
1697     SSL_CONNECTION *s = cbarg;
1698 
1699     return ssl_security(s, op, bits, nid, other);
1700 }
1701 
1702 static const OSSL_DISPATCH rlayer_dispatch[] = {
1703     { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1704     { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1705     { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1706     { 0, NULL }
1707 };
1708 
ssl_select_next_record_layer(SSL_CONNECTION * s,int level)1709 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1710                                                               int level)
1711 {
1712 
1713     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1714         if (SSL_CONNECTION_IS_DTLS(s))
1715             return &ossl_dtls_record_method;
1716 
1717         return &ossl_tls_record_method;
1718     }
1719 
1720 #ifndef OPENSSL_NO_KTLS
1721     /* KTLS does not support renegotiation */
1722     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1723             && (s->options & SSL_OP_ENABLE_KTLS) != 0
1724             && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1725         return &ossl_ktls_record_method;
1726 #endif
1727 
1728     /* Default to the current OSSL_RECORD_METHOD */
1729     return s->rlayer.rrlmethod;
1730 }
1731 
ssl_post_record_layer_select(SSL_CONNECTION * s)1732 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1733 {
1734 #ifndef OPENSSL_NO_KTLS
1735     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1736 
1737     if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1738         /* KTLS does not support renegotiation so disallow it */
1739         SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1740     }
1741 #endif
1742     if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
1743         s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
1744 
1745     if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
1746         s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
1747 
1748     return 1;
1749 }
1750 
ssl_set_new_record_layer(SSL_CONNECTION * s,int version,int direction,int level,unsigned char * key,size_t keylen,unsigned char * iv,size_t ivlen,unsigned char * mackey,size_t mackeylen,const EVP_CIPHER * ciph,size_t taglen,int mactype,const EVP_MD * md,const SSL_COMP * comp)1751 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1752                              int direction, int level,
1753                              unsigned char *key, size_t keylen,
1754                              unsigned char *iv,  size_t ivlen,
1755                              unsigned char *mackey, size_t mackeylen,
1756                              const EVP_CIPHER *ciph, size_t taglen,
1757                              int mactype, const EVP_MD *md,
1758                              const SSL_COMP *comp)
1759 {
1760     OSSL_PARAM options[5], *opts = options;
1761     OSSL_PARAM settings[6], *set =  settings;
1762     const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1763     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1764     const OSSL_RECORD_METHOD *meth;
1765     int use_etm, stream_mac = 0, tlstree = 0;
1766     unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1767     int use_early_data = 0;
1768     uint32_t max_early_data;
1769 
1770     meth = ssl_select_next_record_layer(s, level);
1771 
1772     if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
1773         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1774         return 0;
1775     }
1776 
1777     s->rlayer.rrl = NULL;
1778     if (meth != NULL)
1779         s->rlayer.rrlmethod = meth;
1780 
1781     if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
1782         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1783         return 0;
1784     }
1785 
1786     /* Parameters that *may* be supported by a record layer if passed */
1787     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1788                                           &s->options);
1789     *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1790                                           &s->mode);
1791     *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1792                                           &s->rlayer.default_read_buf_len);
1793     *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1794                                        &s->rlayer.read_ahead);
1795     *opts = OSSL_PARAM_construct_end();
1796 
1797     /* Parameters that *must* be supported by a record layer if passed */
1798     if (direction == OSSL_RECORD_DIRECTION_READ) {
1799         use_etm = SSL_READ_ETM(s) ? 1 : 0;
1800         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1801             stream_mac = 1;
1802 
1803         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1804             tlstree = 1;
1805     } else {
1806         use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1807         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1808             stream_mac = 1;
1809 
1810         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1811             tlstree = 1;
1812     }
1813 
1814     if (use_etm)
1815         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1816                                           &use_etm);
1817 
1818     if (stream_mac)
1819         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1820                                           &stream_mac);
1821 
1822     if (tlstree)
1823         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1824                                           &tlstree);
1825 
1826     if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1827         maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1828 
1829     if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1830         *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1831                                            &maxfrag);
1832 
1833     /*
1834      * The record layer must check the amount of early data sent or received
1835      * using the early keys. A server also needs to worry about rejected early
1836      * data that might arrive when the handshake keys are in force.
1837      */
1838     /* TODO(RECLAYER): Check this when doing the "write" record layer */
1839     if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1840         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1841                           || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1842     } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1843         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1844     }
1845     if (use_early_data) {
1846         max_early_data = ossl_get_max_early_data(s);
1847 
1848         if (max_early_data != 0)
1849             *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1850                                             &max_early_data);
1851     }
1852 
1853     *set = OSSL_PARAM_construct_end();
1854 
1855     for (;;) {
1856         int rlret;
1857         BIO *prev = s->rlayer.rrlnext;
1858         unsigned int epoch = 0;;
1859 
1860         if (SSL_CONNECTION_IS_DTLS(s)
1861                 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1862             epoch =  DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1863 
1864         if (SSL_CONNECTION_IS_DTLS(s))
1865             s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
1866         else
1867             s->rlayer.rrlnext = BIO_new(BIO_s_mem());
1868 
1869         if (s->rlayer.rrlnext == NULL) {
1870             BIO_free(prev);
1871             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1872             return 0;
1873         }
1874 
1875         rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
1876                                                       sctx->propq,
1877                                                       version, s->server,
1878                                                       direction, level, epoch,
1879                                                       key, keylen, iv, ivlen,
1880                                                       mackey, mackeylen, ciph,
1881                                                       taglen, mactype, md, comp,
1882                                                       prev, s->rbio,
1883                                                       s->rlayer.rrlnext, NULL,
1884                                                       NULL, settings, options,
1885                                                       rlayer_dispatch, s,
1886                                                       &s->rlayer.rrl);
1887         BIO_free(prev);
1888         switch (rlret) {
1889         case OSSL_RECORD_RETURN_FATAL:
1890             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1891             return 0;
1892 
1893         case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1894             if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
1895                 /*
1896                  * We tried a new record layer method, but it didn't work out,
1897                  * so we fallback to the original method and try again
1898                  */
1899                 s->rlayer.rrlmethod = origmeth;
1900                 continue;
1901             }
1902             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1903             return 0;
1904 
1905         case OSSL_RECORD_RETURN_SUCCESS:
1906             break;
1907 
1908         default:
1909             /* Should not happen */
1910             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1911             return 0;
1912         }
1913         break;
1914     }
1915 
1916     return ssl_post_record_layer_select(s);
1917 }
1918