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