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