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