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