xref: /openbsd/lib/libssl/ssl_both.c (revision 689a9b7e)
1 /* $OpenBSD: ssl_both.c,v 1.47 2024/02/03 15:58:33 beck Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116 
117 #include <limits.h>
118 #include <stdio.h>
119 #include <string.h>
120 
121 #include <openssl/buffer.h>
122 #include <openssl/evp.h>
123 #include <openssl/objects.h>
124 #include <openssl/x509.h>
125 
126 #include "bytestring.h"
127 #include "dtls_local.h"
128 #include "ssl_local.h"
129 
130 /*
131  * Send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
132  * SSL3_RT_CHANGE_CIPHER_SPEC).
133  */
134 int
ssl3_do_write(SSL * s,int type)135 ssl3_do_write(SSL *s, int type)
136 {
137 	int ret;
138 
139 	ret = ssl3_write_bytes(s, type, &s->init_buf->data[s->init_off],
140 	    s->init_num);
141 	if (ret < 0)
142 		return (-1);
143 
144 	if (type == SSL3_RT_HANDSHAKE)
145 		/*
146 		 * Should not be done for 'Hello Request's, but in that case
147 		 * we'll ignore the result anyway.
148 		 */
149 		tls1_transcript_record(s,
150 		    (unsigned char *)&s->init_buf->data[s->init_off], ret);
151 
152 	if (ret == s->init_num) {
153 		ssl_msg_callback(s, 1, type, s->init_buf->data,
154 		    (size_t)(s->init_off + s->init_num));
155 		return (1);
156 	}
157 
158 	s->init_off += ret;
159 	s->init_num -= ret;
160 
161 	return (0);
162 }
163 
164 static int
ssl3_add_cert(CBB * cbb,X509 * x)165 ssl3_add_cert(CBB *cbb, X509 *x)
166 {
167 	unsigned char *data;
168 	int cert_len;
169 	int ret = 0;
170 	CBB cert;
171 
172 	if ((cert_len = i2d_X509(x, NULL)) < 0)
173 		goto err;
174 
175 	if (!CBB_add_u24_length_prefixed(cbb, &cert))
176 		goto err;
177 	if (!CBB_add_space(&cert, &data, cert_len))
178 		goto err;
179 	if (i2d_X509(x, &data) < 0)
180 		goto err;
181 	if (!CBB_flush(cbb))
182 		goto err;
183 
184 	ret = 1;
185 
186  err:
187 	return (ret);
188 }
189 
190 int
ssl3_output_cert_chain(SSL * s,CBB * cbb,SSL_CERT_PKEY * cpk)191 ssl3_output_cert_chain(SSL *s, CBB *cbb, SSL_CERT_PKEY *cpk)
192 {
193 	X509_STORE_CTX *xs_ctx = NULL;
194 	STACK_OF(X509) *chain;
195 	CBB cert_list;
196 	X509 *x;
197 	int ret = 0;
198 	int i;
199 
200 	if (!CBB_add_u24_length_prefixed(cbb, &cert_list))
201 		goto err;
202 
203 	/* Send an empty certificate list when no certificate is available. */
204 	if (cpk == NULL)
205 		goto done;
206 
207 	if ((chain = cpk->chain) == NULL)
208 		chain = s->ctx->extra_certs;
209 
210 	if (chain != NULL || (s->mode & SSL_MODE_NO_AUTO_CHAIN)) {
211 		if (!ssl3_add_cert(&cert_list, cpk->x509))
212 			goto err;
213 	} else {
214 		if ((xs_ctx = X509_STORE_CTX_new()) == NULL)
215 			goto err;
216 		if (!X509_STORE_CTX_init(xs_ctx, s->ctx->cert_store,
217 		    cpk->x509, NULL)) {
218 			SSLerror(s, ERR_R_X509_LIB);
219 			goto err;
220 		}
221 		X509_VERIFY_PARAM_set_flags(X509_STORE_CTX_get0_param(xs_ctx),
222 		    X509_V_FLAG_LEGACY_VERIFY);
223 		X509_verify_cert(xs_ctx);
224 		ERR_clear_error();
225 		chain = X509_STORE_CTX_get0_chain(xs_ctx);
226 	}
227 
228 	for (i = 0; i < sk_X509_num(chain); i++) {
229 		x = sk_X509_value(chain, i);
230 		if (!ssl3_add_cert(&cert_list, x))
231 			goto err;
232 	}
233 
234  done:
235 	if (!CBB_flush(cbb))
236 		goto err;
237 
238 	ret = 1;
239 
240  err:
241 	X509_STORE_CTX_free(xs_ctx);
242 
243 	return (ret);
244 }
245 
246 /*
247  * Obtain handshake message of message type 'mt' (any if mt == -1),
248  * maximum acceptable body length 'max'.
249  * The first four bytes (msg_type and length) are read in state 'st1',
250  * the body is read in state 'stn'.
251  */
252 int
ssl3_get_message(SSL * s,int st1,int stn,int mt,long max)253 ssl3_get_message(SSL *s, int st1, int stn, int mt, long max)
254 {
255 	unsigned char *p;
256 	uint32_t l;
257 	long n;
258 	int i, al;
259 	CBS cbs;
260 	uint8_t u8;
261 
262 	if (SSL_is_dtls(s))
263 		return dtls1_get_message(s, st1, stn, mt, max);
264 
265 	if (s->s3->hs.tls12.reuse_message) {
266 		s->s3->hs.tls12.reuse_message = 0;
267 		if ((mt >= 0) && (s->s3->hs.tls12.message_type != mt)) {
268 			al = SSL_AD_UNEXPECTED_MESSAGE;
269 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
270 			goto fatal_err;
271 		}
272 		s->init_msg = s->init_buf->data +
273 		    SSL3_HM_HEADER_LENGTH;
274 		s->init_num = (int)s->s3->hs.tls12.message_size;
275 		return 1;
276 	}
277 
278 	p = (unsigned char *)s->init_buf->data;
279 
280 	if (s->s3->hs.state == st1) {
281 		int skip_message;
282 
283 		do {
284 			while (s->init_num < SSL3_HM_HEADER_LENGTH) {
285 				i = s->method->ssl_read_bytes(s,
286 				    SSL3_RT_HANDSHAKE, &p[s->init_num],
287 				    SSL3_HM_HEADER_LENGTH - s->init_num, 0);
288 				if (i <= 0) {
289 					s->rwstate = SSL_READING;
290 					return i;
291 				}
292 				s->init_num += i;
293 			}
294 
295 			skip_message = 0;
296 			if (!s->server && p[0] == SSL3_MT_HELLO_REQUEST) {
297 				/*
298 				 * The server may always send 'Hello Request'
299 				 * messages -- we are doing a handshake anyway
300 				 * now, so ignore them if their format is
301 				 * correct.  Does not count for 'Finished' MAC.
302 				 */
303 				if (p[1] == 0 && p[2] == 0 &&p[3] == 0) {
304 					s->init_num = 0;
305 					skip_message = 1;
306 
307 					ssl_msg_callback(s, 0,
308 					    SSL3_RT_HANDSHAKE, p,
309 					    SSL3_HM_HEADER_LENGTH);
310 				}
311 			}
312 		} while (skip_message);
313 
314 		if ((mt >= 0) && (*p != mt)) {
315 			al = SSL_AD_UNEXPECTED_MESSAGE;
316 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
317 			goto fatal_err;
318 		}
319 
320 		CBS_init(&cbs, p, SSL3_HM_HEADER_LENGTH);
321 		if (!CBS_get_u8(&cbs, &u8) ||
322 		    !CBS_get_u24(&cbs, &l)) {
323 			SSLerror(s, ERR_R_BUF_LIB);
324 			goto err;
325 		}
326 		s->s3->hs.tls12.message_type = u8;
327 
328 		if (l > (unsigned long)max) {
329 			al = SSL_AD_ILLEGAL_PARAMETER;
330 			SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
331 			goto fatal_err;
332 		}
333 		if (l && !BUF_MEM_grow_clean(s->init_buf,
334 		    l + SSL3_HM_HEADER_LENGTH)) {
335 			SSLerror(s, ERR_R_BUF_LIB);
336 			goto err;
337 		}
338 		s->s3->hs.tls12.message_size = l;
339 		s->s3->hs.state = stn;
340 
341 		s->init_msg = s->init_buf->data +
342 		    SSL3_HM_HEADER_LENGTH;
343 		s->init_num = 0;
344 	}
345 
346 	/* next state (stn) */
347 	p = s->init_msg;
348 	n = s->s3->hs.tls12.message_size - s->init_num;
349 	while (n > 0) {
350 		i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
351 		    &p[s->init_num], n, 0);
352 		if (i <= 0) {
353 			s->rwstate = SSL_READING;
354 			return i;
355 		}
356 		s->init_num += i;
357 		n -= i;
358 	}
359 
360 	/* Feed this message into MAC computation. */
361 	if (s->mac_packet) {
362 		tls1_transcript_record(s, (unsigned char *)s->init_buf->data,
363 		    s->init_num + SSL3_HM_HEADER_LENGTH);
364 
365 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE,
366 		    s->init_buf->data,
367 		    (size_t)s->init_num + SSL3_HM_HEADER_LENGTH);
368 	}
369 
370 	return 1;
371 
372  fatal_err:
373 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
374  err:
375 	return -1;
376 }
377 
378 int
ssl_cert_type(EVP_PKEY * pkey)379 ssl_cert_type(EVP_PKEY *pkey)
380 {
381 	if (pkey == NULL)
382 		return -1;
383 
384 	switch (EVP_PKEY_id(pkey)) {
385 	case EVP_PKEY_EC:
386 		return SSL_PKEY_ECC;
387 	case EVP_PKEY_RSA:
388 	case EVP_PKEY_RSA_PSS:
389 		return SSL_PKEY_RSA;
390 	}
391 
392 	return -1;
393 }
394 
395 int
ssl_verify_alarm_type(long type)396 ssl_verify_alarm_type(long type)
397 {
398 	int al;
399 
400 	switch (type) {
401 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
402 	case X509_V_ERR_UNABLE_TO_GET_CRL:
403 	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
404 		al = SSL_AD_UNKNOWN_CA;
405 		break;
406 	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
407 	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
408 	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
409 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
410 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
411 	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
412 	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
413 	case X509_V_ERR_CERT_NOT_YET_VALID:
414 	case X509_V_ERR_CRL_NOT_YET_VALID:
415 	case X509_V_ERR_CERT_UNTRUSTED:
416 	case X509_V_ERR_CERT_REJECTED:
417 		al = SSL_AD_BAD_CERTIFICATE;
418 		break;
419 	case X509_V_ERR_CERT_SIGNATURE_FAILURE:
420 	case X509_V_ERR_CRL_SIGNATURE_FAILURE:
421 		al = SSL_AD_DECRYPT_ERROR;
422 		break;
423 	case X509_V_ERR_CERT_HAS_EXPIRED:
424 	case X509_V_ERR_CRL_HAS_EXPIRED:
425 		al = SSL_AD_CERTIFICATE_EXPIRED;
426 		break;
427 	case X509_V_ERR_CERT_REVOKED:
428 		al = SSL_AD_CERTIFICATE_REVOKED;
429 		break;
430 	case X509_V_ERR_OUT_OF_MEM:
431 		al = SSL_AD_INTERNAL_ERROR;
432 		break;
433 	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
434 	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
435 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
436 	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
437 	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
438 	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
439 	case X509_V_ERR_INVALID_CA:
440 		al = SSL_AD_UNKNOWN_CA;
441 		break;
442 	case X509_V_ERR_APPLICATION_VERIFICATION:
443 		al = SSL_AD_HANDSHAKE_FAILURE;
444 		break;
445 	case X509_V_ERR_INVALID_PURPOSE:
446 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
447 		break;
448 	default:
449 		al = SSL_AD_CERTIFICATE_UNKNOWN;
450 		break;
451 	}
452 	return (al);
453 }
454 
455 int
ssl3_setup_init_buffer(SSL * s)456 ssl3_setup_init_buffer(SSL *s)
457 {
458 	BUF_MEM *buf = NULL;
459 
460 	if (s->init_buf != NULL)
461 		return (1);
462 
463 	if ((buf = BUF_MEM_new()) == NULL)
464 		goto err;
465 	if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH))
466 		goto err;
467 
468 	s->init_buf = buf;
469 	return (1);
470 
471  err:
472 	BUF_MEM_free(buf);
473 	return (0);
474 }
475 
476 void
ssl3_release_init_buffer(SSL * s)477 ssl3_release_init_buffer(SSL *s)
478 {
479 	BUF_MEM_free(s->init_buf);
480 	s->init_buf = NULL;
481 	s->init_msg = NULL;
482 	s->init_num = 0;
483 	s->init_off = 0;
484 }
485 
486 int
ssl3_setup_read_buffer(SSL * s)487 ssl3_setup_read_buffer(SSL *s)
488 {
489 	unsigned char *p;
490 	size_t len, align, headerlen;
491 
492 	if (SSL_is_dtls(s))
493 		headerlen = DTLS1_RT_HEADER_LENGTH;
494 	else
495 		headerlen = SSL3_RT_HEADER_LENGTH;
496 
497 	align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
498 
499 	if (s->s3->rbuf.buf == NULL) {
500 		len = SSL3_RT_MAX_PLAIN_LENGTH +
501 		    SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
502 		if ((p = calloc(1, len)) == NULL)
503 			goto err;
504 		s->s3->rbuf.buf = p;
505 		s->s3->rbuf.len = len;
506 	}
507 
508 	s->packet = s->s3->rbuf.buf;
509 	return 1;
510 
511  err:
512 	SSLerror(s, ERR_R_MALLOC_FAILURE);
513 	return 0;
514 }
515 
516 int
ssl3_setup_write_buffer(SSL * s)517 ssl3_setup_write_buffer(SSL *s)
518 {
519 	unsigned char *p;
520 	size_t len, align, headerlen;
521 
522 	if (SSL_is_dtls(s))
523 		headerlen = DTLS1_RT_HEADER_LENGTH + 1;
524 	else
525 		headerlen = SSL3_RT_HEADER_LENGTH;
526 
527 	align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
528 
529 	if (s->s3->wbuf.buf == NULL) {
530 		len = s->max_send_fragment +
531 		    SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
532 		if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
533 			len += headerlen + align +
534 			    SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
535 
536 		if ((p = calloc(1, len)) == NULL)
537 			goto err;
538 		s->s3->wbuf.buf = p;
539 		s->s3->wbuf.len = len;
540 	}
541 
542 	return 1;
543 
544  err:
545 	SSLerror(s, ERR_R_MALLOC_FAILURE);
546 	return 0;
547 }
548 
549 int
ssl3_setup_buffers(SSL * s)550 ssl3_setup_buffers(SSL *s)
551 {
552 	if (!ssl3_setup_read_buffer(s))
553 		return 0;
554 	if (!ssl3_setup_write_buffer(s))
555 		return 0;
556 	return 1;
557 }
558 
559 void
ssl3_release_buffer(SSL3_BUFFER_INTERNAL * b)560 ssl3_release_buffer(SSL3_BUFFER_INTERNAL *b)
561 {
562 	freezero(b->buf, b->len);
563 	b->buf = NULL;
564 	b->len = 0;
565 }
566 
567 void
ssl3_release_read_buffer(SSL * s)568 ssl3_release_read_buffer(SSL *s)
569 {
570 	ssl3_release_buffer(&s->s3->rbuf);
571 }
572 
573 void
ssl3_release_write_buffer(SSL * s)574 ssl3_release_write_buffer(SSL *s)
575 {
576 	ssl3_release_buffer(&s->s3->wbuf);
577 }
578