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