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