ssl_lib.c revision 1.147
1/* $OpenBSD: ssl_lib.c,v 1.147 2017/01/24 14:57:31 jsing Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 * ECC cipher suite support in OpenSSL originally developed by
114 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115 */
116/* ====================================================================
117 * Copyright 2005 Nokia. All rights reserved.
118 *
119 * The portions of the attached software ("Contribution") is developed by
120 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
121 * license.
122 *
123 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
124 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
125 * support (see RFC 4279) to OpenSSL.
126 *
127 * No patent licenses or other rights except those expressly stated in
128 * the OpenSSL open source license shall be deemed granted or received
129 * expressly, by implication, estoppel, or otherwise.
130 *
131 * No assurances are provided by Nokia that the Contribution does not
132 * infringe the patent or other intellectual property rights of any third
133 * party or that the license provides you with all the necessary rights
134 * to make use of the Contribution.
135 *
136 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
137 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
138 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
139 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
140 * OTHERWISE.
141 */
142
143#include <stdio.h>
144
145#include "ssl_locl.h"
146
147#include <openssl/bn.h>
148#include <openssl/dh.h>
149#include <openssl/lhash.h>
150#include <openssl/objects.h>
151#include <openssl/ocsp.h>
152#include <openssl/x509v3.h>
153
154#ifndef OPENSSL_NO_ENGINE
155#include <openssl/engine.h>
156#endif
157
158#include "bytestring.h"
159
160const char *SSL_version_str = OPENSSL_VERSION_TEXT;
161
162SSL3_ENC_METHOD ssl3_undef_enc_method = {
163	/*
164	 * Evil casts, but these functions are only called if there's a
165	 * library bug.
166	 */
167	.enc = (int (*)(SSL *, int))ssl_undefined_function,
168	.mac = (int (*)(SSL *, unsigned char *, int))ssl_undefined_function,
169	.setup_key_block = ssl_undefined_function,
170	.generate_master_secret = (int (*)(SSL *, unsigned char *,
171	    unsigned char *, int))ssl_undefined_function,
172	.change_cipher_state = (int (*)(SSL*, int))ssl_undefined_function,
173	.final_finish_mac = (int (*)(SSL *,  const char*, int,
174	    unsigned char *))ssl_undefined_function,
175	.finish_mac_length = 0,
176	.cert_verify_mac = (int (*)(SSL *, int,
177	    unsigned char *))ssl_undefined_function,
178	.client_finished_label = NULL,
179	.client_finished_label_len = 0,
180	.server_finished_label = NULL,
181	.server_finished_label_len = 0,
182	.alert_value = (int (*)(int))ssl_undefined_function,
183	.export_keying_material = (int (*)(SSL *, unsigned char *, size_t,
184	    const char *, size_t, const unsigned char *, size_t,
185	    int use_context))ssl_undefined_function,
186	.enc_flags = 0,
187};
188
189int
190SSL_clear(SSL *s)
191{
192	if (s->method == NULL) {
193		SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
194		return (0);
195	}
196
197	if (ssl_clear_bad_session(s)) {
198		SSL_SESSION_free(s->session);
199		s->session = NULL;
200	}
201
202	s->error = 0;
203	s->internal->hit = 0;
204	s->internal->shutdown = 0;
205
206	if (s->internal->renegotiate) {
207		SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
208		return (0);
209	}
210
211	s->internal->type = 0;
212
213	s->internal->state = SSL_ST_BEFORE|((s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT);
214
215	s->version = s->method->internal->version;
216	s->client_version = s->version;
217	s->internal->rwstate = SSL_NOTHING;
218	s->internal->rstate = SSL_ST_READ_HEADER;
219
220	BUF_MEM_free(s->internal->init_buf);
221	s->internal->init_buf = NULL;
222
223	ssl_clear_cipher_ctx(s);
224	ssl_clear_hash_ctx(&s->read_hash);
225	ssl_clear_hash_ctx(&s->internal->write_hash);
226
227	s->internal->first_packet = 0;
228
229	/*
230	 * Check to see if we were changed into a different method, if
231	 * so, revert back if we are not doing session-id reuse.
232	 */
233	if (!s->internal->in_handshake && (s->session == NULL) &&
234	    (s->method != s->ctx->method)) {
235		s->method->internal->ssl_free(s);
236		s->method = s->ctx->method;
237		if (!s->method->internal->ssl_new(s))
238			return (0);
239	} else
240		s->method->internal->ssl_clear(s);
241
242	return (1);
243}
244
245/* Used to change an SSL_CTXs default SSL method type */
246int
247SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
248{
249	STACK_OF(SSL_CIPHER)	*sk;
250
251	ctx->method = meth;
252
253	sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
254	    &(ctx->internal->cipher_list_by_id), SSL_DEFAULT_CIPHER_LIST);
255	if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
256		SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
257		    SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
258		return (0);
259	}
260	return (1);
261}
262
263SSL *
264SSL_new(SSL_CTX *ctx)
265{
266	SSL	*s;
267
268	if (ctx == NULL) {
269		SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
270		return (NULL);
271	}
272	if (ctx->method == NULL) {
273		SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
274		return (NULL);
275	}
276
277	if ((s = calloc(1, sizeof(*s))) == NULL) {
278		SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
279		return (NULL);
280	}
281	if ((s->internal = calloc(1, sizeof(*s->internal))) == NULL) {
282		free(s);
283		SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
284		return (NULL);
285	}
286
287	s->internal->options = ctx->internal->options;
288	s->internal->mode = ctx->internal->mode;
289	s->internal->max_cert_list = ctx->internal->max_cert_list;
290
291	if (ctx->internal->cert != NULL) {
292		/*
293		 * Earlier library versions used to copy the pointer to
294		 * the CERT, not its contents; only when setting new
295		 * parameters for the per-SSL copy, ssl_cert_new would be
296		 * called (and the direct reference to the per-SSL_CTX
297		 * settings would be lost, but those still were indirectly
298		 * accessed for various purposes, and for that reason they
299		 * used to be known as s->ctx->default_cert).
300		 * Now we don't look at the SSL_CTX's CERT after having
301		 * duplicated it once.
302		*/
303		s->cert = ssl_cert_dup(ctx->internal->cert);
304		if (s->cert == NULL)
305			goto err;
306	} else
307		s->cert=NULL; /* Cannot really happen (see SSL_CTX_new) */
308
309	s->internal->read_ahead = ctx->internal->read_ahead;
310	s->internal->msg_callback = ctx->internal->msg_callback;
311	s->internal->msg_callback_arg = ctx->internal->msg_callback_arg;
312	s->verify_mode = ctx->verify_mode;
313	s->sid_ctx_length = ctx->sid_ctx_length;
314	OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
315	memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
316	s->internal->verify_callback = ctx->internal->default_verify_callback;
317	s->internal->generate_session_id = ctx->internal->generate_session_id;
318
319	s->param = X509_VERIFY_PARAM_new();
320	if (!s->param)
321		goto err;
322	X509_VERIFY_PARAM_inherit(s->param, ctx->param);
323	s->internal->quiet_shutdown = ctx->internal->quiet_shutdown;
324	s->max_send_fragment = ctx->internal->max_send_fragment;
325
326	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
327	s->ctx = ctx;
328	s->internal->tlsext_debug_cb = 0;
329	s->internal->tlsext_debug_arg = NULL;
330	s->internal->tlsext_ticket_expected = 0;
331	s->tlsext_status_type = -1;
332	s->internal->tlsext_status_expected = 0;
333	s->internal->tlsext_ocsp_ids = NULL;
334	s->internal->tlsext_ocsp_exts = NULL;
335	s->internal->tlsext_ocsp_resp = NULL;
336	s->internal->tlsext_ocsp_resplen = -1;
337	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
338	s->initial_ctx = ctx;
339
340	if (ctx->internal->tlsext_ecpointformatlist != NULL) {
341		s->internal->tlsext_ecpointformatlist =
342		    calloc(ctx->internal->tlsext_ecpointformatlist_length,
343			sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
344		if (s->internal->tlsext_ecpointformatlist == NULL)
345			goto err;
346		memcpy(s->internal->tlsext_ecpointformatlist,
347		    ctx->internal->tlsext_ecpointformatlist,
348		    ctx->internal->tlsext_ecpointformatlist_length *
349		    sizeof(ctx->internal->tlsext_ecpointformatlist[0]));
350		s->internal->tlsext_ecpointformatlist_length =
351		    ctx->internal->tlsext_ecpointformatlist_length;
352	}
353	if (ctx->internal->tlsext_supportedgroups != NULL) {
354		s->internal->tlsext_supportedgroups =
355		    calloc(ctx->internal->tlsext_supportedgroups_length,
356			sizeof(ctx->internal->tlsext_supportedgroups));
357		if (s->internal->tlsext_supportedgroups == NULL)
358			goto err;
359		memcpy(s->internal->tlsext_supportedgroups,
360		    ctx->internal->tlsext_supportedgroups,
361		    ctx->internal->tlsext_supportedgroups_length *
362		    sizeof(ctx->internal->tlsext_supportedgroups[0]));
363		s->internal->tlsext_supportedgroups_length =
364		    ctx->internal->tlsext_supportedgroups_length;
365	}
366
367	s->internal->next_proto_negotiated = NULL;
368
369	if (s->ctx->internal->alpn_client_proto_list != NULL) {
370		s->internal->alpn_client_proto_list =
371		    malloc(s->ctx->internal->alpn_client_proto_list_len);
372		if (s->internal->alpn_client_proto_list == NULL)
373			goto err;
374		memcpy(s->internal->alpn_client_proto_list,
375		    s->ctx->internal->alpn_client_proto_list,
376		    s->ctx->internal->alpn_client_proto_list_len);
377		s->internal->alpn_client_proto_list_len =
378		    s->ctx->internal->alpn_client_proto_list_len;
379	}
380
381	s->verify_result = X509_V_OK;
382
383	s->method = ctx->method;
384
385	if (!s->method->internal->ssl_new(s))
386		goto err;
387
388	s->references = 1;
389	s->server = (ctx->method->internal->ssl_accept == ssl_undefined_function) ? 0 : 1;
390
391	SSL_clear(s);
392
393	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
394
395	return (s);
396
397 err:
398	SSL_free(s);
399	SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
400	return (NULL);
401}
402
403int
404SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
405    unsigned int sid_ctx_len)
406{
407	if (sid_ctx_len > sizeof ctx->sid_ctx) {
408		SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
409		    SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
410		return (0);
411	}
412	ctx->sid_ctx_length = sid_ctx_len;
413	memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
414
415	return (1);
416}
417
418int
419SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
420    unsigned int sid_ctx_len)
421{
422	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
423		SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
424		    SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
425		return (0);
426	}
427	ssl->sid_ctx_length = sid_ctx_len;
428	memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
429
430	return (1);
431}
432
433int
434SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
435{
436	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
437	ctx->internal->generate_session_id = cb;
438	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
439	return (1);
440}
441
442int
443SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
444{
445	CRYPTO_w_lock(CRYPTO_LOCK_SSL);
446	ssl->internal->generate_session_id = cb;
447	CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
448	return (1);
449}
450
451int
452SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
453    unsigned int id_len)
454{
455	/*
456	 * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp
457	 * shows how we can "construct" a session to give us the desired
458	 * check - ie. to find if there's a session in the hash table
459	 * that would conflict with any new session built out of this
460	 * id/id_len and the ssl_version in use by this SSL.
461	 */
462	SSL_SESSION r, *p;
463
464	if (id_len > sizeof r.session_id)
465		return (0);
466
467	r.ssl_version = ssl->version;
468	r.session_id_length = id_len;
469	memcpy(r.session_id, id, id_len);
470
471	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
472	p = lh_SSL_SESSION_retrieve(ssl->ctx->internal->sessions, &r);
473	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
474	return (p != NULL);
475}
476
477int
478SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
479{
480	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
481}
482
483int
484SSL_set_purpose(SSL *s, int purpose)
485{
486	return (X509_VERIFY_PARAM_set_purpose(s->param, purpose));
487}
488
489int
490SSL_CTX_set_trust(SSL_CTX *s, int trust)
491{
492	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
493}
494
495int
496SSL_set_trust(SSL *s, int trust)
497{
498	return (X509_VERIFY_PARAM_set_trust(s->param, trust));
499}
500
501int
502SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
503{
504	return (X509_VERIFY_PARAM_set1(ctx->param, vpm));
505}
506
507int
508SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
509{
510	return (X509_VERIFY_PARAM_set1(ssl->param, vpm));
511}
512
513void
514SSL_free(SSL *s)
515{
516	int	i;
517
518	if (s == NULL)
519		return;
520
521	i = CRYPTO_add(&s->references, -1, CRYPTO_LOCK_SSL);
522	if (i > 0)
523		return;
524
525	if (s->param)
526		X509_VERIFY_PARAM_free(s->param);
527
528	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->internal->ex_data);
529
530	if (s->bbio != NULL) {
531		/* If the buffering BIO is in place, pop it off */
532		if (s->bbio == s->wbio) {
533			s->wbio = BIO_pop(s->wbio);
534		}
535		BIO_free(s->bbio);
536		s->bbio = NULL;
537	}
538
539	if (s->rbio != s->wbio)
540		BIO_free_all(s->rbio);
541	BIO_free_all(s->wbio);
542
543	if (s->internal->init_buf != NULL)
544		BUF_MEM_free(s->internal->init_buf);
545
546	/* add extra stuff */
547	sk_SSL_CIPHER_free(s->cipher_list);
548	sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
549
550	/* Make the next call work :-) */
551	if (s->session != NULL) {
552		ssl_clear_bad_session(s);
553		SSL_SESSION_free(s->session);
554	}
555
556	ssl_clear_cipher_ctx(s);
557	ssl_clear_hash_ctx(&s->read_hash);
558	ssl_clear_hash_ctx(&s->internal->write_hash);
559
560	ssl_cert_free(s->cert);
561
562	free(s->tlsext_hostname);
563	SSL_CTX_free(s->initial_ctx);
564
565	free(s->internal->tlsext_ecpointformatlist);
566	free(s->internal->tlsext_supportedgroups);
567
568	sk_X509_EXTENSION_pop_free(s->internal->tlsext_ocsp_exts,
569	    X509_EXTENSION_free);
570	sk_OCSP_RESPID_pop_free(s->internal->tlsext_ocsp_ids, OCSP_RESPID_free);
571	free(s->internal->tlsext_ocsp_resp);
572
573	sk_X509_NAME_pop_free(s->internal->client_CA, X509_NAME_free);
574
575	if (s->method != NULL)
576		s->method->internal->ssl_free(s);
577
578	SSL_CTX_free(s->ctx);
579
580	free(s->internal->next_proto_negotiated);
581	free(s->internal->alpn_client_proto_list);
582
583#ifndef OPENSSL_NO_SRTP
584	if (s->internal->srtp_profiles)
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
1849	ret->cert_store = NULL;
1850	ret->internal->session_cache_mode = SSL_SESS_CACHE_SERVER;
1851	ret->internal->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1852	ret->internal->session_cache_head = NULL;
1853	ret->internal->session_cache_tail = NULL;
1854
1855	/* We take the system default */
1856	ret->session_timeout = meth->internal->get_timeout();
1857
1858	ret->internal->new_session_cb = 0;
1859	ret->internal->remove_session_cb = 0;
1860	ret->internal->get_session_cb = 0;
1861	ret->internal->generate_session_id = 0;
1862
1863	memset((char *)&ret->internal->stats, 0, sizeof(ret->internal->stats));
1864
1865	ret->references = 1;
1866	ret->internal->quiet_shutdown = 0;
1867
1868	ret->internal->info_callback = NULL;
1869
1870	ret->internal->app_verify_callback = 0;
1871	ret->internal->app_verify_arg = NULL;
1872
1873	ret->internal->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1874	ret->internal->read_ahead = 0;
1875	ret->internal->msg_callback = 0;
1876	ret->internal->msg_callback_arg = NULL;
1877	ret->verify_mode = SSL_VERIFY_NONE;
1878	ret->sid_ctx_length = 0;
1879	ret->internal->default_verify_callback = NULL;
1880	if ((ret->internal->cert = ssl_cert_new()) == NULL)
1881		goto err;
1882
1883	ret->default_passwd_callback = 0;
1884	ret->default_passwd_callback_userdata = NULL;
1885	ret->internal->client_cert_cb = 0;
1886	ret->internal->app_gen_cookie_cb = 0;
1887	ret->internal->app_verify_cookie_cb = 0;
1888
1889	ret->internal->sessions = lh_SSL_SESSION_new();
1890	if (ret->internal->sessions == NULL)
1891		goto err;
1892	ret->cert_store = X509_STORE_new();
1893	if (ret->cert_store == NULL)
1894		goto err;
1895
1896	ssl_create_cipher_list(ret->method, &ret->cipher_list,
1897	    &ret->internal->cipher_list_by_id, SSL_DEFAULT_CIPHER_LIST);
1898	if (ret->cipher_list == NULL ||
1899	    sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
1900		SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
1901		goto err2;
1902	}
1903
1904	ret->param = X509_VERIFY_PARAM_new();
1905	if (!ret->param)
1906		goto err;
1907
1908	if ((ret->internal->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
1909		SSLerr(SSL_F_SSL_CTX_NEW,
1910		    SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
1911		goto err2;
1912	}
1913	if ((ret->internal->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
1914		SSLerr(SSL_F_SSL_CTX_NEW,
1915		    SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
1916		goto err2;
1917	}
1918
1919	if ((ret->internal->client_CA = sk_X509_NAME_new_null()) == NULL)
1920		goto err;
1921
1922	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->internal->ex_data);
1923
1924	ret->extra_certs = NULL;
1925
1926	ret->internal->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1927
1928	ret->internal->tlsext_servername_callback = 0;
1929	ret->internal->tlsext_servername_arg = NULL;
1930
1931	/* Setup RFC4507 ticket keys */
1932	arc4random_buf(ret->internal->tlsext_tick_key_name, 16);
1933	arc4random_buf(ret->internal->tlsext_tick_hmac_key, 16);
1934	arc4random_buf(ret->internal->tlsext_tick_aes_key, 16);
1935
1936	ret->internal->tlsext_status_cb = 0;
1937	ret->internal->tlsext_status_arg = NULL;
1938
1939	ret->internal->next_protos_advertised_cb = 0;
1940	ret->internal->next_proto_select_cb = 0;
1941
1942#ifndef OPENSSL_NO_ENGINE
1943	ret->internal->client_cert_engine = NULL;
1944#ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
1945#define eng_strx(x)	#x
1946#define eng_str(x)	eng_strx(x)
1947	/* Use specific client engine automatically... ignore errors */
1948	{
1949		ENGINE *eng;
1950		eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1951		if (!eng) {
1952			ERR_clear_error();
1953			ENGINE_load_builtin_engines();
1954			eng = ENGINE_by_id(eng_str(
1955			    OPENSSL_SSL_CLIENT_ENGINE_AUTO));
1956		}
1957		if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
1958			ERR_clear_error();
1959	}
1960#endif
1961#endif
1962	/*
1963	 * Default is to connect to non-RI servers. When RI is more widely
1964	 * deployed might change this.
1965	 */
1966	ret->internal->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1967
1968	return (ret);
1969err:
1970	SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
1971err2:
1972	SSL_CTX_free(ret);
1973	return (NULL);
1974}
1975
1976void
1977SSL_CTX_free(SSL_CTX *ctx)
1978{
1979	int	i;
1980
1981	if (ctx == NULL)
1982		return;
1983
1984	i = CRYPTO_add(&ctx->references, -1, CRYPTO_LOCK_SSL_CTX);
1985	if (i > 0)
1986		return;
1987
1988	if (ctx->param)
1989		X509_VERIFY_PARAM_free(ctx->param);
1990
1991	/*
1992	 * Free internal session cache. However: the remove_cb() may reference
1993	 * the ex_data of SSL_CTX, thus the ex_data store can only be removed
1994	 * after the sessions were flushed.
1995	 * As the ex_data handling routines might also touch the session cache,
1996	 * the most secure solution seems to be: empty (flush) the cache, then
1997	 * free ex_data, then finally free the cache.
1998	 * (See ticket [openssl.org #212].)
1999	 */
2000	if (ctx->internal->sessions != NULL)
2001		SSL_CTX_flush_sessions(ctx, 0);
2002
2003	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ctx, &ctx->internal->ex_data);
2004
2005	if (ctx->internal->sessions != NULL)
2006		lh_SSL_SESSION_free(ctx->internal->sessions);
2007
2008	if (ctx->cert_store != NULL)
2009		X509_STORE_free(ctx->cert_store);
2010	sk_SSL_CIPHER_free(ctx->cipher_list);
2011	sk_SSL_CIPHER_free(ctx->internal->cipher_list_by_id);
2012	ssl_cert_free(ctx->internal->cert);
2013	sk_X509_NAME_pop_free(ctx->internal->client_CA, X509_NAME_free);
2014	sk_X509_pop_free(ctx->extra_certs, X509_free);
2015
2016#ifndef OPENSSL_NO_SRTP
2017	if (ctx->internal->srtp_profiles)
2018		sk_SRTP_PROTECTION_PROFILE_free(ctx->internal->srtp_profiles);
2019#endif
2020
2021#ifndef OPENSSL_NO_ENGINE
2022	if (ctx->internal->client_cert_engine)
2023		ENGINE_finish(ctx->internal->client_cert_engine);
2024#endif
2025
2026	free(ctx->internal->tlsext_ecpointformatlist);
2027	free(ctx->internal->tlsext_supportedgroups);
2028
2029	free(ctx->internal->alpn_client_proto_list);
2030
2031	free(ctx->internal);
2032	free(ctx);
2033}
2034
2035void
2036SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2037{
2038	ctx->default_passwd_callback = cb;
2039}
2040
2041void
2042SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2043{
2044	ctx->default_passwd_callback_userdata = u;
2045}
2046
2047void
2048SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*cb)(X509_STORE_CTX *,
2049    void *), void *arg)
2050{
2051	ctx->internal->app_verify_callback = cb;
2052	ctx->internal->app_verify_arg = arg;
2053}
2054
2055void
2056SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*cb)(int, X509_STORE_CTX *))
2057{
2058	ctx->verify_mode = mode;
2059	ctx->internal->default_verify_callback = cb;
2060}
2061
2062void
2063SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2064{
2065	X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2066}
2067
2068void
2069ssl_set_cert_masks(CERT *c, const SSL_CIPHER *cipher)
2070{
2071	int		 rsa_enc, rsa_sign, dh_tmp, dsa_sign;
2072	int		 have_ecc_cert, have_ecdh_tmp;
2073	unsigned long	 mask_k, mask_a;
2074	X509		*x = NULL;
2075	CERT_PKEY	*cpk;
2076
2077	if (c == NULL)
2078		return;
2079
2080	dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL ||
2081	    c->dh_tmp_auto != 0);
2082
2083	have_ecdh_tmp = (c->ecdh_tmp != NULL || c->ecdh_tmp_cb != NULL ||
2084	    c->ecdh_tmp_auto != 0);
2085
2086	cpk = &(c->pkeys[SSL_PKEY_RSA_ENC]);
2087	rsa_enc = (cpk->x509 != NULL && cpk->privatekey != NULL);
2088	cpk = &(c->pkeys[SSL_PKEY_RSA_SIGN]);
2089	rsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
2090	cpk = &(c->pkeys[SSL_PKEY_DSA_SIGN]);
2091	dsa_sign = (cpk->x509 != NULL && cpk->privatekey != NULL);
2092/* FIX THIS EAY EAY EAY */
2093	cpk = &(c->pkeys[SSL_PKEY_ECC]);
2094	have_ecc_cert = (cpk->x509 != NULL && cpk->privatekey != NULL);
2095	mask_k = 0;
2096	mask_a = 0;
2097
2098	cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2099	if (cpk->x509 != NULL && cpk->privatekey !=NULL) {
2100		mask_k |= SSL_kGOST;
2101		mask_a |= SSL_aGOST01;
2102	}
2103
2104	if (rsa_enc)
2105		mask_k|=SSL_kRSA;
2106
2107	if (dh_tmp)
2108		mask_k|=SSL_kDHE;
2109
2110	if (rsa_enc || rsa_sign)
2111		mask_a|=SSL_aRSA;
2112
2113	if (dsa_sign)
2114		mask_a|=SSL_aDSS;
2115
2116	mask_a|=SSL_aNULL;
2117
2118	/*
2119	 * An ECC certificate may be usable for ECDH and/or
2120	 * ECDSA cipher suites depending on the key usage extension.
2121	 */
2122	if (have_ecc_cert) {
2123		x = (c->pkeys[SSL_PKEY_ECC]).x509;
2124
2125		/* This call populates extension flags (ex_flags). */
2126		X509_check_purpose(x, -1, 0);
2127
2128		/* Key usage, if present, must allow signing. */
2129		if ((x->ex_flags & EXFLAG_KUSAGE) == 0 ||
2130		    (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE))
2131			mask_a|=SSL_aECDSA;
2132	}
2133
2134	if (have_ecdh_tmp)
2135		mask_k|=SSL_kECDHE;
2136
2137	c->mask_k = mask_k;
2138	c->mask_a = mask_a;
2139	c->valid = 1;
2140}
2141
2142int
2143ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2144{
2145	const SSL_CIPHER	*cs = S3I(s)->tmp.new_cipher;
2146	unsigned long		 alg_a;
2147
2148	alg_a = cs->algorithm_auth;
2149
2150	if (alg_a & SSL_aECDSA) {
2151		/* This call populates extension flags (ex_flags). */
2152		X509_check_purpose(x, -1, 0);
2153
2154		/* Key usage, if present, must allow signing. */
2155		if ((x->ex_flags & EXFLAG_KUSAGE) &&
2156		    ((x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE) == 0)) {
2157			SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2158			    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2159			return (0);
2160		}
2161	}
2162
2163	return (1);
2164}
2165
2166CERT_PKEY *
2167ssl_get_server_send_pkey(const SSL *s)
2168{
2169	unsigned long	 alg_a;
2170	CERT		*c;
2171	int		 i;
2172
2173	c = s->cert;
2174	ssl_set_cert_masks(c, S3I(s)->tmp.new_cipher);
2175
2176	alg_a = S3I(s)->tmp.new_cipher->algorithm_auth;
2177
2178	if (alg_a & SSL_aECDSA) {
2179		i = SSL_PKEY_ECC;
2180	} else if (alg_a & SSL_aDSS) {
2181		i = SSL_PKEY_DSA_SIGN;
2182	} else if (alg_a & SSL_aRSA) {
2183		if (c->pkeys[SSL_PKEY_RSA_ENC].x509 == NULL)
2184			i = SSL_PKEY_RSA_SIGN;
2185		else
2186			i = SSL_PKEY_RSA_ENC;
2187	} else if (alg_a & SSL_aGOST01) {
2188		i = SSL_PKEY_GOST01;
2189	} else { /* if (alg_a & SSL_aNULL) */
2190		SSLerr(SSL_F_SSL_GET_SERVER_SEND_PKEY, ERR_R_INTERNAL_ERROR);
2191		return (NULL);
2192	}
2193
2194	return (c->pkeys + i);
2195}
2196
2197X509 *
2198ssl_get_server_send_cert(const SSL *s)
2199{
2200	CERT_PKEY	*cpk;
2201
2202	cpk = ssl_get_server_send_pkey(s);
2203	if (!cpk)
2204		return (NULL);
2205	return (cpk->x509);
2206}
2207
2208EVP_PKEY *
2209ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher, const EVP_MD **pmd)
2210{
2211	unsigned long	 alg_a;
2212	CERT		*c;
2213	int		 idx = -1;
2214
2215	alg_a = cipher->algorithm_auth;
2216	c = s->cert;
2217
2218	if ((alg_a & SSL_aDSS) &&
2219	    (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2220		idx = SSL_PKEY_DSA_SIGN;
2221	else if (alg_a & SSL_aRSA) {
2222		if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2223			idx = SSL_PKEY_RSA_SIGN;
2224		else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2225			idx = SSL_PKEY_RSA_ENC;
2226	} else if ((alg_a & SSL_aECDSA) &&
2227	    (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2228		idx = SSL_PKEY_ECC;
2229	if (idx == -1) {
2230		SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2231		return (NULL);
2232	}
2233	if (pmd)
2234		*pmd = c->pkeys[idx].digest;
2235	return (c->pkeys[idx].privatekey);
2236}
2237
2238DH *
2239ssl_get_auto_dh(SSL *s)
2240{
2241	CERT_PKEY *cpk;
2242	int keylen;
2243	DH *dhp;
2244
2245	if (s->cert->dh_tmp_auto == 2) {
2246		keylen = 1024;
2247	} else if (S3I(s)->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
2248		keylen = 1024;
2249		if (S3I(s)->tmp.new_cipher->strength_bits == 256)
2250			keylen = 3072;
2251	} else {
2252		if ((cpk = ssl_get_server_send_pkey(s)) == NULL)
2253			return (NULL);
2254		if (cpk->privatekey == NULL || cpk->privatekey->pkey.dh == NULL)
2255			return (NULL);
2256		keylen = EVP_PKEY_bits(cpk->privatekey);
2257	}
2258
2259	if ((dhp = DH_new()) == NULL)
2260		return (NULL);
2261
2262	dhp->g = BN_new();
2263	if (dhp->g != NULL)
2264		BN_set_word(dhp->g, 2);
2265
2266	if (keylen >= 8192)
2267		dhp->p = get_rfc3526_prime_8192(NULL);
2268	else if (keylen >= 4096)
2269		dhp->p = get_rfc3526_prime_4096(NULL);
2270	else if (keylen >= 3072)
2271		dhp->p = get_rfc3526_prime_3072(NULL);
2272	else if (keylen >= 2048)
2273		dhp->p = get_rfc3526_prime_2048(NULL);
2274	else if (keylen >= 1536)
2275		dhp->p = get_rfc3526_prime_1536(NULL);
2276	else
2277		dhp->p = get_rfc2409_prime_1024(NULL);
2278
2279	if (dhp->p == NULL || dhp->g == NULL) {
2280		DH_free(dhp);
2281		return (NULL);
2282	}
2283	return (dhp);
2284}
2285
2286void
2287ssl_update_cache(SSL *s, int mode)
2288{
2289	int	i;
2290
2291	/*
2292	 * If the session_id_length is 0, we are not supposed to cache it,
2293	 * and it would be rather hard to do anyway :-)
2294	 */
2295	if (s->session->session_id_length == 0)
2296		return;
2297
2298	i = s->session_ctx->internal->session_cache_mode;
2299	if ((i & mode) && (!s->internal->hit) && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2300	    || SSL_CTX_add_session(s->session_ctx, s->session))
2301	    && (s->session_ctx->internal->new_session_cb != NULL)) {
2302		CRYPTO_add(&s->session->references, 1, CRYPTO_LOCK_SSL_SESSION);
2303		if (!s->session_ctx->internal->new_session_cb(s, s->session))
2304			SSL_SESSION_free(s->session);
2305	}
2306
2307	/* auto flush every 255 connections */
2308	if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) &&
2309	    ((i & mode) == mode)) {
2310		if ((((mode & SSL_SESS_CACHE_CLIENT) ?
2311		    s->session_ctx->internal->stats.sess_connect_good :
2312		    s->session_ctx->internal->stats.sess_accept_good) & 0xff) == 0xff) {
2313			SSL_CTX_flush_sessions(s->session_ctx, time(NULL));
2314		}
2315	}
2316}
2317
2318const SSL_METHOD *
2319SSL_get_ssl_method(SSL *s)
2320{
2321	return (s->method);
2322}
2323
2324int
2325SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2326{
2327	int	conn = -1;
2328	int	ret = 1;
2329
2330	if (s->method != meth) {
2331		if (s->internal->handshake_func != NULL)
2332			conn = (s->internal->handshake_func == s->method->internal->ssl_connect);
2333
2334		if (s->method->internal->version == meth->internal->version)
2335			s->method = meth;
2336		else {
2337			s->method->internal->ssl_free(s);
2338			s->method = meth;
2339			ret = s->method->internal->ssl_new(s);
2340		}
2341
2342		if (conn == 1)
2343			s->internal->handshake_func = meth->internal->ssl_connect;
2344		else if (conn == 0)
2345			s->internal->handshake_func = meth->internal->ssl_accept;
2346	}
2347	return (ret);
2348}
2349
2350int
2351SSL_get_error(const SSL *s, int i)
2352{
2353	int		 reason;
2354	unsigned long	 l;
2355	BIO		*bio;
2356
2357	if (i > 0)
2358		return (SSL_ERROR_NONE);
2359
2360	/* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake
2361	 * etc, where we do encode the error */
2362	if ((l = ERR_peek_error()) != 0) {
2363		if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2364			return (SSL_ERROR_SYSCALL);
2365		else
2366			return (SSL_ERROR_SSL);
2367	}
2368
2369	if ((i < 0) && SSL_want_read(s)) {
2370		bio = SSL_get_rbio(s);
2371		if (BIO_should_read(bio)) {
2372			return (SSL_ERROR_WANT_READ);
2373		} else if (BIO_should_write(bio)) {
2374			/*
2375			 * This one doesn't make too much sense...  We never
2376			 * try to write to the rbio, and an application
2377			 * program where rbio and wbio are separate couldn't
2378			 * even know what it should wait for.  However if we
2379			 * ever set s->internal->rwstate incorrectly (so that we have
2380			 * SSL_want_read(s) instead of SSL_want_write(s))
2381			 * and rbio and wbio *are* the same, this test works
2382			 * around that bug; so it might be safer to keep it.
2383			 */
2384			return (SSL_ERROR_WANT_WRITE);
2385		} else if (BIO_should_io_special(bio)) {
2386			reason = BIO_get_retry_reason(bio);
2387			if (reason == BIO_RR_CONNECT)
2388				return (SSL_ERROR_WANT_CONNECT);
2389			else if (reason == BIO_RR_ACCEPT)
2390				return (SSL_ERROR_WANT_ACCEPT);
2391			else
2392				return (SSL_ERROR_SYSCALL); /* unknown */
2393		}
2394	}
2395
2396	if ((i < 0) && SSL_want_write(s)) {
2397		bio = SSL_get_wbio(s);
2398		if (BIO_should_write(bio)) {
2399			return (SSL_ERROR_WANT_WRITE);
2400		} else if (BIO_should_read(bio)) {
2401			/*
2402			 * See above (SSL_want_read(s) with
2403			 * BIO_should_write(bio))
2404			 */
2405			return (SSL_ERROR_WANT_READ);
2406		} else if (BIO_should_io_special(bio)) {
2407			reason = BIO_get_retry_reason(bio);
2408			if (reason == BIO_RR_CONNECT)
2409				return (SSL_ERROR_WANT_CONNECT);
2410			else if (reason == BIO_RR_ACCEPT)
2411				return (SSL_ERROR_WANT_ACCEPT);
2412			else
2413				return (SSL_ERROR_SYSCALL);
2414		}
2415	}
2416	if ((i < 0) && SSL_want_x509_lookup(s)) {
2417		return (SSL_ERROR_WANT_X509_LOOKUP);
2418	}
2419
2420	if (i == 0) {
2421		if ((s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2422		    (S3I(s)->warn_alert == SSL_AD_CLOSE_NOTIFY))
2423		return (SSL_ERROR_ZERO_RETURN);
2424	}
2425	return (SSL_ERROR_SYSCALL);
2426}
2427
2428int
2429SSL_do_handshake(SSL *s)
2430{
2431	int	ret = 1;
2432
2433	if (s->internal->handshake_func == NULL) {
2434		SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
2435		return (-1);
2436	}
2437
2438	s->method->internal->ssl_renegotiate_check(s);
2439
2440	if (SSL_in_init(s) || SSL_in_before(s)) {
2441		ret = s->internal->handshake_func(s);
2442	}
2443	return (ret);
2444}
2445
2446/*
2447 * For the next 2 functions, SSL_clear() sets shutdown and so
2448 * one of these calls will reset it
2449 */
2450void
2451SSL_set_accept_state(SSL *s)
2452{
2453	s->server = 1;
2454	s->internal->shutdown = 0;
2455	s->internal->state = SSL_ST_ACCEPT|SSL_ST_BEFORE;
2456	s->internal->handshake_func = s->method->internal->ssl_accept;
2457	/* clear the current cipher */
2458	ssl_clear_cipher_ctx(s);
2459	ssl_clear_hash_ctx(&s->read_hash);
2460	ssl_clear_hash_ctx(&s->internal->write_hash);
2461}
2462
2463void
2464SSL_set_connect_state(SSL *s)
2465{
2466	s->server = 0;
2467	s->internal->shutdown = 0;
2468	s->internal->state = SSL_ST_CONNECT|SSL_ST_BEFORE;
2469	s->internal->handshake_func = s->method->internal->ssl_connect;
2470	/* clear the current cipher */
2471	ssl_clear_cipher_ctx(s);
2472	ssl_clear_hash_ctx(&s->read_hash);
2473	ssl_clear_hash_ctx(&s->internal->write_hash);
2474}
2475
2476int
2477ssl_undefined_function(SSL *s)
2478{
2479	SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION,
2480	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2481	return (0);
2482}
2483
2484int
2485ssl_undefined_void_function(void)
2486{
2487	SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
2488	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2489	return (0);
2490}
2491
2492int
2493ssl_undefined_const_function(const SSL *s)
2494{
2495	SSLerr(SSL_F_SSL_UNDEFINED_CONST_FUNCTION,
2496	    ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
2497	return (0);
2498}
2499
2500const char *
2501ssl_version_string(int ver)
2502{
2503	switch (ver) {
2504	case DTLS1_VERSION:
2505		return (SSL_TXT_DTLS1);
2506	case TLS1_VERSION:
2507		return (SSL_TXT_TLSV1);
2508	case TLS1_1_VERSION:
2509		return (SSL_TXT_TLSV1_1);
2510	case TLS1_2_VERSION:
2511		return (SSL_TXT_TLSV1_2);
2512	default:
2513		return ("unknown");
2514	}
2515}
2516
2517const char *
2518SSL_get_version(const SSL *s)
2519{
2520	return ssl_version_string(s->version);
2521}
2522
2523int
2524ssl_enabled_version_range(SSL *s, uint16_t *min_ver, uint16_t *max_ver)
2525{
2526	uint16_t min_version, max_version;
2527
2528	/*
2529	 * The enabled versions have to be a contiguous range, which means we
2530	 * cannot enable and disable single versions at our whim, even though
2531	 * this is what the OpenSSL flags allow. The historical way this has
2532	 * been handled is by making a flag mean that all higher versions
2533	 * are disabled, if any version lower than the flag is enabled.
2534	 */
2535
2536	min_version = 0;
2537	max_version = TLS1_2_VERSION;
2538
2539	if ((s->internal->options & SSL_OP_NO_TLSv1) == 0)
2540		min_version = TLS1_VERSION;
2541	else if ((s->internal->options & SSL_OP_NO_TLSv1_1) == 0)
2542		min_version = TLS1_1_VERSION;
2543	else if ((s->internal->options & SSL_OP_NO_TLSv1_2) == 0)
2544		min_version = TLS1_2_VERSION;
2545
2546	if ((s->internal->options & SSL_OP_NO_TLSv1_2) && min_version < TLS1_2_VERSION)
2547		max_version = TLS1_1_VERSION;
2548	if ((s->internal->options & SSL_OP_NO_TLSv1_1) && min_version < TLS1_1_VERSION)
2549		max_version = TLS1_VERSION;
2550	if ((s->internal->options & SSL_OP_NO_TLSv1) && min_version < TLS1_VERSION)
2551		max_version = 0;
2552
2553	/* Everything has been disabled... */
2554	if (min_version == 0 || max_version == 0)
2555		return 0;
2556
2557	if (min_ver != NULL)
2558		*min_ver = min_version;
2559	if (max_ver != NULL)
2560		*max_ver = max_version;
2561
2562	return 1;
2563}
2564
2565int
2566ssl_max_shared_version(SSL *s, uint16_t peer_ver, uint16_t *max_ver)
2567{
2568	uint16_t min_version, max_version, shared_version;
2569
2570	*max_ver = 0;
2571
2572	if (peer_ver >= TLS1_2_VERSION)
2573		shared_version = TLS1_2_VERSION;
2574	else if (peer_ver >= TLS1_1_VERSION)
2575		shared_version = TLS1_1_VERSION;
2576	else if (peer_ver >= TLS1_VERSION)
2577		shared_version = TLS1_VERSION;
2578	else
2579		return 0;
2580
2581	if (!ssl_enabled_version_range(s, &min_version, &max_version))
2582		return 0;
2583
2584	if (shared_version < min_version)
2585		return 0;
2586
2587	if (shared_version > max_version)
2588		shared_version = max_version;
2589
2590	*max_ver = shared_version;
2591
2592	return 1;
2593}
2594
2595uint16_t
2596ssl_max_server_version(SSL *s)
2597{
2598	uint16_t max_version;
2599
2600	/*
2601	 * The SSL method will be changed during version negotiation, as such
2602	 * we want to use the SSL method from the context.
2603	 */
2604	max_version = s->ctx->method->internal->version;
2605
2606	if (SSL_IS_DTLS(s))
2607		return (DTLS1_VERSION);
2608
2609	if ((s->internal->options & SSL_OP_NO_TLSv1_2) == 0 &&
2610	    max_version >= TLS1_2_VERSION)
2611		return (TLS1_2_VERSION);
2612	if ((s->internal->options & SSL_OP_NO_TLSv1_1) == 0 &&
2613	    max_version >= TLS1_1_VERSION)
2614		return (TLS1_1_VERSION);
2615	if ((s->internal->options & SSL_OP_NO_TLSv1) == 0 &&
2616	    max_version >= TLS1_VERSION)
2617		return (TLS1_VERSION);
2618
2619	return (0);
2620}
2621
2622SSL *
2623SSL_dup(SSL *s)
2624{
2625	STACK_OF(X509_NAME) *sk;
2626	X509_NAME *xn;
2627	SSL *ret;
2628	int i;
2629
2630	if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
2631		return (NULL);
2632
2633	ret->version = s->version;
2634	ret->internal->type = s->internal->type;
2635	ret->method = s->method;
2636
2637	if (s->session != NULL) {
2638		/* This copies session-id, SSL_METHOD, sid_ctx, and 'cert' */
2639		SSL_copy_session_id(ret, s);
2640	} else {
2641		/*
2642		 * No session has been established yet, so we have to expect
2643		 * that s->cert or ret->cert will be changed later --
2644		 * they should not both point to the same object,
2645		 * and thus we can't use SSL_copy_session_id.
2646		 */
2647
2648		ret->method->internal->ssl_free(ret);
2649		ret->method = s->method;
2650		ret->method->internal->ssl_new(ret);
2651
2652		if (s->cert != NULL) {
2653			ssl_cert_free(ret->cert);
2654			ret->cert = ssl_cert_dup(s->cert);
2655			if (ret->cert == NULL)
2656				goto err;
2657		}
2658
2659		SSL_set_session_id_context(ret,
2660		s->sid_ctx, s->sid_ctx_length);
2661	}
2662
2663	ret->internal->options = s->internal->options;
2664	ret->internal->mode = s->internal->mode;
2665	SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
2666	SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
2667	ret->internal->msg_callback = s->internal->msg_callback;
2668	ret->internal->msg_callback_arg = s->internal->msg_callback_arg;
2669	SSL_set_verify(ret, SSL_get_verify_mode(s),
2670	SSL_get_verify_callback(s));
2671	SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
2672	ret->internal->generate_session_id = s->internal->generate_session_id;
2673
2674	SSL_set_info_callback(ret, SSL_get_info_callback(s));
2675
2676	ret->internal->debug = s->internal->debug;
2677
2678	/* copy app data, a little dangerous perhaps */
2679	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL,
2680	    &ret->internal->ex_data, &s->internal->ex_data))
2681		goto err;
2682
2683	/* setup rbio, and wbio */
2684	if (s->rbio != NULL) {
2685		if (!BIO_dup_state(s->rbio,(char *)&ret->rbio))
2686			goto err;
2687	}
2688	if (s->wbio != NULL) {
2689		if (s->wbio != s->rbio) {
2690			if (!BIO_dup_state(s->wbio,(char *)&ret->wbio))
2691				goto err;
2692		} else
2693			ret->wbio = ret->rbio;
2694	}
2695	ret->internal->rwstate = s->internal->rwstate;
2696	ret->internal->in_handshake = s->internal->in_handshake;
2697	ret->internal->handshake_func = s->internal->handshake_func;
2698	ret->server = s->server;
2699	ret->internal->renegotiate = s->internal->renegotiate;
2700	ret->internal->new_session = s->internal->new_session;
2701	ret->internal->quiet_shutdown = s->internal->quiet_shutdown;
2702	ret->internal->shutdown = s->internal->shutdown;
2703	/* SSL_dup does not really work at any state, though */
2704	ret->internal->state = s->internal->state;
2705	ret->internal->rstate = s->internal->rstate;
2706
2707	/*
2708	 * Would have to copy ret->init_buf, ret->init_msg, ret->init_num,
2709	 * ret->init_off
2710	 */
2711	ret->internal->init_num = 0;
2712
2713	ret->internal->hit = s->internal->hit;
2714
2715	X509_VERIFY_PARAM_inherit(ret->param, s->param);
2716
2717	/* dup the cipher_list and cipher_list_by_id stacks */
2718	if (s->cipher_list != NULL) {
2719		if ((ret->cipher_list =
2720		    sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
2721			goto err;
2722	}
2723	if (s->internal->cipher_list_by_id != NULL) {
2724		if ((ret->internal->cipher_list_by_id =
2725		    sk_SSL_CIPHER_dup(s->internal->cipher_list_by_id)) == NULL)
2726			goto err;
2727	}
2728
2729	/* Dup the client_CA list */
2730	if (s->internal->client_CA != NULL) {
2731		if ((sk = sk_X509_NAME_dup(s->internal->client_CA)) == NULL) goto err;
2732			ret->internal->client_CA = sk;
2733		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2734			xn = sk_X509_NAME_value(sk, i);
2735			if (sk_X509_NAME_set(sk, i,
2736			    X509_NAME_dup(xn)) == NULL) {
2737				X509_NAME_free(xn);
2738				goto err;
2739			}
2740		}
2741	}
2742
2743	if (0) {
2744err:
2745		if (ret != NULL)
2746			SSL_free(ret);
2747		ret = NULL;
2748	}
2749	return (ret);
2750}
2751
2752void
2753ssl_clear_cipher_ctx(SSL *s)
2754{
2755	EVP_CIPHER_CTX_free(s->enc_read_ctx);
2756	s->enc_read_ctx = NULL;
2757	EVP_CIPHER_CTX_free(s->internal->enc_write_ctx);
2758	s->internal->enc_write_ctx = NULL;
2759
2760	if (s->internal->aead_read_ctx != NULL) {
2761		EVP_AEAD_CTX_cleanup(&s->internal->aead_read_ctx->ctx);
2762		free(s->internal->aead_read_ctx);
2763		s->internal->aead_read_ctx = NULL;
2764	}
2765	if (s->internal->aead_write_ctx != NULL) {
2766		EVP_AEAD_CTX_cleanup(&s->internal->aead_write_ctx->ctx);
2767		free(s->internal->aead_write_ctx);
2768		s->internal->aead_write_ctx = NULL;
2769	}
2770
2771}
2772
2773/* Fix this function so that it takes an optional type parameter */
2774X509 *
2775SSL_get_certificate(const SSL *s)
2776{
2777	if (s->cert != NULL)
2778		return (s->cert->key->x509);
2779	else
2780		return (NULL);
2781}
2782
2783/* Fix this function so that it takes an optional type parameter */
2784EVP_PKEY *
2785SSL_get_privatekey(SSL *s)
2786{
2787	if (s->cert != NULL)
2788		return (s->cert->key->privatekey);
2789	else
2790		return (NULL);
2791}
2792
2793const SSL_CIPHER *
2794SSL_get_current_cipher(const SSL *s)
2795{
2796	if ((s->session != NULL) && (s->session->cipher != NULL))
2797		return (s->session->cipher);
2798	return (NULL);
2799}
2800const void *
2801SSL_get_current_compression(SSL *s)
2802{
2803	return (NULL);
2804}
2805
2806const void *
2807SSL_get_current_expansion(SSL *s)
2808{
2809	return (NULL);
2810}
2811
2812int
2813ssl_init_wbio_buffer(SSL *s, int push)
2814{
2815	BIO	*bbio;
2816
2817	if (s->bbio == NULL) {
2818		bbio = BIO_new(BIO_f_buffer());
2819		if (bbio == NULL)
2820			return (0);
2821		s->bbio = bbio;
2822	} else {
2823		bbio = s->bbio;
2824		if (s->bbio == s->wbio)
2825			s->wbio = BIO_pop(s->wbio);
2826	}
2827	(void)BIO_reset(bbio);
2828/*	if (!BIO_set_write_buffer_size(bbio,16*1024)) */
2829	if (!BIO_set_read_buffer_size(bbio, 1)) {
2830		SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
2831		return (0);
2832	}
2833	if (push) {
2834		if (s->wbio != bbio)
2835			s->wbio = BIO_push(bbio, s->wbio);
2836	} else {
2837		if (s->wbio == bbio)
2838			s->wbio = BIO_pop(bbio);
2839	}
2840	return (1);
2841}
2842
2843void
2844ssl_free_wbio_buffer(SSL *s)
2845{
2846	if (s == NULL)
2847		return;
2848
2849	if (s->bbio == NULL)
2850		return;
2851
2852	if (s->bbio == s->wbio) {
2853		/* remove buffering */
2854		s->wbio = BIO_pop(s->wbio);
2855	}
2856	BIO_free(s->bbio);
2857	s->bbio = NULL;
2858}
2859
2860void
2861SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
2862{
2863	ctx->internal->quiet_shutdown = mode;
2864}
2865
2866int
2867SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
2868{
2869	return (ctx->internal->quiet_shutdown);
2870}
2871
2872void
2873SSL_set_quiet_shutdown(SSL *s, int mode)
2874{
2875	s->internal->quiet_shutdown = mode;
2876}
2877
2878int
2879SSL_get_quiet_shutdown(const SSL *s)
2880{
2881	return (s->internal->quiet_shutdown);
2882}
2883
2884void
2885SSL_set_shutdown(SSL *s, int mode)
2886{
2887	s->internal->shutdown = mode;
2888}
2889
2890int
2891SSL_get_shutdown(const SSL *s)
2892{
2893	return (s->internal->shutdown);
2894}
2895
2896int
2897SSL_version(const SSL *s)
2898{
2899	return (s->version);
2900}
2901
2902SSL_CTX *
2903SSL_get_SSL_CTX(const SSL *ssl)
2904{
2905	return (ssl->ctx);
2906}
2907
2908SSL_CTX *
2909SSL_set_SSL_CTX(SSL *ssl, SSL_CTX* ctx)
2910{
2911	CERT *ocert = ssl->cert;
2912
2913	if (ssl->ctx == ctx)
2914		return (ssl->ctx);
2915	if (ctx == NULL)
2916		ctx = ssl->initial_ctx;
2917	ssl->cert = ssl_cert_dup(ctx->internal->cert);
2918	if (ocert != NULL) {
2919		int i;
2920		/* Copy negotiated digests from original certificate. */
2921		for (i = 0; i < SSL_PKEY_NUM; i++)
2922			ssl->cert->pkeys[i].digest = ocert->pkeys[i].digest;
2923		ssl_cert_free(ocert);
2924	}
2925	CRYPTO_add(&ctx->references, 1, CRYPTO_LOCK_SSL_CTX);
2926	SSL_CTX_free(ssl->ctx); /* decrement reference count */
2927	ssl->ctx = ctx;
2928	return (ssl->ctx);
2929}
2930
2931int
2932SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
2933{
2934	return (X509_STORE_set_default_paths(ctx->cert_store));
2935}
2936
2937int
2938SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2939    const char *CApath)
2940{
2941	return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
2942}
2943
2944int
2945SSL_CTX_load_verify_mem(SSL_CTX *ctx, void *buf, int len)
2946{
2947	return (X509_STORE_load_mem(ctx->cert_store, buf, len));
2948}
2949
2950void
2951SSL_set_info_callback(SSL *ssl, void (*cb)(const SSL *ssl, int type, int val))
2952{
2953	ssl->internal->info_callback = cb;
2954}
2955
2956void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type, int val)
2957{
2958	return (ssl->internal->info_callback);
2959}
2960
2961int
2962SSL_state(const SSL *ssl)
2963{
2964	return (ssl->internal->state);
2965}
2966
2967void
2968SSL_set_state(SSL *ssl, int state)
2969{
2970	ssl->internal->state = state;
2971}
2972
2973void
2974SSL_set_verify_result(SSL *ssl, long arg)
2975{
2976	ssl->verify_result = arg;
2977}
2978
2979long
2980SSL_get_verify_result(const SSL *ssl)
2981{
2982	return (ssl->verify_result);
2983}
2984
2985int
2986SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2987    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
2988{
2989	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, argl, argp,
2990	    new_func, dup_func, free_func));
2991}
2992
2993int
2994SSL_set_ex_data(SSL *s, int idx, void *arg)
2995{
2996	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
2997}
2998
2999void *
3000SSL_get_ex_data(const SSL *s, int idx)
3001{
3002	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
3003}
3004
3005int
3006SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
3007    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
3008{
3009	return (CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, argl, argp,
3010	    new_func, dup_func, free_func));
3011}
3012
3013int
3014SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3015{
3016	return (CRYPTO_set_ex_data(&s->internal->ex_data, idx, arg));
3017}
3018
3019void *
3020SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3021{
3022	return (CRYPTO_get_ex_data(&s->internal->ex_data, idx));
3023}
3024
3025int
3026ssl_ok(SSL *s)
3027{
3028	return (1);
3029}
3030
3031X509_STORE *
3032SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3033{
3034	return (ctx->cert_store);
3035}
3036
3037void
3038SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3039{
3040	if (ctx->cert_store != NULL)
3041		X509_STORE_free(ctx->cert_store);
3042	ctx->cert_store = store;
3043}
3044
3045int
3046SSL_want(const SSL *s)
3047{
3048	return (s->internal->rwstate);
3049}
3050
3051void
3052SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export,
3053    int keylength))
3054{
3055	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3056}
3057
3058void
3059SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
3060    int keylength))
3061{
3062	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_RSA_CB,(void (*)(void))cb);
3063}
3064
3065void
3066SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, DH *(*dh)(SSL *ssl, int is_export,
3067    int keylength))
3068{
3069	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3070}
3071
3072void
3073SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh)(SSL *ssl, int is_export,
3074    int keylength))
3075{
3076	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB,(void (*)(void))dh);
3077}
3078
3079void
3080SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx, EC_KEY *(*ecdh)(SSL *ssl,
3081    int is_export, int keylength))
3082{
3083	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH_CB,
3084	    (void (*)(void))ecdh);
3085}
3086
3087void
3088SSL_set_tmp_ecdh_callback(SSL *ssl, EC_KEY *(*ecdh)(SSL *ssl, int is_export,
3089    int keylength))
3090{
3091	SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH_CB,(void (*)(void))ecdh);
3092}
3093
3094
3095void
3096SSL_CTX_set_msg_callback(SSL_CTX *ctx, void (*cb)(int write_p, int version,
3097    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3098{
3099	SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK,
3100	    (void (*)(void))cb);
3101}
3102
3103void
3104SSL_set_msg_callback(SSL *ssl, void (*cb)(int write_p, int version,
3105    int content_type, const void *buf, size_t len, SSL *ssl, void *arg))
3106{
3107	SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3108}
3109
3110void
3111ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3112{
3113	if (*hash)
3114		EVP_MD_CTX_destroy(*hash);
3115	*hash = NULL;
3116}
3117
3118void
3119SSL_set_debug(SSL *s, int debug)
3120{
3121	s->internal->debug = debug;
3122}
3123
3124int
3125SSL_cache_hit(SSL *s)
3126{
3127	return (s->internal->hit);
3128}
3129
3130
3131static int
3132ssl_cipher_id_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
3133{
3134	SSL_CIPHER const *a = a_;
3135	SSL_CIPHER const *b = b_;
3136	return ssl_cipher_id_cmp(a, b);
3137}
3138
3139SSL_CIPHER *
3140OBJ_bsearch_ssl_cipher_id(SSL_CIPHER *key, SSL_CIPHER const *base, int num)
3141{
3142	return (SSL_CIPHER *)OBJ_bsearch_(key, base, num, sizeof(SSL_CIPHER),
3143	    ssl_cipher_id_cmp_BSEARCH_CMP_FN);
3144}
3145