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