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