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