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