xref: /freebsd/crypto/openssl/ssl/record/rec_layer_s3.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  * Copyright 1995-2025 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 "internal/e_os.h"
11 
12 #include <stdio.h>
13 #include <limits.h>
14 #include <errno.h>
15 #include <assert.h>
16 #include "../ssl_local.h"
17 #include "../quic/quic_local.h"
18 #include <openssl/evp.h>
19 #include <openssl/buffer.h>
20 #include <openssl/rand.h>
21 #include <openssl/core_names.h>
22 #include "record_local.h"
23 #include "internal/packet.h"
24 #include "internal/comp.h"
25 #include "internal/ssl_unwrap.h"
26 
RECORD_LAYER_init(RECORD_LAYER * rl,SSL_CONNECTION * s)27 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
28 {
29     rl->s = s;
30 }
31 
RECORD_LAYER_clear(RECORD_LAYER * rl)32 int RECORD_LAYER_clear(RECORD_LAYER *rl)
33 {
34     int ret = 1;
35 
36     /* Clear any buffered records we no longer need */
37     while (rl->curr_rec < rl->num_recs)
38         ret &= ssl_release_record(rl->s,
39                                   &(rl->tlsrecs[rl->curr_rec++]),
40                                   0);
41 
42 
43     rl->wnum = 0;
44     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
45     rl->handshake_fragment_len = 0;
46     rl->wpend_tot = 0;
47     rl->wpend_type = 0;
48     rl->wpend_buf = NULL;
49     rl->alert_count = 0;
50     rl->num_recs = 0;
51     rl->curr_rec = 0;
52 
53     BIO_free(rl->rrlnext);
54     rl->rrlnext = NULL;
55 
56     if (rl->rrlmethod != NULL)
57         rl->rrlmethod->free(rl->rrl); /* Ignore return value */
58     if (rl->wrlmethod != NULL)
59         rl->wrlmethod->free(rl->wrl); /* Ignore return value */
60     BIO_free(rl->rrlnext);
61     rl->rrlmethod = NULL;
62     rl->wrlmethod = NULL;
63     rl->rrlnext = NULL;
64     rl->rrl = NULL;
65     rl->wrl = NULL;
66 
67     if (rl->d)
68         DTLS_RECORD_LAYER_clear(rl);
69 
70     return ret;
71 }
72 
RECORD_LAYER_reset(RECORD_LAYER * rl)73 int RECORD_LAYER_reset(RECORD_LAYER *rl)
74 {
75     int ret;
76 
77     ret = RECORD_LAYER_clear(rl);
78 
79     /* We try and reset both record layers even if one fails */
80     ret &= ssl_set_new_record_layer(rl->s,
81                                     SSL_CONNECTION_IS_DTLS(rl->s)
82                                         ? DTLS_ANY_VERSION : TLS_ANY_VERSION,
83                                     OSSL_RECORD_DIRECTION_READ,
84                                     OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
85                                     NULL, 0, NULL, 0, NULL,  0, NULL, 0,
86                                     NID_undef, NULL, NULL, NULL);
87 
88     ret &= ssl_set_new_record_layer(rl->s,
89                                     SSL_CONNECTION_IS_DTLS(rl->s)
90                                         ? DTLS_ANY_VERSION : TLS_ANY_VERSION,
91                                     OSSL_RECORD_DIRECTION_WRITE,
92                                     OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
93                                     NULL, 0, NULL, 0, NULL,  0, NULL, 0,
94                                     NID_undef, NULL, NULL, NULL);
95 
96     /* SSLfatal already called in the event of failure */
97     return ret;
98 }
99 
100 /* Checks if we have unprocessed read ahead data pending */
RECORD_LAYER_read_pending(const RECORD_LAYER * rl)101 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
102 {
103     return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
104 }
105 
106 /* Checks if we have decrypted unread record data pending */
RECORD_LAYER_processed_read_pending(const RECORD_LAYER * rl)107 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
108 {
109     return (rl->curr_rec < rl->num_recs)
110            || rl->rrlmethod->processed_read_pending(rl->rrl);
111 }
112 
RECORD_LAYER_write_pending(const RECORD_LAYER * rl)113 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
114 {
115     return rl->wpend_tot > 0;
116 }
117 
ossl_get_max_early_data(SSL_CONNECTION * s)118 static uint32_t ossl_get_max_early_data(SSL_CONNECTION *s)
119 {
120     uint32_t max_early_data;
121     SSL_SESSION *sess = s->session;
122 
123     /*
124      * If we are a client then we always use the max_early_data from the
125      * session/psksession. Otherwise we go with the lowest out of the max early
126      * data set in the session and the configured max_early_data.
127      */
128     if (!s->server && sess->ext.max_early_data == 0) {
129         if (!ossl_assert(s->psksession != NULL
130                          && s->psksession->ext.max_early_data > 0)) {
131             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
132             return 0;
133         }
134         sess = s->psksession;
135     }
136 
137     if (!s->server)
138         max_early_data = sess->ext.max_early_data;
139     else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
140         max_early_data = s->recv_max_early_data;
141     else
142         max_early_data = s->recv_max_early_data < sess->ext.max_early_data
143                          ? s->recv_max_early_data : sess->ext.max_early_data;
144 
145     return max_early_data;
146 }
147 
ossl_early_data_count_ok(SSL_CONNECTION * s,size_t length,size_t overhead,int send)148 static int ossl_early_data_count_ok(SSL_CONNECTION *s, size_t length,
149                                     size_t overhead, int send)
150 {
151     uint32_t max_early_data;
152 
153     max_early_data = ossl_get_max_early_data(s);
154 
155     if (max_early_data == 0) {
156         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
157                  SSL_R_TOO_MUCH_EARLY_DATA);
158         return 0;
159     }
160 
161     /* If we are dealing with ciphertext we need to allow for the overhead */
162     max_early_data += overhead;
163 
164     if (s->early_data_count + length > max_early_data) {
165         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
166                  SSL_R_TOO_MUCH_EARLY_DATA);
167         return 0;
168     }
169     s->early_data_count += length;
170 
171     return 1;
172 }
173 
ssl3_pending(const SSL * s)174 size_t ssl3_pending(const SSL *s)
175 {
176     size_t i, num = 0;
177     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
178 
179     if (sc == NULL)
180         return 0;
181 
182     if (SSL_CONNECTION_IS_DTLS(sc)) {
183         TLS_RECORD *rdata;
184         pitem *item, *iter;
185 
186         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data);
187         while ((item = pqueue_next(&iter)) != NULL) {
188             rdata = item->data;
189             num += rdata->length;
190         }
191     }
192 
193     for (i = 0; i < sc->rlayer.num_recs; i++) {
194         if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
195             return num;
196         num += sc->rlayer.tlsrecs[i].length;
197     }
198 
199     num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
200 
201     return num;
202 }
203 
SSL_CTX_set_default_read_buffer_len(SSL_CTX * ctx,size_t len)204 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
205 {
206     ctx->default_read_buf_len = len;
207 }
208 
SSL_set_default_read_buffer_len(SSL * s,size_t len)209 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
210 {
211     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
212 
213     if (sc == NULL || IS_QUIC(s))
214         return;
215     sc->rlayer.default_read_buf_len = len;
216 }
217 
SSL_rstate_string_long(const SSL * s)218 const char *SSL_rstate_string_long(const SSL *s)
219 {
220     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
221     const char *lng;
222 
223     if (sc == NULL)
224         return NULL;
225 
226     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
227         return "unknown";
228 
229     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
230 
231     return lng;
232 }
233 
SSL_rstate_string(const SSL * s)234 const char *SSL_rstate_string(const SSL *s)
235 {
236     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
237     const char *shrt;
238 
239     if (sc == NULL)
240         return NULL;
241 
242     if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
243         return "unknown";
244 
245     sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
246 
247     return shrt;
248 }
249 
tls_write_check_pending(SSL_CONNECTION * s,uint8_t type,const unsigned char * buf,size_t len)250 static int tls_write_check_pending(SSL_CONNECTION *s, uint8_t type,
251                                    const unsigned char *buf, size_t len)
252 {
253     if (s->rlayer.wpend_tot == 0)
254         return 0;
255 
256     /* We have pending data, so do some sanity checks */
257     if ((s->rlayer.wpend_tot > len)
258         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
259             && (s->rlayer.wpend_buf != buf))
260         || (s->rlayer.wpend_type != type)) {
261         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
262         return -1;
263     }
264     return 1;
265 }
266 
267 /*
268  * Call this to write data in records of type 'type' It will return <= 0 if
269  * not all data has been sent or non-blocking IO.
270  */
ssl3_write_bytes(SSL * ssl,uint8_t type,const void * buf_,size_t len,size_t * written)271 int ssl3_write_bytes(SSL *ssl, uint8_t type, const void *buf_, size_t len,
272                      size_t *written)
273 {
274     const unsigned char *buf = buf_;
275     size_t tot;
276     size_t n, max_send_fragment, split_send_fragment, maxpipes;
277     int i;
278     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
279     OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
280     unsigned int recversion;
281 
282     if (s == NULL)
283         return -1;
284 
285     s->rwstate = SSL_NOTHING;
286     tot = s->rlayer.wnum;
287     /*
288      * ensure that if we end up with a smaller value of data to write out
289      * than the original len from a write which didn't complete for
290      * non-blocking I/O and also somehow ended up avoiding the check for
291      * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
292      * possible to end up with (len-tot) as a large number that will then
293      * promptly send beyond the end of the users buffer ... so we trap and
294      * report the error in a way the user will notice
295      */
296     if ((len < s->rlayer.wnum)
297         || ((s->rlayer.wpend_tot != 0)
298             && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
299         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
300         return -1;
301     }
302 
303     if (s->early_data_state == SSL_EARLY_DATA_WRITING
304             && !ossl_early_data_count_ok(s, len, 0, 1)) {
305         /* SSLfatal() already called */
306         return -1;
307     }
308 
309     s->rlayer.wnum = 0;
310 
311     /*
312      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
313      * into init unless we have writes pending - in which case we should finish
314      * doing that first.
315      */
316     if (s->rlayer.wpend_tot == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
317                                      || s->ext.extra_tickets_expected > 0))
318         ossl_statem_set_in_init(s, 1);
319 
320     /*
321      * When writing early data on the server side we could be "in_init" in
322      * between receiving the EoED and the CF - but we don't want to handle those
323      * messages yet.
324      */
325     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
326             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
327         i = s->handshake_func(ssl);
328         /* SSLfatal() already called */
329         if (i < 0)
330             return i;
331         if (i == 0) {
332             return -1;
333         }
334     }
335 
336     i = tls_write_check_pending(s, type, buf, len);
337     if (i < 0) {
338         /* SSLfatal() already called */
339         return i;
340     } else if (i > 0) {
341         /* Retry needed */
342         i = HANDLE_RLAYER_WRITE_RETURN(s,
343                 s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl));
344         if (i <= 0) {
345             s->rlayer.wnum = tot;
346             return i;
347         }
348         tot += s->rlayer.wpend_tot;
349         s->rlayer.wpend_tot = 0;
350     } /* else no retry required */
351 
352     if (tot == 0) {
353         /*
354          * We've not previously sent any data for this write so memorize
355          * arguments so that we can detect bad write retries later
356          */
357         s->rlayer.wpend_tot = 0;
358         s->rlayer.wpend_type = type;
359         s->rlayer.wpend_buf = buf;
360     }
361 
362     if (tot == len) {           /* done? */
363         *written = tot;
364         return 1;
365     }
366 
367     /* If we have an alert to send, lets send it */
368     if (s->s3.alert_dispatch > 0) {
369         i = ssl->method->ssl_dispatch_alert(ssl);
370         if (i <= 0) {
371             /* SSLfatal() already called if appropriate */
372             s->rlayer.wnum = tot;
373             return i;
374         }
375         /* if it went, fall through and send more stuff */
376     }
377 
378     n = (len - tot);
379 
380     max_send_fragment = ssl_get_max_send_fragment(s);
381     split_send_fragment = ssl_get_split_send_fragment(s);
382 
383     if (max_send_fragment == 0
384             || split_send_fragment == 0
385             || split_send_fragment > max_send_fragment) {
386         /*
387          * We should have prevented this when we set/get the split and max send
388          * fragments so we shouldn't get here
389          */
390         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
391         return -1;
392     }
393 
394     /*
395      * Some servers hang if initial client hello is larger than 256 bytes
396      * and record version number > TLS 1.0
397      */
398     recversion = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION : s->version;
399     if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
400             && !s->renegotiate
401             && TLS1_get_version(ssl) > TLS1_VERSION
402             && s->hello_retry_request == SSL_HRR_NONE)
403         recversion = TLS1_VERSION;
404 
405     for (;;) {
406         size_t tmppipelen, remain;
407         size_t j, lensofar = 0;
408 
409         /*
410         * Ask the record layer how it would like to split the amount of data
411         * that we have, and how many of those records it would like in one go.
412         */
413         maxpipes = s->rlayer.wrlmethod->get_max_records(s->rlayer.wrl, type, n,
414                                                         max_send_fragment,
415                                                         &split_send_fragment);
416         /*
417         * If max_pipelines is 0 then this means "undefined" and we default to
418         * whatever the record layer wants to do. Otherwise we use the smallest
419         * value from the number requested by the record layer, and max number
420         * configured by the user.
421         */
422         if (s->max_pipelines > 0 && maxpipes > s->max_pipelines)
423             maxpipes = s->max_pipelines;
424 
425         if (maxpipes > SSL_MAX_PIPELINES)
426             maxpipes = SSL_MAX_PIPELINES;
427 
428         if (split_send_fragment > max_send_fragment) {
429             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
430             return -1;
431         }
432 
433         if (n / maxpipes >= split_send_fragment) {
434             /*
435              * We have enough data to completely fill all available
436              * pipelines
437              */
438             for (j = 0; j < maxpipes; j++) {
439                 tmpls[j].type = type;
440                 tmpls[j].version = recversion;
441                 tmpls[j].buf = &(buf[tot]) + (j * split_send_fragment);
442                 tmpls[j].buflen = split_send_fragment;
443             }
444             /* Remember how much data we are going to be sending */
445             s->rlayer.wpend_tot = maxpipes * split_send_fragment;
446         } else {
447             /* We can partially fill all available pipelines */
448             tmppipelen = n / maxpipes;
449             remain = n % maxpipes;
450             /*
451              * If there is a remainder we add an extra byte to the first few
452              * pipelines
453              */
454             if (remain > 0)
455                 tmppipelen++;
456             for (j = 0; j < maxpipes; j++) {
457                 tmpls[j].type = type;
458                 tmpls[j].version = recversion;
459                 tmpls[j].buf = &(buf[tot]) + lensofar;
460                 tmpls[j].buflen = tmppipelen;
461                 lensofar += tmppipelen;
462                 if (j + 1 == remain)
463                     tmppipelen--;
464             }
465             /* Remember how much data we are going to be sending */
466             s->rlayer.wpend_tot = n;
467         }
468 
469         i = HANDLE_RLAYER_WRITE_RETURN(s,
470             s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, maxpipes));
471         if (i <= 0) {
472             /* SSLfatal() already called if appropriate */
473             s->rlayer.wnum = tot;
474             return i;
475         }
476 
477         if (s->rlayer.wpend_tot == n
478                 || (type == SSL3_RT_APPLICATION_DATA
479                     && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)) {
480             *written = tot + s->rlayer.wpend_tot;
481             s->rlayer.wpend_tot = 0;
482             return 1;
483         }
484 
485         n -= s->rlayer.wpend_tot;
486         tot += s->rlayer.wpend_tot;
487     }
488 }
489 
ossl_tls_handle_rlayer_return(SSL_CONNECTION * s,int writing,int ret,char * file,int line)490 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
491                                   char *file, int line)
492 {
493     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
494 
495     if (ret == OSSL_RECORD_RETURN_RETRY) {
496         s->rwstate = writing ? SSL_WRITING : SSL_READING;
497         ret = -1;
498     } else {
499         s->rwstate = SSL_NOTHING;
500         if (ret == OSSL_RECORD_RETURN_EOF) {
501             if (writing) {
502                 /*
503                  * This shouldn't happen with a writing operation. We treat it
504                  * as fatal.
505                  */
506                 ERR_new();
507                 ERR_set_debug(file, line, 0);
508                 ossl_statem_fatal(s, SSL_AD_INTERNAL_ERROR,
509                                   ERR_R_INTERNAL_ERROR, NULL);
510                 ret = OSSL_RECORD_RETURN_FATAL;
511             } else if ((s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) != 0) {
512                 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
513                 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
514             } else {
515                 ERR_new();
516                 ERR_set_debug(file, line, 0);
517                 /*
518                  * This reason code is part of the API and may be used by
519                  * applications for control flow decisions.
520                  */
521                 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
522                                   SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
523             }
524         } else if (ret == OSSL_RECORD_RETURN_FATAL) {
525             int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
526 
527             if (al != SSL_AD_NO_ALERT) {
528                 ERR_new();
529                 ERR_set_debug(file, line, 0);
530                 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
531             }
532             /*
533              * else some failure but there is no alert code. We don't log an
534              * error for this. The record layer should have logged an error
535              * already or, if not, its due to some sys call error which will be
536              * reported via SSL_ERROR_SYSCALL and errno.
537              */
538         }
539         /*
540          * The record layer distinguishes the cases of EOF, non-fatal
541          * err and retry. Upper layers do not.
542          * If we got a retry or success then *ret is already correct,
543          * otherwise we need to convert the return value.
544          */
545         if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
546             ret = 0;
547         else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
548             ret = -1;
549     }
550 
551     return ret;
552 }
553 
554 /*
555  * Release data from a record.
556  * If length == 0 then we will release the entire record.
557  */
ssl_release_record(SSL_CONNECTION * s,TLS_RECORD * rr,size_t length)558 int ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr, size_t length)
559 {
560     assert(rr->length >= length);
561     if (rr->rechandle != NULL) {
562         if (length == 0)
563             length = rr->length;
564         /* The record layer allocated the buffers for this record */
565         if (HANDLE_RLAYER_READ_RETURN(s,
566                 s->rlayer.rrlmethod->release_record(s->rlayer.rrl,
567                                                     rr->rechandle,
568                                                     length)) <= 0) {
569             /* RLAYER_fatal already called */
570             return 0;
571         }
572 
573         if (length == rr->length)
574             s->rlayer.curr_rec++;
575     } else if (length == 0 || length == rr->length) {
576         /* We allocated the buffers for this record (only happens with DTLS) */
577         OPENSSL_free(rr->allocdata);
578         rr->allocdata = NULL;
579         s->rlayer.curr_rec++;
580     }
581     rr->length -= length;
582     if (rr->length > 0)
583         rr->off += length;
584     else
585         rr->off = 0;
586 
587     return 1;
588 }
589 
590 /*-
591  * Return up to 'len' payload bytes received in 'type' records.
592  * 'type' is one of the following:
593  *
594  *   -  SSL3_RT_HANDSHAKE (when tls_get_message_header and tls_get_message_body
595  *			   call us)
596  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
597  *   -  0 (during a shutdown, no data has to be returned)
598  *
599  * If we don't have stored data to work from, read an SSL/TLS record first
600  * (possibly multiple records if we still don't have anything to return).
601  *
602  * This function must handle any surprises the peer may have for us, such as
603  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
604  * messages are treated as if they were handshake messages *if* the |recvd_type|
605  * argument is non NULL.
606  * Also if record payloads contain fragments too small to process, we store
607  * them until there is enough for the respective protocol (the record protocol
608  * may use arbitrary fragmentation and even interleaving):
609  *     Change cipher spec protocol
610  *             just 1 byte needed, no need for keeping anything stored
611  *     Alert protocol
612  *             2 bytes needed (AlertLevel, AlertDescription)
613  *     Handshake protocol
614  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
615  *             to detect unexpected Client Hello and Hello Request messages
616  *             here, anything else is handled by higher layers
617  *     Application data protocol
618  *             none of our business
619  */
ssl3_read_bytes(SSL * ssl,uint8_t type,uint8_t * recvd_type,unsigned char * buf,size_t len,int peek,size_t * readbytes)620 int ssl3_read_bytes(SSL *ssl, uint8_t type, uint8_t *recvd_type,
621                     unsigned char *buf, size_t len,
622                     int peek, size_t *readbytes)
623 {
624     int i, j, ret;
625     size_t n, curr_rec, totalbytes;
626     TLS_RECORD *rr;
627     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
628     int is_tls13;
629     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
630 
631     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
632 
633     if ((type != 0
634             && (type != SSL3_RT_APPLICATION_DATA)
635             && (type != SSL3_RT_HANDSHAKE))
636         || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
637         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
638         return -1;
639     }
640 
641     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
642         /* (partially) satisfy request from storage */
643     {
644         unsigned char *src = s->rlayer.handshake_fragment;
645         unsigned char *dst = buf;
646         unsigned int k;
647 
648         /* peek == 0 */
649         n = 0;
650         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
651             *dst++ = *src++;
652             len--;
653             s->rlayer.handshake_fragment_len--;
654             n++;
655         }
656         /* move any remaining fragment bytes: */
657         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
658             s->rlayer.handshake_fragment[k] = *src++;
659 
660         if (recvd_type != NULL)
661             *recvd_type = SSL3_RT_HANDSHAKE;
662 
663         *readbytes = n;
664         return 1;
665     }
666 
667     /*
668      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
669      */
670 
671     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
672         /* type == SSL3_RT_APPLICATION_DATA */
673         i = s->handshake_func(ssl);
674         /* SSLfatal() already called */
675         if (i < 0)
676             return i;
677         if (i == 0)
678             return -1;
679     }
680  start:
681     s->rwstate = SSL_NOTHING;
682 
683     /*-
684      * For each record 'i' up to |num_recs]
685      * rr[i].type     - is the type of record
686      * rr[i].data,    - data
687      * rr[i].off,     - offset into 'data' for next read
688      * rr[i].length,  - number of bytes.
689      */
690     /* get new records if necessary */
691     if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
692         s->rlayer.curr_rec = s->rlayer.num_recs = 0;
693         do {
694             rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
695 
696             ret = HANDLE_RLAYER_READ_RETURN(s,
697                     s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
698                                                      &rr->rechandle,
699                                                      &rr->version, &rr->type,
700                                                      &rr->data, &rr->length,
701                                                      NULL, NULL));
702             if (ret <= 0) {
703                 /* SSLfatal() already called if appropriate */
704                 return ret;
705             }
706             rr->off = 0;
707             s->rlayer.num_recs++;
708         } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
709                  && s->rlayer.num_recs < SSL_MAX_PIPELINES);
710     }
711     rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
712 
713     if (s->rlayer.handshake_fragment_len > 0
714             && rr->type != SSL3_RT_HANDSHAKE
715             && SSL_CONNECTION_IS_TLS13(s)) {
716         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
717                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
718         return -1;
719     }
720 
721     /*
722      * Reset the count of consecutive warning alerts if we've got a non-empty
723      * record that isn't an alert.
724      */
725     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
726         s->rlayer.alert_count = 0;
727 
728     /* we now have a packet which can be read and processed */
729 
730     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
731                                   * reset by ssl3_get_finished */
732         && (rr->type != SSL3_RT_HANDSHAKE)) {
733         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
734                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
735         return -1;
736     }
737 
738     /*
739      * If the other end has shut down, throw anything we read away (even in
740      * 'peek' mode)
741      */
742     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
743         s->rlayer.curr_rec++;
744         s->rwstate = SSL_NOTHING;
745         return 0;
746     }
747 
748     if (type == rr->type
749         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
750             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
751             && !is_tls13)) {
752         /*
753          * SSL3_RT_APPLICATION_DATA or
754          * SSL3_RT_HANDSHAKE or
755          * SSL3_RT_CHANGE_CIPHER_SPEC
756          */
757         /*
758          * make sure that we are not getting application data when we are
759          * doing a handshake for the first time
760          */
761         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
762                 && SSL_IS_FIRST_HANDSHAKE(s)) {
763             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
764             return -1;
765         }
766 
767         if (type == SSL3_RT_HANDSHAKE
768             && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
769             && s->rlayer.handshake_fragment_len > 0) {
770             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
771             return -1;
772         }
773 
774         if (recvd_type != NULL)
775             *recvd_type = rr->type;
776 
777         if (len == 0) {
778             /*
779              * Skip a zero length record. This ensures multiple calls to
780              * SSL_read() with a zero length buffer will eventually cause
781              * SSL_pending() to report data as being available.
782              */
783             if (rr->length == 0 && !ssl_release_record(s, rr, 0))
784                 return -1;
785 
786             return 0;
787         }
788 
789         totalbytes = 0;
790         curr_rec = s->rlayer.curr_rec;
791         do {
792             if (len - totalbytes > rr->length)
793                 n = rr->length;
794             else
795                 n = len - totalbytes;
796 
797             memcpy(buf, &(rr->data[rr->off]), n);
798             buf += n;
799             if (peek) {
800                 /* Mark any zero length record as consumed CVE-2016-6305 */
801                 if (rr->length == 0 && !ssl_release_record(s, rr, 0))
802                     return -1;
803             } else {
804                 if (!ssl_release_record(s, rr, n))
805                     return -1;
806             }
807             if (rr->length == 0
808                 || (peek && n == rr->length)) {
809                 rr++;
810                 curr_rec++;
811             }
812             totalbytes += n;
813         } while (type == SSL3_RT_APPLICATION_DATA
814                     && curr_rec < s->rlayer.num_recs
815                     && totalbytes < len);
816         if (totalbytes == 0) {
817             /* We must have read empty records. Get more data */
818             goto start;
819         }
820         *readbytes = totalbytes;
821         return 1;
822     }
823 
824     /*
825      * If we get here, then type != rr->type; if we have a handshake message,
826      * then it was unexpected (Hello Request or Client Hello) or invalid (we
827      * were actually expecting a CCS).
828      */
829 
830     /*
831      * Lets just double check that we've not got an SSLv2 record
832      */
833     if (rr->version == SSL2_VERSION) {
834         /*
835          * Should never happen. ssl3_get_record() should only give us an SSLv2
836          * record back if this is the first packet and we are looking for an
837          * initial ClientHello. Therefore |type| should always be equal to
838          * |rr->type|. If not then something has gone horribly wrong
839          */
840         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
841         return -1;
842     }
843 
844     if (ssl->method->version == TLS_ANY_VERSION
845         && (s->server || rr->type != SSL3_RT_ALERT)) {
846         /*
847          * If we've got this far and still haven't decided on what version
848          * we're using then this must be a client side alert we're dealing
849          * with. We shouldn't be receiving anything other than a ClientHello
850          * if we are a server.
851          */
852         s->version = rr->version;
853         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
854         return -1;
855     }
856 
857     /*-
858      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
859      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
860      */
861 
862     if (rr->type == SSL3_RT_ALERT) {
863         unsigned int alert_level, alert_descr;
864         const unsigned char *alert_bytes = rr->data + rr->off;
865         PACKET alert;
866 
867         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
868                 || !PACKET_get_1(&alert, &alert_level)
869                 || !PACKET_get_1(&alert, &alert_descr)
870                 || PACKET_remaining(&alert) != 0) {
871             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
872             return -1;
873         }
874 
875         if (s->msg_callback)
876             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
877                             s->msg_callback_arg);
878 
879         if (s->info_callback != NULL)
880             cb = s->info_callback;
881         else if (ssl->ctx->info_callback != NULL)
882             cb = ssl->ctx->info_callback;
883 
884         if (cb != NULL) {
885             j = (alert_level << 8) | alert_descr;
886             cb(ssl, SSL_CB_READ_ALERT, j);
887         }
888 
889         if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
890                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
891             s->s3.warn_alert = alert_descr;
892             if (!ssl_release_record(s, rr, 0))
893                 return -1;
894 
895             s->rlayer.alert_count++;
896             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
897                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
898                          SSL_R_TOO_MANY_WARN_ALERTS);
899                 return -1;
900             }
901         }
902 
903         /*
904          * Apart from close_notify the only other warning alert in TLSv1.3
905          * is user_cancelled - which we just ignore.
906          */
907         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
908             goto start;
909         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
910                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
911             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
912             return 0;
913         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
914             s->rwstate = SSL_NOTHING;
915             s->s3.fatal_alert = alert_descr;
916             SSLfatal_data(s, SSL_AD_NO_ALERT,
917                           SSL_AD_REASON_OFFSET + alert_descr,
918                           "SSL alert number %d", alert_descr);
919             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
920             if (!ssl_release_record(s, rr, 0))
921                 return -1;
922             SSL_CTX_remove_session(s->session_ctx, s->session);
923             return 0;
924         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
925             /*
926              * This is a warning but we receive it if we requested
927              * renegotiation and the peer denied it. Terminate with a fatal
928              * alert because if the application tried to renegotiate it
929              * presumably had a good reason and expects it to succeed. In
930              * the future we might have a renegotiation where we don't care
931              * if the peer refused it where we carry on.
932              */
933             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
934             return -1;
935         } else if (alert_level == SSL3_AL_WARNING) {
936             /* We ignore any other warning alert in TLSv1.2 and below */
937             goto start;
938         }
939 
940         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
941         return -1;
942     }
943 
944     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
945         if (rr->type == SSL3_RT_HANDSHAKE) {
946             BIO *rbio;
947 
948             /*
949              * We ignore any handshake messages sent to us unless they are
950              * TLSv1.3 in which case we want to process them. For all other
951              * handshake messages we can't do anything reasonable with them
952              * because we are unable to write any response due to having already
953              * sent close_notify.
954              */
955             if (!SSL_CONNECTION_IS_TLS13(s)) {
956                 if (!ssl_release_record(s, rr, 0))
957                     return -1;
958 
959                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
960                     goto start;
961 
962                 s->rwstate = SSL_READING;
963                 rbio = SSL_get_rbio(ssl);
964                 BIO_clear_retry_flags(rbio);
965                 BIO_set_retry_read(rbio);
966                 return -1;
967             }
968         } else {
969             /*
970              * The peer is continuing to send application data, but we have
971              * already sent close_notify. If this was expected we should have
972              * been called via SSL_read() and this would have been handled
973              * above.
974              * No alert sent because we already sent close_notify
975              */
976             if (!ssl_release_record(s, rr, 0))
977                 return -1;
978             SSLfatal(s, SSL_AD_NO_ALERT,
979                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
980             return -1;
981         }
982     }
983 
984     /*
985      * For handshake data we have 'fragment' storage, so fill that so that we
986      * can process the header at a fixed place. This is done after the
987      * "SHUTDOWN" code above to avoid filling the fragment storage with data
988      * that we're just going to discard.
989      */
990     if (rr->type == SSL3_RT_HANDSHAKE) {
991         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
992         unsigned char *dest = s->rlayer.handshake_fragment;
993         size_t *dest_len = &s->rlayer.handshake_fragment_len;
994 
995         n = dest_maxlen - *dest_len; /* available space in 'dest' */
996         if (rr->length < n)
997             n = rr->length; /* available bytes */
998 
999         /* now move 'n' bytes: */
1000         if (n > 0) {
1001             memcpy(dest + *dest_len, rr->data + rr->off, n);
1002             *dest_len += n;
1003         }
1004         /*
1005          * We release the number of bytes consumed, or the whole record if it
1006          * is zero length
1007          */
1008         if ((n > 0 || rr->length == 0) && !ssl_release_record(s, rr, n))
1009             return -1;
1010 
1011         if (*dest_len < dest_maxlen)
1012             goto start;     /* fragment was too small */
1013     }
1014 
1015     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1016         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1017         return -1;
1018     }
1019 
1020     /*
1021      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1022      * protocol violation)
1023      */
1024     if ((s->rlayer.handshake_fragment_len >= 4)
1025             && !ossl_statem_get_in_handshake(s)) {
1026         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1027 
1028         /* We found handshake data, so we're going back into init */
1029         ossl_statem_set_in_init(s, 1);
1030 
1031         i = s->handshake_func(ssl);
1032         /* SSLfatal() already called if appropriate */
1033         if (i < 0)
1034             return i;
1035         if (i == 0) {
1036             return -1;
1037         }
1038 
1039         /*
1040          * If we were actually trying to read early data and we found a
1041          * handshake message, then we don't want to continue to try and read
1042          * the application data any more. It won't be "early" now.
1043          */
1044         if (ined)
1045             return -1;
1046 
1047         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1048             if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1049                 BIO *bio;
1050                 /*
1051                  * In the case where we try to read application data, but we
1052                  * trigger an SSL handshake, we return -1 with the retry
1053                  * option set.  Otherwise renegotiation may cause nasty
1054                  * problems in the blocking world
1055                  */
1056                 s->rwstate = SSL_READING;
1057                 bio = SSL_get_rbio(ssl);
1058                 BIO_clear_retry_flags(bio);
1059                 BIO_set_retry_read(bio);
1060                 return -1;
1061             }
1062         }
1063         goto start;
1064     }
1065 
1066     switch (rr->type) {
1067     default:
1068         /*
1069          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1070          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1071          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1072          * no progress is being made and the peer continually sends unrecognised
1073          * record types, using up resources processing them.
1074          */
1075         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1076         return -1;
1077     case SSL3_RT_CHANGE_CIPHER_SPEC:
1078     case SSL3_RT_ALERT:
1079     case SSL3_RT_HANDSHAKE:
1080         /*
1081          * we already handled all of these, with the possible exception of
1082          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1083          * that should not happen when type != rr->type
1084          */
1085         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1086         return -1;
1087     case SSL3_RT_APPLICATION_DATA:
1088         /*
1089          * At this point, we were expecting handshake data, but have
1090          * application data.  If the library was running inside ssl3_read()
1091          * (i.e. in_read_app_data is set) and it makes sense to read
1092          * application data at this point (session renegotiation not yet
1093          * started), we will indulge it.
1094          */
1095         if (ossl_statem_app_data_allowed(s)) {
1096             s->s3.in_read_app_data = 2;
1097             return -1;
1098         } else if (ossl_statem_skip_early_data(s)) {
1099             /*
1100              * This can happen after a client sends a CH followed by early_data,
1101              * but the server responds with a HelloRetryRequest. The server
1102              * reads the next record from the client expecting to find a
1103              * plaintext ClientHello but gets a record which appears to be
1104              * application data. The trial decrypt "works" because null
1105              * decryption was applied. We just skip it and move on to the next
1106              * record.
1107              */
1108             if (!ossl_early_data_count_ok(s, rr->length,
1109                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1110                 /* SSLfatal() already called */
1111                 return -1;
1112             }
1113             if (!ssl_release_record(s, rr, 0))
1114                 return -1;
1115             goto start;
1116         } else {
1117             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1118             return -1;
1119         }
1120     }
1121 }
1122 
1123 /*
1124  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1125  * format and false otherwise.
1126  */
RECORD_LAYER_is_sslv2_record(RECORD_LAYER * rl)1127 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1128 {
1129     if (SSL_CONNECTION_IS_DTLS(rl->s))
1130         return 0;
1131     return rl->tlsrecs[0].version == SSL2_VERSION;
1132 }
1133 
1134 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)1135 static void rlayer_msg_callback_wrapper(int write_p, int version,
1136                                         int content_type, const void *buf,
1137                                         size_t len, void *cbarg)
1138 {
1139     SSL_CONNECTION *s = cbarg;
1140     SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
1141 
1142     if (s->msg_callback != NULL)
1143         s->msg_callback(write_p, version, content_type, buf, len, ssl,
1144                         s->msg_callback_arg);
1145 }
1146 
1147 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
rlayer_security_wrapper(void * cbarg,int op,int bits,int nid,void * other)1148 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1149                                    void *other)
1150 {
1151     SSL_CONNECTION *s = cbarg;
1152 
1153     return ssl_security(s, op, bits, nid, other);
1154 }
1155 
1156 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
rlayer_padding_wrapper(void * cbarg,int type,size_t len)1157 static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
1158 {
1159     SSL_CONNECTION *s = cbarg;
1160     SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
1161 
1162     return s->rlayer.record_padding_cb(ssl, type, len,
1163                                        s->rlayer.record_padding_arg);
1164 }
1165 
1166 static const OSSL_DISPATCH rlayer_dispatch[] = {
1167     { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1168     { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1169     { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1170     { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
1171     OSSL_DISPATCH_END
1172 };
1173 
ossl_ssl_set_custom_record_layer(SSL_CONNECTION * s,const OSSL_RECORD_METHOD * meth,void * rlarg)1174 void ossl_ssl_set_custom_record_layer(SSL_CONNECTION *s,
1175                                       const OSSL_RECORD_METHOD *meth,
1176                                       void *rlarg)
1177 {
1178     s->rlayer.custom_rlmethod = meth;
1179     s->rlayer.rlarg = rlarg;
1180 }
1181 
ssl_select_next_record_layer(SSL_CONNECTION * s,int direction,int level)1182 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1183                                                               int direction,
1184                                                               int level)
1185 {
1186     if (s->rlayer.custom_rlmethod != NULL)
1187         return s->rlayer.custom_rlmethod;
1188 
1189     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1190         if (SSL_CONNECTION_IS_DTLS(s))
1191             return &ossl_dtls_record_method;
1192 
1193         return &ossl_tls_record_method;
1194     }
1195 
1196 #ifndef OPENSSL_NO_KTLS
1197     /* KTLS does not support renegotiation */
1198     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1199             && (s->options & SSL_OP_ENABLE_KTLS) != 0
1200             && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1201         return &ossl_ktls_record_method;
1202 #endif
1203 
1204     /* Default to the current OSSL_RECORD_METHOD */
1205     return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
1206                                                    : s->rlayer.wrlmethod;
1207 }
1208 
ssl_post_record_layer_select(SSL_CONNECTION * s,int direction)1209 static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
1210 {
1211     const OSSL_RECORD_METHOD *thismethod;
1212     OSSL_RECORD_LAYER *thisrl;
1213 
1214     if (direction == OSSL_RECORD_DIRECTION_READ) {
1215         thismethod = s->rlayer.rrlmethod;
1216         thisrl = s->rlayer.rrl;
1217     } else {
1218         thismethod = s->rlayer.wrlmethod;
1219         thisrl = s->rlayer.wrl;
1220     }
1221 
1222 #ifndef OPENSSL_NO_KTLS
1223     {
1224         SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1225 
1226         if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1227             /* KTLS does not support renegotiation so disallow it */
1228             SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1229         }
1230     }
1231 #endif
1232     if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
1233         thismethod->set_first_handshake(thisrl, 1);
1234 
1235     if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
1236         thismethod->set_max_pipelines(thisrl, s->max_pipelines);
1237 
1238     return 1;
1239 }
1240 
ssl_set_new_record_layer(SSL_CONNECTION * s,int version,int direction,int level,unsigned char * secret,size_t secretlen,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,const EVP_MD * kdfdigest)1241 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1242                              int direction, int level,
1243                              unsigned char *secret, size_t secretlen,
1244                              unsigned char *key, size_t keylen,
1245                              unsigned char *iv,  size_t ivlen,
1246                              unsigned char *mackey, size_t mackeylen,
1247                              const EVP_CIPHER *ciph, size_t taglen,
1248                              int mactype, const EVP_MD *md,
1249                              const SSL_COMP *comp, const EVP_MD *kdfdigest)
1250 {
1251     OSSL_PARAM options[5], *opts = options;
1252     OSSL_PARAM settings[6], *set =  settings;
1253     const OSSL_RECORD_METHOD **thismethod;
1254     OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
1255     BIO *thisbio;
1256     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1257     const OSSL_RECORD_METHOD *meth;
1258     int use_etm, stream_mac = 0, tlstree = 0;
1259     unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
1260                            ? ssl_get_max_send_fragment(s)
1261                            : SSL3_RT_MAX_PLAIN_LENGTH;
1262     int use_early_data = 0;
1263     uint32_t max_early_data;
1264     COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
1265 
1266     meth = ssl_select_next_record_layer(s, direction, level);
1267 
1268     if (direction == OSSL_RECORD_DIRECTION_READ) {
1269         thismethod = &s->rlayer.rrlmethod;
1270         thisrl = &s->rlayer.rrl;
1271         thisbio = s->rbio;
1272     } else {
1273         thismethod = &s->rlayer.wrlmethod;
1274         thisrl = &s->rlayer.wrl;
1275         thisbio = s->wbio;
1276     }
1277 
1278     if (meth == NULL)
1279         meth = *thismethod;
1280 
1281     if (!ossl_assert(meth != NULL)) {
1282         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1283         return 0;
1284     }
1285 
1286     /* Parameters that *may* be supported by a record layer if passed */
1287     *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1288                                           &s->options);
1289     *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1290                                           &s->mode);
1291     if (direction == OSSL_RECORD_DIRECTION_READ) {
1292         *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1293                                               &s->rlayer.default_read_buf_len);
1294         *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1295                                            &s->rlayer.read_ahead);
1296     } else {
1297         *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
1298                                               &s->rlayer.block_padding);
1299         *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_HS_PADDING,
1300                                               &s->rlayer.hs_padding);
1301     }
1302     *opts = OSSL_PARAM_construct_end();
1303 
1304     /* Parameters that *must* be supported by a record layer if passed */
1305     if (direction == OSSL_RECORD_DIRECTION_READ) {
1306         use_etm = SSL_READ_ETM(s) ? 1 : 0;
1307         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1308             stream_mac = 1;
1309 
1310         if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1311             tlstree = 1;
1312     } else {
1313         use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1314         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1315             stream_mac = 1;
1316 
1317         if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1318             tlstree = 1;
1319     }
1320 
1321     if (use_etm)
1322         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1323                                           &use_etm);
1324 
1325     if (stream_mac)
1326         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1327                                           &stream_mac);
1328 
1329     if (tlstree)
1330         *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1331                                           &tlstree);
1332 
1333     /*
1334      * We only need to do this for the read side. The write side should already
1335      * have the correct value due to the ssl_get_max_send_fragment() call above
1336      */
1337     if (direction == OSSL_RECORD_DIRECTION_READ
1338             && s->session != NULL
1339             && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1340         maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1341 
1342 
1343     if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1344         *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1345                                            &maxfrag);
1346 
1347     /*
1348      * The record layer must check the amount of early data sent or received
1349      * using the early keys. A server also needs to worry about rejected early
1350      * data that might arrive when the handshake keys are in force.
1351      */
1352     if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1353         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1354                           || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1355     } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1356         use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1357     }
1358     if (use_early_data) {
1359         max_early_data = ossl_get_max_early_data(s);
1360 
1361         if (max_early_data != 0)
1362             *set++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1363                                                  &max_early_data);
1364     }
1365 
1366     *set = OSSL_PARAM_construct_end();
1367 
1368     for (;;) {
1369         int rlret;
1370         BIO *prev = NULL;
1371         BIO *next = NULL;
1372         unsigned int epoch = 0;
1373         OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
1374         size_t i, j;
1375 
1376         if (direction == OSSL_RECORD_DIRECTION_READ) {
1377             prev = s->rlayer.rrlnext;
1378             if (SSL_CONNECTION_IS_DTLS(s)
1379                     && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1380                 epoch = dtls1_get_epoch(s, SSL3_CC_READ); /* new epoch */
1381 
1382 #ifndef OPENSSL_NO_DGRAM
1383             if (SSL_CONNECTION_IS_DTLS(s))
1384                 next = BIO_new(BIO_s_dgram_mem());
1385             else
1386 #endif
1387                 next = BIO_new(BIO_s_mem());
1388 
1389             if (next == NULL) {
1390                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1391                 return 0;
1392             }
1393             s->rlayer.rrlnext = next;
1394         } else {
1395             if (SSL_CONNECTION_IS_DTLS(s)
1396                     && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1397                 epoch = dtls1_get_epoch(s, SSL3_CC_WRITE); /* new epoch */
1398         }
1399 
1400         /*
1401          * Create a copy of the dispatch array, missing out wrappers for
1402          * callbacks that we don't need.
1403          */
1404         for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
1405             switch (rlayer_dispatch[i].function_id) {
1406             case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1407                 if (s->msg_callback == NULL)
1408                     continue;
1409                 break;
1410             case OSSL_FUNC_RLAYER_PADDING:
1411                 if (s->rlayer.record_padding_cb == NULL)
1412                     continue;
1413                 break;
1414             default:
1415                 break;
1416             }
1417             rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
1418         }
1419 
1420         rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
1421                                        s->server, direction, level, epoch,
1422                                        secret, secretlen, key, keylen, iv,
1423                                        ivlen, mackey, mackeylen, ciph, taglen,
1424                                        mactype, md, compm, kdfdigest, prev,
1425                                        thisbio, next, NULL, NULL, settings,
1426                                        options, rlayer_dispatch_tmp, s,
1427                                        s->rlayer.rlarg, &newrl);
1428         BIO_free(prev);
1429         switch (rlret) {
1430         case OSSL_RECORD_RETURN_FATAL:
1431             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1432             return 0;
1433 
1434         case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1435             if (*thismethod != meth && *thismethod != NULL) {
1436                 /*
1437                  * We tried a new record layer method, but it didn't work out,
1438                  * so we fallback to the original method and try again
1439                  */
1440                 meth = *thismethod;
1441                 continue;
1442             }
1443             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1444             return 0;
1445 
1446         case OSSL_RECORD_RETURN_SUCCESS:
1447             break;
1448 
1449         default:
1450             /* Should not happen */
1451             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1452             return 0;
1453         }
1454         break;
1455     }
1456 
1457     /*
1458      * Free the old record layer if we have one except in the case of DTLS when
1459      * writing and there are still buffered sent messages in our queue. In that
1460      * case the record layer is still referenced by those buffered messages for
1461      * potential retransmit. Only when those buffered messages get freed do we
1462      * free the record layer object (see dtls1_hm_fragment_free)
1463      */
1464     if (!SSL_CONNECTION_IS_DTLS(s)
1465             || direction == OSSL_RECORD_DIRECTION_READ
1466             || pqueue_peek(s->d1->sent_messages) == NULL) {
1467         if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
1468             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1469             return 0;
1470         }
1471     }
1472 
1473     *thisrl = newrl;
1474     *thismethod = meth;
1475 
1476     return ssl_post_record_layer_select(s, direction);
1477 }
1478 
ssl_set_record_protocol_version(SSL_CONNECTION * s,int vers)1479 int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
1480 {
1481     if (!ossl_assert(s->rlayer.rrlmethod != NULL)
1482             || !ossl_assert(s->rlayer.wrlmethod != NULL))
1483         return 0;
1484     s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
1485     s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);
1486 
1487     return 1;
1488 }
1489