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