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