xref: /openbsd-src/lib/libssl/ssl_lib.c (revision b46d8ef224b95de1dddcd1f01c1ab482f0ab3778)
1 /* $OpenBSD: ssl_lib.c,v 1.207 2019/11/17 19:07:07 jsing 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-2007 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  * Copyright 2005 Nokia. All rights reserved.
118  *
119  * The portions of the attached software ("Contribution") is developed by
120  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121  * license.
122  *
123  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125  * support (see RFC 4279) to OpenSSL.
126  *
127  * No patent licenses or other rights except those expressly stated in
128  * the OpenSSL open source license shall be deemed granted or received
129  * expressly, by implication, estoppel, or otherwise.
130  *
131  * No assurances are provided by Nokia that the Contribution does not
132  * infringe the patent or other intellectual property rights of any third
133  * party or that the license provides you with all the necessary rights
134  * to make use of the Contribution.
135  *
136  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140  * OTHERWISE.
141  */
142 
143 #include <arpa/inet.h>
144 #include <sys/socket.h>
145 #include <netinet/in.h>
146 
147 #include <stdio.h>
148 
149 #include "ssl_locl.h"
150 
151 #include <openssl/bn.h>
152 #include <openssl/dh.h>
153 #include <openssl/lhash.h>
154 #include <openssl/objects.h>
155 #include <openssl/ocsp.h>
156 #include <openssl/x509v3.h>
157 
158 #ifndef OPENSSL_NO_ENGINE
159 #include <openssl/engine.h>
160 #endif
161 
162 #include "bytestring.h"
163 #include "ssl_sigalgs.h"
164 
165 const char *SSL_version_str = OPENSSL_VERSION_TEXT;
166 
167 int
168 SSL_clear(SSL *s)
169 {
170 	if (s->method == NULL) {
171 		SSLerror(s, SSL_R_NO_METHOD_SPECIFIED);
172 		return (0);
173 	}
174 
175 	if (ssl_clear_bad_session(s)) {
176 		SSL_SESSION_free(s->session);
177 		s->session = NULL;
178 	}
179 
180 	s->error = 0;
181 	s->internal->hit = 0;
182 	s->internal->shutdown = 0;
183 
184 	if (s->internal->renegotiate) {
185 		SSLerror(s, ERR_R_INTERNAL_ERROR);
186 		return (0);
187 	}
188 
189 	s->internal->type = 0;
190 
191 	s->version = s->method->internal->version;
192 	s->client_version = s->version;
193 	s->internal->rwstate = SSL_NOTHING;
194 	s->internal->rstate = SSL_ST_READ_HEADER;
195 
196 	BUF_MEM_free(s->internal->init_buf);
197 	s->internal->init_buf = NULL;
198 
199 	ssl_clear_cipher_state(s);
200 
201 	s->internal->first_packet = 0;
202 
203 	/*
204 	 * Check to see if we were changed into a different method, if
205 	 * so, revert back if we are not doing session-id reuse.
206 	 */
207 	if (!s->internal->in_handshake && (s->session == NULL) &&
208 	    (s->method != s->ctx->method)) {
209 		s->method->internal->ssl_free(s);
210 		s->method = s->ctx->method;
211 		if (!s->method->internal->ssl_new(s))
212 			return (0);
213 	} else
214 		s->method->internal->ssl_clear(s);
215 
216 	S3I(s)->hs.state = SSL_ST_BEFORE|((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
217 
218 	return (1);
219 }
220 
221 /* Used to change an SSL_CTXs default SSL method type */
222 int
223 SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
224 {
225 	STACK_OF(SSL_CIPHER)	*sk;
226 
227 	ctx->method = meth;
228 
229 	sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
230 	    &(ctx->internal->cipher_list_by_id), SSL_DEFAULT_CIPHER_LIST);
231 	if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
232 		SSLerrorx(SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
233 		return (0);
234 	}
235 	return (1);
236 }
237 
238 SSL *
239 SSL_new(SSL_CTX *ctx)
240 {
241 	SSL	*s;
242 
243 	if (ctx == NULL) {
244 		SSLerrorx(SSL_R_NULL_SSL_CTX);
245 		return (NULL);
246 	}
247 	if (ctx->method == NULL) {
248 		SSLerrorx(SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
249 		return (NULL);
250 	}
251 
252 	if ((s = calloc(1, sizeof(*s))) == NULL) {
253 		SSLerrorx(ERR_R_MALLOC_FAILURE);
254 		return (NULL);
255 	}
256 	if ((s->internal = calloc(1, sizeof(*s->internal))) == NULL) {
257 		free(s);
258 		SSLerrorx(ERR_R_MALLOC_FAILURE);
259 		return (NULL);
260 	}
261 
262 	s->internal->min_version = ctx->internal->min_version;
263 	s->internal->max_version = ctx->internal->max_version;
264 
265 	s->internal->options = ctx->internal->options;
266 	s->internal->mode = ctx->internal->mode;
267 	s->internal->max_cert_list = ctx->internal->max_cert_list;
268 
269 	if ((s->cert = ssl_cert_dup(ctx->internal->cert)) == NULL)
270 		goto err;
271 
272 	s->internal->read_ahead = ctx->internal->read_ahead;
273 	s->internal->msg_callback = ctx->internal->msg_callback;
274 	s->internal->msg_callback_arg = ctx->internal->msg_callback_arg;
275 	s->verify_mode = ctx->verify_mode;
276 	s->sid_ctx_length = ctx->sid_ctx_length;
277 	OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
278 	memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
279 	s->internal->verify_callback = ctx->internal->default_verify_callback;
280 	s->internal->generate_session_id = ctx->internal->generate_session_id;
281 
282 	s->param = X509_VERIFY_PARAM_new();
283 	if (!s->param)
284 		goto err;
285 	X509_VERIFY_PARAM_inherit(s->param, ctx->param);
286 	s->internal->quiet_shutdown = ctx->internal->quiet_shutdown;
287 	s->max_send_fragment = ctx->internal->max_send_fragment;
288 
289 	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
290 	s->ctx = ctx;
291 	s->internal->tlsext_debug_cb = 0;
292 	s->internal->tlsext_debug_arg = NULL;
293 	s->internal->tlsext_ticket_expected = 0;
294 	s->tlsext_status_type = -1;
295 	s->internal->tlsext_status_expected = 0;
296 	s->internal->tlsext_ocsp_ids = NULL;
297 	s->internal->tlsext_ocsp_exts = NULL;
298 	s->internal->tlsext_ocsp_resp = NULL;
299 	s->internal->tlsext_ocsp_resplen = -1;
300 	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
301 	s->initial_ctx = ctx;
302 
303 	if (ctx->internal->tlsext_ecpointformatlist != NULL) {
304 		s->internal->tlsext_ecpointformatlist =
305 		    calloc(ctx->internal->tlsext_ecpointformatlist_length,
306 			sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
307 		if (s->internal->tlsext_ecpointformatlist == NULL)
308 			goto err;
309 		memcpy(s->internal->tlsext_ecpointformatlist,
310 		    ctx->internal->tlsext_ecpointformatlist,
311 		    ctx->internal->tlsext_ecpointformatlist_length *
312 		    sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
313 		s->internal->tlsext_ecpointformatlist_length =
314 		    ctx->internal->tlsext_ecpointformatlist_length;
315 	}
316 	if (ctx->internal->tlsext_supportedgroups != NULL) {
317 		s->internal->tlsext_supportedgroups =
318 		    calloc(ctx->internal->tlsext_supportedgroups_length,
319 			sizeof(ctx->internal->tlsext_supportedgroups[0]));
320 		if (s->internal->tlsext_supportedgroups == NULL)
321 			goto err;
322 		memcpy(s->internal->tlsext_supportedgroups,
323 		    ctx->internal->tlsext_supportedgroups,
324 		    ctx->internal->tlsext_supportedgroups_length *
325 		    sizeof(ctx->internal->tlsext_supportedgroups[0]));
326 		s->internal->tlsext_supportedgroups_length =
327 		    ctx->internal->tlsext_supportedgroups_length;
328 	}
329 
330 	if (s->ctx->internal->alpn_client_proto_list != NULL) {
331 		s->internal->alpn_client_proto_list =
332 		    malloc(s->ctx->internal->alpn_client_proto_list_len);
333 		if (s->internal->alpn_client_proto_list == NULL)
334 			goto err;
335 		memcpy(s->internal->alpn_client_proto_list,
336 		    s->ctx->internal->alpn_client_proto_list,
337 		    s->ctx->internal->alpn_client_proto_list_len);
338 		s->internal->alpn_client_proto_list_len =
339 		    s->ctx->internal->alpn_client_proto_list_len;
340 	}
341 
342 	s->verify_result = X509_V_OK;
343 
344 	s->method = ctx->method;
345 
346 	if (!s->method->internal->ssl_new(s))
347 		goto err;
348 
349 	s->references = 1;
350 	s->server = (ctx->method->internal->ssl_accept == ssl_undefined_function) ? 0 : 1;
351 
352 	SSL_clear(s);
353 
354 	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
355 
356 	return (s);
357 
358  err:
359 	SSL_free(s);
360 	SSLerrorx(ERR_R_MALLOC_FAILURE);
361 	return (NULL);
362 }
363 
364 int
365 SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
366     unsigned int sid_ctx_len)
367 {
368 	if (sid_ctx_len > sizeof ctx->sid_ctx) {
369 		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
370 		return (0);
371 	}
372 	ctx->sid_ctx_length = sid_ctx_len;
373 	memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
374 
375 	return (1);
376 }
377 
378 int
379 SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
380     unsigned int sid_ctx_len)
381 {
382 	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
383 		SSLerror(ssl, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
384 		return (0);
385 	}
386 	ssl->sid_ctx_length = sid_ctx_len;
387 	memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
388 
389 	return (1);
390 }
391 
392 int
393 SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
394 {
395 	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
396 	ctx->internal->generate_session_id = cb;
397 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
398 	return (1);
399 }
400 
401 int
402 SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
403 {
404 	CRYPTO_w_lock(CRYPTO_LOCK_SSL);
405 	ssl->internal->generate_session_id = cb;
406 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
407 	return (1);
408 }
409 
410 int
411 SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
412     unsigned int id_len)
413 {
414 	/*
415 	 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp
416 	 * shows how we can "construct" a session to give us the desired
417 	 * check - ie. to find if there's a session in the hash table
418 	 * that would conflict with any new session built out of this
419 	 * id/id_len and the ssl_version in use by this SSL.
420 	 */
421 	SSL_SESSION r, *p;
422 
423 	if (id_len > sizeof r.session_id)
424 		return (0);
425 
426 	r.ssl_version = ssl->version;
427 	r.session_id_length = id_len;
428 	memcpy(r.session_id, id, id_len);
429 
430 	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
431 	p = lh_SSL_SESSION_retrieve(ssl->ctx->internal->sessions, &r);
432 	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
433 	return (p != NULL);
434 }
435 
436 int
437 SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
438 {
439 	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
440 }
441 
442 int
443 SSL_set_purpose(SSL *s, int purpose)
444 {
445 	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
446 }
447 
448 int
449 SSL_CTX_set_trust(SSL_CTX *s, int trust)
450 {
451 	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
452 }
453 
454 int
455 SSL_set_trust(SSL *s, int trust)
456 {
457 	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
458 }
459 
460 int
461 SSL_set1_host(SSL *s, const char *hostname)
462 {
463 	struct in_addr ina;
464 	struct in6_addr in6a;
465 
466 	if (hostname != NULL && *hostname != '\0' &&
467 	    (inet_pton(AF_INET, hostname, &ina) == 1 ||
468 	    inet_pton(AF_INET6, hostname, &in6a) == 1))
469 		return X509_VERIFY_PARAM_set1_ip_asc(s->param, hostname);
470 	else
471 		return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
472 }
473 
474 X509_VERIFY_PARAM *
475 SSL_CTX_get0_param(SSL_CTX *ctx)
476 {
477 	return (ctx->param);
478 }
479 
480 int
481 SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
482 {
483 	return (X509_VERIFY_PARAM_set1(ctx->param, vpm));
484 }
485 
486 X509_VERIFY_PARAM *
487 SSL_get0_param(SSL *ssl)
488 {
489 	return (ssl->param);
490 }
491 
492 int
493 SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
494 {
495 	return (X509_VERIFY_PARAM_set1(ssl->param, vpm));
496 }
497 
498 void
499 SSL_free(SSL *s)
500 {
501 	int	i;
502 
503 	if (s == NULL)
504 		return;
505 
506 	i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
507 	if (i > 0)
508 		return;
509 
510 	X509_VERIFY_PARAM_free(s->param);
511 
512 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
513 
514 	if (s->bbio != NULL) {
515 		/* If the buffering BIO is in place, pop it off */
516 		if (s->bbio == s->wbio) {
517 			s->wbio = BIO_pop(s->wbio);
518 		}
519 		BIO_free(s->bbio);
520 		s->bbio = NULL;
521 	}
522 
523 	if (s->rbio != s->wbio)
524 		BIO_free_all(s->rbio);
525 	BIO_free_all(s->wbio);
526 
527 	BUF_MEM_free(s->internal->init_buf);
528 
529 	/* add extra stuff */
530 	sk_SSL_CIPHER_free(s->cipher_list);
531 	sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
532 
533 	/* Make the next call work :-) */
534 	if (s->session != NULL) {
535 		ssl_clear_bad_session(s);
536 		SSL_SESSION_free(s->session);
537 	}
538 
539 	ssl_clear_cipher_state(s);
540 
541 	ssl_cert_free(s->cert);
542 
543 	free(s->tlsext_hostname);
544 	SSL_CTX_free(s->initial_ctx);
545 
546 	free(s->internal->tlsext_ecpointformatlist);
547 	free(s->internal->tlsext_supportedgroups);
548 
549 	sk_X509_EXTENSION_pop_free(s->internal->tlsext_ocsp_exts,
550 	    X509_EXTENSION_free);
551 	sk_OCSP_RESPID_pop_free(s->internal->tlsext_ocsp_ids, OCSP_RESPID_free);
552 	free(s->internal->tlsext_ocsp_resp);
553 
554 	sk_X509_NAME_pop_free(s->internal->client_CA, X509_NAME_free);
555 
556 	if (s->method != NULL)
557 		s->method->internal->ssl_free(s);
558 
559 	SSL_CTX_free(s->ctx);
560 
561 	free(s->internal->alpn_client_proto_list);
562 
563 #ifndef OPENSSL_NO_SRTP
564 	sk_SRTP_PROTECTION_PROFILE_free(s->internal->srtp_profiles);
565 #endif
566 
567 	free(s->internal);
568 	free(s);
569 }
570 
571 int
572 SSL_up_ref(SSL *s)
573 {
574 	int refs = CRYPTO_add(&s->references, 1, CRYPTO_LOCK_SSL);
575 	return (refs > 1) ? 1 : 0;
576 }
577 
578 void
579 SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
580 {
581 	/* If the output buffering BIO is still in place, remove it */
582 	if (s->bbio != NULL) {
583 		if (s->wbio == s->bbio) {
584 			s->wbio = s->wbio->next_bio;
585 			s->bbio->next_bio = NULL;
586 		}
587 	}
588 
589 	if (s->rbio != rbio && s->rbio != s->wbio)
590 		BIO_free_all(s->rbio);
591 	if (s->wbio != wbio)
592 		BIO_free_all(s->wbio);
593 	s->rbio = rbio;
594 	s->wbio = wbio;
595 }
596 
597 BIO *
598 SSL_get_rbio(const SSL *s)
599 {
600 	return (s->rbio);
601 }
602 
603 BIO *
604 SSL_get_wbio(const SSL *s)
605 {
606 	return (s->wbio);
607 }
608 
609 int
610 SSL_get_fd(const SSL *s)
611 {
612 	return (SSL_get_rfd(s));
613 }
614 
615 int
616 SSL_get_rfd(const SSL *s)
617 {
618 	int	 ret = -1;
619 	BIO	*b, *r;
620 
621 	b = SSL_get_rbio(s);
622 	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
623 	if (r != NULL)
624 		BIO_get_fd(r, &ret);
625 	return (ret);
626 }
627 
628 int
629 SSL_get_wfd(const SSL *s)
630 {
631 	int	 ret = -1;
632 	BIO	*b, *r;
633 
634 	b = SSL_get_wbio(s);
635 	r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
636 	if (r != NULL)
637 		BIO_get_fd(r, &ret);
638 	return (ret);
639 }
640 
641 int
642 SSL_set_fd(SSL *s, int fd)
643 {
644 	int	 ret = 0;
645 	BIO	*bio = NULL;
646 
647 	bio = BIO_new(BIO_s_socket());
648 
649 	if (bio == NULL) {
650 		SSLerror(s, ERR_R_BUF_LIB);
651 		goto err;
652 	}
653 	BIO_set_fd(bio, fd, BIO_NOCLOSE);
654 	SSL_set_bio(s, bio, bio);
655 	ret = 1;
656 err:
657 	return (ret);
658 }
659 
660 int
661 SSL_set_wfd(SSL *s, int fd)
662 {
663 	int	 ret = 0;
664 	BIO	*bio = NULL;
665 
666 	if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
667 	    || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
668 		bio = BIO_new(BIO_s_socket());
669 
670 		if (bio == NULL) {
671 			SSLerror(s, ERR_R_BUF_LIB);
672 			goto err;
673 		}
674 		BIO_set_fd(bio, fd, BIO_NOCLOSE);
675 		SSL_set_bio(s, SSL_get_rbio(s), bio);
676 	} else
677 		SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
678 	ret = 1;
679 err:
680 	return (ret);
681 }
682 
683 int
684 SSL_set_rfd(SSL *s, int fd)
685 {
686 	int	 ret = 0;
687 	BIO	*bio = NULL;
688 
689 	if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
690 	    || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
691 		bio = BIO_new(BIO_s_socket());
692 
693 		if (bio == NULL) {
694 			SSLerror(s, ERR_R_BUF_LIB);
695 			goto err;
696 		}
697 		BIO_set_fd(bio, fd, BIO_NOCLOSE);
698 		SSL_set_bio(s, bio, SSL_get_wbio(s));
699 	} else
700 		SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
701 	ret = 1;
702 err:
703 	return (ret);
704 }
705 
706 
707 /* return length of latest Finished message we sent, copy to 'buf' */
708 size_t
709 SSL_get_finished(const SSL *s, void *buf, size_t count)
710 {
711 	size_t	ret;
712 
713 	ret = S3I(s)->tmp.finish_md_len;
714 	if (count > ret)
715 		count = ret;
716 	memcpy(buf, S3I(s)->tmp.finish_md, count);
717 	return (ret);
718 }
719 
720 /* return length of latest Finished message we expected, copy to 'buf' */
721 size_t
722 SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
723 {
724 	size_t	ret;
725 
726 	ret = S3I(s)->tmp.peer_finish_md_len;
727 	if (count > ret)
728 		count = ret;
729 	memcpy(buf, S3I(s)->tmp.peer_finish_md, count);
730 	return (ret);
731 }
732 
733 
734 int
735 SSL_get_verify_mode(const SSL *s)
736 {
737 	return (s->verify_mode);
738 }
739 
740 int
741 SSL_get_verify_depth(const SSL *s)
742 {
743 	return (X509_VERIFY_PARAM_get_depth(s->param));
744 }
745 
746 int
747 (*SSL_get_verify_callback(const SSL *s))(int, X509_STORE_CTX *)
748 {
749 	return (s->internal->verify_callback);
750 }
751 
752 int
753 SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
754 {
755 	return (ctx->verify_mode);
756 }
757 
758 int
759 SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
760 {
761 	return (X509_VERIFY_PARAM_get_depth(ctx->param));
762 }
763 
764 int
765 (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *)
766 {
767 	return (ctx->internal->default_verify_callback);
768 }
769 
770 void
771 SSL_set_verify(SSL *s, int mode,
772     int (*callback)(int ok, X509_STORE_CTX *ctx))
773 {
774 	s->verify_mode = mode;
775 	if (callback != NULL)
776 		s->internal->verify_callback = callback;
777 }
778 
779 void
780 SSL_set_verify_depth(SSL *s, int depth)
781 {
782 	X509_VERIFY_PARAM_set_depth(s->param, depth);
783 }
784 
785 void
786 SSL_set_read_ahead(SSL *s, int yes)
787 {
788 	s->internal->read_ahead = yes;
789 }
790 
791 int
792 SSL_get_read_ahead(const SSL *s)
793 {
794 	return (s->internal->read_ahead);
795 }
796 
797 int
798 SSL_pending(const SSL *s)
799 {
800 	/*
801 	 * SSL_pending cannot work properly if read-ahead is enabled
802 	 * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)),
803 	 * and it is impossible to fix since SSL_pending cannot report
804 	 * errors that may be observed while scanning the new data.
805 	 * (Note that SSL_pending() is often used as a boolean value,
806 	 * so we'd better not return -1.)
807 	 */
808 	return (ssl3_pending(s));
809 }
810 
811 X509 *
812 SSL_get_peer_certificate(const SSL *s)
813 {
814 	X509	*r;
815 
816 	if ((s == NULL) || (s->session == NULL))
817 		r = NULL;
818 	else
819 		r = s->session->peer;
820 
821 	if (r == NULL)
822 		return (r);
823 
824 	CRYPTO_add(&r->references, 1, CRYPTO_LOCK_X509);
825 
826 	return (r);
827 }
828 
829 STACK_OF(X509) *
830 SSL_get_peer_cert_chain(const SSL *s)
831 {
832 	STACK_OF(X509)	*r;
833 
834 	if ((s == NULL) || (s->session == NULL) ||
835 	    (SSI(s)->sess_cert == NULL))
836 		r = NULL;
837 	else
838 		r = SSI(s)->sess_cert->cert_chain;
839 
840 	/*
841 	 * If we are a client, cert_chain includes the peer's own
842 	 * certificate;
843 	 * if we are a server, it does not.
844 	 */
845 	return (r);
846 }
847 
848 /*
849  * Now in theory, since the calling process own 't' it should be safe to
850  * modify.  We need to be able to read f without being hassled
851  */
852 int
853 SSL_copy_session_id(SSL *t, const SSL *f)
854 {
855 	CERT	*tmp;
856 
857 	/* Do we need to do SSL locking? */
858 	if (!SSL_set_session(t, SSL_get_session(f)))
859 		return 0;
860 
861 	/* What if we are set up for one protocol but want to talk another? */
862 	if (t->method != f->method) {
863 		t->method->internal->ssl_free(t);
864 		t->method = f->method;
865 		if (!t->method->internal->ssl_new(t))
866 			return 0;
867 	}
868 
869 	tmp = t->cert;
870 	if (f->cert != NULL) {
871 		CRYPTO_add(&f->cert->references, 1, CRYPTO_LOCK_SSL_CERT);
872 		t->cert = f->cert;
873 	} else
874 		t->cert = NULL;
875 	ssl_cert_free(tmp);
876 
877 	if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length))
878 		return 0;
879 
880 	return 1;
881 }
882 
883 /* Fix this so it checks all the valid key/cert options */
884 int
885 SSL_CTX_check_private_key(const SSL_CTX *ctx)
886 {
887 	if ((ctx == NULL) || (ctx->internal->cert == NULL) ||
888 	    (ctx->internal->cert->key->x509 == NULL)) {
889 		SSLerrorx(SSL_R_NO_CERTIFICATE_ASSIGNED);
890 		return (0);
891 	}
892 	if (ctx->internal->cert->key->privatekey == NULL) {
893 		SSLerrorx(SSL_R_NO_PRIVATE_KEY_ASSIGNED);
894 		return (0);
895 	}
896 	return (X509_check_private_key(ctx->internal->cert->key->x509,
897 	    ctx->internal->cert->key->privatekey));
898 }
899 
900 /* Fix this function so that it takes an optional type parameter */
901 int
902 SSL_check_private_key(const SSL *ssl)
903 {
904 	if (ssl == NULL) {
905 		SSLerrorx(ERR_R_PASSED_NULL_PARAMETER);
906 		return (0);
907 	}
908 	if (ssl->cert == NULL) {
909 		SSLerror(ssl, SSL_R_NO_CERTIFICATE_ASSIGNED);
910 		return (0);
911 	}
912 	if (ssl->cert->key->x509 == NULL) {
913 		SSLerror(ssl, SSL_R_NO_CERTIFICATE_ASSIGNED);
914 		return (0);
915 	}
916 	if (ssl->cert->key->privatekey == NULL) {
917 		SSLerror(ssl, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
918 		return (0);
919 	}
920 	return (X509_check_private_key(ssl->cert->key->x509,
921 	    ssl->cert->key->privatekey));
922 }
923 
924 int
925 SSL_accept(SSL *s)
926 {
927 	if (s->internal->handshake_func == NULL)
928 		SSL_set_accept_state(s); /* Not properly initialized yet */
929 
930 	return (s->method->internal->ssl_accept(s));
931 }
932 
933 int
934 SSL_connect(SSL *s)
935 {
936 	if (s->internal->handshake_func == NULL)
937 		SSL_set_connect_state(s); /* Not properly initialized yet */
938 
939 	return (s->method->internal->ssl_connect(s));
940 }
941 
942 int
943 SSL_is_server(const SSL *s)
944 {
945 	return s->server;
946 }
947 
948 long
949 SSL_get_default_timeout(const SSL *s)
950 {
951 	return (s->method->internal->get_timeout());
952 }
953 
954 int
955 SSL_read(SSL *s, void *buf, int num)
956 {
957 	if (s->internal->handshake_func == NULL) {
958 		SSLerror(s, SSL_R_UNINITIALIZED);
959 		return (-1);
960 	}
961 
962 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
963 		s->internal->rwstate = SSL_NOTHING;
964 		return (0);
965 	}
966 	return ssl3_read(s, buf, num);
967 }
968 
969 int
970 SSL_peek(SSL *s, void *buf, int num)
971 {
972 	if (s->internal->handshake_func == NULL) {
973 		SSLerror(s, SSL_R_UNINITIALIZED);
974 		return (-1);
975 	}
976 
977 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
978 		return (0);
979 	}
980 	return ssl3_peek(s, buf, num);
981 }
982 
983 int
984 SSL_write(SSL *s, const void *buf, int num)
985 {
986 	if (s->internal->handshake_func == NULL) {
987 		SSLerror(s, SSL_R_UNINITIALIZED);
988 		return (-1);
989 	}
990 
991 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
992 		s->internal->rwstate = SSL_NOTHING;
993 		SSLerror(s, SSL_R_PROTOCOL_IS_SHUTDOWN);
994 		return (-1);
995 	}
996 	return ssl3_write(s, buf, num);
997 }
998 
999 int
1000 SSL_shutdown(SSL *s)
1001 {
1002 	/*
1003 	 * Note that this function behaves differently from what one might
1004 	 * expect.  Return values are 0 for no success (yet),
1005 	 * 1 for success; but calling it once is usually not enough,
1006 	 * even if blocking I/O is used (see ssl3_shutdown).
1007 	 */
1008 
1009 	if (s->internal->handshake_func == NULL) {
1010 		SSLerror(s, SSL_R_UNINITIALIZED);
1011 		return (-1);
1012 	}
1013 
1014 	if (s != NULL && !SSL_in_init(s))
1015 		return (s->method->internal->ssl_shutdown(s));
1016 
1017 	return (1);
1018 }
1019 
1020 int
1021 SSL_renegotiate(SSL *s)
1022 {
1023 	if (s->internal->renegotiate == 0)
1024 		s->internal->renegotiate = 1;
1025 
1026 	s->internal->new_session = 1;
1027 
1028 	return (s->method->internal->ssl_renegotiate(s));
1029 }
1030 
1031 int
1032 SSL_renegotiate_abbreviated(SSL *s)
1033 {
1034 	if (s->internal->renegotiate == 0)
1035 		s->internal->renegotiate = 1;
1036 
1037 	s->internal->new_session = 0;
1038 
1039 	return (s->method->internal->ssl_renegotiate(s));
1040 }
1041 
1042 int
1043 SSL_renegotiate_pending(SSL *s)
1044 {
1045 	/*
1046 	 * Becomes true when negotiation is requested;
1047 	 * false again once a handshake has finished.
1048 	 */
1049 	return (s->internal->renegotiate != 0);
1050 }
1051 
1052 long
1053 SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1054 {
1055 	long	l;
1056 
1057 	switch (cmd) {
1058 	case SSL_CTRL_GET_READ_AHEAD:
1059 		return (s->internal->read_ahead);
1060 	case SSL_CTRL_SET_READ_AHEAD:
1061 		l = s->internal->read_ahead;
1062 		s->internal->read_ahead = larg;
1063 		return (l);
1064 
1065 	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1066 		s->internal->msg_callback_arg = parg;
1067 		return (1);
1068 
1069 	case SSL_CTRL_OPTIONS:
1070 		return (s->internal->options|=larg);
1071 	case SSL_CTRL_CLEAR_OPTIONS:
1072 		return (s->internal->options&=~larg);
1073 	case SSL_CTRL_MODE:
1074 		return (s->internal->mode|=larg);
1075 	case SSL_CTRL_CLEAR_MODE:
1076 		return (s->internal->mode &=~larg);
1077 	case SSL_CTRL_GET_MAX_CERT_LIST:
1078 		return (s->internal->max_cert_list);
1079 	case SSL_CTRL_SET_MAX_CERT_LIST:
1080 		l = s->internal->max_cert_list;
1081 		s->internal->max_cert_list = larg;
1082 		return (l);
1083 	case SSL_CTRL_SET_MTU:
1084 #ifndef OPENSSL_NO_DTLS1
1085 		if (larg < (long)dtls1_min_mtu())
1086 			return (0);
1087 #endif
1088 		if (SSL_IS_DTLS(s)) {
1089 			D1I(s)->mtu = larg;
1090 			return (larg);
1091 		}
1092 		return (0);
1093 	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1094 		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1095 			return (0);
1096 		s->max_send_fragment = larg;
1097 		return (1);
1098 	case SSL_CTRL_GET_RI_SUPPORT:
1099 		if (s->s3)
1100 			return (S3I(s)->send_connection_binding);
1101 		else return (0);
1102 	default:
1103 		if (SSL_IS_DTLS(s))
1104 			return dtls1_ctrl(s, cmd, larg, parg);
1105 		return ssl3_ctrl(s, cmd, larg, parg);
1106 	}
1107 }
1108 
1109 long
1110 SSL_callback_ctrl(SSL *s, int cmd, void (*fp)(void))
1111 {
1112 	switch (cmd) {
1113 	case SSL_CTRL_SET_MSG_CALLBACK:
1114 		s->internal->msg_callback = (void (*)(int write_p, int version,
1115 		    int content_type, const void *buf, size_t len,
1116 		    SSL *ssl, void *arg))(fp);
1117 		return (1);
1118 
1119 	default:
1120 		return (ssl3_callback_ctrl(s, cmd, fp));
1121 	}
1122 }
1123 
1124 struct lhash_st_SSL_SESSION *
1125 SSL_CTX_sessions(SSL_CTX *ctx)
1126 {
1127 	return (ctx->internal->sessions);
1128 }
1129 
1130 long
1131 SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1132 {
1133 	long	l;
1134 
1135 	switch (cmd) {
1136 	case SSL_CTRL_GET_READ_AHEAD:
1137 		return (ctx->internal->read_ahead);
1138 	case SSL_CTRL_SET_READ_AHEAD:
1139 		l = ctx->internal->read_ahead;
1140 		ctx->internal->read_ahead = larg;
1141 		return (l);
1142 
1143 	case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1144 		ctx->internal->msg_callback_arg = parg;
1145 		return (1);
1146 
1147 	case SSL_CTRL_GET_MAX_CERT_LIST:
1148 		return (ctx->internal->max_cert_list);
1149 	case SSL_CTRL_SET_MAX_CERT_LIST:
1150 		l = ctx->internal->max_cert_list;
1151 		ctx->internal->max_cert_list = larg;
1152 		return (l);
1153 
1154 	case SSL_CTRL_SET_SESS_CACHE_SIZE:
1155 		l = ctx->internal->session_cache_size;
1156 		ctx->internal->session_cache_size = larg;
1157 		return (l);
1158 	case SSL_CTRL_GET_SESS_CACHE_SIZE:
1159 		return (ctx->internal->session_cache_size);
1160 	case SSL_CTRL_SET_SESS_CACHE_MODE:
1161 		l = ctx->internal->session_cache_mode;
1162 		ctx->internal->session_cache_mode = larg;
1163 		return (l);
1164 	case SSL_CTRL_GET_SESS_CACHE_MODE:
1165 		return (ctx->internal->session_cache_mode);
1166 
1167 	case SSL_CTRL_SESS_NUMBER:
1168 		return (lh_SSL_SESSION_num_items(ctx->internal->sessions));
1169 	case SSL_CTRL_SESS_CONNECT:
1170 		return (ctx->internal->stats.sess_connect);
1171 	case SSL_CTRL_SESS_CONNECT_GOOD:
1172 		return (ctx->internal->stats.sess_connect_good);
1173 	case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1174 		return (ctx->internal->stats.sess_connect_renegotiate);
1175 	case SSL_CTRL_SESS_ACCEPT:
1176 		return (ctx->internal->stats.sess_accept);
1177 	case SSL_CTRL_SESS_ACCEPT_GOOD:
1178 		return (ctx->internal->stats.sess_accept_good);
1179 	case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1180 		return (ctx->internal->stats.sess_accept_renegotiate);
1181 	case SSL_CTRL_SESS_HIT:
1182 		return (ctx->internal->stats.sess_hit);
1183 	case SSL_CTRL_SESS_CB_HIT:
1184 		return (ctx->internal->stats.sess_cb_hit);
1185 	case SSL_CTRL_SESS_MISSES:
1186 		return (ctx->internal->stats.sess_miss);
1187 	case SSL_CTRL_SESS_TIMEOUTS:
1188 		return (ctx->internal->stats.sess_timeout);
1189 	case SSL_CTRL_SESS_CACHE_FULL:
1190 		return (ctx->internal->stats.sess_cache_full);
1191 	case SSL_CTRL_OPTIONS:
1192 		return (ctx->internal->options|=larg);
1193 	case SSL_CTRL_CLEAR_OPTIONS:
1194 		return (ctx->internal->options&=~larg);
1195 	case SSL_CTRL_MODE:
1196 		return (ctx->internal->mode|=larg);
1197 	case SSL_CTRL_CLEAR_MODE:
1198 		return (ctx->internal->mode&=~larg);
1199 	case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1200 		if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1201 			return (0);
1202 		ctx->internal->max_send_fragment = larg;
1203 		return (1);
1204 	default:
1205 		return (ssl3_ctx_ctrl(ctx, cmd, larg, parg));
1206 	}
1207 }
1208 
1209 long
1210 SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp)(void))
1211 {
1212 	switch (cmd) {
1213 	case SSL_CTRL_SET_MSG_CALLBACK:
1214 		ctx->internal->msg_callback = (void (*)(int write_p, int version,
1215 		    int content_type, const void *buf, size_t len, SSL *ssl,
1216 		    void *arg))(fp);
1217 		return (1);
1218 
1219 	default:
1220 		return (ssl3_ctx_callback_ctrl(ctx, cmd, fp));
1221 	}
1222 }
1223 
1224 int
1225 ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1226 {
1227 	long	l;
1228 
1229 	l = a->id - b->id;
1230 	if (l == 0L)
1231 		return (0);
1232 	else
1233 		return ((l > 0) ? 1:-1);
1234 }
1235 
1236 int
1237 ssl_cipher_ptr_id_cmp(const SSL_CIPHER * const *ap,
1238     const SSL_CIPHER * const *bp)
1239 {
1240 	long	l;
1241 
1242 	l = (*ap)->id - (*bp)->id;
1243 	if (l == 0L)
1244 		return (0);
1245 	else
1246 		return ((l > 0) ? 1:-1);
1247 }
1248 
1249 /*
1250  * Return a STACK of the ciphers available for the SSL and in order of
1251  * preference.
1252  */
1253 STACK_OF(SSL_CIPHER) *
1254 SSL_get_ciphers(const SSL *s)
1255 {
1256 	if (s != NULL) {
1257 		if (s->cipher_list != NULL) {
1258 			return (s->cipher_list);
1259 		} else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1260 			return (s->ctx->cipher_list);
1261 		}
1262 	}
1263 	return (NULL);
1264 }
1265 
1266 STACK_OF(SSL_CIPHER) *
1267 SSL_get_client_ciphers(const SSL *s)
1268 {
1269 	if (s == NULL || s->session == NULL || !s->server)
1270 		return NULL;
1271 	return s->session->ciphers;
1272 }
1273 
1274 STACK_OF(SSL_CIPHER) *
1275 SSL_get1_supported_ciphers(SSL *s)
1276 {
1277 	STACK_OF(SSL_CIPHER) *supported_ciphers = NULL, *ciphers;
1278 	const SSL_CIPHER *cipher;
1279 	uint16_t min_vers, max_vers;
1280 	int i;
1281 
1282 	if (s == NULL)
1283 		return NULL;
1284 	if (!ssl_supported_version_range(s, &min_vers, &max_vers))
1285 		return NULL;
1286 	if ((ciphers = SSL_get_ciphers(s)) == NULL)
1287 		return NULL;
1288 	if ((supported_ciphers = sk_SSL_CIPHER_new_null()) == NULL)
1289 		return NULL;
1290 
1291 	for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1292 		if ((cipher = sk_SSL_CIPHER_value(ciphers, i)) == NULL)
1293 			goto err;
1294 		if (!ssl_cipher_is_permitted(cipher, min_vers, max_vers))
1295 			continue;
1296 		if (!sk_SSL_CIPHER_push(supported_ciphers, cipher))
1297 			goto err;
1298 	}
1299 
1300 	if (sk_SSL_CIPHER_num(supported_ciphers) > 0)
1301 		return supported_ciphers;
1302 
1303  err:
1304 	sk_SSL_CIPHER_free(supported_ciphers);
1305 	return NULL;
1306 }
1307 
1308 /*
1309  * Return a STACK of the ciphers available for the SSL and in order of
1310  * algorithm id.
1311  */
1312 STACK_OF(SSL_CIPHER) *
1313 ssl_get_ciphers_by_id(SSL *s)
1314 {
1315 	if (s != NULL) {
1316 		if (s->internal->cipher_list_by_id != NULL) {
1317 			return (s->internal->cipher_list_by_id);
1318 		} else if ((s->ctx != NULL) &&
1319 		    (s->ctx->internal->cipher_list_by_id != NULL)) {
1320 			return (s->ctx->internal->cipher_list_by_id);
1321 		}
1322 	}
1323 	return (NULL);
1324 }
1325 
1326 /* See if we have any ECC cipher suites. */
1327 int
1328 ssl_has_ecc_ciphers(SSL *s)
1329 {
1330 	STACK_OF(SSL_CIPHER) *ciphers;
1331 	unsigned long alg_k, alg_a;
1332 	SSL_CIPHER *cipher;
1333 	int i;
1334 
1335 	if (s->version == DTLS1_VERSION)
1336 		return 0;
1337 	if ((ciphers = SSL_get_ciphers(s)) == NULL)
1338 		return 0;
1339 
1340 	for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1341 		cipher = sk_SSL_CIPHER_value(ciphers, i);
1342 
1343 		alg_k = cipher->algorithm_mkey;
1344 		alg_a = cipher->algorithm_auth;
1345 
1346 		if ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
1347 			return 1;
1348 	}
1349 
1350 	return 0;
1351 }
1352 
1353 /* The old interface to get the same thing as SSL_get_ciphers(). */
1354 const char *
1355 SSL_get_cipher_list(const SSL *s, int n)
1356 {
1357 	SSL_CIPHER		*c;
1358 	STACK_OF(SSL_CIPHER)	*sk;
1359 
1360 	if (s == NULL)
1361 		return (NULL);
1362 	sk = SSL_get_ciphers(s);
1363 	if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
1364 		return (NULL);
1365 	c = sk_SSL_CIPHER_value(sk, n);
1366 	if (c == NULL)
1367 		return (NULL);
1368 	return (c->name);
1369 }
1370 
1371 STACK_OF(SSL_CIPHER) *
1372 SSL_CTX_get_ciphers(const SSL_CTX *ctx)
1373 {
1374 	return ctx->cipher_list;
1375 }
1376 
1377 /* Specify the ciphers to be used by default by the SSL_CTX. */
1378 int
1379 SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
1380 {
1381 	STACK_OF(SSL_CIPHER)	*sk;
1382 
1383 	sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1384 	    &ctx->internal->cipher_list_by_id, str);
1385 	/*
1386 	 * ssl_create_cipher_list may return an empty stack if it
1387 	 * was unable to find a cipher matching the given rule string
1388 	 * (for example if the rule string specifies a cipher which
1389 	 * has been disabled). This is not an error as far as
1390 	 * ssl_create_cipher_list is concerned, and hence
1391 	 * ctx->cipher_list and ctx->internal->cipher_list_by_id has been
1392 	 * updated.
1393 	 */
1394 	if (sk == NULL)
1395 		return (0);
1396 	else if (sk_SSL_CIPHER_num(sk) == 0) {
1397 		SSLerrorx(SSL_R_NO_CIPHER_MATCH);
1398 		return (0);
1399 	}
1400 	return (1);
1401 }
1402 
1403 /* Specify the ciphers to be used by the SSL. */
1404 int
1405 SSL_set_cipher_list(SSL *s, const char *str)
1406 {
1407 	STACK_OF(SSL_CIPHER)	*sk;
1408 
1409 	sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1410 	&s->internal->cipher_list_by_id, str);
1411 	/* see comment in SSL_CTX_set_cipher_list */
1412 	if (sk == NULL)
1413 		return (0);
1414 	else if (sk_SSL_CIPHER_num(sk) == 0) {
1415 		SSLerror(s, SSL_R_NO_CIPHER_MATCH);
1416 		return (0);
1417 	}
1418 	return (1);
1419 }
1420 
1421 /* works well for SSLv2, not so good for SSLv3 */
1422 char *
1423 SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
1424 {
1425 	char			*end;
1426 	STACK_OF(SSL_CIPHER)	*sk;
1427 	SSL_CIPHER		*c;
1428 	size_t			 curlen = 0;
1429 	int			 i;
1430 
1431 	if (s->session == NULL || s->session->ciphers == NULL || len < 2)
1432 		return (NULL);
1433 
1434 	sk = s->session->ciphers;
1435 	if (sk_SSL_CIPHER_num(sk) == 0)
1436 		return (NULL);
1437 
1438 	buf[0] = '\0';
1439 	for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1440 		c = sk_SSL_CIPHER_value(sk, i);
1441 		end = buf + curlen;
1442 		if (strlcat(buf, c->name, len) >= len ||
1443 		    (curlen = strlcat(buf, ":", len)) >= len) {
1444 			/* remove truncated cipher from list */
1445 			*end = '\0';
1446 			break;
1447 		}
1448 	}
1449 	/* remove trailing colon */
1450 	if ((end = strrchr(buf, ':')) != NULL)
1451 		*end = '\0';
1452 	return (buf);
1453 }
1454 
1455 /*
1456  * Return a servername extension value if provided in Client Hello, or NULL.
1457  * So far, only host_name types are defined (RFC 3546).
1458  */
1459 const char *
1460 SSL_get_servername(const SSL *s, const int type)
1461 {
1462 	if (type != TLSEXT_NAMETYPE_host_name)
1463 		return (NULL);
1464 
1465 	return (s->session && !s->tlsext_hostname ?
1466 	    s->session->tlsext_hostname :
1467 	    s->tlsext_hostname);
1468 }
1469 
1470 int
1471 SSL_get_servername_type(const SSL *s)
1472 {
1473 	if (s->session &&
1474 	    (!s->tlsext_hostname ?
1475 	    s->session->tlsext_hostname : s->tlsext_hostname))
1476 		return (TLSEXT_NAMETYPE_host_name);
1477 	return (-1);
1478 }
1479 
1480 /*
1481  * SSL_select_next_proto implements standard protocol selection. It is
1482  * expected that this function is called from the callback set by
1483  * SSL_CTX_set_alpn_select_cb.
1484  *
1485  * The protocol data is assumed to be a vector of 8-bit, length prefixed byte
1486  * strings. The length byte itself is not included in the length. A byte
1487  * string of length 0 is invalid. No byte string may be truncated.
1488  *
1489  * It returns either:
1490  * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or
1491  * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1492  */
1493 int
1494 SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
1495     const unsigned char *server, unsigned int server_len,
1496     const unsigned char *client, unsigned int client_len)
1497 {
1498 	unsigned int		 i, j;
1499 	const unsigned char	*result;
1500 	int			 status = OPENSSL_NPN_UNSUPPORTED;
1501 
1502 	/*
1503 	 * For each protocol in server preference order,
1504 	 * see if we support it.
1505 	 */
1506 	for (i = 0; i < server_len; ) {
1507 		for (j = 0; j < client_len; ) {
1508 			if (server[i] == client[j] &&
1509 			    memcmp(&server[i + 1],
1510 			    &client[j + 1], server[i]) == 0) {
1511 				/* We found a match */
1512 				result = &server[i];
1513 				status = OPENSSL_NPN_NEGOTIATED;
1514 				goto found;
1515 			}
1516 			j += client[j];
1517 			j++;
1518 		}
1519 		i += server[i];
1520 		i++;
1521 	}
1522 
1523 	/* There's no overlap between our protocols and the server's list. */
1524 	result = client;
1525 	status = OPENSSL_NPN_NO_OVERLAP;
1526 
1527 found:
1528 	*out = (unsigned char *) result + 1;
1529 	*outlen = result[0];
1530 	return (status);
1531 }
1532 
1533 /* SSL_get0_next_proto_negotiated is deprecated. */
1534 void
1535 SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
1536     unsigned *len)
1537 {
1538 	*data = NULL;
1539 	*len = 0;
1540 }
1541 
1542 /* SSL_CTX_set_next_protos_advertised_cb is deprecated. */
1543 void
1544 SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl,
1545     const unsigned char **out, unsigned int *outlen, void *arg), void *arg)
1546 {
1547 }
1548 
1549 /* SSL_CTX_set_next_proto_select_cb is deprecated. */
1550 void
1551 SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, int (*cb) (SSL *s,
1552     unsigned char **out, unsigned char *outlen, const unsigned char *in,
1553     unsigned int inlen, void *arg), void *arg)
1554 {
1555 }
1556 
1557 /*
1558  * SSL_CTX_set_alpn_protos sets the ALPN protocol list to the specified
1559  * protocols, which must be in wire-format (i.e. a series of non-empty,
1560  * 8-bit length-prefixed strings). Returns 0 on success.
1561  */
1562 int
1563 SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
1564     unsigned int protos_len)
1565 {
1566 	int failed = 1;
1567 
1568 	if (protos == NULL || protos_len == 0)
1569 		goto err;
1570 
1571 	free(ctx->internal->alpn_client_proto_list);
1572 	ctx->internal->alpn_client_proto_list = NULL;
1573 	ctx->internal->alpn_client_proto_list_len = 0;
1574 
1575 	if ((ctx->internal->alpn_client_proto_list = malloc(protos_len))
1576 	    == NULL)
1577 		goto err;
1578 	ctx->internal->alpn_client_proto_list_len = protos_len;
1579 
1580 	memcpy(ctx->internal->alpn_client_proto_list, protos, protos_len);
1581 
1582 	failed = 0;
1583 
1584  err:
1585 	/* NOTE: Return values are the reverse of what you expect. */
1586 	return (failed);
1587 }
1588 
1589 /*
1590  * SSL_set_alpn_protos sets the ALPN protocol list to the specified
1591  * protocols, which must be in wire-format (i.e. a series of non-empty,
1592  * 8-bit length-prefixed strings). Returns 0 on success.
1593  */
1594 int
1595 SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
1596     unsigned int protos_len)
1597 {
1598 	int failed = 1;
1599 
1600 	if (protos == NULL || protos_len == 0)
1601 		goto err;
1602 
1603 	free(ssl->internal->alpn_client_proto_list);
1604 	ssl->internal->alpn_client_proto_list = NULL;
1605 	ssl->internal->alpn_client_proto_list_len = 0;
1606 
1607 	if ((ssl->internal->alpn_client_proto_list = malloc(protos_len))
1608 	    == NULL)
1609 		goto err;
1610 	ssl->internal->alpn_client_proto_list_len = protos_len;
1611 
1612 	memcpy(ssl->internal->alpn_client_proto_list, protos, protos_len);
1613 
1614 	failed = 0;
1615 
1616  err:
1617 	/* NOTE: Return values are the reverse of what you expect. */
1618 	return (failed);
1619 }
1620 
1621 /*
1622  * SSL_CTX_set_alpn_select_cb sets a callback function that is called during
1623  * ClientHello processing in order to select an ALPN protocol from the
1624  * client's list of offered protocols.
1625  */
1626 void
1627 SSL_CTX_set_alpn_select_cb(SSL_CTX* ctx,
1628     int (*cb) (SSL *ssl, const unsigned char **out, unsigned char *outlen,
1629     const unsigned char *in, unsigned int inlen, void *arg), void *arg)
1630 {
1631 	ctx->internal->alpn_select_cb = cb;
1632 	ctx->internal->alpn_select_cb_arg = arg;
1633 }
1634 
1635 /*
1636  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any). On return
1637  * it sets data to point to len bytes of protocol name (not including the
1638  * leading length-prefix byte). If the server didn't respond with* a negotiated
1639  * protocol then len will be zero.
1640  */
1641 void
1642 SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
1643     unsigned *len)
1644 {
1645 	*data = NULL;
1646 	*len = 0;
1647 
1648 	*data = ssl->s3->internal->alpn_selected;
1649 	*len = ssl->s3->internal->alpn_selected_len;
1650 }
1651 
1652 int
1653 SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1654     const char *label, size_t llen, const unsigned char *p, size_t plen,
1655     int use_context)
1656 {
1657 	return (tls1_export_keying_material(s, out, olen,
1658 	    label, llen, p, plen, use_context));
1659 }
1660 
1661 static unsigned long
1662 ssl_session_hash(const SSL_SESSION *a)
1663 {
1664 	unsigned long	l;
1665 
1666 	l = (unsigned long)
1667 	    ((unsigned int) a->session_id[0]     )|
1668 	    ((unsigned int) a->session_id[1]<< 8L)|
1669 	    ((unsigned long)a->session_id[2]<<16L)|
1670 	    ((unsigned long)a->session_id[3]<<24L);
1671 	return (l);
1672 }
1673 
1674 /*
1675  * NB: If this function (or indeed the hash function which uses a sort of
1676  * coarser function than this one) is changed, ensure
1677  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being
1678  * able to construct an SSL_SESSION that will collide with any existing session
1679  * with a matching session ID.
1680  */
1681 static int
1682 ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
1683 {
1684 	if (a->ssl_version != b->ssl_version)
1685 		return (1);
1686 	if (a->session_id_length != b->session_id_length)
1687 		return (1);
1688 	if (timingsafe_memcmp(a->session_id, b->session_id, a->session_id_length) != 0)
1689 		return (1);
1690 	return (0);
1691 }
1692 
1693 /*
1694  * These wrapper functions should remain rather than redeclaring
1695  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
1696  * variable. The reason is that the functions aren't static, they're exposed via
1697  * ssl.h.
1698  */
1699 static unsigned long
1700 ssl_session_LHASH_HASH(const void *arg)
1701 {
1702 	const SSL_SESSION *a = arg;
1703 
1704 	return ssl_session_hash(a);
1705 }
1706 
1707 static int
1708 ssl_session_LHASH_COMP(const void *arg1, const void *arg2)
1709 {
1710 	const SSL_SESSION *a = arg1;
1711 	const SSL_SESSION *b = arg2;
1712 
1713 	return ssl_session_cmp(a, b);
1714 }
1715 
1716 SSL_CTX *
1717 SSL_CTX_new(const SSL_METHOD *meth)
1718 {
1719 	SSL_CTX	*ret;
1720 
1721 	if (!OPENSSL_init_ssl(0, NULL)) {
1722 		SSLerrorx(SSL_R_LIBRARY_BUG);
1723 		return (NULL);
1724 	}
1725 
1726 	if (meth == NULL) {
1727 		SSLerrorx(SSL_R_NULL_SSL_METHOD_PASSED);
1728 		return (NULL);
1729 	}
1730 
1731 	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
1732 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1733 		return (NULL);
1734 	}
1735 	if ((ret->internal = calloc(1, sizeof(*ret->internal))) == NULL) {
1736 		free(ret);
1737 		SSLerrorx(ERR_R_MALLOC_FAILURE);
1738 		return (NULL);
1739 	}
1740 
1741 	if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1742 		SSLerrorx(SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1743 		goto err;
1744 	}
1745 
1746 	ret->method = meth;
1747 	ret->internal->min_version = meth->internal->min_version;
1748 	ret->internal->max_version = meth->internal->max_version;
1749 
1750 	ret->cert_store = NULL;
1751 	ret->internal->session_cache_mode = SSL_SESS_CACHE_SERVER;
1752 	ret->internal->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1753 	ret->internal->session_cache_head = NULL;
1754 	ret->internal->session_cache_tail = NULL;
1755 
1756 	/* We take the system default */
1757 	ret->session_timeout = meth->internal->get_timeout();
1758 
1759 	ret->internal->new_session_cb = 0;
1760 	ret->internal->remove_session_cb = 0;
1761 	ret->internal->get_session_cb = 0;
1762 	ret->internal->generate_session_id = 0;
1763 
1764 	memset((char *)&ret->internal->stats, 0, sizeof(ret->internal->stats));
1765 
1766 	ret->references = 1;
1767 	ret->internal->quiet_shutdown = 0;
1768 
1769 	ret->internal->info_callback = NULL;
1770 
1771 	ret->internal->app_verify_callback = 0;
1772 	ret->internal->app_verify_arg = NULL;
1773 
1774 	ret->internal->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1775 	ret->internal->read_ahead = 0;
1776 	ret->internal->msg_callback = 0;
1777 	ret->internal->msg_callback_arg = NULL;
1778 	ret->verify_mode = SSL_VERIFY_NONE;
1779 	ret->sid_ctx_length = 0;
1780 	ret->internal->default_verify_callback = NULL;
1781 
1782 	if ((ret->internal->cert = ssl_cert_new()) == NULL)
1783 		goto err;
1784 
1785 	ret->default_passwd_callback = 0;
1786 	ret->default_passwd_callback_userdata = NULL;
1787 	ret->internal->client_cert_cb = 0;
1788 	ret->internal->app_gen_cookie_cb = 0;
1789 	ret->internal->app_verify_cookie_cb = 0;
1790 
1791 	ret->internal->sessions = lh_SSL_SESSION_new();
1792 	if (ret->internal->sessions == NULL)
1793 		goto err;
1794 	ret->cert_store = X509_STORE_new();
1795 	if (ret->cert_store == NULL)
1796 		goto err;
1797 
1798 	ssl_create_cipher_list(ret->method, &ret->cipher_list,
1799 	    &ret->internal->cipher_list_by_id, SSL_DEFAULT_CIPHER_LIST);
1800 	if (ret->cipher_list == NULL ||
1801 	    sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1802 		SSLerrorx(SSL_R_LIBRARY_HAS_NO_CIPHERS);
1803 		goto err2;
1804 	}
1805 
1806 	ret->param = X509_VERIFY_PARAM_new();
1807 	if (!ret->param)
1808 		goto err;
1809 
1810 	if ((ret->internal->client_CA = sk_X509_NAME_new_null()) == NULL)
1811 		goto err;
1812 
1813 	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->internal->ex_data);
1814 
1815 	ret->extra_certs = NULL;
1816 
1817 	ret->internal->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1818 
1819 	ret->internal->tlsext_servername_callback = 0;
1820 	ret->internal->tlsext_servername_arg = NULL;
1821 
1822 	/* Setup RFC4507 ticket keys */
1823 	arc4random_buf(ret->internal->tlsext_tick_key_name, 16);
1824 	arc4random_buf(ret->internal->tlsext_tick_hmac_key, 16);
1825 	arc4random_buf(ret->internal->tlsext_tick_aes_key, 16);
1826 
1827 	ret->internal->tlsext_status_cb = 0;
1828 	ret->internal->tlsext_status_arg = NULL;
1829 
1830 #ifndef OPENSSL_NO_ENGINE
1831 	ret->internal->client_cert_engine = NULL;
1832 #ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1833 #define eng_strx(x)	#x
1834 #define eng_str(x)	eng_strx(x)
1835 	/* Use specific client engine automatically... ignore errors */
1836 	{
1837 		ENGINE *eng;
1838 		eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1839 		if (!eng) {
1840 			ERR_clear_error();
1841 			ENGINE_load_builtin_engines();
1842 			eng = ENGINE_by_id(eng_str(
1843 			    OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1844 		}
1845 		if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
1846 			ERR_clear_error();
1847 	}
1848 #endif
1849 #endif
1850 	/*
1851 	 * Default is to connect to non-RI servers. When RI is more widely
1852 	 * deployed might change this.
1853 	 */
1854 	ret->internal->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1855 
1856 	return (ret);
1857 err:
1858 	SSLerrorx(ERR_R_MALLOC_FAILURE);
1859 err2:
1860 	SSL_CTX_free(ret);
1861 	return (NULL);
1862 }
1863 
1864 void
1865 SSL_CTX_free(SSL_CTX *ctx)
1866 {
1867 	int	i;
1868 
1869 	if (ctx == NULL)
1870 		return;
1871 
1872 	i = CRYPTO_add(&ctx->references, -1, CRYPTO_LOCK_SSL_CTX);
1873 	if (i > 0)
1874 		return;
1875 
1876 	X509_VERIFY_PARAM_free(ctx->param);
1877 
1878 	/*
1879 	 * Free internal session cache. However: the remove_cb() may reference
1880 	 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
1881 	 * after the sessions were flushed.
1882 	 * As the ex_data handling routines might also touch the session cache,
1883 	 * the most secure solution seems to be: empty (flush) the cache, then
1884 	 * free ex_data, then finally free the cache.
1885 	 * (See ticket [openssl.org #212].)
1886 	 */
1887 	if (ctx->internal->sessions != NULL)
1888 		SSL_CTX_flush_sessions(ctx, 0);
1889 
1890 	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ctx, &ctx->internal->ex_data);
1891 
1892 	lh_SSL_SESSION_free(ctx->internal->sessions);
1893 
1894 	X509_STORE_free(ctx->cert_store);
1895 	sk_SSL_CIPHER_free(ctx->cipher_list);
1896 	sk_SSL_CIPHER_free(ctx->internal->cipher_list_by_id);
1897 	ssl_cert_free(ctx->internal->cert);
1898 	sk_X509_NAME_pop_free(ctx->internal->client_CA, X509_NAME_free);
1899 	sk_X509_pop_free(ctx->extra_certs, X509_free);
1900 
1901 #ifndef OPENSSL_NO_SRTP
1902 	if (ctx->internal->srtp_profiles)
1903 		sk_SRTP_PROTECTION_PROFILE_free(ctx->internal->srtp_profiles);
1904 #endif
1905 
1906 #ifndef OPENSSL_NO_ENGINE
1907 	ENGINE_finish(ctx->internal->client_cert_engine);
1908 #endif
1909 
1910 	free(ctx->internal->tlsext_ecpointformatlist);
1911 	free(ctx->internal->tlsext_supportedgroups);
1912 
1913 	free(ctx->internal->alpn_client_proto_list);
1914 
1915 	free(ctx->internal);
1916 	free(ctx);
1917 }
1918 
1919 int
1920 SSL_CTX_up_ref(SSL_CTX *ctx)
1921 {
1922 	int refs = CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
1923 	return ((refs > 1) ? 1 : 0);
1924 }
1925 
1926 pem_password_cb *
1927 SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
1928 {
1929 	return (ctx->default_passwd_callback);
1930 }
1931 
1932 void
1933 SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
1934 {
1935 	ctx->default_passwd_callback = cb;
1936 }
1937 
1938 void *
1939 SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
1940 {
1941 	return ctx->default_passwd_callback_userdata;
1942 }
1943 
1944 void
1945 SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
1946 {
1947 	ctx->default_passwd_callback_userdata = u;
1948 }
1949 
1950 void
1951 SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,
1952     void *), void *arg)
1953 {
1954 	ctx->internal->app_verify_callback = cb;
1955 	ctx->internal->app_verify_arg = arg;
1956 }
1957 
1958 void
1959 SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*cb)(int, X509_STORE_CTX *))
1960 {
1961 	ctx->verify_mode = mode;
1962 	ctx->internal->default_verify_callback = cb;
1963 }
1964 
1965 void
1966 SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
1967 {
1968 	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
1969 }
1970 
1971 void
1972 ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
1973 {
1974 	int		 rsa_enc, rsa_sign, dh_tmp;
1975 	int		 have_ecc_cert;
1976 	unsigned long	 mask_k, mask_a;
1977 	X509		*x = NULL;
1978 	CERT_PKEY	*cpk;
1979 
1980 	if (c == NULL)
1981 		return;
1982 
1983 	dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL ||
1984 	    c->dh_tmp_auto != 0);
1985 
1986 	cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
1987 	rsa_enc = (cpk->x509 != NULL && cpk->privatekey != NULL);
1988 	cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
1989 	rsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
1990 	cpk = &(c->pkeys[SSL_PKEY_ECC]);
1991 	have_ecc_cert = (cpk->x509 != NULL && cpk->privatekey != NULL);
1992 
1993 	mask_k = 0;
1994 	mask_a = 0;
1995 
1996 	cpk = &(c->pkeys[SSL_PKEY_GOST01]);
1997 	if (cpk->x509 != NULL && cpk->privatekey !=NULL) {
1998 		mask_k |= SSL_kGOST;
1999 		mask_a |= SSL_aGOST01;
2000 	}
2001 
2002 	if (rsa_enc)
2003 		mask_k |= SSL_kRSA;
2004 
2005 	if (dh_tmp)
2006 		mask_k |= SSL_kDHE;
2007 
2008 	if (rsa_enc || rsa_sign)
2009 		mask_a |= SSL_aRSA;
2010 
2011 	mask_a |= SSL_aNULL;
2012 
2013 	/*
2014 	 * An ECC certificate may be usable for ECDH and/or
2015 	 * ECDSA cipher suites depending on the key usage extension.
2016 	 */
2017 	if (have_ecc_cert) {
2018 		x = (c->pkeys[SSL_PKEY_ECC]).x509;
2019 
2020 		/* This call populates extension flags (ex_flags). */
2021 		X509_check_purpose(x, -1, 0);
2022 
2023 		/* Key usage, if present, must allow signing. */
2024 		if ((x->ex_flags & EXFLAG_KUSAGE) == 0 ||
2025 		    (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE))
2026 			mask_a |= SSL_aECDSA;
2027 	}
2028 
2029 	mask_k |= SSL_kECDHE;
2030 
2031 	c->mask_k = mask_k;
2032 	c->mask_a = mask_a;
2033 	c->valid = 1;
2034 }
2035 
2036 /* See if this handshake is using an ECC cipher suite. */
2037 int
2038 ssl_using_ecc_cipher(SSL *s)
2039 {
2040 	unsigned long alg_a, alg_k;
2041 
2042 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2043 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2044 
2045 	return SSI(s)->tlsext_ecpointformatlist != NULL &&
2046 	    SSI(s)->tlsext_ecpointformatlist_length > 0 &&
2047 	    ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA));
2048 }
2049 
2050 int
2051 ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2052 {
2053 	const SSL_CIPHER	*cs = S3I(s)->hs.new_cipher;
2054 	unsigned long		 alg_a;
2055 
2056 	alg_a = cs->algorithm_auth;
2057 
2058 	if (alg_a & SSL_aECDSA) {
2059 		/* This call populates extension flags (ex_flags). */
2060 		X509_check_purpose(x, -1, 0);
2061 
2062 		/* Key usage, if present, must allow signing. */
2063 		if ((x->ex_flags & EXFLAG_KUSAGE) &&
2064 		    ((x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) == 0)) {
2065 			SSLerror(s, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2066 			return (0);
2067 		}
2068 	}
2069 
2070 	return (1);
2071 }
2072 
2073 CERT_PKEY *
2074 ssl_get_server_send_pkey(const SSL *s)
2075 {
2076 	unsigned long	 alg_a;
2077 	CERT		*c;
2078 	int		 i;
2079 
2080 	c = s->cert;
2081 	ssl_set_cert_masks(c, S3I(s)->hs.new_cipher);
2082 
2083 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2084 
2085 	if (alg_a & SSL_aECDSA) {
2086 		i = SSL_PKEY_ECC;
2087 	} else if (alg_a & SSL_aRSA) {
2088 		if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
2089 			i = SSL_PKEY_RSA_SIGN;
2090 		else
2091 			i = SSL_PKEY_RSA_ENC;
2092 	} else if (alg_a & SSL_aGOST01) {
2093 		i = SSL_PKEY_GOST01;
2094 	} else { /* if (alg_a & SSL_aNULL) */
2095 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2096 		return (NULL);
2097 	}
2098 
2099 	return (c->pkeys + i);
2100 }
2101 
2102 EVP_PKEY *
2103 ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher, const EVP_MD **pmd,
2104     const struct ssl_sigalg **sap)
2105 {
2106 	const struct ssl_sigalg *sigalg = NULL;
2107 	EVP_PKEY *pkey = NULL;
2108 	unsigned long	 alg_a;
2109 	CERT		*c;
2110 	int		 idx = -1;
2111 
2112 	alg_a = cipher->algorithm_auth;
2113 	c = s->cert;
2114 
2115 	if (alg_a & SSL_aRSA) {
2116 		if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2117 			idx = SSL_PKEY_RSA_SIGN;
2118 		else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2119 			idx = SSL_PKEY_RSA_ENC;
2120 	} else if ((alg_a & SSL_aECDSA) &&
2121 	    (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2122 		idx = SSL_PKEY_ECC;
2123 	if (idx == -1) {
2124 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2125 		return (NULL);
2126 	}
2127 
2128 	pkey = c->pkeys[idx].privatekey;
2129 	if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2130 		SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2131 		return (NULL);
2132 	}
2133 	*pmd = sigalg->md();
2134 	*sap = sigalg;
2135 
2136 	return (pkey);
2137 }
2138 
2139 DH *
2140 ssl_get_auto_dh(SSL *s)
2141 {
2142 	CERT_PKEY *cpk;
2143 	int keylen;
2144 	DH *dhp;
2145 
2146 	if (s->cert->dh_tmp_auto == 2) {
2147 		keylen = 1024;
2148 	} else if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
2149 		keylen = 1024;
2150 		if (S3I(s)->hs.new_cipher->strength_bits == 256)
2151 			keylen = 3072;
2152 	} else {
2153 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL)
2154 			return (NULL);
2155 		if (cpk->privatekey == NULL || cpk->privatekey->pkey.dh == NULL)
2156 			return (NULL);
2157 		keylen = EVP_PKEY_bits(cpk->privatekey);
2158 	}
2159 
2160 	if ((dhp = DH_new()) == NULL)
2161 		return (NULL);
2162 
2163 	dhp->g = BN_new();
2164 	if (dhp->g != NULL)
2165 		BN_set_word(dhp->g, 2);
2166 
2167 	if (keylen >= 8192)
2168 		dhp->p = get_rfc3526_prime_8192(NULL);
2169 	else if (keylen >= 4096)
2170 		dhp->p = get_rfc3526_prime_4096(NULL);
2171 	else if (keylen >= 3072)
2172 		dhp->p = get_rfc3526_prime_3072(NULL);
2173 	else if (keylen >= 2048)
2174 		dhp->p = get_rfc3526_prime_2048(NULL);
2175 	else if (keylen >= 1536)
2176 		dhp->p = get_rfc3526_prime_1536(NULL);
2177 	else
2178 		dhp->p = get_rfc2409_prime_1024(NULL);
2179 
2180 	if (dhp->p == NULL || dhp->g == NULL) {
2181 		DH_free(dhp);
2182 		return (NULL);
2183 	}
2184 	return (dhp);
2185 }
2186 
2187 void
2188 ssl_update_cache(SSL *s, int mode)
2189 {
2190 	int	i;
2191 
2192 	/*
2193 	 * If the session_id_length is 0, we are not supposed to cache it,
2194 	 * and it would be rather hard to do anyway :-)
2195 	 */
2196 	if (s->session->session_id_length == 0)
2197 		return;
2198 
2199 	i = s->session_ctx->internal->session_cache_mode;
2200 	if ((i & mode) && (!s->internal->hit) && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2201 	    || SSL_CTX_add_session(s->session_ctx, s->session))
2202 	    && (s->session_ctx->internal->new_session_cb != NULL)) {
2203 		CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2204 		if (!s->session_ctx->internal->new_session_cb(s, s->session))
2205 			SSL_SESSION_free(s->session);
2206 	}
2207 
2208 	/* auto flush every 255 connections */
2209 	if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
2210 	    ((i & mode) == mode)) {
2211 		if ((((mode & SSL_SESS_CACHE_CLIENT) ?
2212 		    s->session_ctx->internal->stats.sess_connect_good :
2213 		    s->session_ctx->internal->stats.sess_accept_good) & 0xff) == 0xff) {
2214 			SSL_CTX_flush_sessions(s->session_ctx, time(NULL));
2215 		}
2216 	}
2217 }
2218 
2219 const SSL_METHOD *
2220 SSL_get_ssl_method(SSL *s)
2221 {
2222 	return (s->method);
2223 }
2224 
2225 int
2226 SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2227 {
2228 	int	conn = -1;
2229 	int	ret = 1;
2230 
2231 	if (s->method != meth) {
2232 		if (s->internal->handshake_func != NULL)
2233 			conn = (s->internal->handshake_func == s->method->internal->ssl_connect);
2234 
2235 		if (s->method->internal->version == meth->internal->version)
2236 			s->method = meth;
2237 		else {
2238 			s->method->internal->ssl_free(s);
2239 			s->method = meth;
2240 			ret = s->method->internal->ssl_new(s);
2241 		}
2242 
2243 		if (conn == 1)
2244 			s->internal->handshake_func = meth->internal->ssl_connect;
2245 		else if (conn == 0)
2246 			s->internal->handshake_func = meth->internal->ssl_accept;
2247 	}
2248 	return (ret);
2249 }
2250 
2251 int
2252 SSL_get_error(const SSL *s, int i)
2253 {
2254 	int		 reason;
2255 	unsigned long	 l;
2256 	BIO		*bio;
2257 
2258 	if (i > 0)
2259 		return (SSL_ERROR_NONE);
2260 
2261 	/* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2262 	 * etc, where we do encode the error */
2263 	if ((l = ERR_peek_error()) != 0) {
2264 		if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2265 			return (SSL_ERROR_SYSCALL);
2266 		else
2267 			return (SSL_ERROR_SSL);
2268 	}
2269 
2270 	if ((i < 0) && SSL_want_read(s)) {
2271 		bio = SSL_get_rbio(s);
2272 		if (BIO_should_read(bio)) {
2273 			return (SSL_ERROR_WANT_READ);
2274 		} else if (BIO_should_write(bio)) {
2275 			/*
2276 			 * This one doesn't make too much sense...  We never
2277 			 * try to write to the rbio, and an application
2278 			 * program where rbio and wbio are separate couldn't
2279 			 * even know what it should wait for.  However if we
2280 			 * ever set s->internal->rwstate incorrectly (so that we have
2281 			 * SSL_want_read(s) instead of SSL_want_write(s))
2282 			 * and rbio and wbio *are* the same, this test works
2283 			 * around that bug; so it might be safer to keep it.
2284 			 */
2285 			return (SSL_ERROR_WANT_WRITE);
2286 		} else if (BIO_should_io_special(bio)) {
2287 			reason = BIO_get_retry_reason(bio);
2288 			if (reason == BIO_RR_CONNECT)
2289 				return (SSL_ERROR_WANT_CONNECT);
2290 			else if (reason == BIO_RR_ACCEPT)
2291 				return (SSL_ERROR_WANT_ACCEPT);
2292 			else
2293 				return (SSL_ERROR_SYSCALL); /* unknown */
2294 		}
2295 	}
2296 
2297 	if ((i < 0) && SSL_want_write(s)) {
2298 		bio = SSL_get_wbio(s);
2299 		if (BIO_should_write(bio)) {
2300 			return (SSL_ERROR_WANT_WRITE);
2301 		} else if (BIO_should_read(bio)) {
2302 			/*
2303 			 * See above (SSL_want_read(s) with
2304 			 * BIO_should_write(bio))
2305 			 */
2306 			return (SSL_ERROR_WANT_READ);
2307 		} else if (BIO_should_io_special(bio)) {
2308 			reason = BIO_get_retry_reason(bio);
2309 			if (reason == BIO_RR_CONNECT)
2310 				return (SSL_ERROR_WANT_CONNECT);
2311 			else if (reason == BIO_RR_ACCEPT)
2312 				return (SSL_ERROR_WANT_ACCEPT);
2313 			else
2314 				return (SSL_ERROR_SYSCALL);
2315 		}
2316 	}
2317 	if ((i < 0) && SSL_want_x509_lookup(s)) {
2318 		return (SSL_ERROR_WANT_X509_LOOKUP);
2319 	}
2320 
2321 	if (i == 0) {
2322 		if ((s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2323 		    (S3I(s)->warn_alert == SSL_AD_CLOSE_NOTIFY))
2324 		return (SSL_ERROR_ZERO_RETURN);
2325 	}
2326 	return (SSL_ERROR_SYSCALL);
2327 }
2328 
2329 int
2330 SSL_do_handshake(SSL *s)
2331 {
2332 	int	ret = 1;
2333 
2334 	if (s->internal->handshake_func == NULL) {
2335 		SSLerror(s, SSL_R_CONNECTION_TYPE_NOT_SET);
2336 		return (-1);
2337 	}
2338 
2339 	s->method->internal->ssl_renegotiate_check(s);
2340 
2341 	if (SSL_in_init(s) || SSL_in_before(s)) {
2342 		ret = s->internal->handshake_func(s);
2343 	}
2344 	return (ret);
2345 }
2346 
2347 /*
2348  * For the next 2 functions, SSL_clear() sets shutdown and so
2349  * one of these calls will reset it
2350  */
2351 void
2352 SSL_set_accept_state(SSL *s)
2353 {
2354 	s->server = 1;
2355 	s->internal->shutdown = 0;
2356 	S3I(s)->hs.state = SSL_ST_ACCEPT|SSL_ST_BEFORE;
2357 	s->internal->handshake_func = s->method->internal->ssl_accept;
2358 	ssl_clear_cipher_state(s);
2359 }
2360 
2361 void
2362 SSL_set_connect_state(SSL *s)
2363 {
2364 	s->server = 0;
2365 	s->internal->shutdown = 0;
2366 	S3I(s)->hs.state = SSL_ST_CONNECT|SSL_ST_BEFORE;
2367 	s->internal->handshake_func = s->method->internal->ssl_connect;
2368 	ssl_clear_cipher_state(s);
2369 }
2370 
2371 int
2372 ssl_undefined_function(SSL *s)
2373 {
2374 	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2375 	return (0);
2376 }
2377 
2378 int
2379 ssl_undefined_void_function(void)
2380 {
2381 	SSLerrorx(ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2382 	return (0);
2383 }
2384 
2385 int
2386 ssl_undefined_const_function(const SSL *s)
2387 {
2388 	SSLerror(s, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2389 	return (0);
2390 }
2391 
2392 const char *
2393 ssl_version_string(int ver)
2394 {
2395 	switch (ver) {
2396 	case DTLS1_VERSION:
2397 		return (SSL_TXT_DTLS1);
2398 	case TLS1_VERSION:
2399 		return (SSL_TXT_TLSV1);
2400 	case TLS1_1_VERSION:
2401 		return (SSL_TXT_TLSV1_1);
2402 	case TLS1_2_VERSION:
2403 		return (SSL_TXT_TLSV1_2);
2404 	case TLS1_3_VERSION:
2405 		return (SSL_TXT_TLSV1_3);
2406 	default:
2407 		return ("unknown");
2408 	}
2409 }
2410 
2411 const char *
2412 SSL_get_version(const SSL *s)
2413 {
2414 	return ssl_version_string(s->version);
2415 }
2416 
2417 SSL *
2418 SSL_dup(SSL *s)
2419 {
2420 	STACK_OF(X509_NAME) *sk;
2421 	X509_NAME *xn;
2422 	SSL *ret;
2423 	int i;
2424 
2425 	if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2426 		goto err;
2427 
2428 	ret->version = s->version;
2429 	ret->internal->type = s->internal->type;
2430 	ret->method = s->method;
2431 
2432 	if (s->session != NULL) {
2433 		if (!SSL_copy_session_id(ret, s))
2434 			goto err;
2435 	} else {
2436 		/*
2437 		 * No session has been established yet, so we have to expect
2438 		 * that s->cert or ret->cert will be changed later --
2439 		 * they should not both point to the same object,
2440 		 * and thus we can't use SSL_copy_session_id.
2441 		 */
2442 
2443 		ret->method->internal->ssl_free(ret);
2444 		ret->method = s->method;
2445 		ret->method->internal->ssl_new(ret);
2446 
2447 		ssl_cert_free(ret->cert);
2448 		if ((ret->cert = ssl_cert_dup(s->cert)) == NULL)
2449 			goto err;
2450 
2451 		if (!SSL_set_session_id_context(ret, s->sid_ctx,
2452 		    s->sid_ctx_length))
2453 			goto err;
2454 	}
2455 
2456 	ret->internal->options = s->internal->options;
2457 	ret->internal->mode = s->internal->mode;
2458 	SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2459 	SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2460 	ret->internal->msg_callback = s->internal->msg_callback;
2461 	ret->internal->msg_callback_arg = s->internal->msg_callback_arg;
2462 	SSL_set_verify(ret, SSL_get_verify_mode(s),
2463 	SSL_get_verify_callback(s));
2464 	SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2465 	ret->internal->generate_session_id = s->internal->generate_session_id;
2466 
2467 	SSL_set_info_callback(ret, SSL_get_info_callback(s));
2468 
2469 	ret->internal->debug = s->internal->debug;
2470 
2471 	/* copy app data, a little dangerous perhaps */
2472 	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL,
2473 	    &ret->internal->ex_data, &s->internal->ex_data))
2474 		goto err;
2475 
2476 	/* setup rbio, and wbio */
2477 	if (s->rbio != NULL) {
2478 		if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
2479 			goto err;
2480 	}
2481 	if (s->wbio != NULL) {
2482 		if (s->wbio != s->rbio) {
2483 			if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
2484 				goto err;
2485 		} else
2486 			ret->wbio = ret->rbio;
2487 	}
2488 	ret->internal->rwstate = s->internal->rwstate;
2489 	ret->internal->in_handshake = s->internal->in_handshake;
2490 	ret->internal->handshake_func = s->internal->handshake_func;
2491 	ret->server = s->server;
2492 	ret->internal->renegotiate = s->internal->renegotiate;
2493 	ret->internal->new_session = s->internal->new_session;
2494 	ret->internal->quiet_shutdown = s->internal->quiet_shutdown;
2495 	ret->internal->shutdown = s->internal->shutdown;
2496 	/* SSL_dup does not really work at any state, though */
2497 	S3I(ret)->hs.state = S3I(s)->hs.state;
2498 	ret->internal->rstate = s->internal->rstate;
2499 
2500 	/*
2501 	 * Would have to copy ret->init_buf, ret->init_msg, ret->init_num,
2502 	 * ret->init_off
2503 	 */
2504 	ret->internal->init_num = 0;
2505 
2506 	ret->internal->hit = s->internal->hit;
2507 
2508 	X509_VERIFY_PARAM_inherit(ret->param, s->param);
2509 
2510 	/* dup the cipher_list and cipher_list_by_id stacks */
2511 	if (s->cipher_list != NULL) {
2512 		if ((ret->cipher_list =
2513 		    sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2514 			goto err;
2515 	}
2516 	if (s->internal->cipher_list_by_id != NULL) {
2517 		if ((ret->internal->cipher_list_by_id =
2518 		    sk_SSL_CIPHER_dup(s->internal->cipher_list_by_id)) == NULL)
2519 			goto err;
2520 	}
2521 
2522 	/* Dup the client_CA list */
2523 	if (s->internal->client_CA != NULL) {
2524 		if ((sk = sk_X509_NAME_dup(s->internal->client_CA)) == NULL) goto err;
2525 			ret->internal->client_CA = sk;
2526 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2527 			xn = sk_X509_NAME_value(sk, i);
2528 			if (sk_X509_NAME_set(sk, i,
2529 			    X509_NAME_dup(xn)) == NULL) {
2530 				X509_NAME_free(xn);
2531 				goto err;
2532 			}
2533 		}
2534 	}
2535 
2536 	return ret;
2537  err:
2538 	SSL_free(ret);
2539 	return NULL;
2540 }
2541 
2542 void
2543 ssl_clear_cipher_state(SSL *s)
2544 {
2545 	ssl_clear_cipher_read_state(s);
2546 	ssl_clear_cipher_write_state(s);
2547 }
2548 
2549 void
2550 ssl_clear_cipher_read_state(SSL *s)
2551 {
2552 	EVP_CIPHER_CTX_free(s->enc_read_ctx);
2553 	s->enc_read_ctx = NULL;
2554 	EVP_MD_CTX_free(s->read_hash);
2555 	s->read_hash = NULL;
2556 
2557 	if (s->internal->aead_read_ctx != NULL) {
2558 		EVP_AEAD_CTX_cleanup(&s->internal->aead_read_ctx->ctx);
2559 		free(s->internal->aead_read_ctx);
2560 		s->internal->aead_read_ctx = NULL;
2561 	}
2562 }
2563 
2564 void
2565 ssl_clear_cipher_write_state(SSL *s)
2566 {
2567 	EVP_CIPHER_CTX_free(s->internal->enc_write_ctx);
2568 	s->internal->enc_write_ctx = NULL;
2569 	EVP_MD_CTX_free(s->internal->write_hash);
2570 	s->internal->write_hash = NULL;
2571 
2572 	if (s->internal->aead_write_ctx != NULL) {
2573 		EVP_AEAD_CTX_cleanup(&s->internal->aead_write_ctx->ctx);
2574 		free(s->internal->aead_write_ctx);
2575 		s->internal->aead_write_ctx = NULL;
2576 	}
2577 }
2578 
2579 /* Fix this function so that it takes an optional type parameter */
2580 X509 *
2581 SSL_get_certificate(const SSL *s)
2582 {
2583 	return (s->cert->key->x509);
2584 }
2585 
2586 /* Fix this function so that it takes an optional type parameter */
2587 EVP_PKEY *
2588 SSL_get_privatekey(const SSL *s)
2589 {
2590 	return (s->cert->key->privatekey);
2591 }
2592 
2593 const SSL_CIPHER *
2594 SSL_get_current_cipher(const SSL *s)
2595 {
2596 	if ((s->session != NULL) && (s->session->cipher != NULL))
2597 		return (s->session->cipher);
2598 	return (NULL);
2599 }
2600 const void *
2601 SSL_get_current_compression(SSL *s)
2602 {
2603 	return (NULL);
2604 }
2605 
2606 const void *
2607 SSL_get_current_expansion(SSL *s)
2608 {
2609 	return (NULL);
2610 }
2611 
2612 size_t
2613 SSL_get_client_random(const SSL *s, unsigned char *out, size_t max_out)
2614 {
2615 	size_t len = sizeof(s->s3->client_random);
2616 
2617 	if (out == NULL)
2618 		return len;
2619 
2620 	if (len > max_out)
2621 		len = max_out;
2622 
2623 	memcpy(out, s->s3->client_random, len);
2624 
2625 	return len;
2626 }
2627 
2628 size_t
2629 SSL_get_server_random(const SSL *s, unsigned char *out, size_t max_out)
2630 {
2631 	size_t len = sizeof(s->s3->server_random);
2632 
2633 	if (out == NULL)
2634 		return len;
2635 
2636 	if (len > max_out)
2637 		len = max_out;
2638 
2639 	memcpy(out, s->s3->server_random, len);
2640 
2641 	return len;
2642 }
2643 
2644 int
2645 ssl_init_wbio_buffer(SSL *s, int push)
2646 {
2647 	BIO	*bbio;
2648 
2649 	if (s->bbio == NULL) {
2650 		bbio = BIO_new(BIO_f_buffer());
2651 		if (bbio == NULL)
2652 			return (0);
2653 		s->bbio = bbio;
2654 	} else {
2655 		bbio = s->bbio;
2656 		if (s->bbio == s->wbio)
2657 			s->wbio = BIO_pop(s->wbio);
2658 	}
2659 	(void)BIO_reset(bbio);
2660 /*	if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2661 	if (!BIO_set_read_buffer_size(bbio, 1)) {
2662 		SSLerror(s, ERR_R_BUF_LIB);
2663 		return (0);
2664 	}
2665 	if (push) {
2666 		if (s->wbio != bbio)
2667 			s->wbio = BIO_push(bbio, s->wbio);
2668 	} else {
2669 		if (s->wbio == bbio)
2670 			s->wbio = BIO_pop(bbio);
2671 	}
2672 	return (1);
2673 }
2674 
2675 void
2676 ssl_free_wbio_buffer(SSL *s)
2677 {
2678 	if (s == NULL)
2679 		return;
2680 
2681 	if (s->bbio == NULL)
2682 		return;
2683 
2684 	if (s->bbio == s->wbio) {
2685 		/* remove buffering */
2686 		s->wbio = BIO_pop(s->wbio);
2687 	}
2688 	BIO_free(s->bbio);
2689 	s->bbio = NULL;
2690 }
2691 
2692 void
2693 SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2694 {
2695 	ctx->internal->quiet_shutdown = mode;
2696 }
2697 
2698 int
2699 SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2700 {
2701 	return (ctx->internal->quiet_shutdown);
2702 }
2703 
2704 void
2705 SSL_set_quiet_shutdown(SSL *s, int mode)
2706 {
2707 	s->internal->quiet_shutdown = mode;
2708 }
2709 
2710 int
2711 SSL_get_quiet_shutdown(const SSL *s)
2712 {
2713 	return (s->internal->quiet_shutdown);
2714 }
2715 
2716 void
2717 SSL_set_shutdown(SSL *s, int mode)
2718 {
2719 	s->internal->shutdown = mode;
2720 }
2721 
2722 int
2723 SSL_get_shutdown(const SSL *s)
2724 {
2725 	return (s->internal->shutdown);
2726 }
2727 
2728 int
2729 SSL_version(const SSL *s)
2730 {
2731 	return (s->version);
2732 }
2733 
2734 SSL_CTX *
2735 SSL_get_SSL_CTX(const SSL *ssl)
2736 {
2737 	return (ssl->ctx);
2738 }
2739 
2740 SSL_CTX *
2741 SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2742 {
2743 	if (ssl->ctx == ctx)
2744 		return (ssl->ctx);
2745 	if (ctx == NULL)
2746 		ctx = ssl->initial_ctx;
2747 
2748 	ssl_cert_free(ssl->cert);
2749 	ssl->cert = ssl_cert_dup(ctx->internal->cert);
2750 
2751 	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2752 	SSL_CTX_free(ssl->ctx); /* decrement reference count */
2753 	ssl->ctx = ctx;
2754 	return (ssl->ctx);
2755 }
2756 
2757 int
2758 SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2759 {
2760 	return (X509_STORE_set_default_paths(ctx->cert_store));
2761 }
2762 
2763 int
2764 SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2765     const char *CApath)
2766 {
2767 	return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
2768 }
2769 
2770 int
2771 SSL_CTX_load_verify_mem(SSL_CTX *ctx, void *buf, int len)
2772 {
2773 	return (X509_STORE_load_mem(ctx->cert_store, buf, len));
2774 }
2775 
2776 void
2777 SSL_set_info_callback(SSL *ssl, void (*cb)(const SSL *ssl, int type, int val))
2778 {
2779 	ssl->internal->info_callback = cb;
2780 }
2781 
2782 void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type, int val)
2783 {
2784 	return (ssl->internal->info_callback);
2785 }
2786 
2787 int
2788 SSL_state(const SSL *ssl)
2789 {
2790 	return (S3I(ssl)->hs.state);
2791 }
2792 
2793 void
2794 SSL_set_state(SSL *ssl, int state)
2795 {
2796 	S3I(ssl)->hs.state = state;
2797 }
2798 
2799 void
2800 SSL_set_verify_result(SSL *ssl, long arg)
2801 {
2802 	ssl->verify_result = arg;
2803 }
2804 
2805 long
2806 SSL_get_verify_result(const SSL *ssl)
2807 {
2808 	return (ssl->verify_result);
2809 }
2810 
2811 int
2812 SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2813     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2814 {
2815 	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
2816 	    new_func, dup_func, free_func));
2817 }
2818 
2819 int
2820 SSL_set_ex_data(SSL *s, int idx, void *arg)
2821 {
2822 	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
2823 }
2824 
2825 void *
2826 SSL_get_ex_data(const SSL *s, int idx)
2827 {
2828 	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
2829 }
2830 
2831 int
2832 SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2833     CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2834 {
2835 	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
2836 	    new_func, dup_func, free_func));
2837 }
2838 
2839 int
2840 SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
2841 {
2842 	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
2843 }
2844 
2845 void *
2846 SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
2847 {
2848 	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
2849 }
2850 
2851 int
2852 ssl_ok(SSL *s)
2853 {
2854 	return (1);
2855 }
2856 
2857 X509_STORE *
2858 SSL_CTX_get_cert_store(const SSL_CTX *ctx)
2859 {
2860 	return (ctx->cert_store);
2861 }
2862 
2863 void
2864 SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
2865 {
2866 	X509_STORE_free(ctx->cert_store);
2867 	ctx->cert_store = store;
2868 }
2869 
2870 X509 *
2871 SSL_CTX_get0_certificate(const SSL_CTX *ctx)
2872 {
2873 	if (ctx->internal->cert == NULL)
2874 		return NULL;
2875 
2876 	return ctx->internal->cert->key->x509;
2877 }
2878 
2879 int
2880 SSL_want(const SSL *s)
2881 {
2882 	return (s->internal->rwstate);
2883 }
2884 
2885 void
2886 SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export,
2887     int keylength))
2888 {
2889 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2890 }
2891 
2892 void
2893 SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
2894     int keylength))
2895 {
2896 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
2897 }
2898 
2899 void
2900 SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*dh)(SSL *ssl, int is_export,
2901     int keylength))
2902 {
2903 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2904 }
2905 
2906 void
2907 SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh)(SSL *ssl, int is_export,
2908     int keylength))
2909 {
2910 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
2911 }
2912 
2913 void
2914 SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, EC_KEY *(*ecdh)(SSL *ssl,
2915     int is_export, int keylength))
2916 {
2917 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
2918 	    (void (*)(void))ecdh);
2919 }
2920 
2921 void
2922 SSL_set_tmp_ecdh_callback(SSL *ssl, EC_KEY *(*ecdh)(SSL *ssl, int is_export,
2923     int keylength))
2924 {
2925 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
2926 }
2927 
2928 
2929 void
2930 SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version,
2931     int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
2932 {
2933 	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK,
2934 	    (void (*)(void))cb);
2935 }
2936 
2937 void
2938 SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version,
2939     int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
2940 {
2941 	SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
2942 }
2943 
2944 void
2945 SSL_set_debug(SSL *s, int debug)
2946 {
2947 	s->internal->debug = debug;
2948 }
2949 
2950 int
2951 SSL_cache_hit(SSL *s)
2952 {
2953 	return (s->internal->hit);
2954 }
2955 
2956 int
2957 SSL_CTX_get_min_proto_version(SSL_CTX *ctx)
2958 {
2959 	return ctx->internal->min_version;
2960 }
2961 
2962 int
2963 SSL_CTX_set_min_proto_version(SSL_CTX *ctx, uint16_t version)
2964 {
2965 	return ssl_version_set_min(ctx->method, version,
2966 	    ctx->internal->max_version, &ctx->internal->min_version);
2967 }
2968 
2969 int
2970 SSL_CTX_get_max_proto_version(SSL_CTX *ctx)
2971 {
2972 	return ctx->internal->max_version;
2973 }
2974 
2975 int
2976 SSL_CTX_set_max_proto_version(SSL_CTX *ctx, uint16_t version)
2977 {
2978 	return ssl_version_set_max(ctx->method, version,
2979 	    ctx->internal->min_version, &ctx->internal->max_version);
2980 }
2981 
2982 int
2983 SSL_get_min_proto_version(SSL *ssl)
2984 {
2985 	return ssl->internal->min_version;
2986 }
2987 
2988 int
2989 SSL_set_min_proto_version(SSL *ssl, uint16_t version)
2990 {
2991 	return ssl_version_set_min(ssl->method, version,
2992 	    ssl->internal->max_version, &ssl->internal->min_version);
2993 }
2994 int
2995 SSL_get_max_proto_version(SSL *ssl)
2996 {
2997 	return ssl->internal->max_version;
2998 }
2999 
3000 int
3001 SSL_set_max_proto_version(SSL *ssl, uint16_t version)
3002 {
3003 	return ssl_version_set_max(ssl->method, version,
3004 	    ssl->internal->min_version, &ssl->internal->max_version);
3005 }
3006 
3007 static int
3008 ssl_cipher_id_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
3009 {
3010 	SSL_CIPHER const *a = a_;
3011 	SSL_CIPHER const *b = b_;
3012 	return ssl_cipher_id_cmp(a, b);
3013 }
3014 
3015 SSL_CIPHER *
3016 OBJ_bsearch_ssl_cipher_id(SSL_CIPHER *key, SSL_CIPHER const *base, int num)
3017 {
3018 	return (SSL_CIPHER *)OBJ_bsearch_(key, base, num, sizeof(SSL_CIPHER),
3019 	    ssl_cipher_id_cmp_BSEARCH_CMP_FN);
3020 }
3021