1 /*
2 * Copyright 2022-2024 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 align = 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 align = SSL3_ALIGN_PAYLOAD - 1;
164 #endif
165
166 defltlen = align + 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 + align + 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, align = 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 align = (-SSL3_RT_HEADER_LENGTH) & (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 + align;
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) ||
579 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
580 size_t sslv2len;
581 unsigned int type;
582
583 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
584 TLS_BUFFER_get_len(rbuf), 0,
585 num_recs == 0 ? 1 : 0, &n);
586
587 if (rret < OSSL_RECORD_RETURN_SUCCESS)
588 return rret; /* error or non-blocking */
589
590 rl->rstate = SSL_ST_READ_BODY;
591
592 p = rl->packet;
593 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
594 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
595 return OSSL_RECORD_RETURN_FATAL;
596 }
597 sslv2pkt = pkt;
598 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
599 || !PACKET_get_1(&sslv2pkt, &type)) {
600 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
601 return OSSL_RECORD_RETURN_FATAL;
602 }
603 /*
604 * The first record received by the server may be a V2ClientHello.
605 */
606 if (rl->role == OSSL_RECORD_ROLE_SERVER
607 && rl->is_first_record
608 && (sslv2len & 0x8000) != 0
609 && (type == SSL2_MT_CLIENT_HELLO)) {
610 /*
611 * SSLv2 style record
612 *
613 * |num_recs| here will actually always be 0 because
614 * |num_recs > 0| only ever occurs when we are processing
615 * multiple app data records - which we know isn't the case here
616 * because it is an SSLv2ClientHello. We keep it using
617 * |num_recs| for the sake of consistency
618 */
619 thisrr->type = SSL3_RT_HANDSHAKE;
620 thisrr->rec_version = SSL2_VERSION;
621
622 thisrr->length = sslv2len & 0x7fff;
623
624 if (thisrr->length > TLS_BUFFER_get_len(rbuf)
625 - SSL2_RT_HEADER_LENGTH) {
626 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
627 SSL_R_PACKET_LENGTH_TOO_LONG);
628 return OSSL_RECORD_RETURN_FATAL;
629 }
630 } else {
631 /* SSLv3+ style record */
632
633 /* Pull apart the header into the TLS_RL_RECORD */
634 if (!PACKET_get_1(&pkt, &type)
635 || !PACKET_get_net_2(&pkt, &version)
636 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
637 if (rl->msg_callback != NULL)
638 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
639 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
640 return OSSL_RECORD_RETURN_FATAL;
641 }
642 thisrr->type = type;
643 thisrr->rec_version = version;
644
645 /*
646 * When we call validate_record_header() only records actually
647 * received in SSLv2 format should have the record version set
648 * to SSL2_VERSION. This way validate_record_header() can know
649 * what format the record was in based on the version.
650 */
651 if (thisrr->rec_version == SSL2_VERSION) {
652 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
653 SSL_R_WRONG_VERSION_NUMBER);
654 return OSSL_RECORD_RETURN_FATAL;
655 }
656
657 if (rl->msg_callback != NULL)
658 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
659
660 if (thisrr->length >
661 TLS_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
662 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
663 SSL_R_PACKET_LENGTH_TOO_LONG);
664 return OSSL_RECORD_RETURN_FATAL;
665 }
666 }
667
668 if (!rl->funcs->validate_record_header(rl, thisrr)) {
669 /* RLAYERfatal already called */
670 return OSSL_RECORD_RETURN_FATAL;
671 }
672
673 /* now rl->rstate == SSL_ST_READ_BODY */
674 }
675
676 /*
677 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
678 * how much more data we need to read for the rest of the record
679 */
680 if (thisrr->rec_version == SSL2_VERSION) {
681 more = thisrr->length + SSL2_RT_HEADER_LENGTH
682 - SSL3_RT_HEADER_LENGTH;
683 } else {
684 more = thisrr->length;
685 }
686
687 if (more > 0) {
688 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
689
690 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
691 if (rret < OSSL_RECORD_RETURN_SUCCESS)
692 return rret; /* error or non-blocking io */
693 }
694
695 /* set state for later operations */
696 rl->rstate = SSL_ST_READ_HEADER;
697
698 /*
699 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
700 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
701 * + thisrr->length and we have that many bytes in rl->packet
702 */
703 if (thisrr->rec_version == SSL2_VERSION)
704 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
705 else
706 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
707
708 /*
709 * ok, we can now read from 'rl->packet' data into 'thisrr'.
710 * thisrr->input points at thisrr->length bytes, which need to be copied
711 * into thisrr->data by either the decryption or by the decompression.
712 * When the data is 'copied' into the thisrr->data buffer,
713 * thisrr->input will be updated to point at the new buffer
714 */
715
716 /*
717 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
718 * thisrr->length bytes of encrypted compressed stuff.
719 */
720
721 /* decrypt in place in 'thisrr->input' */
722 thisrr->data = thisrr->input;
723 thisrr->orig_len = thisrr->length;
724
725 num_recs++;
726
727 /* we have pulled in a full packet so zero things */
728 rl->packet_length = 0;
729 rl->is_first_record = 0;
730 } while (num_recs < max_recs
731 && thisrr->type == SSL3_RT_APPLICATION_DATA
732 && RLAYER_USE_EXPLICIT_IV(rl)
733 && rl->enc_ctx != NULL
734 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
735 & EVP_CIPH_FLAG_PIPELINE) != 0
736 && tls_record_app_data_waiting(rl));
737
738 if (num_recs == 1
739 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
740 /* The following can happen in tlsany_meth after HRR */
741 && rl->version == TLS1_3_VERSION
742 && rl->is_first_handshake) {
743 /*
744 * CCS messages must be exactly 1 byte long, containing the value 0x01
745 */
746 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
747 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
748 SSL_R_INVALID_CCS_MESSAGE);
749 return OSSL_RECORD_RETURN_FATAL;
750 }
751 /*
752 * CCS messages are ignored in TLSv1.3. We treat it like an empty
753 * handshake record
754 */
755 thisrr->type = SSL3_RT_HANDSHAKE;
756 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
757 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
758 SSL_R_UNEXPECTED_CCS_MESSAGE);
759 return OSSL_RECORD_RETURN_FATAL;
760 }
761 rl->num_recs = 0;
762 rl->curr_rec = 0;
763 rl->num_released = 0;
764
765 return OSSL_RECORD_RETURN_SUCCESS;
766 }
767
768 if (rl->md_ctx != NULL) {
769 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
770
771 if (tmpmd != NULL) {
772 imac_size = EVP_MD_get_size(tmpmd);
773 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
774 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
775 return OSSL_RECORD_RETURN_FATAL;
776 }
777 mac_size = (size_t)imac_size;
778 }
779 }
780
781 /*
782 * If in encrypt-then-mac mode calculate mac from encrypted record. All
783 * the details below are public so no timing details can leak.
784 */
785 if (rl->use_etm && rl->md_ctx != NULL) {
786 unsigned char *mac;
787
788 for (j = 0; j < num_recs; j++) {
789 thisrr = &rr[j];
790
791 if (thisrr->length < mac_size) {
792 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
793 return OSSL_RECORD_RETURN_FATAL;
794 }
795 thisrr->length -= mac_size;
796 mac = thisrr->data + thisrr->length;
797 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
798 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
799 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
800 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
801 return OSSL_RECORD_RETURN_FATAL;
802 }
803 }
804 /*
805 * We've handled the mac now - there is no MAC inside the encrypted
806 * record
807 */
808 mac_size = 0;
809 }
810
811 if (mac_size > 0) {
812 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
813 if (macbufs == NULL) {
814 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
815 return OSSL_RECORD_RETURN_FATAL;
816 }
817 }
818
819 ERR_set_mark();
820 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
821
822 /*-
823 * enc_err is:
824 * 0: if the record is publicly invalid, or an internal error, or AEAD
825 * decryption failed, or ETM decryption failed.
826 * 1: Success or MTE decryption failed (MAC will be randomised)
827 */
828 if (enc_err == 0) {
829 if (rl->alert != SSL_AD_NO_ALERT) {
830 /* RLAYERfatal() already got called */
831 ERR_clear_last_mark();
832 goto end;
833 }
834 if (num_recs == 1
835 && rl->skip_early_data != NULL
836 && rl->skip_early_data(rl->cbarg)) {
837 /*
838 * Valid early_data that we cannot decrypt will fail here. We treat
839 * it like an empty record.
840 */
841
842 /*
843 * Remove any errors from the stack. Decryption failures are normal
844 * behaviour.
845 */
846 ERR_pop_to_mark();
847
848 thisrr = &rr[0];
849
850 if (!rlayer_early_data_count_ok(rl, thisrr->length,
851 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
852 /* RLAYERfatal() already called */
853 goto end;
854 }
855
856 thisrr->length = 0;
857 rl->num_recs = 0;
858 rl->curr_rec = 0;
859 rl->num_released = 0;
860 /* Reset the read sequence */
861 memset(rl->sequence, 0, sizeof(rl->sequence));
862 ret = 1;
863 goto end;
864 }
865 ERR_clear_last_mark();
866 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
867 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
868 goto end;
869 } else {
870 ERR_clear_last_mark();
871 }
872 OSSL_TRACE_BEGIN(TLS) {
873 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
874 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
875 } OSSL_TRACE_END(TLS);
876
877 /* r->length is now the compressed data plus mac */
878 if (rl->enc_ctx != NULL
879 && !rl->use_etm
880 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
881 for (j = 0; j < num_recs; j++) {
882 SSL_MAC_BUF *thismb = &macbufs[j];
883
884 thisrr = &rr[j];
885
886 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
887 if (i == 0 || thismb == NULL || thismb->mac == NULL
888 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
889 enc_err = 0;
890 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
891 enc_err = 0;
892 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
893 if (enc_err == 0 && mac_size > 0 && thismb != NULL &&
894 thismb->mac != NULL && (md[0] ^ thismb->mac[0]) != 0xFF) {
895 enc_err = 1;
896 }
897 #endif
898 }
899 }
900
901 if (enc_err == 0) {
902 if (rl->alert != SSL_AD_NO_ALERT) {
903 /* We already called RLAYERfatal() */
904 goto end;
905 }
906 /*
907 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
908 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
909 * failure is directly visible from the ciphertext anyway, we should
910 * not reveal which kind of error occurred -- this might become
911 * visible to an attacker (e.g. via a logfile)
912 */
913 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
914 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
915 goto end;
916 }
917
918 for (j = 0; j < num_recs; j++) {
919 thisrr = &rr[j];
920
921 if (!rl->funcs->post_process_record(rl, thisrr)) {
922 /* RLAYERfatal already called */
923 goto end;
924 }
925
926 /*
927 * Record overflow checking (e.g. checking if
928 * thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) is the responsibility of
929 * the post_process_record() function above. However we check here if
930 * the received packet overflows the current Max Fragment Length setting
931 * if there is one.
932 * Note: rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH and KTLS are
933 * mutually exclusive. Also note that with KTLS thisrr->length can
934 * be > SSL3_RT_MAX_PLAIN_LENGTH (and rl->max_frag_len must be ignored)
935 */
936 if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH
937 && thisrr->length > rl->max_frag_len) {
938 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
939 goto end;
940 }
941
942 thisrr->off = 0;
943 /*-
944 * So at this point the following is true
945 * thisrr->type is the type of record
946 * thisrr->length == number of bytes in record
947 * thisrr->off == offset to first valid byte
948 * thisrr->data == where to take bytes from, increment after use :-).
949 */
950
951 /* just read a 0 length packet */
952 if (thisrr->length == 0) {
953 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
954 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
955 SSL_R_RECORD_TOO_SMALL);
956 goto end;
957 }
958 } else {
959 rl->empty_record_count = 0;
960 }
961 }
962
963 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
964 thisrr = &rr[0];
965 if (thisrr->type == SSL3_RT_APPLICATION_DATA
966 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
967 /* RLAYERfatal already called */
968 goto end;
969 }
970 }
971
972 rl->num_recs = num_recs;
973 rl->curr_rec = 0;
974 rl->num_released = 0;
975 ret = OSSL_RECORD_RETURN_SUCCESS;
976 end:
977 if (macbufs != NULL) {
978 for (j = 0; j < num_recs; j++) {
979 if (macbufs[j].alloced)
980 OPENSSL_free(macbufs[j].mac);
981 }
982 OPENSSL_free(macbufs);
983 }
984 return ret;
985 }
986
987 /* Shared by ssl3_meth and tls1_meth */
tls_default_validate_record_header(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)988 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
989 {
990 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
991
992 if (rec->rec_version != rl->version) {
993 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
994 return 0;
995 }
996
997 #ifndef OPENSSL_NO_COMP
998 /*
999 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
1000 * does not include the compression overhead anyway.
1001 */
1002 if (rl->compctx == NULL)
1003 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1004 #endif
1005
1006 if (rec->length > len) {
1007 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1008 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1009 return 0;
1010 }
1011
1012 return 1;
1013 }
1014
tls_do_compress(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * wr)1015 int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr)
1016 {
1017 #ifndef OPENSSL_NO_COMP
1018 int i;
1019
1020 i = COMP_compress_block(rl->compctx, wr->data,
1021 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
1022 wr->input, (int)wr->length);
1023 if (i < 0)
1024 return 0;
1025
1026 wr->length = i;
1027 wr->input = wr->data;
1028 return 1;
1029 #else
1030 return 0;
1031 #endif
1032 }
1033
tls_do_uncompress(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1034 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1035 {
1036 #ifndef OPENSSL_NO_COMP
1037 int i;
1038
1039 if (rec->comp == NULL) {
1040 rec->comp = (unsigned char *)
1041 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
1042 }
1043 if (rec->comp == NULL)
1044 return 0;
1045
1046 i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
1047 rec->data, (int)rec->length);
1048 if (i < 0)
1049 return 0;
1050 else
1051 rec->length = i;
1052 rec->data = rec->comp;
1053 return 1;
1054 #else
1055 return 0;
1056 #endif
1057 }
1058
1059 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
tls_default_post_process_record(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1060 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1061 {
1062 if (rl->compctx != NULL) {
1063 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1064 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1065 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1066 return 0;
1067 }
1068 if (!tls_do_uncompress(rl, rec)) {
1069 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1070 SSL_R_BAD_DECOMPRESSION);
1071 return 0;
1072 }
1073 }
1074
1075 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1076 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1077 return 0;
1078 }
1079
1080 return 1;
1081 }
1082
1083 /* Shared by tls13_meth and ktls_meth */
tls13_common_post_process_record(OSSL_RECORD_LAYER * rl,TLS_RL_RECORD * rec)1084 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1085 {
1086 if (rec->type != SSL3_RT_APPLICATION_DATA
1087 && rec->type != SSL3_RT_ALERT
1088 && rec->type != SSL3_RT_HANDSHAKE) {
1089 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1090 return 0;
1091 }
1092
1093 if (rl->msg_callback != NULL)
1094 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1095 1, rl->cbarg);
1096
1097 /*
1098 * TLSv1.3 alert and handshake records are required to be non-zero in
1099 * length.
1100 */
1101 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1102 && rec->length == 0) {
1103 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1104 return 0;
1105 }
1106
1107 return 1;
1108 }
1109
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)1110 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1111 uint8_t *type, const unsigned char **data, size_t *datalen,
1112 uint16_t *epoch, unsigned char *seq_num)
1113 {
1114 TLS_RL_RECORD *rec;
1115
1116 /*
1117 * tls_get_more_records() can return success without actually reading
1118 * anything useful (i.e. if empty records are read). We loop here until
1119 * we have something useful. tls_get_more_records() will eventually fail if
1120 * too many sequential empty records are read.
1121 */
1122 while (rl->curr_rec >= rl->num_recs) {
1123 int ret;
1124
1125 if (rl->num_released != rl->num_recs) {
1126 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1127 return OSSL_RECORD_RETURN_FATAL;
1128 }
1129
1130 ret = rl->funcs->get_more_records(rl);
1131
1132 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1133 return ret;
1134 }
1135
1136 /*
1137 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1138 * points to the next one to read.
1139 */
1140 rec = &rl->rrec[rl->curr_rec++];
1141
1142 *rechandle = rec;
1143 *rversion = rec->rec_version;
1144 *type = rec->type;
1145 *data = rec->data + rec->off;
1146 *datalen = rec->length;
1147 if (rl->isdtls) {
1148 *epoch = rec->epoch;
1149 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1150 }
1151
1152 return OSSL_RECORD_RETURN_SUCCESS;
1153 }
1154
tls_release_record(OSSL_RECORD_LAYER * rl,void * rechandle,size_t length)1155 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length)
1156 {
1157 TLS_RL_RECORD *rec = &rl->rrec[rl->num_released];
1158
1159 if (!ossl_assert(rl->num_released < rl->curr_rec)
1160 || !ossl_assert(rechandle == rec)) {
1161 /* Should not happen */
1162 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1163 return OSSL_RECORD_RETURN_FATAL;
1164 }
1165
1166 if (rec->length < length) {
1167 /* Should not happen */
1168 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1169 return OSSL_RECORD_RETURN_FATAL;
1170 }
1171
1172 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
1173 OPENSSL_cleanse(rec->data + rec->off, length);
1174
1175 rec->off += length;
1176 rec->length -= length;
1177
1178 if (rec->length > 0)
1179 return OSSL_RECORD_RETURN_SUCCESS;
1180
1181 rl->num_released++;
1182
1183 if (rl->curr_rec == rl->num_released
1184 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1185 && TLS_BUFFER_get_left(&rl->rbuf) == 0)
1186 tls_release_read_buffer(rl);
1187
1188 return OSSL_RECORD_RETURN_SUCCESS;
1189 }
1190
tls_set_options(OSSL_RECORD_LAYER * rl,const OSSL_PARAM * options)1191 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1192 {
1193 const OSSL_PARAM *p;
1194
1195 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1196 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1197 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1198 return 0;
1199 }
1200
1201 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1202 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1203 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1204 return 0;
1205 }
1206
1207 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1208 p = OSSL_PARAM_locate_const(options,
1209 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1210 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1211 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1212 return 0;
1213 }
1214 } else {
1215 p = OSSL_PARAM_locate_const(options,
1216 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1217 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1218 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1219 return 0;
1220 }
1221 }
1222
1223 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1224 /*
1225 * We ignore any read_ahead setting prior to the application protection
1226 * level. Otherwise we may read ahead data in a lower protection level
1227 * that is destined for a higher protection level. To simplify the logic
1228 * we don't support that at this stage.
1229 */
1230 p = OSSL_PARAM_locate_const(options,
1231 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1232 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1233 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1234 return 0;
1235 }
1236 }
1237
1238 return 1;
1239 }
1240
1241 int
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)1242 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1243 int role, int direction, int level,
1244 const EVP_CIPHER *ciph, size_t taglen,
1245 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1246 BIO *transport, BIO *next, const OSSL_PARAM *settings,
1247 const OSSL_PARAM *options,
1248 const OSSL_DISPATCH *fns, void *cbarg,
1249 OSSL_RECORD_LAYER **retrl)
1250 {
1251 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1252 const OSSL_PARAM *p;
1253
1254 *retrl = NULL;
1255
1256 if (rl == NULL)
1257 return OSSL_RECORD_RETURN_FATAL;
1258
1259 /*
1260 * Default the value for max_frag_len. This may be overridden by the
1261 * settings
1262 */
1263 rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
1264
1265 /* Loop through all the settings since they must all be understood */
1266 if (settings != NULL) {
1267 for (p = settings; p->key != NULL; p++) {
1268 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1269 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1270 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1271 goto err;
1272 }
1273 } else if (strcmp(p->key,
1274 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1275 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1276 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1277 goto err;
1278 }
1279 } else if (strcmp(p->key,
1280 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1281 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1282 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1283 goto err;
1284 }
1285 } else if (strcmp(p->key,
1286 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1287 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
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_TLSTREE) == 0) {
1293 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1294 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1295 goto err;
1296 }
1297 } else {
1298 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1299 goto err;
1300 }
1301 }
1302 }
1303
1304 rl->libctx = libctx;
1305 rl->propq = propq;
1306
1307 rl->version = vers;
1308 rl->role = role;
1309 rl->direction = direction;
1310 rl->level = level;
1311 rl->taglen = taglen;
1312 rl->md = md;
1313
1314 rl->alert = SSL_AD_NO_ALERT;
1315 rl->rstate = SSL_ST_READ_HEADER;
1316
1317 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1318 rl->is_first_record = 1;
1319
1320 if (!tls_set1_bio(rl, transport))
1321 goto err;
1322
1323 if (prev != NULL && !BIO_up_ref(prev))
1324 goto err;
1325 rl->prev = prev;
1326
1327 if (next != NULL && !BIO_up_ref(next))
1328 goto err;
1329 rl->next = next;
1330
1331 rl->cbarg = cbarg;
1332 if (fns != NULL) {
1333 for (; fns->function_id != 0; fns++) {
1334 switch (fns->function_id) {
1335 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1336 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1337 break;
1338 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1339 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1340 break;
1341 case OSSL_FUNC_RLAYER_SECURITY:
1342 rl->security = OSSL_FUNC_rlayer_security(fns);
1343 break;
1344 case OSSL_FUNC_RLAYER_PADDING:
1345 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1346 default:
1347 /* Just ignore anything we don't understand */
1348 break;
1349 }
1350 }
1351 }
1352
1353 if (!tls_set_options(rl, options)) {
1354 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1355 goto err;
1356 }
1357
1358 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1359 && rl->version <= TLS1_VERSION
1360 && !EVP_CIPHER_is_a(ciph, "NULL")
1361 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1362 /*
1363 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1364 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1365 */
1366 rl->need_empty_fragments = 1;
1367 }
1368
1369 *retrl = rl;
1370 return OSSL_RECORD_RETURN_SUCCESS;
1371 err:
1372 tls_int_free(rl);
1373 return OSSL_RECORD_RETURN_FATAL;
1374 }
1375
1376 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)1377 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1378 int role, int direction, int level, uint16_t epoch,
1379 unsigned char *secret, size_t secretlen,
1380 unsigned char *key, size_t keylen, unsigned char *iv,
1381 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1382 const EVP_CIPHER *ciph, size_t taglen,
1383 int mactype,
1384 const EVP_MD *md, COMP_METHOD *comp,
1385 const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
1386 BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1387 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1388 const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
1389 OSSL_RECORD_LAYER **retrl)
1390 {
1391 int ret;
1392
1393 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1394 ciph, taglen, md, comp, prev,
1395 transport, next, settings,
1396 options, fns, cbarg, retrl);
1397
1398 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1399 return ret;
1400
1401 switch (vers) {
1402 case TLS_ANY_VERSION:
1403 (*retrl)->funcs = &tls_any_funcs;
1404 break;
1405 case TLS1_3_VERSION:
1406 (*retrl)->funcs = &tls_1_3_funcs;
1407 break;
1408 case TLS1_2_VERSION:
1409 case TLS1_1_VERSION:
1410 case TLS1_VERSION:
1411 (*retrl)->funcs = &tls_1_funcs;
1412 break;
1413 case SSL3_VERSION:
1414 (*retrl)->funcs = &ssl_3_0_funcs;
1415 break;
1416 default:
1417 /* Should not happen */
1418 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1419 ret = OSSL_RECORD_RETURN_FATAL;
1420 goto err;
1421 }
1422
1423 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1424 ivlen, mackey, mackeylen, ciph,
1425 taglen, mactype, md, comp);
1426
1427 err:
1428 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1429 tls_int_free(*retrl);
1430 *retrl = NULL;
1431 }
1432 return ret;
1433 }
1434
tls_int_free(OSSL_RECORD_LAYER * rl)1435 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1436 {
1437 BIO_free(rl->prev);
1438 BIO_free(rl->bio);
1439 BIO_free(rl->next);
1440 ossl_tls_buffer_release(&rl->rbuf);
1441
1442 tls_release_write_buffer(rl);
1443
1444 EVP_CIPHER_CTX_free(rl->enc_ctx);
1445 EVP_MAC_CTX_free(rl->mac_ctx);
1446 EVP_MD_CTX_free(rl->md_ctx);
1447 #ifndef OPENSSL_NO_COMP
1448 COMP_CTX_free(rl->compctx);
1449 #endif
1450 OPENSSL_free(rl->iv);
1451 OPENSSL_free(rl->nonce);
1452 if (rl->version == SSL3_VERSION)
1453 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1454
1455 TLS_RL_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1456
1457 OPENSSL_free(rl);
1458 }
1459
tls_free(OSSL_RECORD_LAYER * rl)1460 int tls_free(OSSL_RECORD_LAYER *rl)
1461 {
1462 TLS_BUFFER *rbuf;
1463 size_t left, written;
1464 int ret = 1;
1465
1466 if (rl == NULL)
1467 return 1;
1468
1469 rbuf = &rl->rbuf;
1470
1471 left = TLS_BUFFER_get_left(rbuf);
1472 if (left > 0) {
1473 /*
1474 * This record layer is closing but we still have data left in our
1475 * buffer. It must be destined for the next epoch - so push it there.
1476 */
1477 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1478 }
1479 tls_int_free(rl);
1480
1481 return ret;
1482 }
1483
tls_unprocessed_read_pending(OSSL_RECORD_LAYER * rl)1484 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1485 {
1486 return TLS_BUFFER_get_left(&rl->rbuf) != 0;
1487 }
1488
tls_processed_read_pending(OSSL_RECORD_LAYER * rl)1489 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1490 {
1491 return rl->curr_rec < rl->num_recs;
1492 }
1493
tls_app_data_pending(OSSL_RECORD_LAYER * rl)1494 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1495 {
1496 size_t i;
1497 size_t num = 0;
1498
1499 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1500 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1501 return num;
1502 num += rl->rrec[i].length;
1503 }
1504 return num;
1505 }
1506
tls_get_max_records_default(OSSL_RECORD_LAYER * rl,uint8_t type,size_t len,size_t maxfrag,size_t * preffrag)1507 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type,
1508 size_t len,
1509 size_t maxfrag, size_t *preffrag)
1510 {
1511 /*
1512 * If we have a pipeline capable cipher, and we have been configured to use
1513 * it, then return the preferred number of pipelines.
1514 */
1515 if (rl->max_pipelines > 0
1516 && rl->enc_ctx != NULL
1517 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1518 & EVP_CIPH_FLAG_PIPELINE) != 0
1519 && RLAYER_USE_EXPLICIT_IV(rl)) {
1520 size_t pipes;
1521
1522 if (len == 0)
1523 return 1;
1524 pipes = ((len - 1) / *preffrag) + 1;
1525
1526 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1527 }
1528
1529 return 1;
1530 }
1531
tls_get_max_records(OSSL_RECORD_LAYER * rl,uint8_t type,size_t len,size_t maxfrag,size_t * preffrag)1532 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
1533 size_t maxfrag, size_t *preffrag)
1534 {
1535 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1536 }
1537
tls_allocate_write_buffers_default(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl,size_t * prefix)1538 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1539 OSSL_RECORD_TEMPLATE *templates,
1540 size_t numtempl,
1541 size_t *prefix)
1542 {
1543 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1544 /* RLAYERfatal() already called */
1545 return 0;
1546 }
1547
1548 return 1;
1549 }
1550
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)1551 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1552 OSSL_RECORD_TEMPLATE *templates,
1553 size_t numtempl,
1554 OSSL_RECORD_TEMPLATE *prefixtempl,
1555 WPACKET *pkt,
1556 TLS_BUFFER *bufs,
1557 size_t *wpinited)
1558 {
1559 WPACKET *thispkt;
1560 size_t j, align;
1561 TLS_BUFFER *wb;
1562
1563 for (j = 0; j < numtempl; j++) {
1564 thispkt = &pkt[j];
1565 wb = &bufs[j];
1566
1567 wb->type = templates[j].type;
1568
1569 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1570 align = (size_t)TLS_BUFFER_get_buf(wb);
1571 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1572 align = SSL3_ALIGN_PAYLOAD - 1
1573 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1574 #endif
1575 TLS_BUFFER_set_offset(wb, align);
1576
1577 if (!WPACKET_init_static_len(thispkt, TLS_BUFFER_get_buf(wb),
1578 TLS_BUFFER_get_len(wb), 0)) {
1579 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1580 return 0;
1581 }
1582 (*wpinited)++;
1583 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1584 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1585 return 0;
1586 }
1587 }
1588
1589 return 1;
1590 }
1591
tls_prepare_record_header_default(OSSL_RECORD_LAYER * rl,WPACKET * thispkt,OSSL_RECORD_TEMPLATE * templ,uint8_t rectype,unsigned char ** recdata)1592 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1593 WPACKET *thispkt,
1594 OSSL_RECORD_TEMPLATE *templ,
1595 uint8_t rectype,
1596 unsigned char **recdata)
1597 {
1598 size_t maxcomplen;
1599
1600 *recdata = NULL;
1601
1602 maxcomplen = templ->buflen;
1603 if (rl->compctx != NULL)
1604 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1605
1606 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1607 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1608 || !WPACKET_start_sub_packet_u16(thispkt)
1609 || (rl->eivlen > 0
1610 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1611 || (maxcomplen > 0
1612 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1613 recdata))) {
1614 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1615 return 0;
1616 }
1617
1618 return 1;
1619 }
1620
tls_prepare_for_encryption_default(OSSL_RECORD_LAYER * rl,size_t mac_size,WPACKET * thispkt,TLS_RL_RECORD * thiswr)1621 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1622 size_t mac_size,
1623 WPACKET *thispkt,
1624 TLS_RL_RECORD *thiswr)
1625 {
1626 size_t len;
1627 unsigned char *recordstart;
1628
1629 /*
1630 * we should still have the output to thiswr->data and the input from
1631 * wr->input. Length should be thiswr->length. thiswr->data still points
1632 * in the wb->buf
1633 */
1634
1635 if (!rl->use_etm && mac_size != 0) {
1636 unsigned char *mac;
1637
1638 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1639 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1640 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1641 return 0;
1642 }
1643 }
1644
1645 /*
1646 * Reserve some bytes for any growth that may occur during encryption. If
1647 * we are adding the MAC independently of the cipher algorithm, then the
1648 * max encrypted overhead does not need to include an allocation for that
1649 * MAC
1650 */
1651 if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
1652 - mac_size, NULL)
1653 /*
1654 * We also need next the amount of bytes written to this
1655 * sub-packet
1656 */
1657 || !WPACKET_get_length(thispkt, &len)) {
1658 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1659 return 0;
1660 }
1661
1662 /* Get a pointer to the start of this record excluding header */
1663 recordstart = WPACKET_get_curr(thispkt) - len;
1664 TLS_RL_RECORD_set_data(thiswr, recordstart);
1665 TLS_RL_RECORD_reset_input(thiswr);
1666 TLS_RL_RECORD_set_length(thiswr, len);
1667
1668 return 1;
1669 }
1670
tls_post_encryption_processing_default(OSSL_RECORD_LAYER * rl,size_t mac_size,OSSL_RECORD_TEMPLATE * thistempl,WPACKET * thispkt,TLS_RL_RECORD * thiswr)1671 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1672 size_t mac_size,
1673 OSSL_RECORD_TEMPLATE *thistempl,
1674 WPACKET *thispkt,
1675 TLS_RL_RECORD *thiswr)
1676 {
1677 size_t origlen, len;
1678 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1679 : SSL3_RT_HEADER_LENGTH;
1680
1681 /* Allocate bytes for the encryption overhead */
1682 if (!WPACKET_get_length(thispkt, &origlen)
1683 /* Check we allowed enough room for the encryption growth */
1684 || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
1685 - mac_size >= thiswr->length)
1686 /* Encryption should never shrink the data! */
1687 || origlen > thiswr->length
1688 || (thiswr->length > origlen
1689 && !WPACKET_allocate_bytes(thispkt,
1690 thiswr->length - origlen,
1691 NULL))) {
1692 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1693 return 0;
1694 }
1695 if (rl->use_etm && mac_size != 0) {
1696 unsigned char *mac;
1697
1698 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1699 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1700 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1701 return 0;
1702 }
1703
1704 TLS_RL_RECORD_add_length(thiswr, mac_size);
1705 }
1706
1707 if (!WPACKET_get_length(thispkt, &len)
1708 || !WPACKET_close(thispkt)) {
1709 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1710 return 0;
1711 }
1712
1713 if (rl->msg_callback != NULL) {
1714 unsigned char *recordstart;
1715
1716 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1717 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1718 headerlen, rl->cbarg);
1719
1720 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1721 unsigned char ctype = thistempl->type;
1722
1723 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1724 &ctype, 1, rl->cbarg);
1725 }
1726 }
1727
1728 if (!WPACKET_finish(thispkt)) {
1729 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1730 return 0;
1731 }
1732
1733 TLS_RL_RECORD_add_length(thiswr, headerlen);
1734
1735 return 1;
1736 }
1737
tls_write_records_default(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl)1738 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1739 OSSL_RECORD_TEMPLATE *templates,
1740 size_t numtempl)
1741 {
1742 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1743 TLS_RL_RECORD wr[SSL_MAX_PIPELINES + 1];
1744 WPACKET *thispkt;
1745 TLS_RL_RECORD *thiswr;
1746 int mac_size = 0, ret = 0;
1747 size_t wpinited = 0;
1748 size_t j, prefix = 0;
1749 OSSL_RECORD_TEMPLATE prefixtempl;
1750 OSSL_RECORD_TEMPLATE *thistempl;
1751
1752 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1753 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1754 if (mac_size < 0) {
1755 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1756 goto err;
1757 }
1758 }
1759
1760 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1761 /* RLAYERfatal() already called */
1762 goto err;
1763 }
1764
1765 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1766 &prefixtempl, pkt, rl->wbuf,
1767 &wpinited)) {
1768 /* RLAYERfatal() already called */
1769 goto err;
1770 }
1771
1772 /* Clear our TLS_RL_RECORD structures */
1773 memset(wr, 0, sizeof(wr));
1774 for (j = 0; j < numtempl + prefix; j++) {
1775 unsigned char *compressdata = NULL;
1776 uint8_t rectype;
1777
1778 thispkt = &pkt[j];
1779 thiswr = &wr[j];
1780 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1781
1782 /*
1783 * Default to the record type as specified in the template unless the
1784 * protocol implementation says differently.
1785 */
1786 if (rl->funcs->get_record_type != NULL)
1787 rectype = rl->funcs->get_record_type(rl, thistempl);
1788 else
1789 rectype = thistempl->type;
1790
1791 TLS_RL_RECORD_set_type(thiswr, rectype);
1792 TLS_RL_RECORD_set_rec_version(thiswr, thistempl->version);
1793
1794 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1795 &compressdata)) {
1796 /* RLAYERfatal() already called */
1797 goto err;
1798 }
1799
1800 /* lets setup the record stuff. */
1801 TLS_RL_RECORD_set_data(thiswr, compressdata);
1802 TLS_RL_RECORD_set_length(thiswr, thistempl->buflen);
1803
1804 TLS_RL_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1805
1806 /*
1807 * we now 'read' from thiswr->input, thiswr->length bytes into
1808 * thiswr->data
1809 */
1810
1811 /* first we compress */
1812 if (rl->compctx != NULL) {
1813 if (!tls_do_compress(rl, thiswr)
1814 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1815 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1816 goto err;
1817 }
1818 } else if (compressdata != NULL) {
1819 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1820 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1821 goto err;
1822 }
1823 TLS_RL_RECORD_reset_input(&wr[j]);
1824 }
1825
1826 if (rl->funcs->add_record_padding != NULL
1827 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1828 thiswr)) {
1829 /* RLAYERfatal() already called */
1830 goto err;
1831 }
1832
1833 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1834 /* RLAYERfatal() already called */
1835 goto err;
1836 }
1837 }
1838
1839 if (prefix) {
1840 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1841 if (rl->alert == SSL_AD_NO_ALERT) {
1842 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1843 }
1844 goto err;
1845 }
1846 }
1847
1848 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1849 if (rl->alert == SSL_AD_NO_ALERT) {
1850 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1851 }
1852 goto err;
1853 }
1854
1855 for (j = 0; j < numtempl + prefix; j++) {
1856 thispkt = &pkt[j];
1857 thiswr = &wr[j];
1858 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1859
1860 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1861 thispkt, thiswr)) {
1862 /* RLAYERfatal() already called */
1863 goto err;
1864 }
1865
1866 /* now let's set up wb */
1867 TLS_BUFFER_set_left(&rl->wbuf[j], TLS_RL_RECORD_get_length(thiswr));
1868 }
1869
1870 ret = 1;
1871 err:
1872 for (j = 0; j < wpinited; j++)
1873 WPACKET_cleanup(&pkt[j]);
1874 return ret;
1875 }
1876
tls_write_records(OSSL_RECORD_LAYER * rl,OSSL_RECORD_TEMPLATE * templates,size_t numtempl)1877 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1878 size_t numtempl)
1879 {
1880 /* Check we don't have pending data waiting to write */
1881 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1882 || TLS_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1883 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1884 return OSSL_RECORD_RETURN_FATAL;
1885 }
1886
1887 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1888 /* RLAYERfatal already called */
1889 return OSSL_RECORD_RETURN_FATAL;
1890 }
1891
1892 rl->nextwbuf = 0;
1893 /* we now just need to write the buffers */
1894 return tls_retry_write_records(rl);
1895 }
1896
tls_retry_write_records(OSSL_RECORD_LAYER * rl)1897 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1898 {
1899 int i, ret;
1900 TLS_BUFFER *thiswb;
1901 size_t tmpwrit = 0;
1902
1903 if (rl->nextwbuf >= rl->numwpipes)
1904 return OSSL_RECORD_RETURN_SUCCESS;
1905
1906 for (;;) {
1907 thiswb = &rl->wbuf[rl->nextwbuf];
1908
1909 clear_sys_error();
1910 if (rl->bio != NULL) {
1911 if (rl->funcs->prepare_write_bio != NULL) {
1912 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1913 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1914 return ret;
1915 }
1916 i = BIO_write(rl->bio, (char *)
1917 &(TLS_BUFFER_get_buf(thiswb)
1918 [TLS_BUFFER_get_offset(thiswb)]),
1919 (unsigned int)TLS_BUFFER_get_left(thiswb));
1920 if (i >= 0) {
1921 tmpwrit = i;
1922 if (i == 0 && BIO_should_retry(rl->bio))
1923 ret = OSSL_RECORD_RETURN_RETRY;
1924 else
1925 ret = OSSL_RECORD_RETURN_SUCCESS;
1926 } else {
1927 if (BIO_should_retry(rl->bio)) {
1928 ret = OSSL_RECORD_RETURN_RETRY;
1929 } else {
1930 ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
1931 "tls_retry_write_records failure");
1932 ret = OSSL_RECORD_RETURN_FATAL;
1933 }
1934 }
1935 } else {
1936 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1937 ret = OSSL_RECORD_RETURN_FATAL;
1938 i = -1;
1939 }
1940
1941 /*
1942 * When an empty fragment is sent on a connection using KTLS,
1943 * it is sent as a write of zero bytes. If this zero byte
1944 * write succeeds, i will be 0 rather than a non-zero value.
1945 * Treat i == 0 as success rather than an error for zero byte
1946 * writes to permit this case.
1947 */
1948 if (i >= 0 && tmpwrit == TLS_BUFFER_get_left(thiswb)) {
1949 TLS_BUFFER_set_left(thiswb, 0);
1950 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1951 if (++(rl->nextwbuf) < rl->numwpipes)
1952 continue;
1953
1954 if (rl->nextwbuf == rl->numwpipes
1955 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1956 tls_release_write_buffer(rl);
1957 return OSSL_RECORD_RETURN_SUCCESS;
1958 } else if (i <= 0) {
1959 if (rl->isdtls) {
1960 /*
1961 * For DTLS, just drop it. That's kind of the whole point in
1962 * using a datagram service
1963 */
1964 TLS_BUFFER_set_left(thiswb, 0);
1965 if (++(rl->nextwbuf) == rl->numwpipes
1966 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1967 tls_release_write_buffer(rl);
1968
1969 }
1970 return ret;
1971 }
1972 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1973 TLS_BUFFER_sub_left(thiswb, tmpwrit);
1974 }
1975 }
1976
tls_get_alert_code(OSSL_RECORD_LAYER * rl)1977 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1978 {
1979 return rl->alert;
1980 }
1981
tls_set1_bio(OSSL_RECORD_LAYER * rl,BIO * bio)1982 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1983 {
1984 if (bio != NULL && !BIO_up_ref(bio))
1985 return 0;
1986 BIO_free(rl->bio);
1987 rl->bio = bio;
1988
1989 return 1;
1990 }
1991
1992 /* Shared by most methods except tlsany_meth */
tls_default_set_protocol_version(OSSL_RECORD_LAYER * rl,int version)1993 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1994 {
1995 if (rl->version != version)
1996 return 0;
1997
1998 return 1;
1999 }
2000
tls_set_protocol_version(OSSL_RECORD_LAYER * rl,int version)2001 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
2002 {
2003 return rl->funcs->set_protocol_version(rl, version);
2004 }
2005
tls_set_plain_alerts(OSSL_RECORD_LAYER * rl,int allow)2006 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
2007 {
2008 rl->allow_plain_alerts = allow;
2009 }
2010
tls_set_first_handshake(OSSL_RECORD_LAYER * rl,int first)2011 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
2012 {
2013 rl->is_first_handshake = first;
2014 }
2015
tls_set_max_pipelines(OSSL_RECORD_LAYER * rl,size_t max_pipelines)2016 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
2017 {
2018 rl->max_pipelines = max_pipelines;
2019 if (max_pipelines > 1)
2020 rl->read_ahead = 1;
2021 }
2022
tls_get_state(OSSL_RECORD_LAYER * rl,const char ** shortstr,const char ** longstr)2023 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
2024 const char **longstr)
2025 {
2026 const char *shrt, *lng;
2027
2028 switch (rl->rstate) {
2029 case SSL_ST_READ_HEADER:
2030 shrt = "RH";
2031 lng = "read header";
2032 break;
2033 case SSL_ST_READ_BODY:
2034 shrt = "RB";
2035 lng = "read body";
2036 break;
2037 default:
2038 shrt = lng = "unknown";
2039 break;
2040 }
2041 if (shortstr != NULL)
2042 *shortstr = shrt;
2043 if (longstr != NULL)
2044 *longstr = lng;
2045 }
2046
tls_get_compression(OSSL_RECORD_LAYER * rl)2047 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
2048 {
2049 #ifndef OPENSSL_NO_COMP
2050 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
2051 #else
2052 return NULL;
2053 #endif
2054 }
2055
tls_set_max_frag_len(OSSL_RECORD_LAYER * rl,size_t max_frag_len)2056 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
2057 {
2058 rl->max_frag_len = max_frag_len;
2059 /*
2060 * We don't need to adjust buffer sizes. Write buffer sizes are
2061 * automatically checked anyway. We should only be changing the read buffer
2062 * size during the handshake, so we will create a new buffer when we create
2063 * the new record layer. We can't change the existing buffer because it may
2064 * already have data in it.
2065 */
2066 }
2067
tls_increment_sequence_ctr(OSSL_RECORD_LAYER * rl)2068 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2069 {
2070 int i;
2071
2072 /* Increment the sequence counter */
2073 for (i = SEQ_NUM_SIZE; i > 0; i--) {
2074 ++(rl->sequence[i - 1]);
2075 if (rl->sequence[i - 1] != 0)
2076 break;
2077 }
2078 if (i == 0) {
2079 /* Sequence has wrapped */
2080 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2081 return 0;
2082 }
2083 return 1;
2084 }
2085
tls_alloc_buffers(OSSL_RECORD_LAYER * rl)2086 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
2087 {
2088 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2089 /* If we have a pending write then buffers are already allocated */
2090 if (rl->nextwbuf < rl->numwpipes)
2091 return 1;
2092 /*
2093 * We assume 1 pipe with default sized buffer. If what we need ends up
2094 * being a different size to that then it will be reallocated on demand.
2095 * If we need more than 1 pipe then that will also be allocated on
2096 * demand
2097 */
2098 if (!tls_setup_write_buffer(rl, 1, 0, 0))
2099 return 0;
2100
2101 /*
2102 * Normally when we allocate write buffers we immediately write
2103 * something into it. In this case we're not doing that so mark the
2104 * buffer as empty.
2105 */
2106 TLS_BUFFER_set_left(&rl->wbuf[0], 0);
2107 return 1;
2108 }
2109
2110 /* Read direction */
2111
2112 /* If we have pending data to be read then buffers are already allocated */
2113 if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
2114 return 1;
2115 return tls_setup_read_buffer(rl);
2116 }
2117
tls_free_buffers(OSSL_RECORD_LAYER * rl)2118 int tls_free_buffers(OSSL_RECORD_LAYER *rl)
2119 {
2120 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2121 if (rl->nextwbuf < rl->numwpipes) {
2122 /*
2123 * We may have pending data. If we've just got one empty buffer
2124 * allocated then it has probably just been alloc'd via
2125 * tls_alloc_buffers, and it is fine to free it. Otherwise this
2126 * looks like real pending data and it is an error.
2127 */
2128 if (rl->nextwbuf != 0
2129 || rl->numwpipes != 1
2130 || TLS_BUFFER_get_left(&rl->wbuf[0]) != 0)
2131 return 0;
2132 }
2133 tls_release_write_buffer(rl);
2134 return 1;
2135 }
2136
2137 /* Read direction */
2138
2139 /* If we have pending data to be read then fail */
2140 if (rl->curr_rec < rl->num_recs
2141 || rl->curr_rec != rl->num_released
2142 || TLS_BUFFER_get_left(&rl->rbuf) != 0
2143 || rl->rstate == SSL_ST_READ_BODY)
2144 return 0;
2145
2146 return tls_release_read_buffer(rl);
2147 }
2148
2149 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2150 tls_new_record_layer,
2151 tls_free,
2152 tls_unprocessed_read_pending,
2153 tls_processed_read_pending,
2154 tls_app_data_pending,
2155 tls_get_max_records,
2156 tls_write_records,
2157 tls_retry_write_records,
2158 tls_read_record,
2159 tls_release_record,
2160 tls_get_alert_code,
2161 tls_set1_bio,
2162 tls_set_protocol_version,
2163 tls_set_plain_alerts,
2164 tls_set_first_handshake,
2165 tls_set_max_pipelines,
2166 NULL,
2167 tls_get_state,
2168 tls_set_options,
2169 tls_get_compression,
2170 tls_set_max_frag_len,
2171 NULL,
2172 tls_increment_sequence_ctr,
2173 tls_alloc_buffers,
2174 tls_free_buffers
2175 };
2176