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