1 /*
2 * Copyright 2022-2025 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <assert.h>
11 #include <openssl/bio.h>
12 #include <openssl/ssl.h>
13 #include <openssl/err.h>
14 #include <openssl/core_names.h>
15 #include <openssl/comp.h>
16 #include <openssl/ssl.h>
17 #include "internal/e_os.h"
18 #include "internal/packet.h"
19 #include "internal/ssl3_cbc.h"
20 #include "../../ssl_local.h"
21 #include "../record_local.h"
22 #include "recmethod_local.h"
23
24 static void tls_int_free(OSSL_RECORD_LAYER *rl);
25
ossl_tls_buffer_release(TLS_BUFFER * b)26 void ossl_tls_buffer_release(TLS_BUFFER *b)
27 {
28 OPENSSL_free(b->buf);
29 b->buf = NULL;
30 }
31
TLS_RL_RECORD_release(TLS_RL_RECORD * r,size_t num_recs)32 static void TLS_RL_RECORD_release(TLS_RL_RECORD *r, size_t num_recs)
33 {
34 size_t i;
35
36 for (i = 0; i < num_recs; i++) {
37 OPENSSL_free(r[i].comp);
38 r[i].comp = NULL;
39 }
40 }
41
ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD * r,const unsigned char * seq_num)42 void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r,
43 const unsigned char *seq_num)
44 {
45 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
46 }
47
ossl_rlayer_fatal(OSSL_RECORD_LAYER * rl,int al,int reason,const char * fmt,...)48 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
49 const char *fmt, ...)
50 {
51 va_list args;
52
53 va_start(args, fmt);
54 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
55 va_end(args);
56
57 rl->alert = al;
58 }
59
ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER * rl,EVP_CIPHER_CTX * ctx,const EVP_CIPHER * ciph,const EVP_MD * md)60 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
61 EVP_CIPHER_CTX *ctx,
62 const EVP_CIPHER *ciph,
63 const EVP_MD *md)
64 {
65 /*
66 * Provided cipher, the TLS padding/MAC removal is performed provider
67 * side so we need to tell the ctx about our TLS version and mac size
68 */
69 OSSL_PARAM params[3], *pprm = params;
70 size_t macsize = 0;
71 int imacsize = -1;
72
73 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
74 && !rl->use_etm)
75 imacsize = EVP_MD_get_size(md);
76 if (imacsize > 0)
77 macsize = (size_t)imacsize;
78
79 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
80 &rl->version);
81 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
82 &macsize);
83 *pprm = OSSL_PARAM_construct_end();
84
85 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
86 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
87 return 0;
88 }
89
90 return 1;
91 }
92
93 /*
94 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
95 * which ssl3_cbc_digest_record supports.
96 */
ssl3_cbc_record_digest_supported(const EVP_MD_CTX * ctx)97 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
98 {
99 switch (EVP_MD_CTX_get_type(ctx)) {
100 case NID_md5:
101 case NID_sha1:
102 case NID_sha224:
103 case NID_sha256:
104 case NID_sha384:
105 case NID_sha512:
106 return 1;
107 default:
108 return 0;
109 }
110 }
111
112 #ifndef OPENSSL_NO_COMP
tls_allow_compression(OSSL_RECORD_LAYER * rl)113 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
114 {
115 if (rl->options & SSL_OP_NO_COMPRESSION)
116 return 0;
117
118 return rl->security == NULL
119 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
120 }
121 #endif
122
tls_release_write_buffer_int(OSSL_RECORD_LAYER * rl,size_t start)123 static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
124 {
125 TLS_BUFFER *wb;
126 size_t pipes;
127
128 pipes = rl->numwpipes;
129
130 while (pipes > start) {
131 wb = &rl->wbuf[pipes - 1];
132
133 if (TLS_BUFFER_is_app_buffer(wb))
134 TLS_BUFFER_set_app_buffer(wb, 0);
135 else
136 OPENSSL_free(wb->buf);
137 wb->buf = NULL;
138 pipes--;
139 }
140 }
141
tls_setup_write_buffer(OSSL_RECORD_LAYER * rl,size_t numwpipes,size_t firstlen,size_t nextlen)142 int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
143 size_t firstlen, size_t nextlen)
144 {
145 unsigned char *p;
146 size_t maxalign = 0, headerlen;
147 TLS_BUFFER *wb;
148 size_t currpipe;
149 size_t defltlen = 0;
150 size_t contenttypelen = 0;
151
152 if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
153 if (rl->isdtls)
154 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
155 else
156 headerlen = SSL3_RT_HEADER_LENGTH;
157
158 /* TLSv1.3 adds an extra content type byte after payload data */
159 if (rl->version == TLS1_3_VERSION)
160 contenttypelen = 1;
161
162 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
163 maxalign = SSL3_ALIGN_PAYLOAD - 1;
164 #endif
165
166 defltlen = maxalign + headerlen + rl->eivlen + rl->max_frag_len
167 + contenttypelen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
168 #ifndef OPENSSL_NO_COMP
169 if (tls_allow_compression(rl))
170 defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
171 #endif
172 /*
173 * We don't need to add eivlen here since empty fragments only occur
174 * when we don't have an explicit IV. The contenttype byte will also
175 * always be 0 in these protocol versions
176 */
177 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0)
178 defltlen += headerlen + maxalign + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
179 }
180
181 wb = rl->wbuf;
182 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
183 TLS_BUFFER *thiswb = &wb[currpipe];
184 size_t len = (currpipe == 0) ? firstlen : nextlen;
185
186 if (len == 0)
187 len = defltlen;
188
189 if (thiswb->len != len) {
190 OPENSSL_free(thiswb->buf);
191 thiswb->buf = NULL; /* force reallocation */
192 }
193
194 p = thiswb->buf;
195 if (p == NULL) {
196 p = OPENSSL_malloc(len);
197 if (p == NULL) {
198 if (rl->numwpipes < currpipe)
199 rl->numwpipes = currpipe;
200 /*
201 * We've got a malloc failure, and we're still initialising
202 * buffers. We assume we're so doomed that we won't even be able
203 * to send an alert.
204 */
205 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
206 return 0;
207 }
208 }
209 memset(thiswb, 0, sizeof(TLS_BUFFER));
210 thiswb->buf = p;
211 thiswb->len = len;
212 }
213
214 /* Free any previously allocated buffers that we are no longer using */
215 tls_release_write_buffer_int(rl, currpipe);
216
217 rl->numwpipes = numwpipes;
218
219 return 1;
220 }
221
tls_release_write_buffer(OSSL_RECORD_LAYER * rl)222 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
223 {
224 tls_release_write_buffer_int(rl, 0);
225
226 rl->numwpipes = 0;
227 }
228
tls_setup_read_buffer(OSSL_RECORD_LAYER * rl)229 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
230 {
231 unsigned char *p;
232 size_t len, maxalign = 0, headerlen;
233 TLS_BUFFER *b;
234
235 b = &rl->rbuf;
236
237 if (rl->isdtls)
238 headerlen = DTLS1_RT_HEADER_LENGTH;
239 else
240 headerlen = SSL3_RT_HEADER_LENGTH;
241
242 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
243 maxalign = SSL3_ALIGN_PAYLOAD - 1;
244 #endif
245
246 if (b->buf == NULL) {
247 len = rl->max_frag_len
248 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + maxalign;
249 #ifndef OPENSSL_NO_COMP
250 if (tls_allow_compression(rl))
251 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
252 #endif
253
254 /* Ensure our buffer is large enough to support all our pipelines */
255 if (rl->max_pipelines > 1)
256 len *= rl->max_pipelines;
257
258 if (b->default_len > len)
259 len = b->default_len;
260
261 if ((p = OPENSSL_malloc(len)) == NULL) {
262 /*
263 * We've got a malloc failure, and we're still initialising buffers.
264 * We assume we're so doomed that we won't even be able to send an
265 * alert.
266 */
267 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
268 return 0;
269 }
270 b->buf = p;
271 b->len = len;
272 }
273
274 return 1;
275 }
276
tls_release_read_buffer(OSSL_RECORD_LAYER * rl)277 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
278 {
279 TLS_BUFFER *b;
280
281 b = &rl->rbuf;
282 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
283 OPENSSL_cleanse(b->buf, b->len);
284 OPENSSL_free(b->buf);
285 b->buf = NULL;
286 rl->packet = NULL;
287 rl->packet_length = 0;
288 return 1;
289 }
290
291 /*
292 * Return values are as per SSL_read()
293 */
tls_default_read_n(OSSL_RECORD_LAYER * rl,size_t n,size_t max,int extend,int clearold,size_t * readbytes)294 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
295 int clearold, size_t *readbytes)
296 {
297 /*
298 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
299 * packet by another n bytes. The packet will be in the sub-array of
300 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
301 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
302 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
303 * packet to the start of the buffer; if clearold == 0 then leave any old
304 * packets where they were
305 */
306 size_t len, left, align = 0;
307 unsigned char *pkt;
308 TLS_BUFFER *rb;
309
310 if (n == 0)
311 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
312
313 rb = &rl->rbuf;
314 left = rb->left;
315 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
316 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
317 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
318 #endif
319
320 if (!extend) {
321 /* start with empty packet ... */
322 if (left == 0)
323 rb->offset = align;
324
325 rl->packet = rb->buf + rb->offset;
326 rl->packet_length = 0;
327 /* ... now we can act as if 'extend' was set */
328 }
329
330 if (!ossl_assert(rl->packet != NULL)) {
331 /* does not happen */
332 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
333 return OSSL_RECORD_RETURN_FATAL;
334 }
335
336 len = rl->packet_length;
337 pkt = rb->buf + align;
338 /*
339 * Move any available bytes to front of buffer: 'len' bytes already
340 * pointed to by 'packet', 'left' extra ones at the end
341 */
342 if (rl->packet != pkt && clearold == 1) {
343 memmove(pkt, rl->packet, len + left);
344 rl->packet = pkt;
345 rb->offset = len + align;
346 }
347
348 /*
349 * For DTLS/UDP reads should not span multiple packets because the read
350 * operation returns the whole packet at once (as long as it fits into
351 * the buffer).
352 */
353 if (rl->isdtls) {
354 if (left == 0 && extend) {
355 /*
356 * We received a record with a header but no body data. This will
357 * get dumped.
358 */
359 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
360 }
361 if (left > 0 && n > left)
362 n = left;
363 }
364
365 /* if there is enough in the buffer from a previous read, take some */
366 if (left >= n) {
367 rl->packet_length += n;
368 rb->left = left - n;
369 rb->offset += n;
370 *readbytes = n;
371 return OSSL_RECORD_RETURN_SUCCESS;
372 }
373
374 /* else we need to read more data */
375
376 if (n > rb->len - rb->offset) {
377 /* does not happen */
378 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
379 return OSSL_RECORD_RETURN_FATAL;
380 }
381
382 /* We always act like read_ahead is set for DTLS */
383 if (!rl->read_ahead && !rl->isdtls) {
384 /* ignore max parameter */
385 max = n;
386 } else {
387 if (max < n)
388 max = n;
389 if (max > rb->len - rb->offset)
390 max = rb->len - rb->offset;
391 }
392
393 while (left < n) {
394 size_t bioread = 0;
395 int ret;
396 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
397
398 /*
399 * Now we have len+left bytes at the front of rl->rbuf.buf and
400 * need to read in more until we have len + n (up to len + max if
401 * possible)
402 */
403
404 clear_sys_error();
405 if (bio != NULL) {
406 ret = BIO_read(bio, pkt + len + left, max - left);
407 if (ret > 0) {
408 bioread = ret;
409 ret = OSSL_RECORD_RETURN_SUCCESS;
410 } else if (BIO_should_retry(bio)) {
411 if (rl->prev != NULL) {
412 /*
413 * We were reading from the previous epoch. Now there is no
414 * more data, so swap to the actual transport BIO
415 */
416 BIO_free(rl->prev);
417 rl->prev = NULL;
418 continue;
419 }
420 ret = OSSL_RECORD_RETURN_RETRY;
421 } else if (BIO_eof(bio)) {
422 ret = OSSL_RECORD_RETURN_EOF;
423 } else {
424 ret = OSSL_RECORD_RETURN_FATAL;
425 }
426 } else {
427 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
428 ret = OSSL_RECORD_RETURN_FATAL;
429 }
430
431 if (ret <= OSSL_RECORD_RETURN_RETRY) {
432 rb->left = left;
433 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
434 if (len + left == 0)
435 tls_release_read_buffer(rl);
436 return ret;
437 }
438 left += bioread;
439 /*
440 * reads should *never* span multiple packets for DTLS because the
441 * underlying transport protocol is message oriented as opposed to
442 * byte oriented as in the TLS case.
443 */
444 if (rl->isdtls) {
445 if (n > left)
446 n = left; /* makes the while condition false */
447 }
448 }
449
450 /* done reading, now the book-keeping */
451 rb->offset += n;
452 rb->left = left - n;
453 rl->packet_length += n;
454 *readbytes = n;
455 return OSSL_RECORD_RETURN_SUCCESS;
456 }
457
458 /*
459 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
460 * for us in the buffer.
461 */
tls_record_app_data_waiting(OSSL_RECORD_LAYER * rl)462 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
463 {
464 TLS_BUFFER *rbuf;
465 size_t left, len;
466 unsigned char *p;
467
468 rbuf = &rl->rbuf;
469
470 p = TLS_BUFFER_get_buf(rbuf);
471 if (p == NULL)
472 return 0;
473
474 left = TLS_BUFFER_get_left(rbuf);
475
476 if (left < SSL3_RT_HEADER_LENGTH)
477 return 0;
478
479 p += TLS_BUFFER_get_offset(rbuf);
480
481 /*
482 * We only check the type and record length, we will sanity check version
483 * etc later
484 */
485 if (*p != SSL3_RT_APPLICATION_DATA)
486 return 0;
487
488 p += 3;
489 n2s(p, len);
490
491 if (left < SSL3_RT_HEADER_LENGTH + len)
492 return 0;
493
494 return 1;
495 }
496
rlayer_early_data_count_ok(OSSL_RECORD_LAYER * rl,size_t length,size_t overhead,int send)497 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
498 size_t overhead, int send)
499 {
500 uint32_t max_early_data = rl->max_early_data;
501
502 if (max_early_data == 0) {
503 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
504 SSL_R_TOO_MUCH_EARLY_DATA);
505 return 0;
506 }
507
508 /* If we are dealing with ciphertext we need to allow for the overhead */
509 max_early_data += overhead;
510
511 if (rl->early_data_count + length > max_early_data) {
512 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
513 SSL_R_TOO_MUCH_EARLY_DATA);
514 return 0;
515 }
516 rl->early_data_count += length;
517
518 return 1;
519 }
520
521 /*
522 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
523 * will be processed per call to tls_get_more_records. Without this limit an
524 * attacker could send empty records at a faster rate than we can process and
525 * cause tls_get_more_records to loop forever.
526 */
527 #define MAX_EMPTY_RECORDS 32
528
529 #define SSL2_RT_HEADER_LENGTH 2
530
531 /*-
532 * Call this to buffer new input records in rl->rrec.
533 * It will return a OSSL_RECORD_RETURN_* value.
534 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
535 * records have been decoded. For each record 'i':
536 * rrec[i].type - is the type of record
537 * rrec[i].data, - data
538 * rrec[i].length, - number of bytes
539 * Multiple records will only be returned if the record types are all
540 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
541 * |max_pipelines|
542 */
tls_get_more_records(OSSL_RECORD_LAYER * rl)543 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
544 {
545 int enc_err, rret;
546 int i;
547 size_t more, n;
548 TLS_RL_RECORD *rr, *thisrr;
549 TLS_BUFFER *rbuf;
550 unsigned char *p;
551 unsigned char md[EVP_MAX_MD_SIZE];
552 unsigned int version;
553 size_t mac_size = 0;
554 int imac_size;
555 size_t num_recs = 0, max_recs, j;
556 PACKET pkt, sslv2pkt;
557 SSL_MAC_BUF *macbufs = NULL;
558 int ret = OSSL_RECORD_RETURN_FATAL;
559
560 rr = rl->rrec;
561 rbuf = &rl->rbuf;
562 if (rbuf->buf == NULL) {
563 if (!tls_setup_read_buffer(rl)) {
564 /* RLAYERfatal() already called */
565 return OSSL_RECORD_RETURN_FATAL;
566 }
567 }
568
569 max_recs = rl->max_pipelines;
570
571 if (max_recs == 0)
572 max_recs = 1;
573
574 do {
575 thisrr = &rr[num_recs];
576
577 /* check if we have the header */
578 if ((rl->rstate != SSL_ST_READ_BODY) || (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
579 size_t sslv2len;
580 unsigned int type;
581
582 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
583 TLS_BUFFER_get_len(rbuf), 0,
584 num_recs == 0 ? 1 : 0, &n);
585
586 if (rret < OSSL_RECORD_RETURN_SUCCESS)
587 return rret; /* error or non-blocking */
588
589 rl->rstate = SSL_ST_READ_BODY;
590
591 p = rl->packet;
592 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
593 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
594 return OSSL_RECORD_RETURN_FATAL;
595 }
596 sslv2pkt = pkt;
597 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
598 || !PACKET_get_1(&sslv2pkt, &type)) {
599 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
600 return OSSL_RECORD_RETURN_FATAL;
601 }
602 /*
603 * The first record received by the server may be a V2ClientHello.
604 */
605 if (rl->role == OSSL_RECORD_ROLE_SERVER
606 && rl->is_first_record
607 && (sslv2len & 0x8000) != 0
608 && (type == SSL2_MT_CLIENT_HELLO)) {
609 /*
610 * SSLv2 style record
611 *
612 * |num_recs| here will actually always be 0 because
613 * |num_recs > 0| only ever occurs when we are processing
614 * multiple app data records - which we know isn't the case here
615 * because it is an SSLv2ClientHello. We keep it using
616 * |num_recs| for the sake of consistency
617 */
618 thisrr->type = SSL3_RT_HANDSHAKE;
619 thisrr->rec_version = SSL2_VERSION;
620
621 thisrr->length = sslv2len & 0x7fff;
622
623 if (thisrr->length > TLS_BUFFER_get_len(rbuf)
624 - SSL2_RT_HEADER_LENGTH) {
625 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
626 SSL_R_PACKET_LENGTH_TOO_LONG);
627 return OSSL_RECORD_RETURN_FATAL;
628 }
629 } else {
630 /* SSLv3+ style record */
631
632 /* Pull apart the header into the TLS_RL_RECORD */
633 if (!PACKET_get_1(&pkt, &type)
634 || !PACKET_get_net_2(&pkt, &version)
635 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
636 if (rl->msg_callback != NULL)
637 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
638 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
639 return OSSL_RECORD_RETURN_FATAL;
640 }
641 thisrr->type = type;
642 thisrr->rec_version = version;
643
644 /*
645 * When we call validate_record_header() only records actually
646 * received in SSLv2 format should have the record version set
647 * to SSL2_VERSION. This way validate_record_header() can know
648 * what format the record was in based on the version.
649 */
650 if (thisrr->rec_version == SSL2_VERSION) {
651 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
652 SSL_R_WRONG_VERSION_NUMBER);
653 return OSSL_RECORD_RETURN_FATAL;
654 }
655
656 if (rl->msg_callback != NULL)
657 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
658
659 if (thisrr->length > TLS_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
660 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
661 SSL_R_PACKET_LENGTH_TOO_LONG);
662 return OSSL_RECORD_RETURN_FATAL;
663 }
664 }
665
666 if (!rl->funcs->validate_record_header(rl, thisrr)) {
667 /* RLAYERfatal already called */
668 return OSSL_RECORD_RETURN_FATAL;
669 }
670
671 /* now rl->rstate == SSL_ST_READ_BODY */
672 }
673
674 /*
675 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
676 * how much more data we need to read for the rest of the record
677 */
678 if (thisrr->rec_version == SSL2_VERSION) {
679 more = thisrr->length + SSL2_RT_HEADER_LENGTH
680 - SSL3_RT_HEADER_LENGTH;
681 } else {
682 more = thisrr->length;
683 }
684
685 if (more > 0) {
686 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
687
688 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
689 if (rret < OSSL_RECORD_RETURN_SUCCESS)
690 return rret; /* error or non-blocking io */
691 }
692
693 /* set state for later operations */
694 rl->rstate = SSL_ST_READ_HEADER;
695
696 /*
697 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
698 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
699 * + thisrr->length and we have that many bytes in rl->packet
700 */
701 if (thisrr->rec_version == SSL2_VERSION)
702 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
703 else
704 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
705
706 /*
707 * ok, we can now read from 'rl->packet' data into 'thisrr'.
708 * thisrr->input points at thisrr->length bytes, which need to be copied
709 * into thisrr->data by either the decryption or by the decompression.
710 * When the data is 'copied' into the thisrr->data buffer,
711 * thisrr->input will be updated to point at the new buffer
712 */
713
714 /*
715 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
716 * thisrr->length bytes of encrypted compressed stuff.
717 */
718
719 /* decrypt in place in 'thisrr->input' */
720 thisrr->data = thisrr->input;
721 thisrr->orig_len = thisrr->length;
722
723 num_recs++;
724
725 /* we have pulled in a full packet so zero things */
726 rl->packet_length = 0;
727 rl->is_first_record = 0;
728 } while (num_recs < max_recs
729 && thisrr->type == SSL3_RT_APPLICATION_DATA
730 && RLAYER_USE_EXPLICIT_IV(rl)
731 && rl->enc_ctx != NULL
732 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
733 & EVP_CIPH_FLAG_PIPELINE)
734 != 0
735 && tls_record_app_data_waiting(rl));
736
737 if (num_recs == 1
738 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
739 /* The following can happen in tlsany_meth after HRR */
740 && rl->version == TLS1_3_VERSION
741 && rl->is_first_handshake) {
742 /*
743 * CCS messages must be exactly 1 byte long, containing the value 0x01
744 */
745 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
746 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
747 SSL_R_INVALID_CCS_MESSAGE);
748 return OSSL_RECORD_RETURN_FATAL;
749 }
750 /*
751 * CCS messages are ignored in TLSv1.3. We treat it like an empty
752 * handshake record - but we still call the msg_callback
753 */
754 if (rl->msg_callback != NULL)
755 rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_CHANGE_CIPHER_SPEC,
756 thisrr->data, 1, rl->cbarg);
757 thisrr->type = SSL3_RT_HANDSHAKE;
758 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
759 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
760 SSL_R_UNEXPECTED_CCS_MESSAGE);
761 return OSSL_RECORD_RETURN_FATAL;
762 }
763 rl->num_recs = 0;
764 rl->curr_rec = 0;
765 rl->num_released = 0;
766
767 return OSSL_RECORD_RETURN_SUCCESS;
768 }
769
770 if (rl->md_ctx != NULL) {
771 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
772
773 if (tmpmd != NULL) {
774 imac_size = EVP_MD_get_size(tmpmd);
775 if (!ossl_assert(imac_size > 0 && imac_size <= EVP_MAX_MD_SIZE)) {
776 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
777 return OSSL_RECORD_RETURN_FATAL;
778 }
779 mac_size = (size_t)imac_size;
780 }
781 }
782
783 /*
784 * If in encrypt-then-mac mode calculate mac from encrypted record. All
785 * the details below are public so no timing details can leak.
786 */
787 if (rl->use_etm && rl->md_ctx != NULL) {
788 unsigned char *mac;
789
790 for (j = 0; j < num_recs; j++) {
791 thisrr = &rr[j];
792
793 if (thisrr->length < mac_size) {
794 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
795 return OSSL_RECORD_RETURN_FATAL;
796 }
797 thisrr->length -= mac_size;
798 mac = thisrr->data + thisrr->length;
799 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
800 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
801 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
802 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
803 return OSSL_RECORD_RETURN_FATAL;
804 }
805 }
806 /*
807 * We've handled the mac now - there is no MAC inside the encrypted
808 * record
809 */
810 mac_size = 0;
811 }
812
813 if (mac_size > 0) {
814 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
815 if (macbufs == NULL) {
816 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
817 return OSSL_RECORD_RETURN_FATAL;
818 }
819 }
820
821 ERR_set_mark();
822 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
823
824 /*-
825 * enc_err is:
826 * 0: if the record is publicly invalid, or an internal error, or AEAD
827 * decryption failed, or ETM decryption failed.
828 * 1: Success or MTE decryption failed (MAC will be randomised)
829 */
830 if (enc_err == 0) {
831 if (rl->alert != SSL_AD_NO_ALERT) {
832 /* RLAYERfatal() already got called */
833 ERR_clear_last_mark();
834 goto end;
835 }
836 if (num_recs == 1
837 && rl->skip_early_data != NULL
838 && rl->skip_early_data(rl->cbarg)) {
839 /*
840 * Valid early_data that we cannot decrypt will fail here. We treat
841 * it like an empty record.
842 */
843
844 /*
845 * Remove any errors from the stack. Decryption failures are normal
846 * behaviour.
847 */
848 ERR_pop_to_mark();
849
850 thisrr = &rr[0];
851
852 if (!rlayer_early_data_count_ok(rl, thisrr->length,
853 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
854 /* RLAYERfatal() already called */
855 goto end;
856 }
857
858 thisrr->length = 0;
859 rl->num_recs = 0;
860 rl->curr_rec = 0;
861 rl->num_released = 0;
862 /* Reset the read sequence */
863 memset(rl->sequence, 0, sizeof(rl->sequence));
864 ret = 1;
865 goto end;
866 }
867 ERR_clear_last_mark();
868 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
869 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
870 goto end;
871 } else {
872 ERR_clear_last_mark();
873 }
874 OSSL_TRACE_BEGIN(TLS)
875 {
876 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
877 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
878 }
879 OSSL_TRACE_END(TLS);
880
881 /* r->length is now the compressed data plus mac */
882 if (rl->enc_ctx != NULL
883 && !rl->use_etm
884 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
885 for (j = 0; j < num_recs; j++) {
886 SSL_MAC_BUF *thismb = &macbufs[j];
887
888 thisrr = &rr[j];
889
890 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
891 if (i == 0 || thismb == NULL || thismb->mac == NULL
892 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
893 enc_err = 0;
894 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
895 enc_err = 0;
896 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
897 if (enc_err == 0 && mac_size > 0 && thismb != NULL && thismb->mac != NULL && (md[0] ^ thismb->mac[0]) != 0xFF) {
898 enc_err = 1;
899 }
900 #endif
901 }
902 }
903
904 if (enc_err == 0) {
905 if (rl->alert != SSL_AD_NO_ALERT) {
906 /* We already called RLAYERfatal() */
907 goto end;
908 }
909 /*
910 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
911 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
912 * failure is directly visible from the ciphertext anyway, we should
913 * not reveal which kind of error occurred -- this might become
914 * visible to an attacker (e.g. via a logfile)
915 */
916 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
917 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
918 goto end;
919 }
920
921 for (j = 0; j < num_recs; j++) {
922 thisrr = &rr[j];
923
924 if (!rl->funcs->post_process_record(rl, thisrr)) {
925 /* RLAYERfatal already called */
926 goto end;
927 }
928
929 /*
930 * Record overflow checking (e.g. checking if
931 * thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) is the responsibility of
932 * the post_process_record() function above. However we check here if
933 * the received packet overflows the current Max Fragment Length setting
934 * if there is one.
935 * Note: rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH and KTLS are
936 * mutually exclusive. Also note that with KTLS thisrr->length can
937 * be > SSL3_RT_MAX_PLAIN_LENGTH (and rl->max_frag_len must be ignored)
938 */
939 if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH
940 && thisrr->length > rl->max_frag_len) {
941 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
942 goto end;
943 }
944
945 thisrr->off = 0;
946 /*-
947 * So at this point the following is true
948 * thisrr->type is the type of record
949 * thisrr->length == number of bytes in record
950 * thisrr->off == offset to first valid byte
951 * thisrr->data == where to take bytes from, increment after use :-).
952 */
953
954 /* just read a 0 length packet */
955 if (thisrr->length == 0) {
956 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
957 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
958 SSL_R_RECORD_TOO_SMALL);
959 goto end;
960 }
961 } else {
962 rl->empty_record_count = 0;
963 }
964 }
965
966 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
967 thisrr = &rr[0];
968 if (thisrr->type == SSL3_RT_APPLICATION_DATA
969 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
970 /* RLAYERfatal already called */
971 goto end;
972 }
973 }
974
975 rl->num_recs = num_recs;
976 rl->curr_rec = 0;
977 rl->num_released = 0;
978 ret = OSSL_RECORD_RETURN_SUCCESS;
979 end:
980 if (macbufs != NULL) {
981 for (j = 0; j < num_recs; j++) {
982 if (macbufs[j].alloced)
983 OPENSSL_free(macbufs[j].mac);
984 }
985 OPENSSL_free(macbufs);
986 }
987 return ret;
988 }
989
990 /* Shared by ssl3_meth and tls1_meth */
tls_default_validate_record_header(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)991 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
992 {
993 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
994
995 if (rec->rec_version != rl->version) {
996 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
997 return 0;
998 }
999
1000 #ifndef OPENSSL_NO_COMP
1001 /*
1002 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
1003 * does not include the compression overhead anyway.
1004 */
1005 if (rl->compctx == NULL)
1006 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1007 #endif
1008
1009 if (rec->length > len) {
1010 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1011 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1012 return 0;
1013 }
1014
1015 return 1;
1016 }
1017
tls_do_compress(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * wr)1018 int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr)
1019 {
1020 #ifndef OPENSSL_NO_COMP
1021 int i;
1022
1023 i = COMP_compress_block(rl->compctx, wr->data,
1024 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
1025 wr->input, (int)wr->length);
1026 if (i < 0)
1027 return 0;
1028
1029 wr->length = i;
1030 wr->input = wr->data;
1031 return 1;
1032 #else
1033 return 0;
1034 #endif
1035 }
1036
tls_do_uncompress(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1037 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1038 {
1039 #ifndef OPENSSL_NO_COMP
1040 int i;
1041
1042 if (rec->comp == NULL) {
1043 rec->comp = (unsigned char *)
1044 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
1045 }
1046 if (rec->comp == NULL)
1047 return 0;
1048
1049 i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
1050 rec->data, (int)rec->length);
1051 if (i < 0)
1052 return 0;
1053 else
1054 rec->length = i;
1055 rec->data = rec->comp;
1056 return 1;
1057 #else
1058 return 0;
1059 #endif
1060 }
1061
1062 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
tls_default_post_process_record(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1063 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1064 {
1065 if (rl->compctx != NULL) {
1066 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1067 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1068 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1069 return 0;
1070 }
1071 if (!tls_do_uncompress(rl, rec)) {
1072 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1073 SSL_R_BAD_DECOMPRESSION);
1074 return 0;
1075 }
1076 }
1077
1078 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1079 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1080 return 0;
1081 }
1082
1083 return 1;
1084 }
1085
1086 /* Shared by tls13_meth and ktls_meth */
tls13_common_post_process_record(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1087 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1088 {
1089 if (rec->type != SSL3_RT_APPLICATION_DATA
1090 && rec->type != SSL3_RT_ALERT
1091 && rec->type != SSL3_RT_HANDSHAKE) {
1092 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1093 return 0;
1094 }
1095
1096 if (rl->msg_callback != NULL) {
1097 unsigned char ctype = (unsigned char)rec->type;
1098
1099 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &ctype,
1100 1, rl->cbarg);
1101 }
1102
1103 /*
1104 * TLSv1.3 alert and handshake records are required to be non-zero in
1105 * length.
1106 */
1107 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1108 && rec->length == 0) {
1109 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1110 return 0;
1111 }
1112
1113 return 1;
1114 }
1115
tls_read_record(OSSL_RECORD_LAYER * rl,void ** rechandle,int * rversion,uint8_t * type,const unsigned char ** data,size_t * datalen,uint16_t * epoch,unsigned char * seq_num)1116 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1117 uint8_t *type, const unsigned char **data, size_t *datalen,
1118 uint16_t *epoch, unsigned char *seq_num)
1119 {
1120 TLS_RL_RECORD *rec;
1121
1122 /*
1123 * tls_get_more_records() can return success without actually reading
1124 * anything useful (i.e. if empty records are read). We loop here until
1125 * we have something useful. tls_get_more_records() will eventually fail if
1126 * too many sequential empty records are read.
1127 */
1128 while (rl->curr_rec >= rl->num_recs) {
1129 int ret;
1130
1131 if (rl->num_released != rl->num_recs) {
1132 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1133 return OSSL_RECORD_RETURN_FATAL;
1134 }
1135
1136 ret = rl->funcs->get_more_records(rl);
1137
1138 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1139 return ret;
1140 }
1141
1142 /*
1143 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1144 * points to the next one to read.
1145 */
1146 rec = &rl->rrec[rl->curr_rec++];
1147
1148 *rechandle = rec;
1149 *rversion = rec->rec_version;
1150 *type = rec->type;
1151 *data = rec->data + rec->off;
1152 *datalen = rec->length;
1153 if (rl->isdtls) {
1154 *epoch = rec->epoch;
1155 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1156 }
1157
1158 return OSSL_RECORD_RETURN_SUCCESS;
1159 }
1160
tls_release_record(OSSL_RECORD_LAYER * rl,void * rechandle,size_t length)1161 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length)
1162 {
1163 TLS_RL_RECORD *rec = &rl->rrec[rl->num_released];
1164
1165 if (!ossl_assert(rl->num_released < rl->curr_rec)
1166 || !ossl_assert(rechandle == rec)) {
1167 /* Should not happen */
1168 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1169 return OSSL_RECORD_RETURN_FATAL;
1170 }
1171
1172 if (rec->length < length) {
1173 /* Should not happen */
1174 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1175 return OSSL_RECORD_RETURN_FATAL;
1176 }
1177
1178 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
1179 OPENSSL_cleanse(rec->data + rec->off, length);
1180
1181 rec->off += length;
1182 rec->length -= length;
1183
1184 if (rec->length > 0)
1185 return OSSL_RECORD_RETURN_SUCCESS;
1186
1187 rl->num_released++;
1188
1189 if (rl->curr_rec == rl->num_released
1190 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1191 && TLS_BUFFER_get_left(&rl->rbuf) == 0)
1192 tls_release_read_buffer(rl);
1193
1194 return OSSL_RECORD_RETURN_SUCCESS;
1195 }
1196
tls_set_options(OSSL_RECORD_LAYER * rl,const OSSL_PARAM * options)1197 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1198 {
1199 const OSSL_PARAM *p;
1200
1201 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1202 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1203 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1204 return 0;
1205 }
1206
1207 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1208 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1209 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1210 return 0;
1211 }
1212
1213 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1214 p = OSSL_PARAM_locate_const(options,
1215 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1216 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1217 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1218 return 0;
1219 }
1220 } else {
1221 p = OSSL_PARAM_locate_const(options,
1222 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1223 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1224 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1225 return 0;
1226 }
1227 p = OSSL_PARAM_locate_const(options,
1228 OSSL_LIBSSL_RECORD_LAYER_PARAM_HS_PADDING);
1229 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->hs_padding)) {
1230 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1231 return 0;
1232 }
1233 }
1234
1235 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1236 /*
1237 * We ignore any read_ahead setting prior to the application protection
1238 * level. Otherwise we may read ahead data in a lower protection level
1239 * that is destined for a higher protection level. To simplify the logic
1240 * we don't support that at this stage.
1241 */
1242 p = OSSL_PARAM_locate_const(options,
1243 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1244 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1245 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1246 return 0;
1247 }
1248 }
1249
1250 return 1;
1251 }
1252
tls_int_new_record_layer(OSSL_LIB_CTX * libctx,const char * propq,int vers,int role,int direction,int level,const EVP_CIPHER * ciph,size_t taglen,const EVP_MD * md,COMP_METHOD * comp,BIO * prev,BIO * transport,BIO * next,const OSSL_PARAM * settings,const OSSL_PARAM * options,const OSSL_DISPATCH * fns,void * cbarg,OSSL_RECORD_LAYER ** retrl)1253 int tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1254 int role, int direction, int level,
1255 const EVP_CIPHER *ciph, size_t taglen,
1256 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1257 BIO *transport, BIO *next, const OSSL_PARAM *settings,
1258 const OSSL_PARAM *options,
1259 const OSSL_DISPATCH *fns, void *cbarg,
1260 OSSL_RECORD_LAYER **retrl)
1261 {
1262 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1263 const OSSL_PARAM *p;
1264
1265 *retrl = NULL;
1266
1267 if (rl == NULL)
1268 return OSSL_RECORD_RETURN_FATAL;
1269
1270 /*
1271 * Default the value for max_frag_len. This may be overridden by the
1272 * settings
1273 */
1274 rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
1275
1276 /* Loop through all the settings since they must all be understood */
1277 if (settings != NULL) {
1278 for (p = settings; p->key != NULL; p++) {
1279 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1280 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1281 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1282 goto err;
1283 }
1284 } else if (strcmp(p->key,
1285 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN)
1286 == 0) {
1287 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1288 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1289 goto err;
1290 }
1291 } else if (strcmp(p->key,
1292 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA)
1293 == 0) {
1294 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1295 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1296 goto err;
1297 }
1298 } else if (strcmp(p->key,
1299 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC)
1300 == 0) {
1301 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1302 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1303 goto err;
1304 }
1305 } else if (strcmp(p->key,
1306 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE)
1307 == 0) {
1308 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1309 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1310 goto err;
1311 }
1312 } else {
1313 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1314 goto err;
1315 }
1316 }
1317 }
1318
1319 rl->libctx = libctx;
1320 rl->propq = propq;
1321
1322 rl->version = vers;
1323 rl->role = role;
1324 rl->direction = direction;
1325 rl->level = level;
1326 rl->taglen = taglen;
1327 rl->md = md;
1328
1329 rl->alert = SSL_AD_NO_ALERT;
1330 rl->rstate = SSL_ST_READ_HEADER;
1331
1332 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1333 rl->is_first_record = 1;
1334
1335 if (!tls_set1_bio(rl, transport))
1336 goto err;
1337
1338 if (prev != NULL && !BIO_up_ref(prev))
1339 goto err;
1340 rl->prev = prev;
1341
1342 if (next != NULL && !BIO_up_ref(next))
1343 goto err;
1344 rl->next = next;
1345
1346 rl->cbarg = cbarg;
1347 if (fns != NULL) {
1348 for (; fns->function_id != 0; fns++) {
1349 switch (fns->function_id) {
1350 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1351 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1352 break;
1353 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1354 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1355 break;
1356 case OSSL_FUNC_RLAYER_SECURITY:
1357 rl->security = OSSL_FUNC_rlayer_security(fns);
1358 break;
1359 case OSSL_FUNC_RLAYER_PADDING:
1360 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1361 default:
1362 /* Just ignore anything we don't understand */
1363 break;
1364 }
1365 }
1366 }
1367
1368 if (!tls_set_options(rl, options)) {
1369 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1370 goto err;
1371 }
1372
1373 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1374 && rl->version <= TLS1_VERSION
1375 && !EVP_CIPHER_is_a(ciph, "NULL")
1376 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1377 /*
1378 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1379 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1380 */
1381 rl->need_empty_fragments = 1;
1382 }
1383
1384 *retrl = rl;
1385 return OSSL_RECORD_RETURN_SUCCESS;
1386 err:
1387 tls_int_free(rl);
1388 return OSSL_RECORD_RETURN_FATAL;
1389 }
1390
1391 static int
tls_new_record_layer(OSSL_LIB_CTX * libctx,const char * propq,int vers,int role,int direction,int level,uint16_t epoch,unsigned char * secret,size_t secretlen,unsigned char * key,size_t keylen,unsigned char * iv,size_t ivlen,unsigned char * mackey,size_t mackeylen,const EVP_CIPHER * ciph,size_t taglen,int mactype,const EVP_MD * md,COMP_METHOD * comp,const EVP_MD * kdfdigest,BIO * prev,BIO * transport,BIO * next,BIO_ADDR * local,BIO_ADDR * peer,const OSSL_PARAM * settings,const OSSL_PARAM * options,const OSSL_DISPATCH * fns,void * cbarg,void * rlarg,OSSL_RECORD_LAYER ** retrl)1392 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1393 int role, int direction, int level, uint16_t epoch,
1394 unsigned char *secret, size_t secretlen,
1395 unsigned char *key, size_t keylen, unsigned char *iv,
1396 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1397 const EVP_CIPHER *ciph, size_t taglen,
1398 int mactype,
1399 const EVP_MD *md, COMP_METHOD *comp,
1400 const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
1401 BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1402 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1403 const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
1404 OSSL_RECORD_LAYER **retrl)
1405 {
1406 int ret;
1407
1408 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1409 ciph, taglen, md, comp, prev,
1410 transport, next, settings,
1411 options, fns, cbarg, retrl);
1412
1413 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1414 return ret;
1415
1416 switch (vers) {
1417 case TLS_ANY_VERSION:
1418 (*retrl)->funcs = &tls_any_funcs;
1419 break;
1420 case TLS1_3_VERSION:
1421 (*retrl)->funcs = &tls_1_3_funcs;
1422 break;
1423 case TLS1_2_VERSION:
1424 case TLS1_1_VERSION:
1425 case TLS1_VERSION:
1426 (*retrl)->funcs = &tls_1_funcs;
1427 break;
1428 case SSL3_VERSION:
1429 (*retrl)->funcs = &ssl_3_0_funcs;
1430 break;
1431 default:
1432 /* Should not happen */
1433 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1434 ret = OSSL_RECORD_RETURN_FATAL;
1435 goto err;
1436 }
1437
1438 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1439 ivlen, mackey, mackeylen, ciph,
1440 taglen, mactype, md, comp);
1441
1442 err:
1443 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1444 tls_int_free(*retrl);
1445 *retrl = NULL;
1446 }
1447 return ret;
1448 }
1449
tls_int_free(OSSL_RECORD_LAYER * rl)1450 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1451 {
1452 BIO_free(rl->prev);
1453 BIO_free(rl->bio);
1454 BIO_free(rl->next);
1455 ossl_tls_buffer_release(&rl->rbuf);
1456
1457 tls_release_write_buffer(rl);
1458
1459 EVP_CIPHER_CTX_free(rl->enc_ctx);
1460 EVP_MAC_CTX_free(rl->mac_ctx);
1461 EVP_MD_CTX_free(rl->md_ctx);
1462 #ifndef OPENSSL_NO_COMP
1463 COMP_CTX_free(rl->compctx);
1464 #endif
1465 OPENSSL_free(rl->iv);
1466 OPENSSL_free(rl->nonce);
1467 if (rl->version == SSL3_VERSION)
1468 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1469
1470 TLS_RL_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1471
1472 OPENSSL_free(rl);
1473 }
1474
tls_free(OSSL_RECORD_LAYER * rl)1475 int tls_free(OSSL_RECORD_LAYER *rl)
1476 {
1477 TLS_BUFFER *rbuf;
1478 size_t left, written;
1479 int ret = 1;
1480
1481 if (rl == NULL)
1482 return 1;
1483
1484 rbuf = &rl->rbuf;
1485
1486 left = TLS_BUFFER_get_left(rbuf);
1487 if (left > 0) {
1488 /*
1489 * This record layer is closing but we still have data left in our
1490 * buffer. It must be destined for the next epoch - so push it there.
1491 */
1492 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1493 }
1494 tls_int_free(rl);
1495
1496 return ret;
1497 }
1498
tls_unprocessed_read_pending(OSSL_RECORD_LAYER * rl)1499 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1500 {
1501 return TLS_BUFFER_get_left(&rl->rbuf) != 0;
1502 }
1503
tls_processed_read_pending(OSSL_RECORD_LAYER * rl)1504 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1505 {
1506 return rl->curr_rec < rl->num_recs;
1507 }
1508
tls_app_data_pending(OSSL_RECORD_LAYER * rl)1509 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1510 {
1511 size_t i;
1512 size_t num = 0;
1513
1514 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1515 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1516 return num;
1517 num += rl->rrec[i].length;
1518 }
1519 return num;
1520 }
1521
tls_get_max_records_default(OSSL_RECORD_LAYER * rl,uint8_t type,size_t len,size_t maxfrag,size_t * preffrag)1522 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type,
1523 size_t len,
1524 size_t maxfrag, size_t *preffrag)
1525 {
1526 /*
1527 * If we have a pipeline capable cipher, and we have been configured to use
1528 * it, then return the preferred number of pipelines.
1529 */
1530 if (rl->max_pipelines > 0
1531 && rl->enc_ctx != NULL
1532 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1533 & EVP_CIPH_FLAG_PIPELINE)
1534 != 0
1535 && RLAYER_USE_EXPLICIT_IV(rl)) {
1536 size_t pipes;
1537
1538 if (len == 0)
1539 return 1;
1540 pipes = ((len - 1) / *preffrag) + 1;
1541
1542 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1543 }
1544
1545 return 1;
1546 }
1547
tls_get_max_records(OSSL_RECORD_LAYER * rl,uint8_t type,size_t len,size_t maxfrag,size_t * preffrag)1548 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
1549 size_t maxfrag, size_t *preffrag)
1550 {
1551 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1552 }
1553
tls_allocate_write_buffers_default(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl,size_t * prefix)1554 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1555 OSSL_RECORD_TEMPLATE *templates,
1556 size_t numtempl,
1557 size_t *prefix)
1558 {
1559 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1560 /* RLAYERfatal() already called */
1561 return 0;
1562 }
1563
1564 return 1;
1565 }
1566
tls_initialise_write_packets_default(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl,OSSL_RECORD_TEMPLATE * prefixtempl,WPACKET * pkt,TLS_BUFFER * bufs,size_t * wpinited)1567 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1568 OSSL_RECORD_TEMPLATE *templates,
1569 size_t numtempl,
1570 OSSL_RECORD_TEMPLATE *prefixtempl,
1571 WPACKET *pkt,
1572 TLS_BUFFER *bufs,
1573 size_t *wpinited)
1574 {
1575 WPACKET *thispkt;
1576 size_t j, align;
1577 TLS_BUFFER *wb;
1578
1579 for (j = 0; j < numtempl; j++) {
1580 thispkt = &pkt[j];
1581 wb = &bufs[j];
1582
1583 wb->type = templates[j].type;
1584
1585 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1586 align = (size_t)TLS_BUFFER_get_buf(wb);
1587 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1588 align = SSL3_ALIGN_PAYLOAD - 1
1589 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1590 #endif
1591 TLS_BUFFER_set_offset(wb, align);
1592
1593 if (!WPACKET_init_static_len(thispkt, TLS_BUFFER_get_buf(wb),
1594 TLS_BUFFER_get_len(wb), 0)) {
1595 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1596 return 0;
1597 }
1598 (*wpinited)++;
1599 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1600 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1601 return 0;
1602 }
1603 }
1604
1605 return 1;
1606 }
1607
tls_prepare_record_header_default(OSSL_RECORD_LAYER * rl,WPACKET * thispkt,OSSL_RECORD_TEMPLATE * templ,uint8_t rectype,unsigned char ** recdata)1608 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1609 WPACKET *thispkt,
1610 OSSL_RECORD_TEMPLATE *templ,
1611 uint8_t rectype,
1612 unsigned char **recdata)
1613 {
1614 size_t maxcomplen;
1615
1616 *recdata = NULL;
1617
1618 maxcomplen = templ->buflen;
1619 if (rl->compctx != NULL)
1620 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1621
1622 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1623 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1624 || !WPACKET_start_sub_packet_u16(thispkt)
1625 || (rl->eivlen > 0
1626 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1627 || (maxcomplen > 0
1628 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1629 recdata))) {
1630 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1631 return 0;
1632 }
1633
1634 return 1;
1635 }
1636
tls_prepare_for_encryption_default(OSSL_RECORD_LAYER * rl,size_t mac_size,WPACKET * thispkt,TLS_RL_RECORD * thiswr)1637 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1638 size_t mac_size,
1639 WPACKET *thispkt,
1640 TLS_RL_RECORD *thiswr)
1641 {
1642 size_t len;
1643 unsigned char *recordstart;
1644
1645 /*
1646 * we should still have the output to thiswr->data and the input from
1647 * wr->input. Length should be thiswr->length. thiswr->data still points
1648 * in the wb->buf
1649 */
1650
1651 if (!rl->use_etm && mac_size != 0) {
1652 unsigned char *mac;
1653
1654 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1655 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1656 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1657 return 0;
1658 }
1659 }
1660
1661 /*
1662 * Reserve some bytes for any growth that may occur during encryption. If
1663 * we are adding the MAC independently of the cipher algorithm, then the
1664 * max encrypted overhead does not need to include an allocation for that
1665 * MAC
1666 */
1667 if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD - mac_size, NULL)
1668 /*
1669 * We also need next the amount of bytes written to this
1670 * sub-packet
1671 */
1672 || !WPACKET_get_length(thispkt, &len)) {
1673 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1674 return 0;
1675 }
1676
1677 /* Get a pointer to the start of this record excluding header */
1678 recordstart = WPACKET_get_curr(thispkt) - len;
1679 TLS_RL_RECORD_set_data(thiswr, recordstart);
1680 TLS_RL_RECORD_reset_input(thiswr);
1681 TLS_RL_RECORD_set_length(thiswr, len);
1682
1683 return 1;
1684 }
1685
tls_post_encryption_processing_default(OSSL_RECORD_LAYER * rl,size_t mac_size,OSSL_RECORD_TEMPLATE * thistempl,WPACKET * thispkt,TLS_RL_RECORD * thiswr)1686 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1687 size_t mac_size,
1688 OSSL_RECORD_TEMPLATE *thistempl,
1689 WPACKET *thispkt,
1690 TLS_RL_RECORD *thiswr)
1691 {
1692 size_t origlen, len;
1693 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1694 : SSL3_RT_HEADER_LENGTH;
1695
1696 /* Allocate bytes for the encryption overhead */
1697 if (!WPACKET_get_length(thispkt, &origlen)
1698 /* Check we allowed enough room for the encryption growth */
1699 || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
1700 - mac_size
1701 >= thiswr->length)
1702 /* Encryption should never shrink the data! */
1703 || origlen > thiswr->length
1704 || (thiswr->length > origlen
1705 && !WPACKET_allocate_bytes(thispkt,
1706 thiswr->length - origlen,
1707 NULL))) {
1708 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1709 return 0;
1710 }
1711 if (rl->use_etm && mac_size != 0) {
1712 unsigned char *mac;
1713
1714 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1715 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1716 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1717 return 0;
1718 }
1719
1720 TLS_RL_RECORD_add_length(thiswr, mac_size);
1721 }
1722
1723 if (!WPACKET_get_length(thispkt, &len)
1724 || !WPACKET_close(thispkt)) {
1725 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1726 return 0;
1727 }
1728
1729 if (rl->msg_callback != NULL) {
1730 unsigned char *recordstart;
1731
1732 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1733 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1734 headerlen, rl->cbarg);
1735
1736 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1737 unsigned char ctype = thistempl->type;
1738
1739 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1740 &ctype, 1, rl->cbarg);
1741 }
1742 }
1743
1744 if (!WPACKET_finish(thispkt)) {
1745 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1746 return 0;
1747 }
1748
1749 TLS_RL_RECORD_add_length(thiswr, headerlen);
1750
1751 return 1;
1752 }
1753
tls_write_records_default(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl)1754 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1755 OSSL_RECORD_TEMPLATE *templates,
1756 size_t numtempl)
1757 {
1758 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1759 TLS_RL_RECORD wr[SSL_MAX_PIPELINES + 1];
1760 WPACKET *thispkt;
1761 TLS_RL_RECORD *thiswr;
1762 int mac_size = 0, ret = 0;
1763 size_t wpinited = 0;
1764 size_t j, prefix = 0;
1765 OSSL_RECORD_TEMPLATE prefixtempl;
1766 OSSL_RECORD_TEMPLATE *thistempl;
1767
1768 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1769 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1770 if (mac_size < 0) {
1771 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1772 goto err;
1773 }
1774 }
1775
1776 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1777 /* RLAYERfatal() already called */
1778 goto err;
1779 }
1780
1781 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1782 &prefixtempl, pkt, rl->wbuf,
1783 &wpinited)) {
1784 /* RLAYERfatal() already called */
1785 goto err;
1786 }
1787
1788 /* Clear our TLS_RL_RECORD structures */
1789 memset(wr, 0, sizeof(wr));
1790 for (j = 0; j < numtempl + prefix; j++) {
1791 unsigned char *compressdata = NULL;
1792 uint8_t rectype;
1793
1794 thispkt = &pkt[j];
1795 thiswr = &wr[j];
1796 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1797
1798 /*
1799 * Default to the record type as specified in the template unless the
1800 * protocol implementation says differently.
1801 */
1802 if (rl->funcs->get_record_type != NULL)
1803 rectype = rl->funcs->get_record_type(rl, thistempl);
1804 else
1805 rectype = thistempl->type;
1806
1807 TLS_RL_RECORD_set_type(thiswr, rectype);
1808 TLS_RL_RECORD_set_rec_version(thiswr, thistempl->version);
1809
1810 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1811 &compressdata)) {
1812 /* RLAYERfatal() already called */
1813 goto err;
1814 }
1815
1816 /* lets setup the record stuff. */
1817 TLS_RL_RECORD_set_data(thiswr, compressdata);
1818 TLS_RL_RECORD_set_length(thiswr, thistempl->buflen);
1819
1820 TLS_RL_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1821
1822 /*
1823 * we now 'read' from thiswr->input, thiswr->length bytes into
1824 * thiswr->data
1825 */
1826
1827 /* first we compress */
1828 if (rl->compctx != NULL) {
1829 if (!tls_do_compress(rl, thiswr)
1830 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1831 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1832 goto err;
1833 }
1834 } else if (compressdata != NULL) {
1835 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1836 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1837 goto err;
1838 }
1839 TLS_RL_RECORD_reset_input(&wr[j]);
1840 }
1841
1842 if (rl->funcs->add_record_padding != NULL
1843 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1844 thiswr)) {
1845 /* RLAYERfatal() already called */
1846 goto err;
1847 }
1848
1849 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1850 /* RLAYERfatal() already called */
1851 goto err;
1852 }
1853 }
1854
1855 if (prefix) {
1856 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1857 if (rl->alert == SSL_AD_NO_ALERT) {
1858 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1859 }
1860 goto err;
1861 }
1862 }
1863
1864 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1865 if (rl->alert == SSL_AD_NO_ALERT) {
1866 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1867 }
1868 goto err;
1869 }
1870
1871 for (j = 0; j < numtempl + prefix; j++) {
1872 thispkt = &pkt[j];
1873 thiswr = &wr[j];
1874 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1875
1876 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1877 thispkt, thiswr)) {
1878 /* RLAYERfatal() already called */
1879 goto err;
1880 }
1881
1882 /* now let's set up wb */
1883 TLS_BUFFER_set_left(&rl->wbuf[j], TLS_RL_RECORD_get_length(thiswr));
1884 }
1885
1886 ret = 1;
1887 err:
1888 for (j = 0; j < wpinited; j++)
1889 WPACKET_cleanup(&pkt[j]);
1890 return ret;
1891 }
1892
tls_write_records(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl)1893 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1894 size_t numtempl)
1895 {
1896 /* Check we don't have pending data waiting to write */
1897 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1898 || TLS_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1899 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1900 return OSSL_RECORD_RETURN_FATAL;
1901 }
1902
1903 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1904 /* RLAYERfatal already called */
1905 return OSSL_RECORD_RETURN_FATAL;
1906 }
1907
1908 rl->nextwbuf = 0;
1909 /* we now just need to write the buffers */
1910 return tls_retry_write_records(rl);
1911 }
1912
tls_retry_write_records(OSSL_RECORD_LAYER * rl)1913 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1914 {
1915 int i, ret;
1916 TLS_BUFFER *thiswb;
1917 size_t tmpwrit = 0;
1918
1919 if (rl->nextwbuf >= rl->numwpipes)
1920 return OSSL_RECORD_RETURN_SUCCESS;
1921
1922 for (;;) {
1923 thiswb = &rl->wbuf[rl->nextwbuf];
1924
1925 clear_sys_error();
1926 if (rl->bio != NULL) {
1927 if (rl->funcs->prepare_write_bio != NULL) {
1928 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1929 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1930 return ret;
1931 }
1932 i = BIO_write(rl->bio, (char *)&(TLS_BUFFER_get_buf(thiswb)[TLS_BUFFER_get_offset(thiswb)]),
1933 (unsigned int)TLS_BUFFER_get_left(thiswb));
1934 if (i >= 0) {
1935 tmpwrit = i;
1936 if (i == 0 && BIO_should_retry(rl->bio))
1937 ret = OSSL_RECORD_RETURN_RETRY;
1938 else
1939 ret = OSSL_RECORD_RETURN_SUCCESS;
1940 } else {
1941 if (BIO_should_retry(rl->bio)) {
1942 ret = OSSL_RECORD_RETURN_RETRY;
1943 } else {
1944 ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
1945 "tls_retry_write_records failure");
1946 ret = OSSL_RECORD_RETURN_FATAL;
1947 }
1948 }
1949 } else {
1950 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1951 ret = OSSL_RECORD_RETURN_FATAL;
1952 i = -1;
1953 }
1954
1955 /*
1956 * When an empty fragment is sent on a connection using KTLS,
1957 * it is sent as a write of zero bytes. If this zero byte
1958 * write succeeds, i will be 0 rather than a non-zero value.
1959 * Treat i == 0 as success rather than an error for zero byte
1960 * writes to permit this case.
1961 */
1962 if (i >= 0 && tmpwrit == TLS_BUFFER_get_left(thiswb)) {
1963 TLS_BUFFER_set_left(thiswb, 0);
1964 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1965 if (++(rl->nextwbuf) < rl->numwpipes)
1966 continue;
1967
1968 if (rl->nextwbuf == rl->numwpipes
1969 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1970 tls_release_write_buffer(rl);
1971 return OSSL_RECORD_RETURN_SUCCESS;
1972 } else if (i <= 0) {
1973 if (rl->isdtls) {
1974 /*
1975 * For DTLS, just drop it. That's kind of the whole point in
1976 * using a datagram service
1977 */
1978 TLS_BUFFER_set_left(thiswb, 0);
1979 if (++(rl->nextwbuf) == rl->numwpipes
1980 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1981 tls_release_write_buffer(rl);
1982 }
1983 return ret;
1984 }
1985 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1986 TLS_BUFFER_sub_left(thiswb, tmpwrit);
1987 }
1988 }
1989
tls_get_alert_code(OSSL_RECORD_LAYER * rl)1990 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1991 {
1992 return rl->alert;
1993 }
1994
tls_set1_bio(OSSL_RECORD_LAYER * rl,BIO * bio)1995 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1996 {
1997 if (bio != NULL && !BIO_up_ref(bio))
1998 return 0;
1999 BIO_free(rl->bio);
2000 rl->bio = bio;
2001
2002 return 1;
2003 }
2004
2005 /* Shared by most methods except tlsany_meth */
tls_default_set_protocol_version(OSSL_RECORD_LAYER * rl,int version)2006 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
2007 {
2008 if (rl->version != version)
2009 return 0;
2010
2011 return 1;
2012 }
2013
tls_set_protocol_version(OSSL_RECORD_LAYER * rl,int version)2014 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
2015 {
2016 return rl->funcs->set_protocol_version(rl, version);
2017 }
2018
tls_set_plain_alerts(OSSL_RECORD_LAYER * rl,int allow)2019 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
2020 {
2021 rl->allow_plain_alerts = allow;
2022 }
2023
tls_set_first_handshake(OSSL_RECORD_LAYER * rl,int first)2024 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
2025 {
2026 rl->is_first_handshake = first;
2027 }
2028
tls_set_max_pipelines(OSSL_RECORD_LAYER * rl,size_t max_pipelines)2029 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
2030 {
2031 rl->max_pipelines = max_pipelines;
2032 if (max_pipelines > 1)
2033 rl->read_ahead = 1;
2034 }
2035
tls_get_state(OSSL_RECORD_LAYER * rl,const char ** shortstr,const char ** longstr)2036 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
2037 const char **longstr)
2038 {
2039 const char *shrt, *lng;
2040
2041 switch (rl->rstate) {
2042 case SSL_ST_READ_HEADER:
2043 shrt = "RH";
2044 lng = "read header";
2045 break;
2046 case SSL_ST_READ_BODY:
2047 shrt = "RB";
2048 lng = "read body";
2049 break;
2050 default:
2051 shrt = lng = "unknown";
2052 break;
2053 }
2054 if (shortstr != NULL)
2055 *shortstr = shrt;
2056 if (longstr != NULL)
2057 *longstr = lng;
2058 }
2059
tls_get_compression(OSSL_RECORD_LAYER * rl)2060 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
2061 {
2062 #ifndef OPENSSL_NO_COMP
2063 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
2064 #else
2065 return NULL;
2066 #endif
2067 }
2068
tls_set_max_frag_len(OSSL_RECORD_LAYER * rl,size_t max_frag_len)2069 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
2070 {
2071 rl->max_frag_len = max_frag_len;
2072 /*
2073 * We don't need to adjust buffer sizes. Write buffer sizes are
2074 * automatically checked anyway. We should only be changing the read buffer
2075 * size during the handshake, so we will create a new buffer when we create
2076 * the new record layer. We can't change the existing buffer because it may
2077 * already have data in it.
2078 */
2079 }
2080
tls_increment_sequence_ctr(OSSL_RECORD_LAYER * rl)2081 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2082 {
2083 int i;
2084
2085 /* Increment the sequence counter */
2086 for (i = SEQ_NUM_SIZE; i > 0; i--) {
2087 ++(rl->sequence[i - 1]);
2088 if (rl->sequence[i - 1] != 0)
2089 break;
2090 }
2091 if (i == 0) {
2092 /* Sequence has wrapped */
2093 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2094 return 0;
2095 }
2096 return 1;
2097 }
2098
tls_alloc_buffers(OSSL_RECORD_LAYER * rl)2099 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
2100 {
2101 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2102 /* If we have a pending write then buffers are already allocated */
2103 if (rl->nextwbuf < rl->numwpipes)
2104 return 1;
2105 /*
2106 * We assume 1 pipe with default sized buffer. If what we need ends up
2107 * being a different size to that then it will be reallocated on demand.
2108 * If we need more than 1 pipe then that will also be allocated on
2109 * demand
2110 */
2111 if (!tls_setup_write_buffer(rl, 1, 0, 0))
2112 return 0;
2113
2114 /*
2115 * Normally when we allocate write buffers we immediately write
2116 * something into it. In this case we're not doing that so mark the
2117 * buffer as empty.
2118 */
2119 TLS_BUFFER_set_left(&rl->wbuf[0], 0);
2120 return 1;
2121 }
2122
2123 /* Read direction */
2124
2125 /* If we have pending data to be read then buffers are already allocated */
2126 if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
2127 return 1;
2128 return tls_setup_read_buffer(rl);
2129 }
2130
tls_free_buffers(OSSL_RECORD_LAYER * rl)2131 int tls_free_buffers(OSSL_RECORD_LAYER *rl)
2132 {
2133 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2134 if (rl->nextwbuf < rl->numwpipes) {
2135 /*
2136 * We may have pending data. If we've just got one empty buffer
2137 * allocated then it has probably just been alloc'd via
2138 * tls_alloc_buffers, and it is fine to free it. Otherwise this
2139 * looks like real pending data and it is an error.
2140 */
2141 if (rl->nextwbuf != 0
2142 || rl->numwpipes != 1
2143 || TLS_BUFFER_get_left(&rl->wbuf[0]) != 0)
2144 return 0;
2145 }
2146 tls_release_write_buffer(rl);
2147 return 1;
2148 }
2149
2150 /* Read direction */
2151
2152 /* If we have pending data to be read then fail */
2153 if (rl->curr_rec < rl->num_recs
2154 || rl->curr_rec != rl->num_released
2155 || TLS_BUFFER_get_left(&rl->rbuf) != 0
2156 || rl->rstate == SSL_ST_READ_BODY)
2157 return 0;
2158
2159 return tls_release_read_buffer(rl);
2160 }
2161
2162 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2163 tls_new_record_layer,
2164 tls_free,
2165 tls_unprocessed_read_pending,
2166 tls_processed_read_pending,
2167 tls_app_data_pending,
2168 tls_get_max_records,
2169 tls_write_records,
2170 tls_retry_write_records,
2171 tls_read_record,
2172 tls_release_record,
2173 tls_get_alert_code,
2174 tls_set1_bio,
2175 tls_set_protocol_version,
2176 tls_set_plain_alerts,
2177 tls_set_first_handshake,
2178 tls_set_max_pipelines,
2179 NULL,
2180 tls_get_state,
2181 tls_set_options,
2182 tls_get_compression,
2183 tls_set_max_frag_len,
2184 NULL,
2185 tls_increment_sequence_ctr,
2186 tls_alloc_buffers,
2187 tls_free_buffers
2188 };
2189