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