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