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