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