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