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