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