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