xref: /openbsd/usr.bin/openssl/s_cb.c (revision d8c45d21)
1 /* $OpenBSD: s_cb.c,v 1.21 2023/04/14 15:27:13 tb 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-2006 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 #include <sys/socket.h>
113 
114 #include <netinet/in.h>
115 
116 #include <netdb.h>
117 #include <stdio.h>
118 #include <stdlib.h>
119 #include <string.h>
120 
121 #include "apps.h"
122 
123 #include <openssl/err.h>
124 #include <openssl/ssl.h>
125 #include <openssl/x509.h>
126 
127 #include "s_apps.h"
128 
129 #define	COOKIE_SECRET_LENGTH	16
130 
131 int verify_depth = 0;
132 int verify_return_error = 0;
133 unsigned char cookie_secret[COOKIE_SECRET_LENGTH];
134 int cookie_initialized = 0;
135 
136 int
verify_callback(int ok,X509_STORE_CTX * ctx)137 verify_callback(int ok, X509_STORE_CTX * ctx)
138 {
139 	X509 *err_cert;
140 	int err, depth;
141 
142 	err_cert = X509_STORE_CTX_get_current_cert(ctx);
143 	err = X509_STORE_CTX_get_error(ctx);
144 	depth = X509_STORE_CTX_get_error_depth(ctx);
145 
146 	BIO_printf(bio_err, "depth=%d ", depth);
147 	if (err_cert) {
148 		X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert),
149 		    0, XN_FLAG_ONELINE);
150 		BIO_puts(bio_err, "\n");
151 	} else
152 		BIO_puts(bio_err, "<no cert>\n");
153 	if (!ok) {
154 		BIO_printf(bio_err, "verify error:num=%d:%s\n", err,
155 		    X509_verify_cert_error_string(err));
156 		if (verify_depth >= depth) {
157 			if (!verify_return_error)
158 				ok = 1;
159 		} else {
160 			ok = 0;
161 		}
162 	}
163 	switch (err) {
164 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
165 		BIO_puts(bio_err, "issuer= ");
166 		if (err_cert == NULL)
167 			BIO_puts(bio_err, "<error getting cert>");
168 		else
169 			X509_NAME_print_ex(bio_err,
170 			    X509_get_issuer_name(err_cert), 0, XN_FLAG_ONELINE);
171 		BIO_puts(bio_err, "\n");
172 		break;
173 	case X509_V_ERR_CERT_NOT_YET_VALID:
174 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
175 		BIO_printf(bio_err, "notBefore=");
176 		if (err_cert == NULL)
177 			BIO_printf(bio_err, " <error getting cert>");
178 		else
179 			ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert));
180 		BIO_printf(bio_err, "\n");
181 		break;
182 	case X509_V_ERR_CERT_HAS_EXPIRED:
183 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
184 		BIO_printf(bio_err, "notAfter=");
185 		if (err_cert == NULL)
186 			BIO_printf(bio_err, " <error getting cert>");
187 		else
188 			ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert));
189 		BIO_printf(bio_err, "\n");
190 		break;
191 	case X509_V_ERR_NO_EXPLICIT_POLICY:
192 		break;
193 	}
194 
195 	BIO_printf(bio_err, "verify return:%d\n", ok);
196 	return (ok);
197 }
198 
199 int
set_cert_stuff(SSL_CTX * ctx,char * cert_file,char * key_file)200 set_cert_stuff(SSL_CTX * ctx, char *cert_file, char *key_file)
201 {
202 	if (cert_file == NULL)
203 		return 1;
204 
205 	if (key_file == NULL)
206 		key_file = cert_file;
207 
208 	if (SSL_CTX_use_certificate_file(ctx, cert_file, SSL_FILETYPE_PEM) <= 0) {
209 		BIO_printf(bio_err,
210 		    "unable to get certificate from '%s'\n", cert_file);
211 		ERR_print_errors(bio_err);
212 		return 0;
213 	}
214 	if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
215 		BIO_printf(bio_err, "unable to get private key from '%s'\n",
216 		    key_file);
217 		ERR_print_errors(bio_err);
218 		return 0;
219 	}
220 
221 	/* Now we know that a key and cert have been set against the context. */
222 	if (!SSL_CTX_check_private_key(ctx)) {
223 		BIO_printf(bio_err,
224 		    "Private key does not match the certificate public key\n");
225 		return 0;
226 	}
227 
228 	return 1;
229 }
230 
231 int
set_cert_key_stuff(SSL_CTX * ctx,X509 * cert,EVP_PKEY * key)232 set_cert_key_stuff(SSL_CTX * ctx, X509 * cert, EVP_PKEY * key)
233 {
234 	if (cert == NULL)
235 		return 1;
236 	if (SSL_CTX_use_certificate(ctx, cert) <= 0) {
237 		BIO_printf(bio_err, "error setting certificate\n");
238 		ERR_print_errors(bio_err);
239 		return 0;
240 	}
241 	if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) {
242 		BIO_printf(bio_err, "error setting private key\n");
243 		ERR_print_errors(bio_err);
244 		return 0;
245 	}
246 	/*
247 	 * Now we know that a key and cert have been set against the SSL
248 	 * context
249 	 */
250 	if (!SSL_CTX_check_private_key(ctx)) {
251 		BIO_printf(bio_err,
252 		    "Private key does not match the certificate public key\n");
253 		return 0;
254 	}
255 	return 1;
256 }
257 
258 int
ssl_print_tmp_key(BIO * out,SSL * s)259 ssl_print_tmp_key(BIO *out, SSL *s)
260 {
261 	const char *cname;
262 	EVP_PKEY *pkey;
263 	EC_KEY *ec;
264 	const EC_GROUP *group;
265 	int nid;
266 
267 	if (!SSL_get_server_tmp_key(s, &pkey))
268 		return 0;
269 
270 	BIO_puts(out, "Server Temp Key: ");
271 	switch (EVP_PKEY_id(pkey)) {
272 	case EVP_PKEY_DH:
273 		BIO_printf(out, "DH, %d bits\n", EVP_PKEY_bits(pkey));
274 		break;
275 
276 	case EVP_PKEY_EC:
277 		if ((ec = EVP_PKEY_get0_EC_KEY(pkey)) == NULL)
278 			goto err;
279 		if ((group = EC_KEY_get0_group(ec)) == NULL)
280 			goto err;
281 
282 		nid = EC_GROUP_get_curve_name(group);
283 
284 		if ((cname = EC_curve_nid2nist(nid)) == NULL)
285 			cname = OBJ_nid2sn(nid);
286 
287 		BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(pkey));
288 		break;
289 
290 	default:
291 		BIO_printf(out, "%s, %d bits\n", OBJ_nid2sn(EVP_PKEY_id(pkey)),
292 		    EVP_PKEY_bits(pkey));
293 	}
294 
295  err:
296 	EVP_PKEY_free(pkey);
297 	return 1;
298 }
299 
300 long
bio_dump_callback(BIO * bio,int cmd,const char * argp,int argi,long argl,long ret)301 bio_dump_callback(BIO * bio, int cmd, const char *argp,
302     int argi, long argl, long ret)
303 {
304 	BIO *out;
305 
306 	out = (BIO *) BIO_get_callback_arg(bio);
307 	if (out == NULL)
308 		return (ret);
309 
310 	if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
311 		BIO_printf(out,
312 		    "read from %p [%p] (%lu bytes => %ld (0x%lX))\n",
313 		    (void *) bio, argp, (unsigned long) argi, ret, ret);
314 		BIO_dump(out, argp, (int) ret);
315 		return (ret);
316 	} else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
317 		BIO_printf(out,
318 		    "write to %p [%p] (%lu bytes => %ld (0x%lX))\n",
319 		    (void *) bio, argp, (unsigned long) argi, ret, ret);
320 		BIO_dump(out, argp, (int) ret);
321 	}
322 	return (ret);
323 }
324 
325 void
apps_ssl_info_callback(const SSL * s,int where,int ret)326 apps_ssl_info_callback(const SSL * s, int where, int ret)
327 {
328 	const char *str;
329 	int w;
330 
331 	w = where & ~SSL_ST_MASK;
332 
333 	if (w & SSL_ST_CONNECT)
334 		str = "SSL_connect";
335 	else if (w & SSL_ST_ACCEPT)
336 		str = "SSL_accept";
337 	else
338 		str = "undefined";
339 
340 	if (where & SSL_CB_LOOP) {
341 		BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s));
342 	} else if (where & SSL_CB_ALERT) {
343 		str = (where & SSL_CB_READ) ? "read" : "write";
344 		BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n", str,
345 		    SSL_alert_type_string_long(ret),
346 		    SSL_alert_desc_string_long(ret));
347 	} else if (where & SSL_CB_EXIT) {
348 		if (ret == 0)
349 			BIO_printf(bio_err, "%s:failed in %s\n",
350 			    str, SSL_state_string_long(s));
351 		else if (ret < 0) {
352 			BIO_printf(bio_err, "%s:error in %s\n",
353 			    str, SSL_state_string_long(s));
354 		}
355 	}
356 }
357 
358 
359 void
msg_cb(int write_p,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)360 msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL * ssl, void *arg)
361 {
362 	BIO *bio = arg;
363 	const char *str_write_p, *str_version, *str_content_type = "",
364 	    *str_details1 = "", *str_details2 = "";
365 
366 	str_write_p = write_p ? ">>>" : "<<<";
367 
368 	/* XXX convert to using ssl_get_version */
369 	switch (version) {
370 	case SSL2_VERSION:
371 		str_version = "SSL 2.0";
372 		break;
373 	case SSL3_VERSION:
374 		str_version = "SSL 3.0 ";
375 		break;
376 	case TLS1_VERSION:
377 		str_version = "TLS 1.0 ";
378 		break;
379 	case TLS1_1_VERSION:
380 		str_version = "TLS 1.1 ";
381 		break;
382 	case TLS1_2_VERSION:
383 		str_version = "TLS 1.2 ";
384 		break;
385 	case TLS1_3_VERSION:
386 		str_version = "TLS 1.3 ";
387 		break;
388 	case DTLS1_VERSION:
389 		str_version = "DTLS 1.0 ";
390 		break;
391 	case DTLS1_2_VERSION:
392 		str_version = "DTLS 1.2 ";
393 		break;
394 	default:
395 		str_version = "???";
396 	}
397 
398 	if (version == SSL2_VERSION) {
399 		str_details1 = "???";
400 
401 		if (len > 0) {
402 			/* XXX magic numbers */
403 			switch (((const unsigned char *) buf)[0]) {
404 			case 0:
405 				str_details1 = ", ERROR:";
406 				str_details2 = " ???";
407 				if (len >= 3) {
408 					unsigned err = (((const unsigned char *) buf)[1] << 8) + ((const unsigned char *) buf)[2];
409 
410 					switch (err) {
411 					case 0x0001:
412 						str_details2 = " NO-CIPHER-ERROR";
413 						break;
414 					case 0x0002:
415 						str_details2 = " NO-CERTIFICATE-ERROR";
416 						break;
417 					case 0x0004:
418 						str_details2 = " BAD-CERTIFICATE-ERROR";
419 						break;
420 					case 0x0006:
421 						str_details2 = " UNSUPPORTED-CERTIFICATE-TYPE-ERROR";
422 						break;
423 					}
424 				}
425 				break;
426 			case 1:
427 				str_details1 = ", CLIENT-HELLO";
428 				break;
429 			case 2:
430 				str_details1 = ", CLIENT-MASTER-KEY";
431 				break;
432 			case 3:
433 				str_details1 = ", CLIENT-FINISHED";
434 				break;
435 			case 4:
436 				str_details1 = ", SERVER-HELLO";
437 				break;
438 			case 5:
439 				str_details1 = ", SERVER-VERIFY";
440 				break;
441 			case 6:
442 				str_details1 = ", SERVER-FINISHED";
443 				break;
444 			case 7:
445 				str_details1 = ", REQUEST-CERTIFICATE";
446 				break;
447 			case 8:
448 				str_details1 = ", CLIENT-CERTIFICATE";
449 				break;
450 			}
451 		}
452 	}
453 	if (version == SSL3_VERSION || version == TLS1_VERSION ||
454 	    version == TLS1_1_VERSION || version == TLS1_2_VERSION ||
455 	    version == TLS1_3_VERSION || version == DTLS1_VERSION ||
456 	    version == DTLS1_2_VERSION) {
457 		/* XXX magic numbers are in ssl3.h */
458 		switch (content_type) {
459 		case 20:
460 			str_content_type = "ChangeCipherSpec";
461 			break;
462 		case 21:
463 			str_content_type = "Alert";
464 			break;
465 		case 22:
466 			str_content_type = "Handshake";
467 			break;
468 		}
469 
470 		if (content_type == 21) {	/* Alert */
471 			str_details1 = ", ???";
472 
473 			if (len == 2) {
474 				switch (((const unsigned char *) buf)[0]) {
475 				case 1:
476 					str_details1 = ", warning";
477 					break;
478 				case 2:
479 					str_details1 = ", fatal";
480 					break;
481 				}
482 
483 				str_details2 = " ???";
484 				switch (((const unsigned char *) buf)[1]) {
485 				case 0:
486 					str_details2 = " close_notify";
487 					break;
488 				case 10:
489 					str_details2 = " unexpected_message";
490 					break;
491 				case 20:
492 					str_details2 = " bad_record_mac";
493 					break;
494 				case 21:
495 					str_details2 = " decryption_failed";
496 					break;
497 				case 22:
498 					str_details2 = " record_overflow";
499 					break;
500 				case 30:
501 					str_details2 = " decompression_failure";
502 					break;
503 				case 40:
504 					str_details2 = " handshake_failure";
505 					break;
506 				case 42:
507 					str_details2 = " bad_certificate";
508 					break;
509 				case 43:
510 					str_details2 = " unsupported_certificate";
511 					break;
512 				case 44:
513 					str_details2 = " certificate_revoked";
514 					break;
515 				case 45:
516 					str_details2 = " certificate_expired";
517 					break;
518 				case 46:
519 					str_details2 = " certificate_unknown";
520 					break;
521 				case 47:
522 					str_details2 = " illegal_parameter";
523 					break;
524 				case 48:
525 					str_details2 = " unknown_ca";
526 					break;
527 				case 49:
528 					str_details2 = " access_denied";
529 					break;
530 				case 50:
531 					str_details2 = " decode_error";
532 					break;
533 				case 51:
534 					str_details2 = " decrypt_error";
535 					break;
536 				case 60:
537 					str_details2 = " export_restriction";
538 					break;
539 				case 70:
540 					str_details2 = " protocol_version";
541 					break;
542 				case 71:
543 					str_details2 = " insufficient_security";
544 					break;
545 				case 80:
546 					str_details2 = " internal_error";
547 					break;
548 				case 90:
549 					str_details2 = " user_canceled";
550 					break;
551 				case 100:
552 					str_details2 = " no_renegotiation";
553 					break;
554 				case 110:
555 					str_details2 = " unsupported_extension";
556 					break;
557 				case 111:
558 					str_details2 = " certificate_unobtainable";
559 					break;
560 				case 112:
561 					str_details2 = " unrecognized_name";
562 					break;
563 				case 113:
564 					str_details2 = " bad_certificate_status_response";
565 					break;
566 				case 114:
567 					str_details2 = " bad_certificate_hash_value";
568 					break;
569 				case 115:
570 					str_details2 = " unknown_psk_identity";
571 					break;
572 				}
573 			}
574 		}
575 		if (content_type == 22) {	/* Handshake */
576 			str_details1 = "???";
577 
578 			if (len > 0) {
579 				switch (((const unsigned char *) buf)[0]) {
580 				case 0:
581 					str_details1 = ", HelloRequest";
582 					break;
583 				case 1:
584 					str_details1 = ", ClientHello";
585 					break;
586 				case 2:
587 					str_details1 = ", ServerHello";
588 					break;
589 				case 3:
590 					str_details1 = ", HelloVerifyRequest";
591 					break;
592 				case 4:
593 					str_details1 = ", NewSessionTicket";
594 					break;
595 				case 5:
596 					str_details1 = ", EndOfEarlyData";
597 					break;
598 				case 8:
599 					str_details1 = ", EncryptedExtensions";
600 					break;
601 				case 11:
602 					str_details1 = ", Certificate";
603 					break;
604 				case 12:
605 					str_details1 = ", ServerKeyExchange";
606 					break;
607 				case 13:
608 					str_details1 = ", CertificateRequest";
609 					break;
610 				case 14:
611 					str_details1 = ", ServerHelloDone";
612 					break;
613 				case 15:
614 					str_details1 = ", CertificateVerify";
615 					break;
616 				case 16:
617 					str_details1 = ", ClientKeyExchange";
618 					break;
619 				case 20:
620 					str_details1 = ", Finished";
621 					break;
622 				case 24:
623 					str_details1 = ", KeyUpdate";
624 					break;
625 				}
626 			}
627 		}
628 	}
629 	BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p,
630 	    str_version, str_content_type, (unsigned long) len,
631 	    str_details1, str_details2);
632 
633 	if (len > 0) {
634 		size_t num, i;
635 
636 		BIO_printf(bio, "   ");
637 		num = len;
638 
639 		for (i = 0; i < num; i++) {
640 			if (i % 16 == 0 && i > 0)
641 				BIO_printf(bio, "\n   ");
642 			BIO_printf(bio, " %02x",
643 			    ((const unsigned char *) buf)[i]);
644 		}
645 		if (i < len)
646 			BIO_printf(bio, " ...");
647 		BIO_printf(bio, "\n");
648 	}
649 	(void) BIO_flush(bio);
650 }
651 
652 void
tlsext_cb(SSL * s,int client_server,int type,unsigned char * data,int len,void * arg)653 tlsext_cb(SSL * s, int client_server, int type, unsigned char *data, int len,
654     void *arg)
655 {
656 	BIO *bio = arg;
657 	char *extname;
658 
659 	switch (type) {
660 	case TLSEXT_TYPE_server_name:
661 		extname = "server name";
662 		break;
663 
664 	case TLSEXT_TYPE_max_fragment_length:
665 		extname = "max fragment length";
666 		break;
667 
668 	case TLSEXT_TYPE_client_certificate_url:
669 		extname = "client certificate URL";
670 		break;
671 
672 	case TLSEXT_TYPE_trusted_ca_keys:
673 		extname = "trusted CA keys";
674 		break;
675 
676 	case TLSEXT_TYPE_truncated_hmac:
677 		extname = "truncated HMAC";
678 		break;
679 
680 	case TLSEXT_TYPE_status_request:
681 		extname = "status request";
682 		break;
683 
684 	case TLSEXT_TYPE_user_mapping:
685 		extname = "user mapping";
686 		break;
687 
688 	case TLSEXT_TYPE_client_authz:
689 		extname = "client authz";
690 		break;
691 
692 	case TLSEXT_TYPE_server_authz:
693 		extname = "server authz";
694 		break;
695 
696 	case TLSEXT_TYPE_cert_type:
697 		extname = "cert type";
698 		break;
699 
700 	case TLSEXT_TYPE_supported_groups:
701 		extname = "supported groups";
702 		break;
703 
704 	case TLSEXT_TYPE_ec_point_formats:
705 		extname = "EC point formats";
706 		break;
707 
708 	case TLSEXT_TYPE_srp:
709 		extname = "SRP";
710 		break;
711 
712 	case TLSEXT_TYPE_signature_algorithms:
713 		extname = "signature algorithms";
714 		break;
715 
716 	case TLSEXT_TYPE_use_srtp:
717 		extname = "use SRTP";
718 		break;
719 
720 	case TLSEXT_TYPE_heartbeat:
721 		extname = "heartbeat";
722 		break;
723 
724 	case TLSEXT_TYPE_application_layer_protocol_negotiation:
725 		extname = "application layer protocol negotiation";
726 		break;
727 
728 	case TLSEXT_TYPE_padding:
729 		extname = "TLS padding";
730 		break;
731 
732 	case TLSEXT_TYPE_session_ticket:
733 		extname = "session ticket";
734 		break;
735 
736 #if defined(LIBRESSL_HAS_TLS1_3) || defined(LIBRESSL_INTERNAL)
737 	case TLSEXT_TYPE_pre_shared_key:
738 		extname = "pre shared key";
739 		break;
740 
741 	case TLSEXT_TYPE_early_data:
742 		extname = "early data";
743 		break;
744 
745 	case TLSEXT_TYPE_supported_versions:
746 		extname = "supported versions";
747 		break;
748 
749 	case TLSEXT_TYPE_cookie:
750 		extname = "cookie";
751 		break;
752 
753 	case TLSEXT_TYPE_psk_key_exchange_modes:
754 		extname = "PSK key exchange modes";
755 		break;
756 
757 	case TLSEXT_TYPE_certificate_authorities:
758 		extname = "certificate authorities";
759 		break;
760 
761 	case TLSEXT_TYPE_oid_filters:
762 		extname = "OID filters";
763 		break;
764 
765 	case TLSEXT_TYPE_post_handshake_auth:
766 		extname = "post handshake auth";
767 		break;
768 
769 	case TLSEXT_TYPE_signature_algorithms_cert:
770 		extname = "signature algorithms cert";
771 		break;
772 
773 	case TLSEXT_TYPE_key_share:
774 		extname = "key share";
775 		break;
776 #endif
777 
778 	case TLSEXT_TYPE_renegotiate:
779 		extname = "renegotiation info";
780 		break;
781 
782 	default:
783 		extname = "unknown";
784 		break;
785 
786 	}
787 
788 	BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n",
789 	    client_server ? "server" : "client", extname, type, len);
790 	BIO_dump(bio, (char *) data, len);
791 	(void) BIO_flush(bio);
792 }
793 
794 int
generate_cookie_callback(SSL * ssl,unsigned char * cookie,unsigned int * cookie_len)795 generate_cookie_callback(SSL * ssl, unsigned char *cookie,
796     unsigned int *cookie_len)
797 {
798 	unsigned char *buffer, result[EVP_MAX_MD_SIZE];
799 	unsigned int length, resultlength;
800 	union {
801 		struct sockaddr sa;
802 		struct sockaddr_in s4;
803 		struct sockaddr_in6 s6;
804 	} peer;
805 
806 	/* Initialize a random secret */
807 	if (!cookie_initialized) {
808 		arc4random_buf(cookie_secret, COOKIE_SECRET_LENGTH);
809 		cookie_initialized = 1;
810 	}
811 	/* Read peer information */
812 	(void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
813 
814 	/* Create buffer with peer's address and port */
815 	length = 0;
816 	switch (peer.sa.sa_family) {
817 	case AF_INET:
818 		length += sizeof(struct in_addr);
819 		length += sizeof(peer.s4.sin_port);
820 		break;
821 	case AF_INET6:
822 		length += sizeof(struct in6_addr);
823 		length += sizeof(peer.s6.sin6_port);
824 		break;
825 	default:
826 		OPENSSL_assert(0);
827 		break;
828 	}
829 	buffer = malloc(length);
830 
831 	if (buffer == NULL) {
832 		BIO_printf(bio_err, "out of memory\n");
833 		return 0;
834 	}
835 	switch (peer.sa.sa_family) {
836 	case AF_INET:
837 		memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
838 		memcpy(buffer + sizeof(peer.s4.sin_port),
839 		    &peer.s4.sin_addr, sizeof(struct in_addr));
840 		break;
841 	case AF_INET6:
842 		memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
843 		memcpy(buffer + sizeof(peer.s6.sin6_port),
844 		    &peer.s6.sin6_addr, sizeof(struct in6_addr));
845 		break;
846 	default:
847 		OPENSSL_assert(0);
848 		break;
849 	}
850 
851 	/* Calculate HMAC of buffer using the secret */
852 	HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
853 	    buffer, length, result, &resultlength);
854 	free(buffer);
855 
856 	memcpy(cookie, result, resultlength);
857 	*cookie_len = resultlength;
858 
859 	return 1;
860 }
861 
862 int
verify_cookie_callback(SSL * ssl,const unsigned char * cookie,unsigned int cookie_len)863 verify_cookie_callback(SSL * ssl, const unsigned char *cookie,
864     unsigned int cookie_len)
865 {
866 	unsigned char *buffer, result[EVP_MAX_MD_SIZE];
867 	unsigned int length, resultlength;
868 	union {
869 		struct sockaddr sa;
870 		struct sockaddr_in s4;
871 		struct sockaddr_in6 s6;
872 	} peer;
873 
874 	/* If secret isn't initialized yet, the cookie can't be valid */
875 	if (!cookie_initialized)
876 		return 0;
877 
878 	/* Read peer information */
879 	(void) BIO_dgram_get_peer(SSL_get_rbio(ssl), &peer);
880 
881 	/* Create buffer with peer's address and port */
882 	length = 0;
883 	switch (peer.sa.sa_family) {
884 	case AF_INET:
885 		length += sizeof(struct in_addr);
886 		length += sizeof(peer.s4.sin_port);
887 		break;
888 	case AF_INET6:
889 		length += sizeof(struct in6_addr);
890 		length += sizeof(peer.s6.sin6_port);
891 		break;
892 	default:
893 		OPENSSL_assert(0);
894 		break;
895 	}
896 	buffer = malloc(length);
897 
898 	if (buffer == NULL) {
899 		BIO_printf(bio_err, "out of memory\n");
900 		return 0;
901 	}
902 	switch (peer.sa.sa_family) {
903 	case AF_INET:
904 		memcpy(buffer, &peer.s4.sin_port, sizeof(peer.s4.sin_port));
905 		memcpy(buffer + sizeof(peer.s4.sin_port),
906 		    &peer.s4.sin_addr, sizeof(struct in_addr));
907 		break;
908 	case AF_INET6:
909 		memcpy(buffer, &peer.s6.sin6_port, sizeof(peer.s6.sin6_port));
910 		memcpy(buffer + sizeof(peer.s6.sin6_port),
911 		    &peer.s6.sin6_addr, sizeof(struct in6_addr));
912 		break;
913 	default:
914 		OPENSSL_assert(0);
915 		break;
916 	}
917 
918 	/* Calculate HMAC of buffer using the secret */
919 	if (HMAC(EVP_sha1(), cookie_secret, COOKIE_SECRET_LENGTH,
920 	    buffer, length, result, &resultlength) == NULL) {
921 		free(buffer);
922 		return 0;
923 	}
924 
925 	free(buffer);
926 
927 	if (cookie_len == resultlength &&
928 	    memcmp(result, cookie, resultlength) == 0)
929 		return 1;
930 
931 	return 0;
932 }
933