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