1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE. */
140 
141 #include <assert.h>
142 #include <stdio.h>
143 #include <string.h>
144 
145 #include <openssl/bytestring.h>
146 #include <openssl/dh.h>
147 #include <openssl/err.h>
148 #include <openssl/lhash.h>
149 #include <openssl/mem.h>
150 #include <openssl/obj.h>
151 #include <openssl/rand.h>
152 #include <openssl/x509v3.h>
153 
154 #include "internal.h"
155 #include "../crypto/internal.h"
156 
157 
158 /* Some error codes are special. Ensure the make_errors.go script never
159  * regresses this. */
160 OPENSSL_COMPILE_ASSERT(SSL_R_TLSV1_ALERT_NO_RENEGOTIATION ==
161                            SSL_AD_NO_RENEGOTIATION + SSL_AD_REASON_OFFSET,
162                        ssl_alert_reason_code_mismatch);
163 
164 /* kMaxHandshakeSize is the maximum size, in bytes, of a handshake message. */
165 static const size_t kMaxHandshakeSize = (1u << 24) - 1;
166 
167 static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl = CRYPTO_EX_DATA_CLASS_INIT;
168 static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl_ctx = CRYPTO_EX_DATA_CLASS_INIT;
169 
SSL_clear(SSL * ssl)170 int SSL_clear(SSL *ssl) {
171   if (ssl->method == NULL) {
172     OPENSSL_PUT_ERROR(SSL, SSL_clear, SSL_R_NO_METHOD_SPECIFIED);
173     return 0;
174   }
175 
176   if (ssl_clear_bad_session(ssl)) {
177     SSL_SESSION_free(ssl->session);
178     ssl->session = NULL;
179   }
180 
181   ssl->hit = 0;
182   ssl->shutdown = 0;
183 
184   /* SSL_clear may be called before or after the |ssl| is initialized in either
185    * accept or connect state. In the latter case, SSL_clear should preserve the
186    * half and reset |ssl->state| accordingly. */
187   if (ssl->handshake_func != NULL) {
188     if (ssl->server) {
189       SSL_set_accept_state(ssl);
190     } else {
191       SSL_set_connect_state(ssl);
192     }
193   } else {
194     assert(ssl->state == 0);
195   }
196 
197   /* TODO(davidben): Some state on |ssl| is reset both in |SSL_new| and
198    * |SSL_clear| because it is per-connection state rather than configuration
199    * state. Per-connection state should be on |ssl->s3| and |ssl->d1| so it is
200    * naturally reset at the right points between |SSL_new|, |SSL_clear|, and
201    * |ssl3_new|. */
202 
203   ssl->rwstate = SSL_NOTHING;
204   ssl->rstate = SSL_ST_READ_HEADER;
205 
206   BUF_MEM_free(ssl->init_buf);
207   ssl->init_buf = NULL;
208 
209   ssl->packet = NULL;
210   ssl->packet_length = 0;
211 
212   ssl_clear_cipher_ctx(ssl);
213 
214   OPENSSL_free(ssl->next_proto_negotiated);
215   ssl->next_proto_negotiated = NULL;
216   ssl->next_proto_negotiated_len = 0;
217 
218   /* The ssl->d1->mtu is simultaneously configuration (preserved across
219    * clear) and connection-specific state (gets reset).
220    *
221    * TODO(davidben): Avoid this. */
222   unsigned mtu = 0;
223   if (ssl->d1 != NULL) {
224     mtu = ssl->d1->mtu;
225   }
226 
227   ssl->method->ssl_free(ssl);
228   if (!ssl->method->ssl_new(ssl)) {
229     return 0;
230   }
231   ssl->enc_method = ssl3_get_enc_method(ssl->version);
232   assert(ssl->enc_method != NULL);
233 
234   if (SSL_IS_DTLS(ssl) && (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
235     ssl->d1->mtu = mtu;
236   }
237 
238   ssl->client_version = ssl->version;
239 
240   return 1;
241 }
242 
SSL_new(SSL_CTX * ctx)243 SSL *SSL_new(SSL_CTX *ctx) {
244   SSL *s;
245 
246   if (ctx == NULL) {
247     OPENSSL_PUT_ERROR(SSL, SSL_new, SSL_R_NULL_SSL_CTX);
248     return NULL;
249   }
250   if (ctx->method == NULL) {
251     OPENSSL_PUT_ERROR(SSL, SSL_new, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
252     return NULL;
253   }
254 
255   s = (SSL *)OPENSSL_malloc(sizeof(SSL));
256   if (s == NULL) {
257     goto err;
258   }
259   memset(s, 0, sizeof(SSL));
260 
261   s->min_version = ctx->min_version;
262   s->max_version = ctx->max_version;
263 
264   s->options = ctx->options;
265   s->mode = ctx->mode;
266   s->max_cert_list = ctx->max_cert_list;
267 
268   s->cert = ssl_cert_dup(ctx->cert);
269   if (s->cert == NULL) {
270     goto err;
271   }
272 
273   s->msg_callback = ctx->msg_callback;
274   s->msg_callback_arg = ctx->msg_callback_arg;
275   s->verify_mode = ctx->verify_mode;
276   s->sid_ctx_length = ctx->sid_ctx_length;
277   assert(s->sid_ctx_length <= sizeof s->sid_ctx);
278   memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
279   s->verify_callback = ctx->default_verify_callback;
280   s->generate_session_id = ctx->generate_session_id;
281 
282   s->param = X509_VERIFY_PARAM_new();
283   if (!s->param) {
284     goto err;
285   }
286   X509_VERIFY_PARAM_inherit(s->param, ctx->param);
287   s->quiet_shutdown = ctx->quiet_shutdown;
288   s->max_send_fragment = ctx->max_send_fragment;
289 
290   CRYPTO_refcount_inc(&ctx->references);
291   s->ctx = ctx;
292   s->tlsext_ticket_expected = 0;
293   CRYPTO_refcount_inc(&ctx->references);
294   s->initial_ctx = ctx;
295   if (ctx->tlsext_ecpointformatlist) {
296     s->tlsext_ecpointformatlist = BUF_memdup(
297         ctx->tlsext_ecpointformatlist, ctx->tlsext_ecpointformatlist_length);
298     if (!s->tlsext_ecpointformatlist) {
299       goto err;
300     }
301     s->tlsext_ecpointformatlist_length = ctx->tlsext_ecpointformatlist_length;
302   }
303 
304   if (ctx->tlsext_ellipticcurvelist) {
305     s->tlsext_ellipticcurvelist =
306         BUF_memdup(ctx->tlsext_ellipticcurvelist,
307                    ctx->tlsext_ellipticcurvelist_length * 2);
308     if (!s->tlsext_ellipticcurvelist) {
309       goto err;
310     }
311     s->tlsext_ellipticcurvelist_length = ctx->tlsext_ellipticcurvelist_length;
312   }
313   s->next_proto_negotiated = NULL;
314 
315   if (s->ctx->alpn_client_proto_list) {
316     s->alpn_client_proto_list = BUF_memdup(s->ctx->alpn_client_proto_list,
317                                            s->ctx->alpn_client_proto_list_len);
318     if (s->alpn_client_proto_list == NULL) {
319       goto err;
320     }
321     s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
322   }
323 
324   s->verify_result = X509_V_OK;
325   s->method = ctx->method;
326 
327   if (!s->method->ssl_new(s)) {
328     goto err;
329   }
330   s->enc_method = ssl3_get_enc_method(s->version);
331   assert(s->enc_method != NULL);
332 
333   s->rwstate = SSL_NOTHING;
334   s->rstate = SSL_ST_READ_HEADER;
335 
336   CRYPTO_new_ex_data(&g_ex_data_class_ssl, s, &s->ex_data);
337 
338   s->psk_identity_hint = NULL;
339   if (ctx->psk_identity_hint) {
340     s->psk_identity_hint = BUF_strdup(ctx->psk_identity_hint);
341     if (s->psk_identity_hint == NULL) {
342       goto err;
343     }
344   }
345   s->psk_client_callback = ctx->psk_client_callback;
346   s->psk_server_callback = ctx->psk_server_callback;
347 
348   s->tlsext_channel_id_enabled = ctx->tlsext_channel_id_enabled;
349   if (ctx->tlsext_channel_id_private) {
350     s->tlsext_channel_id_private =
351         EVP_PKEY_up_ref(ctx->tlsext_channel_id_private);
352   }
353 
354   s->signed_cert_timestamps_enabled = s->ctx->signed_cert_timestamps_enabled;
355   s->ocsp_stapling_enabled = s->ctx->ocsp_stapling_enabled;
356 
357   return s;
358 
359 err:
360   SSL_free(s);
361   OPENSSL_PUT_ERROR(SSL, SSL_new, ERR_R_MALLOC_FAILURE);
362 
363   return NULL;
364 }
365 
SSL_CTX_set_session_id_context(SSL_CTX * ctx,const uint8_t * sid_ctx,unsigned int sid_ctx_len)366 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const uint8_t *sid_ctx,
367                                    unsigned int sid_ctx_len) {
368   if (sid_ctx_len > sizeof ctx->sid_ctx) {
369     OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_session_id_context,
370                       SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
371     return 0;
372   }
373   ctx->sid_ctx_length = sid_ctx_len;
374   memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
375 
376   return 1;
377 }
378 
SSL_set_session_id_context(SSL * ssl,const uint8_t * sid_ctx,unsigned int sid_ctx_len)379 int SSL_set_session_id_context(SSL *ssl, const uint8_t *sid_ctx,
380                                unsigned int sid_ctx_len) {
381   if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
382     OPENSSL_PUT_ERROR(SSL, SSL_set_session_id_context,
383                       SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
384     return 0;
385   }
386   ssl->sid_ctx_length = sid_ctx_len;
387   memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
388 
389   return 1;
390 }
391 
SSL_CTX_set_generate_session_id(SSL_CTX * ctx,GEN_SESSION_CB cb)392 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb) {
393   ctx->generate_session_id = cb;
394   return 1;
395 }
396 
SSL_set_generate_session_id(SSL * ssl,GEN_SESSION_CB cb)397 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb) {
398   ssl->generate_session_id = cb;
399   return 1;
400 }
401 
SSL_has_matching_session_id(const SSL * ssl,const uint8_t * id,unsigned int id_len)402 int SSL_has_matching_session_id(const SSL *ssl, const uint8_t *id,
403                                 unsigned int id_len) {
404   /* A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how we
405    * can "construct" a session to give us the desired check - ie. to find if
406    * there's a session in the hash table that would conflict with any new
407    * session built out of this id/id_len and the ssl_version in use by this
408    * SSL. */
409   SSL_SESSION r, *p;
410 
411   if (id_len > sizeof r.session_id) {
412     return 0;
413   }
414 
415   r.ssl_version = ssl->version;
416   r.session_id_length = id_len;
417   memcpy(r.session_id, id, id_len);
418 
419   CRYPTO_MUTEX_lock_read(&ssl->ctx->lock);
420   p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
421   CRYPTO_MUTEX_unlock(&ssl->ctx->lock);
422   return p != NULL;
423 }
424 
SSL_CTX_set_purpose(SSL_CTX * s,int purpose)425 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose) {
426   return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
427 }
428 
SSL_set_purpose(SSL * s,int purpose)429 int SSL_set_purpose(SSL *s, int purpose) {
430   return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
431 }
432 
SSL_CTX_set_trust(SSL_CTX * s,int trust)433 int SSL_CTX_set_trust(SSL_CTX *s, int trust) {
434   return X509_VERIFY_PARAM_set_trust(s->param, trust);
435 }
436 
SSL_set_trust(SSL * s,int trust)437 int SSL_set_trust(SSL *s, int trust) {
438   return X509_VERIFY_PARAM_set_trust(s->param, trust);
439 }
440 
SSL_CTX_set1_param(SSL_CTX * ctx,X509_VERIFY_PARAM * vpm)441 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm) {
442   return X509_VERIFY_PARAM_set1(ctx->param, vpm);
443 }
444 
SSL_set1_param(SSL * ssl,X509_VERIFY_PARAM * vpm)445 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm) {
446   return X509_VERIFY_PARAM_set1(ssl->param, vpm);
447 }
448 
ssl_cipher_preference_list_free(struct ssl_cipher_preference_list_st * cipher_list)449 void ssl_cipher_preference_list_free(
450     struct ssl_cipher_preference_list_st *cipher_list) {
451   if (cipher_list == NULL) {
452     return;
453   }
454   sk_SSL_CIPHER_free(cipher_list->ciphers);
455   OPENSSL_free(cipher_list->in_group_flags);
456   OPENSSL_free(cipher_list);
457 }
458 
ssl_cipher_preference_list_dup(struct ssl_cipher_preference_list_st * cipher_list)459 struct ssl_cipher_preference_list_st *ssl_cipher_preference_list_dup(
460     struct ssl_cipher_preference_list_st *cipher_list) {
461   struct ssl_cipher_preference_list_st *ret = NULL;
462   size_t n = sk_SSL_CIPHER_num(cipher_list->ciphers);
463 
464   ret = OPENSSL_malloc(sizeof(struct ssl_cipher_preference_list_st));
465   if (!ret) {
466     goto err;
467   }
468 
469   ret->ciphers = NULL;
470   ret->in_group_flags = NULL;
471   ret->ciphers = sk_SSL_CIPHER_dup(cipher_list->ciphers);
472   if (!ret->ciphers) {
473     goto err;
474   }
475   ret->in_group_flags = BUF_memdup(cipher_list->in_group_flags, n);
476   if (!ret->in_group_flags) {
477     goto err;
478   }
479 
480   return ret;
481 
482 err:
483   ssl_cipher_preference_list_free(ret);
484   return NULL;
485 }
486 
ssl_cipher_preference_list_from_ciphers(STACK_OF (SSL_CIPHER)* ciphers)487 struct ssl_cipher_preference_list_st *ssl_cipher_preference_list_from_ciphers(
488     STACK_OF(SSL_CIPHER) *ciphers) {
489   struct ssl_cipher_preference_list_st *ret = NULL;
490   size_t n = sk_SSL_CIPHER_num(ciphers);
491 
492   ret = OPENSSL_malloc(sizeof(struct ssl_cipher_preference_list_st));
493   if (!ret) {
494     goto err;
495   }
496   ret->ciphers = NULL;
497   ret->in_group_flags = NULL;
498   ret->ciphers = sk_SSL_CIPHER_dup(ciphers);
499   if (!ret->ciphers) {
500     goto err;
501   }
502   ret->in_group_flags = OPENSSL_malloc(n);
503   if (!ret->in_group_flags) {
504     goto err;
505   }
506   memset(ret->in_group_flags, 0, n);
507   return ret;
508 
509 err:
510   ssl_cipher_preference_list_free(ret);
511   return NULL;
512 }
513 
SSL_CTX_get0_param(SSL_CTX * ctx)514 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx) { return ctx->param; }
515 
SSL_get0_param(SSL * ssl)516 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl) { return ssl->param; }
517 
SSL_certs_clear(SSL * s)518 void SSL_certs_clear(SSL *s) { ssl_cert_clear_certs(s->cert); }
519 
SSL_free(SSL * ssl)520 void SSL_free(SSL *ssl) {
521   if (ssl == NULL) {
522     return;
523   }
524 
525   X509_VERIFY_PARAM_free(ssl->param);
526 
527   CRYPTO_free_ex_data(&g_ex_data_class_ssl, ssl, &ssl->ex_data);
528 
529   if (ssl->bbio != NULL) {
530     /* If the buffering BIO is in place, pop it off */
531     if (ssl->bbio == ssl->wbio) {
532       ssl->wbio = BIO_pop(ssl->wbio);
533     }
534     BIO_free(ssl->bbio);
535     ssl->bbio = NULL;
536   }
537 
538   int free_wbio = ssl->wbio != ssl->rbio;
539   BIO_free_all(ssl->rbio);
540   if (free_wbio) {
541     BIO_free_all(ssl->wbio);
542   }
543 
544   BUF_MEM_free(ssl->init_buf);
545 
546   /* add extra stuff */
547   ssl_cipher_preference_list_free(ssl->cipher_list);
548   sk_SSL_CIPHER_free(ssl->cipher_list_by_id);
549 
550   ssl_clear_bad_session(ssl);
551   SSL_SESSION_free(ssl->session);
552 
553   ssl_clear_cipher_ctx(ssl);
554 
555   ssl_cert_free(ssl->cert);
556 
557   OPENSSL_free(ssl->tlsext_hostname);
558   SSL_CTX_free(ssl->initial_ctx);
559   OPENSSL_free(ssl->tlsext_ecpointformatlist);
560   OPENSSL_free(ssl->tlsext_ellipticcurvelist);
561   OPENSSL_free(ssl->alpn_client_proto_list);
562   EVP_PKEY_free(ssl->tlsext_channel_id_private);
563   OPENSSL_free(ssl->psk_identity_hint);
564   sk_X509_NAME_pop_free(ssl->client_CA, X509_NAME_free);
565   OPENSSL_free(ssl->next_proto_negotiated);
566   sk_SRTP_PROTECTION_PROFILE_free(ssl->srtp_profiles);
567 
568   if (ssl->method != NULL) {
569     ssl->method->ssl_free(ssl);
570   }
571   SSL_CTX_free(ssl->ctx);
572 
573   OPENSSL_free(ssl);
574 }
575 
SSL_set_bio(SSL * s,BIO * rbio,BIO * wbio)576 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio) {
577   /* If the output buffering BIO is still in place, remove it. */
578   if (s->bbio != NULL) {
579     if (s->wbio == s->bbio) {
580       s->wbio = s->wbio->next_bio;
581       s->bbio->next_bio = NULL;
582     }
583   }
584 
585   if (s->rbio != rbio) {
586     BIO_free_all(s->rbio);
587   }
588   if (s->wbio != wbio && s->rbio != s->wbio) {
589     BIO_free_all(s->wbio);
590   }
591   s->rbio = rbio;
592   s->wbio = wbio;
593 }
594 
SSL_get_rbio(const SSL * s)595 BIO *SSL_get_rbio(const SSL *s) { return s->rbio; }
596 
SSL_get_wbio(const SSL * s)597 BIO *SSL_get_wbio(const SSL *s) { return s->wbio; }
598 
SSL_get_fd(const SSL * s)599 int SSL_get_fd(const SSL *s) { return SSL_get_rfd(s); }
600 
SSL_get_rfd(const SSL * s)601 int SSL_get_rfd(const SSL *s) {
602   int ret = -1;
603   BIO *b, *r;
604 
605   b = SSL_get_rbio(s);
606   r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
607   if (r != NULL) {
608     BIO_get_fd(r, &ret);
609   }
610   return ret;
611 }
612 
SSL_get_wfd(const SSL * s)613 int SSL_get_wfd(const SSL *s) {
614   int ret = -1;
615   BIO *b, *r;
616 
617   b = SSL_get_wbio(s);
618   r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
619   if (r != NULL) {
620     BIO_get_fd(r, &ret);
621   }
622 
623   return ret;
624 }
625 
SSL_set_fd(SSL * s,int fd)626 int SSL_set_fd(SSL *s, int fd) {
627   int ret = 0;
628   BIO *bio = NULL;
629 
630   bio = BIO_new(BIO_s_fd());
631 
632   if (bio == NULL) {
633     OPENSSL_PUT_ERROR(SSL, SSL_set_fd, ERR_R_BUF_LIB);
634     goto err;
635   }
636   BIO_set_fd(bio, fd, BIO_NOCLOSE);
637   SSL_set_bio(s, bio, bio);
638   ret = 1;
639 
640 err:
641   return ret;
642 }
643 
SSL_set_wfd(SSL * s,int fd)644 int SSL_set_wfd(SSL *s, int fd) {
645   int ret = 0;
646   BIO *bio = NULL;
647 
648   if (s->rbio == NULL || BIO_method_type(s->rbio) != BIO_TYPE_FD ||
649       (int)BIO_get_fd(s->rbio, NULL) != fd) {
650     bio = BIO_new(BIO_s_fd());
651 
652     if (bio == NULL) {
653       OPENSSL_PUT_ERROR(SSL, SSL_set_wfd, ERR_R_BUF_LIB);
654       goto err;
655     }
656     BIO_set_fd(bio, fd, BIO_NOCLOSE);
657     SSL_set_bio(s, SSL_get_rbio(s), bio);
658   } else {
659     SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
660   }
661 
662   ret = 1;
663 
664 err:
665   return ret;
666 }
667 
SSL_set_rfd(SSL * s,int fd)668 int SSL_set_rfd(SSL *s, int fd) {
669   int ret = 0;
670   BIO *bio = NULL;
671 
672   if (s->wbio == NULL || BIO_method_type(s->wbio) != BIO_TYPE_FD ||
673       (int)BIO_get_fd(s->wbio, NULL) != fd) {
674     bio = BIO_new(BIO_s_fd());
675 
676     if (bio == NULL) {
677       OPENSSL_PUT_ERROR(SSL, SSL_set_rfd, ERR_R_BUF_LIB);
678       goto err;
679     }
680     BIO_set_fd(bio, fd, BIO_NOCLOSE);
681     SSL_set_bio(s, bio, SSL_get_wbio(s));
682   } else {
683     SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
684   }
685   ret = 1;
686 
687 err:
688   return ret;
689 }
690 
691 /* return length of latest Finished message we sent, copy to 'buf' */
SSL_get_finished(const SSL * s,void * buf,size_t count)692 size_t SSL_get_finished(const SSL *s, void *buf, size_t count) {
693   size_t ret = 0;
694 
695   if (s->s3 != NULL) {
696     ret = s->s3->tmp.finish_md_len;
697     if (count > ret) {
698       count = ret;
699     }
700     memcpy(buf, s->s3->tmp.finish_md, count);
701   }
702 
703   return ret;
704 }
705 
706 /* return length of latest Finished message we expected, copy to 'buf' */
SSL_get_peer_finished(const SSL * s,void * buf,size_t count)707 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count) {
708   size_t ret = 0;
709 
710   if (s->s3 != NULL) {
711     ret = s->s3->tmp.peer_finish_md_len;
712     if (count > ret) {
713       count = ret;
714     }
715     memcpy(buf, s->s3->tmp.peer_finish_md, count);
716   }
717 
718   return ret;
719 }
720 
SSL_get_verify_mode(const SSL * s)721 int SSL_get_verify_mode(const SSL *s) { return s->verify_mode; }
722 
SSL_get_verify_depth(const SSL * s)723 int SSL_get_verify_depth(const SSL *s) {
724   return X509_VERIFY_PARAM_get_depth(s->param);
725 }
726 
SSL_get_verify_callback(const SSL * s)727 int (*SSL_get_verify_callback(const SSL *s))(int, X509_STORE_CTX *) {
728   return s->verify_callback;
729 }
730 
SSL_CTX_get_verify_mode(const SSL_CTX * ctx)731 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx) { return ctx->verify_mode; }
732 
SSL_CTX_get_verify_depth(const SSL_CTX * ctx)733 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx) {
734   return X509_VERIFY_PARAM_get_depth(ctx->param);
735 }
736 
SSL_CTX_get_verify_callback(const SSL_CTX * ctx)737 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx))(int, X509_STORE_CTX *) {
738   return ctx->default_verify_callback;
739 }
740 
SSL_set_verify(SSL * s,int mode,int (* callback)(int ok,X509_STORE_CTX * ctx))741 void SSL_set_verify(SSL *s, int mode,
742                     int (*callback)(int ok, X509_STORE_CTX *ctx)) {
743   s->verify_mode = mode;
744   if (callback != NULL) {
745     s->verify_callback = callback;
746   }
747 }
748 
SSL_set_verify_depth(SSL * s,int depth)749 void SSL_set_verify_depth(SSL *s, int depth) {
750   X509_VERIFY_PARAM_set_depth(s->param, depth);
751 }
752 
SSL_CTX_get_read_ahead(const SSL_CTX * ctx)753 int SSL_CTX_get_read_ahead(const SSL_CTX *ctx) { return 0; }
754 
SSL_get_read_ahead(const SSL * s)755 int SSL_get_read_ahead(const SSL *s) { return 0; }
756 
SSL_CTX_set_read_ahead(SSL_CTX * ctx,int yes)757 void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes) { }
758 
SSL_set_read_ahead(SSL * s,int yes)759 void SSL_set_read_ahead(SSL *s, int yes) { }
760 
SSL_pending(const SSL * s)761 int SSL_pending(const SSL *s) {
762   if (s->rstate == SSL_ST_READ_BODY) {
763     return 0;
764   }
765 
766   return (s->s3->rrec.type == SSL3_RT_APPLICATION_DATA) ? s->s3->rrec.length
767                                                         : 0;
768 }
769 
SSL_get_peer_certificate(const SSL * s)770 X509 *SSL_get_peer_certificate(const SSL *s) {
771   X509 *r;
772 
773   if (s == NULL || s->session == NULL) {
774     r = NULL;
775   } else {
776     r = s->session->peer;
777   }
778 
779   if (r == NULL) {
780     return NULL;
781   }
782 
783   return X509_up_ref(r);
784 }
785 
STACK_OF(X509)786 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s) {
787   STACK_OF(X509) *r;
788 
789   if (s == NULL || s->session == NULL || s->session->sess_cert == NULL) {
790     r = NULL;
791   } else {
792     r = s->session->sess_cert->cert_chain;
793   }
794 
795   /* If we are a client, cert_chain includes the peer's own certificate; if we
796    * are a server, it does not. */
797   return r;
798 }
799 
800 /* Fix this so it checks all the valid key/cert options */
SSL_CTX_check_private_key(const SSL_CTX * ctx)801 int SSL_CTX_check_private_key(const SSL_CTX *ctx) {
802   if (ctx == NULL || ctx->cert == NULL || ctx->cert->key->x509 == NULL) {
803     OPENSSL_PUT_ERROR(SSL, SSL_CTX_check_private_key,
804                       SSL_R_NO_CERTIFICATE_ASSIGNED);
805     return 0;
806   }
807 
808   if (ctx->cert->key->privatekey == NULL) {
809     OPENSSL_PUT_ERROR(SSL, SSL_CTX_check_private_key,
810                       SSL_R_NO_PRIVATE_KEY_ASSIGNED);
811     return 0;
812   }
813 
814   return X509_check_private_key(ctx->cert->key->x509,
815                                 ctx->cert->key->privatekey);
816 }
817 
818 /* Fix this function so that it takes an optional type parameter */
SSL_check_private_key(const SSL * ssl)819 int SSL_check_private_key(const SSL *ssl) {
820   if (ssl == NULL) {
821     OPENSSL_PUT_ERROR(SSL, SSL_check_private_key, ERR_R_PASSED_NULL_PARAMETER);
822     return 0;
823   }
824 
825   if (ssl->cert == NULL) {
826     OPENSSL_PUT_ERROR(SSL, SSL_check_private_key,
827                       SSL_R_NO_CERTIFICATE_ASSIGNED);
828     return 0;
829   }
830 
831   if (ssl->cert->key->x509 == NULL) {
832     OPENSSL_PUT_ERROR(SSL, SSL_check_private_key,
833                       SSL_R_NO_CERTIFICATE_ASSIGNED);
834     return 0;
835   }
836 
837   if (ssl->cert->key->privatekey == NULL) {
838     OPENSSL_PUT_ERROR(SSL, SSL_check_private_key,
839                       SSL_R_NO_PRIVATE_KEY_ASSIGNED);
840     return 0;
841   }
842 
843   return X509_check_private_key(ssl->cert->key->x509,
844                                 ssl->cert->key->privatekey);
845 }
846 
SSL_accept(SSL * s)847 int SSL_accept(SSL *s) {
848   if (s->handshake_func == 0) {
849     /* Not properly initialized yet */
850     SSL_set_accept_state(s);
851   }
852 
853   if (s->handshake_func != s->method->ssl_accept) {
854     OPENSSL_PUT_ERROR(SSL, SSL_accept, ERR_R_INTERNAL_ERROR);
855     return -1;
856   }
857 
858   return s->handshake_func(s);
859 }
860 
SSL_connect(SSL * s)861 int SSL_connect(SSL *s) {
862   if (s->handshake_func == 0) {
863     /* Not properly initialized yet */
864     SSL_set_connect_state(s);
865   }
866 
867   if (s->handshake_func != s->method->ssl_connect) {
868     OPENSSL_PUT_ERROR(SSL, SSL_connect, ERR_R_INTERNAL_ERROR);
869     return -1;
870   }
871 
872   return s->handshake_func(s);
873 }
874 
SSL_get_default_timeout(const SSL * s)875 long SSL_get_default_timeout(const SSL *s) {
876   return SSL_DEFAULT_SESSION_TIMEOUT;
877 }
878 
SSL_read(SSL * s,void * buf,int num)879 int SSL_read(SSL *s, void *buf, int num) {
880   if (s->handshake_func == 0) {
881     OPENSSL_PUT_ERROR(SSL, SSL_read, SSL_R_UNINITIALIZED);
882     return -1;
883   }
884 
885   if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
886     s->rwstate = SSL_NOTHING;
887     return 0;
888   }
889 
890   ERR_clear_system_error();
891   return s->method->ssl_read_app_data(s, buf, num, 0);
892 }
893 
SSL_peek(SSL * s,void * buf,int num)894 int SSL_peek(SSL *s, void *buf, int num) {
895   if (s->handshake_func == 0) {
896     OPENSSL_PUT_ERROR(SSL, SSL_peek, SSL_R_UNINITIALIZED);
897     return -1;
898   }
899 
900   if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
901     return 0;
902   }
903 
904   ERR_clear_system_error();
905   return s->method->ssl_read_app_data(s, buf, num, 1);
906 }
907 
SSL_write(SSL * s,const void * buf,int num)908 int SSL_write(SSL *s, const void *buf, int num) {
909   if (s->handshake_func == 0) {
910     OPENSSL_PUT_ERROR(SSL, SSL_write, SSL_R_UNINITIALIZED);
911     return -1;
912   }
913 
914   if (s->shutdown & SSL_SENT_SHUTDOWN) {
915     s->rwstate = SSL_NOTHING;
916     OPENSSL_PUT_ERROR(SSL, SSL_write, SSL_R_PROTOCOL_IS_SHUTDOWN);
917     return -1;
918   }
919 
920   ERR_clear_system_error();
921   return s->method->ssl_write_app_data(s, buf, num);
922 }
923 
SSL_shutdown(SSL * s)924 int SSL_shutdown(SSL *s) {
925   /* Note that this function behaves differently from what one might expect.
926    * Return values are 0 for no success (yet), 1 for success; but calling it
927    * once is usually not enough, even if blocking I/O is used (see
928    * ssl3_shutdown). */
929 
930   if (s->handshake_func == 0) {
931     OPENSSL_PUT_ERROR(SSL, SSL_shutdown, SSL_R_UNINITIALIZED);
932     return -1;
933   }
934 
935   if (SSL_in_init(s)) {
936     return 1;
937   }
938 
939   /* Do nothing if configured not to send a close_notify. */
940   if (s->quiet_shutdown) {
941     s->shutdown = SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN;
942     return 1;
943   }
944 
945   if (!(s->shutdown & SSL_SENT_SHUTDOWN)) {
946     s->shutdown |= SSL_SENT_SHUTDOWN;
947     ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_CLOSE_NOTIFY);
948 
949     /* our shutdown alert has been sent now, and if it still needs to be
950      * written, s->s3->alert_dispatch will be true */
951     if (s->s3->alert_dispatch) {
952       return -1; /* return WANT_WRITE */
953     }
954   } else if (s->s3->alert_dispatch) {
955     /* resend it if not sent */
956     int ret = s->method->ssl_dispatch_alert(s);
957     if (ret == -1) {
958       /* we only get to return -1 here the 2nd/Nth invocation, we must  have
959        * already signalled return 0 upon a previous invoation, return
960        * WANT_WRITE */
961       return ret;
962     }
963   } else if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
964     /* If we are waiting for a close from our peer, we are closed */
965     s->method->ssl_read_close_notify(s);
966     if (!(s->shutdown & SSL_RECEIVED_SHUTDOWN)) {
967       return -1; /* return WANT_READ */
968     }
969   }
970 
971   if (s->shutdown == (SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN) &&
972       !s->s3->alert_dispatch) {
973     return 1;
974   } else {
975     return 0;
976   }
977 }
978 
SSL_renegotiate(SSL * ssl)979 int SSL_renegotiate(SSL *ssl) {
980   /* Caller-initiated renegotiation is not supported. */
981   OPENSSL_PUT_ERROR(SSL, SSL_renegotiate, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
982   return 0;
983 }
984 
SSL_renegotiate_pending(SSL * ssl)985 int SSL_renegotiate_pending(SSL *ssl) {
986   return SSL_in_init(ssl) && ssl->s3->initial_handshake_complete;
987 }
988 
SSL_CTX_set_options(SSL_CTX * ctx,uint32_t options)989 uint32_t SSL_CTX_set_options(SSL_CTX *ctx, uint32_t options) {
990   ctx->options |= options;
991   return ctx->options;
992 }
993 
SSL_set_options(SSL * ssl,uint32_t options)994 uint32_t SSL_set_options(SSL *ssl, uint32_t options) {
995   ssl->options |= options;
996   return ssl->options;
997 }
998 
SSL_CTX_clear_options(SSL_CTX * ctx,uint32_t options)999 uint32_t SSL_CTX_clear_options(SSL_CTX *ctx, uint32_t options) {
1000   ctx->options &= ~options;
1001   return ctx->options;
1002 }
1003 
SSL_clear_options(SSL * ssl,uint32_t options)1004 uint32_t SSL_clear_options(SSL *ssl, uint32_t options) {
1005   ssl->options &= ~options;
1006   return ssl->options;
1007 }
1008 
SSL_CTX_get_options(const SSL_CTX * ctx)1009 uint32_t SSL_CTX_get_options(const SSL_CTX *ctx) { return ctx->options; }
1010 
SSL_get_options(const SSL * ssl)1011 uint32_t SSL_get_options(const SSL *ssl) { return ssl->options; }
1012 
SSL_CTX_set_mode(SSL_CTX * ctx,uint32_t mode)1013 uint32_t SSL_CTX_set_mode(SSL_CTX *ctx, uint32_t mode) {
1014   ctx->mode |= mode;
1015   return ctx->mode;
1016 }
1017 
SSL_set_mode(SSL * ssl,uint32_t mode)1018 uint32_t SSL_set_mode(SSL *ssl, uint32_t mode) {
1019   ssl->mode |= mode;
1020   return ssl->mode;
1021 }
1022 
SSL_CTX_clear_mode(SSL_CTX * ctx,uint32_t mode)1023 uint32_t SSL_CTX_clear_mode(SSL_CTX *ctx, uint32_t mode) {
1024   ctx->mode &= ~mode;
1025   return ctx->mode;
1026 }
1027 
SSL_clear_mode(SSL * ssl,uint32_t mode)1028 uint32_t SSL_clear_mode(SSL *ssl, uint32_t mode) {
1029   ssl->mode &= ~mode;
1030   return ssl->mode;
1031 }
1032 
SSL_CTX_get_mode(const SSL_CTX * ctx)1033 uint32_t SSL_CTX_get_mode(const SSL_CTX *ctx) { return ctx->mode; }
1034 
SSL_get_mode(const SSL * ssl)1035 uint32_t SSL_get_mode(const SSL *ssl) { return ssl->mode; }
1036 
SSL_CTX_get_max_cert_list(const SSL_CTX * ctx)1037 size_t SSL_CTX_get_max_cert_list(const SSL_CTX *ctx) {
1038   return ctx->max_cert_list;
1039 }
1040 
SSL_CTX_set_max_cert_list(SSL_CTX * ctx,size_t max_cert_list)1041 void SSL_CTX_set_max_cert_list(SSL_CTX *ctx, size_t max_cert_list) {
1042   if (max_cert_list > kMaxHandshakeSize) {
1043     max_cert_list = kMaxHandshakeSize;
1044   }
1045   ctx->max_cert_list = (uint32_t)max_cert_list;
1046 }
1047 
SSL_get_max_cert_list(const SSL * ssl)1048 size_t SSL_get_max_cert_list(const SSL *ssl) {
1049   return ssl->max_cert_list;
1050 }
1051 
SSL_set_max_cert_list(SSL * ssl,size_t max_cert_list)1052 void SSL_set_max_cert_list(SSL *ssl, size_t max_cert_list) {
1053   if (max_cert_list > kMaxHandshakeSize) {
1054     max_cert_list = kMaxHandshakeSize;
1055   }
1056   ssl->max_cert_list = (uint32_t)max_cert_list;
1057 }
1058 
SSL_CTX_set_max_send_fragment(SSL_CTX * ctx,size_t max_send_fragment)1059 void SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, size_t max_send_fragment) {
1060   if (max_send_fragment < 512) {
1061     max_send_fragment = 512;
1062   }
1063   if (max_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1064     max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1065   }
1066   ctx->max_send_fragment = (uint16_t)max_send_fragment;
1067 }
1068 
SSL_set_max_send_fragment(SSL * ssl,size_t max_send_fragment)1069 void SSL_set_max_send_fragment(SSL *ssl, size_t max_send_fragment) {
1070   if (max_send_fragment < 512) {
1071     max_send_fragment = 512;
1072   }
1073   if (max_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1074     max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1075   }
1076   ssl->max_send_fragment = (uint16_t)max_send_fragment;
1077 }
1078 
SSL_set_mtu(SSL * ssl,unsigned mtu)1079 int SSL_set_mtu(SSL *ssl, unsigned mtu) {
1080   if (!SSL_IS_DTLS(ssl) || mtu < dtls1_min_mtu()) {
1081     return 0;
1082   }
1083   ssl->d1->mtu = mtu;
1084   return 1;
1085 }
1086 
SSL_get_secure_renegotiation_support(const SSL * ssl)1087 int SSL_get_secure_renegotiation_support(const SSL *ssl) {
1088   return ssl->s3->send_connection_binding;
1089 }
1090 
SSL_ctrl(SSL * s,int cmd,long larg,void * parg)1091 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg) {
1092   return s->method->ssl_ctrl(s, cmd, larg, parg);
1093 }
1094 
LHASH_OF(SSL_SESSION)1095 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx) { return ctx->sessions; }
1096 
SSL_CTX_sess_number(const SSL_CTX * ctx)1097 size_t SSL_CTX_sess_number(const SSL_CTX *ctx) {
1098   return lh_SSL_SESSION_num_items(ctx->sessions);
1099 }
1100 
SSL_CTX_sess_set_cache_size(SSL_CTX * ctx,unsigned long size)1101 unsigned long SSL_CTX_sess_set_cache_size(SSL_CTX *ctx, unsigned long size) {
1102   unsigned long ret = ctx->session_cache_size;
1103   ctx->session_cache_size = size;
1104   return ret;
1105 }
1106 
SSL_CTX_sess_get_cache_size(const SSL_CTX * ctx)1107 unsigned long SSL_CTX_sess_get_cache_size(const SSL_CTX *ctx) {
1108   return ctx->session_cache_size;
1109 }
1110 
SSL_CTX_set_session_cache_mode(SSL_CTX * ctx,int mode)1111 int SSL_CTX_set_session_cache_mode(SSL_CTX *ctx, int mode) {
1112   int ret = ctx->session_cache_mode;
1113   ctx->session_cache_mode = mode;
1114   return ret;
1115 }
1116 
SSL_CTX_get_session_cache_mode(const SSL_CTX * ctx)1117 int SSL_CTX_get_session_cache_mode(const SSL_CTX *ctx) {
1118   return ctx->session_cache_mode;
1119 }
1120 
SSL_CTX_ctrl(SSL_CTX * ctx,int cmd,long larg,void * parg)1121 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) {
1122   return ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg);
1123 }
1124 
1125 /* return a STACK of the ciphers available for the SSL and in order of
1126  * preference */
STACK_OF(SSL_CIPHER)1127 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s) {
1128   if (s == NULL) {
1129     return NULL;
1130   }
1131 
1132   if (s->cipher_list != NULL) {
1133     return s->cipher_list->ciphers;
1134   }
1135 
1136   if (s->version >= TLS1_1_VERSION && s->ctx != NULL &&
1137       s->ctx->cipher_list_tls11 != NULL) {
1138     return s->ctx->cipher_list_tls11->ciphers;
1139   }
1140 
1141   if (s->ctx != NULL && s->ctx->cipher_list != NULL) {
1142     return s->ctx->cipher_list->ciphers;
1143   }
1144 
1145   return NULL;
1146 }
1147 
1148 /* return a STACK of the ciphers available for the SSL and in order of
1149  * algorithm id */
STACK_OF(SSL_CIPHER)1150 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s) {
1151   if (s == NULL) {
1152     return NULL;
1153   }
1154 
1155   if (s->cipher_list_by_id != NULL) {
1156     return s->cipher_list_by_id;
1157   }
1158 
1159   if (s->ctx != NULL && s->ctx->cipher_list_by_id != NULL) {
1160     return s->ctx->cipher_list_by_id;
1161   }
1162 
1163   return NULL;
1164 }
1165 
1166 /* The old interface to get the same thing as SSL_get_ciphers() */
SSL_get_cipher_list(const SSL * s,int n)1167 const char *SSL_get_cipher_list(const SSL *s, int n) {
1168   const SSL_CIPHER *c;
1169   STACK_OF(SSL_CIPHER) *sk;
1170 
1171   if (s == NULL) {
1172     return NULL;
1173   }
1174 
1175   sk = SSL_get_ciphers(s);
1176   if (sk == NULL || n < 0 || (size_t)n >= sk_SSL_CIPHER_num(sk)) {
1177     return NULL;
1178   }
1179 
1180   c = sk_SSL_CIPHER_value(sk, n);
1181   if (c == NULL) {
1182     return NULL;
1183   }
1184 
1185   return c->name;
1186 }
1187 
1188 /* specify the ciphers to be used by default by the SSL_CTX */
SSL_CTX_set_cipher_list(SSL_CTX * ctx,const char * str)1189 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) {
1190   STACK_OF(SSL_CIPHER) *sk;
1191 
1192   sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
1193                               &ctx->cipher_list_by_id, str);
1194   /* ssl_create_cipher_list may return an empty stack if it was unable to find
1195    * a cipher matching the given rule string (for example if the rule string
1196    * specifies a cipher which has been disabled). This is not an error as far
1197    * as ssl_create_cipher_list is concerned, and hence ctx->cipher_list and
1198    * ctx->cipher_list_by_id has been updated. */
1199   if (sk == NULL) {
1200     return 0;
1201   } else if (sk_SSL_CIPHER_num(sk) == 0) {
1202     OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_cipher_list, SSL_R_NO_CIPHER_MATCH);
1203     return 0;
1204   }
1205 
1206   return 1;
1207 }
1208 
SSL_CTX_set_cipher_list_tls11(SSL_CTX * ctx,const char * str)1209 int SSL_CTX_set_cipher_list_tls11(SSL_CTX *ctx, const char *str) {
1210   STACK_OF(SSL_CIPHER) *sk;
1211 
1212   sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list_tls11, NULL, str);
1213   if (sk == NULL) {
1214     return 0;
1215   } else if (sk_SSL_CIPHER_num(sk) == 0) {
1216     OPENSSL_PUT_ERROR(SSL, SSL_CTX_set_cipher_list_tls11,
1217                       SSL_R_NO_CIPHER_MATCH);
1218     return 0;
1219   }
1220 
1221   return 1;
1222 }
1223 
1224 /* specify the ciphers to be used by the SSL */
SSL_set_cipher_list(SSL * s,const char * str)1225 int SSL_set_cipher_list(SSL *s, const char *str) {
1226   STACK_OF(SSL_CIPHER) *sk;
1227 
1228   sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
1229                               &s->cipher_list_by_id, str);
1230 
1231   /* see comment in SSL_CTX_set_cipher_list */
1232   if (sk == NULL) {
1233     return 0;
1234   } else if (sk_SSL_CIPHER_num(sk) == 0) {
1235     OPENSSL_PUT_ERROR(SSL, SSL_set_cipher_list, SSL_R_NO_CIPHER_MATCH);
1236     return 0;
1237   }
1238 
1239   return 1;
1240 }
1241 
ssl_cipher_list_to_bytes(SSL * s,STACK_OF (SSL_CIPHER)* sk,uint8_t * p)1242 int ssl_cipher_list_to_bytes(SSL *s, STACK_OF(SSL_CIPHER) *sk, uint8_t *p) {
1243   size_t i;
1244   const SSL_CIPHER *c;
1245   CERT *ct = s->cert;
1246   uint8_t *q;
1247   /* Set disabled masks for this session */
1248   ssl_set_client_disabled(s);
1249 
1250   if (sk == NULL) {
1251     return 0;
1252   }
1253   q = p;
1254 
1255   for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
1256     c = sk_SSL_CIPHER_value(sk, i);
1257     /* Skip disabled ciphers */
1258     if (c->algorithm_ssl & ct->mask_ssl ||
1259         c->algorithm_mkey & ct->mask_k ||
1260         c->algorithm_auth & ct->mask_a) {
1261       continue;
1262     }
1263     s2n(ssl_cipher_get_value(c), p);
1264   }
1265 
1266   /* If all ciphers were disabled, return the error to the caller. */
1267   if (p == q) {
1268     return 0;
1269   }
1270 
1271   /* Add SCSVs. */
1272   if (!s->s3->initial_handshake_complete) {
1273     s2n(SSL3_CK_SCSV & 0xffff, p);
1274   }
1275 
1276   if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
1277     s2n(SSL3_CK_FALLBACK_SCSV & 0xffff, p);
1278   }
1279 
1280   return p - q;
1281 }
1282 
STACK_OF(SSL_CIPHER)1283 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, const CBS *cbs) {
1284   CBS cipher_suites = *cbs;
1285   const SSL_CIPHER *c;
1286   STACK_OF(SSL_CIPHER) *sk;
1287 
1288   if (s->s3) {
1289     s->s3->send_connection_binding = 0;
1290   }
1291 
1292   if (CBS_len(&cipher_suites) % 2 != 0) {
1293     OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list,
1294                       SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
1295     return NULL;
1296   }
1297 
1298   sk = sk_SSL_CIPHER_new_null();
1299   if (sk == NULL) {
1300     OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_MALLOC_FAILURE);
1301     goto err;
1302   }
1303 
1304   while (CBS_len(&cipher_suites) > 0) {
1305     uint16_t cipher_suite;
1306 
1307     if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
1308       OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_INTERNAL_ERROR);
1309       goto err;
1310     }
1311 
1312     /* Check for SCSV. */
1313     if (s->s3 && cipher_suite == (SSL3_CK_SCSV & 0xffff)) {
1314       /* SCSV is fatal if renegotiating. */
1315       if (s->s3->initial_handshake_complete) {
1316         OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list,
1317                           SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1318         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1319         goto err;
1320       }
1321       s->s3->send_connection_binding = 1;
1322       continue;
1323     }
1324 
1325     /* Check for FALLBACK_SCSV. */
1326     if (s->s3 && cipher_suite == (SSL3_CK_FALLBACK_SCSV & 0xffff)) {
1327       uint16_t max_version = ssl3_get_max_server_version(s);
1328       if (SSL_IS_DTLS(s) ? (uint16_t)s->version > max_version
1329                          : (uint16_t)s->version < max_version) {
1330         OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list,
1331                           SSL_R_INAPPROPRIATE_FALLBACK);
1332         ssl3_send_alert(s, SSL3_AL_FATAL, SSL3_AD_INAPPROPRIATE_FALLBACK);
1333         goto err;
1334       }
1335       continue;
1336     }
1337 
1338     c = SSL_get_cipher_by_value(cipher_suite);
1339     if (c != NULL && !sk_SSL_CIPHER_push(sk, c)) {
1340       OPENSSL_PUT_ERROR(SSL, ssl_bytes_to_cipher_list, ERR_R_MALLOC_FAILURE);
1341       goto err;
1342     }
1343   }
1344 
1345   return sk;
1346 
1347 err:
1348   sk_SSL_CIPHER_free(sk);
1349   return NULL;
1350 }
1351 
1352 
1353 /* return a servername extension value if provided in Client Hello, or NULL. So
1354  * far, only host_name types are defined (RFC 3546). */
SSL_get_servername(const SSL * s,const int type)1355 const char *SSL_get_servername(const SSL *s, const int type) {
1356   if (type != TLSEXT_NAMETYPE_host_name) {
1357     return NULL;
1358   }
1359 
1360   return s->session && !s->tlsext_hostname ? s->session->tlsext_hostname
1361                                            : s->tlsext_hostname;
1362 }
1363 
SSL_get_servername_type(const SSL * s)1364 int SSL_get_servername_type(const SSL *s) {
1365   if (s->session &&
1366       (!s->tlsext_hostname ? s->session->tlsext_hostname : s->tlsext_hostname)) {
1367     return TLSEXT_NAMETYPE_host_name;
1368   }
1369 
1370   return -1;
1371 }
1372 
SSL_CTX_enable_signed_cert_timestamps(SSL_CTX * ctx)1373 void SSL_CTX_enable_signed_cert_timestamps(SSL_CTX *ctx) {
1374   ctx->signed_cert_timestamps_enabled = 1;
1375 }
1376 
SSL_enable_signed_cert_timestamps(SSL * ssl)1377 int SSL_enable_signed_cert_timestamps(SSL *ssl) {
1378   ssl->signed_cert_timestamps_enabled = 1;
1379   return 1;
1380 }
1381 
SSL_CTX_enable_ocsp_stapling(SSL_CTX * ctx)1382 void SSL_CTX_enable_ocsp_stapling(SSL_CTX *ctx) {
1383   ctx->ocsp_stapling_enabled = 1;
1384 }
1385 
SSL_enable_ocsp_stapling(SSL * ssl)1386 int SSL_enable_ocsp_stapling(SSL *ssl) {
1387   ssl->ocsp_stapling_enabled = 1;
1388   return 1;
1389 }
1390 
SSL_get0_signed_cert_timestamp_list(const SSL * ssl,const uint8_t ** out,size_t * out_len)1391 void SSL_get0_signed_cert_timestamp_list(const SSL *ssl, const uint8_t **out,
1392                                          size_t *out_len) {
1393   SSL_SESSION *session = ssl->session;
1394 
1395   *out_len = 0;
1396   *out = NULL;
1397   if (ssl->server || !session || !session->tlsext_signed_cert_timestamp_list) {
1398     return;
1399   }
1400 
1401   *out = session->tlsext_signed_cert_timestamp_list;
1402   *out_len = session->tlsext_signed_cert_timestamp_list_length;
1403 }
1404 
SSL_get0_ocsp_response(const SSL * ssl,const uint8_t ** out,size_t * out_len)1405 void SSL_get0_ocsp_response(const SSL *ssl, const uint8_t **out,
1406                             size_t *out_len) {
1407   SSL_SESSION *session = ssl->session;
1408 
1409   *out_len = 0;
1410   *out = NULL;
1411   if (ssl->server || !session || !session->ocsp_response) {
1412     return;
1413   }
1414   *out = session->ocsp_response;
1415   *out_len = session->ocsp_response_length;
1416 }
1417 
1418 /* SSL_select_next_proto implements the standard protocol selection. It is
1419  * expected that this function is called from the callback set by
1420  * SSL_CTX_set_next_proto_select_cb.
1421  *
1422  * The protocol data is assumed to be a vector of 8-bit, length prefixed byte
1423  * strings. The length byte itself is not included in the length. A byte
1424  * string of length 0 is invalid. No byte string may be truncated.
1425  *
1426  * The current, but experimental algorithm for selecting the protocol is:
1427  *
1428  * 1) If the server doesn't support NPN then this is indicated to the
1429  * callback. In this case, the client application has to abort the connection
1430  * or have a default application level protocol.
1431  *
1432  * 2) If the server supports NPN, but advertises an empty list then the
1433  * client selects the first protcol in its list, but indicates via the
1434  * API that this fallback case was enacted.
1435  *
1436  * 3) Otherwise, the client finds the first protocol in the server's list
1437  * that it supports and selects this protocol. This is because it's
1438  * assumed that the server has better information about which protocol
1439  * a client should use.
1440  *
1441  * 4) If the client doesn't support any of the server's advertised
1442  * protocols, then this is treated the same as case 2.
1443  *
1444  * It returns either
1445  * OPENSSL_NPN_NEGOTIATED if a common protocol was found, or
1446  * OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
1447  */
SSL_select_next_proto(uint8_t ** out,uint8_t * outlen,const uint8_t * server,unsigned int server_len,const uint8_t * client,unsigned int client_len)1448 int SSL_select_next_proto(uint8_t **out, uint8_t *outlen, const uint8_t *server,
1449                           unsigned int server_len, const uint8_t *client,
1450                           unsigned int client_len) {
1451   unsigned int i, j;
1452   const uint8_t *result;
1453   int status = OPENSSL_NPN_UNSUPPORTED;
1454 
1455   /* For each protocol in server preference order, see if we support it. */
1456   for (i = 0; i < server_len;) {
1457     for (j = 0; j < client_len;) {
1458       if (server[i] == client[j] &&
1459           memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
1460         /* We found a match */
1461         result = &server[i];
1462         status = OPENSSL_NPN_NEGOTIATED;
1463         goto found;
1464       }
1465       j += client[j];
1466       j++;
1467     }
1468     i += server[i];
1469     i++;
1470   }
1471 
1472   /* There's no overlap between our protocols and the server's list. */
1473   result = client;
1474   status = OPENSSL_NPN_NO_OVERLAP;
1475 
1476 found:
1477   *out = (uint8_t *)result + 1;
1478   *outlen = result[0];
1479   return status;
1480 }
1481 
1482 /* SSL_get0_next_proto_negotiated sets *data and *len to point to the client's
1483  * requested protocol for this connection and returns 0. If the client didn't
1484  * request any protocol, then *data is set to NULL.
1485  *
1486  * Note that the client can request any protocol it chooses. The value returned
1487  * from this function need not be a member of the list of supported protocols
1488  * provided by the callback. */
SSL_get0_next_proto_negotiated(const SSL * s,const uint8_t ** data,unsigned * len)1489 void SSL_get0_next_proto_negotiated(const SSL *s, const uint8_t **data,
1490                                     unsigned *len) {
1491   *data = s->next_proto_negotiated;
1492   if (!*data) {
1493     *len = 0;
1494   } else {
1495     *len = s->next_proto_negotiated_len;
1496   }
1497 }
1498 
1499 /* SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when a
1500  * TLS server needs a list of supported protocols for Next Protocol
1501  * Negotiation. The returned list must be in wire format.  The list is returned
1502  * by setting |out| to point to it and |outlen| to its length. This memory will
1503  * not be modified, but one should assume that the SSL* keeps a reference to
1504  * it.
1505  *
1506  * The callback should return SSL_TLSEXT_ERR_OK if it wishes to advertise.
1507  * Otherwise, no such extension will be included in the ServerHello. */
SSL_CTX_set_next_protos_advertised_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,const uint8_t ** out,unsigned int * outlen,void * arg),void * arg)1508 void SSL_CTX_set_next_protos_advertised_cb(
1509     SSL_CTX *ctx,
1510     int (*cb)(SSL *ssl, const uint8_t **out, unsigned int *outlen, void *arg),
1511     void *arg) {
1512   ctx->next_protos_advertised_cb = cb;
1513   ctx->next_protos_advertised_cb_arg = arg;
1514 }
1515 
1516 /* SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
1517  * client needs to select a protocol from the server's provided list. |out|
1518  * must be set to point to the selected protocol (which may be within |in|).
1519  * The length of the protocol name must be written into |outlen|. The server's
1520  * advertised protocols are provided in |in| and |inlen|. The callback can
1521  * assume that |in| is syntactically valid.
1522  *
1523  * The client must select a protocol. It is fatal to the connection if this
1524  * callback returns a value other than SSL_TLSEXT_ERR_OK.
1525  */
SSL_CTX_set_next_proto_select_cb(SSL_CTX * ctx,int (* cb)(SSL * s,uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned int inlen,void * arg),void * arg)1526 void SSL_CTX_set_next_proto_select_cb(
1527     SSL_CTX *ctx, int (*cb)(SSL *s, uint8_t **out, uint8_t *outlen,
1528                             const uint8_t *in, unsigned int inlen, void *arg),
1529     void *arg) {
1530   ctx->next_proto_select_cb = cb;
1531   ctx->next_proto_select_cb_arg = arg;
1532 }
1533 
SSL_CTX_set_alpn_protos(SSL_CTX * ctx,const uint8_t * protos,unsigned protos_len)1534 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos,
1535                             unsigned protos_len) {
1536   OPENSSL_free(ctx->alpn_client_proto_list);
1537   ctx->alpn_client_proto_list = BUF_memdup(protos, protos_len);
1538   if (!ctx->alpn_client_proto_list) {
1539     return 1;
1540   }
1541   ctx->alpn_client_proto_list_len = protos_len;
1542 
1543   return 0;
1544 }
1545 
SSL_set_alpn_protos(SSL * ssl,const uint8_t * protos,unsigned protos_len)1546 int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, unsigned protos_len) {
1547   OPENSSL_free(ssl->alpn_client_proto_list);
1548   ssl->alpn_client_proto_list = BUF_memdup(protos, protos_len);
1549   if (!ssl->alpn_client_proto_list) {
1550     return 1;
1551   }
1552   ssl->alpn_client_proto_list_len = protos_len;
1553 
1554   return 0;
1555 }
1556 
1557 /* SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is called
1558  * during ClientHello processing in order to select an ALPN protocol from the
1559  * client's list of offered protocols. */
SSL_CTX_set_alpn_select_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,const uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned int inlen,void * arg),void * arg)1560 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
1561                                 int (*cb)(SSL *ssl, const uint8_t **out,
1562                                           uint8_t *outlen, const uint8_t *in,
1563                                           unsigned int inlen, void *arg),
1564                                 void *arg) {
1565   ctx->alpn_select_cb = cb;
1566   ctx->alpn_select_cb_arg = arg;
1567 }
1568 
1569 /* SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from |ssl|.
1570  * On return it sets |*data| to point to |*len| bytes of protocol name (not
1571  * including the leading length-prefix byte). If the server didn't respond with
1572  * a negotiated protocol then |*len| will be zero. */
SSL_get0_alpn_selected(const SSL * ssl,const uint8_t ** data,unsigned * len)1573 void SSL_get0_alpn_selected(const SSL *ssl, const uint8_t **data,
1574                             unsigned *len) {
1575   *data = NULL;
1576   if (ssl->s3) {
1577     *data = ssl->s3->alpn_selected;
1578   }
1579   if (*data == NULL) {
1580     *len = 0;
1581   } else {
1582     *len = ssl->s3->alpn_selected_len;
1583   }
1584 }
1585 
SSL_export_keying_material(SSL * s,uint8_t * out,size_t out_len,const char * label,size_t label_len,const uint8_t * context,size_t context_len,int use_context)1586 int SSL_export_keying_material(SSL *s, uint8_t *out, size_t out_len,
1587                                const char *label, size_t label_len,
1588                                const uint8_t *context, size_t context_len,
1589                                int use_context) {
1590   if (s->version < TLS1_VERSION) {
1591     return 0;
1592   }
1593 
1594   return s->enc_method->export_keying_material(
1595       s, out, out_len, label, label_len, context, context_len, use_context);
1596 }
1597 
ssl_session_hash(const SSL_SESSION * a)1598 static uint32_t ssl_session_hash(const SSL_SESSION *a) {
1599   uint32_t hash =
1600       ((uint32_t)a->session_id[0]) ||
1601       ((uint32_t)a->session_id[1] << 8) ||
1602       ((uint32_t)a->session_id[2] << 16) ||
1603       ((uint32_t)a->session_id[3] << 24);
1604 
1605   return hash;
1606 }
1607 
1608 /* NB: If this function (or indeed the hash function which uses a sort of
1609  * coarser function than this one) is changed, ensure
1610  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on being
1611  * able to construct an SSL_SESSION that will collide with any existing session
1612  * with a matching session ID. */
ssl_session_cmp(const SSL_SESSION * a,const SSL_SESSION * b)1613 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b) {
1614   if (a->ssl_version != b->ssl_version) {
1615     return 1;
1616   }
1617 
1618   if (a->session_id_length != b->session_id_length) {
1619     return 1;
1620   }
1621 
1622   return memcmp(a->session_id, b->session_id, a->session_id_length);
1623 }
1624 
SSL_CTX_new(const SSL_METHOD * method)1625 SSL_CTX *SSL_CTX_new(const SSL_METHOD *method) {
1626   SSL_CTX *ret = NULL;
1627 
1628   if (method == NULL) {
1629     OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_NULL_SSL_METHOD_PASSED);
1630     return NULL;
1631   }
1632 
1633   if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
1634     OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
1635     goto err;
1636   }
1637 
1638   ret = (SSL_CTX *)OPENSSL_malloc(sizeof(SSL_CTX));
1639   if (ret == NULL) {
1640     goto err;
1641   }
1642 
1643   memset(ret, 0, sizeof(SSL_CTX));
1644 
1645   ret->method = method->method;
1646 
1647   CRYPTO_MUTEX_init(&ret->lock);
1648 
1649   ret->cert_store = NULL;
1650   ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
1651   ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
1652   ret->session_cache_head = NULL;
1653   ret->session_cache_tail = NULL;
1654 
1655   /* We take the system default */
1656   ret->session_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
1657 
1658   ret->new_session_cb = 0;
1659   ret->remove_session_cb = 0;
1660   ret->get_session_cb = 0;
1661   ret->generate_session_id = 0;
1662 
1663   ret->references = 1;
1664   ret->quiet_shutdown = 0;
1665 
1666   ret->info_callback = NULL;
1667 
1668   ret->app_verify_callback = 0;
1669   ret->app_verify_arg = NULL;
1670 
1671   ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
1672   ret->msg_callback = 0;
1673   ret->msg_callback_arg = NULL;
1674   ret->verify_mode = SSL_VERIFY_NONE;
1675   ret->sid_ctx_length = 0;
1676   ret->default_verify_callback = NULL;
1677   ret->cert = ssl_cert_new();
1678   if (ret->cert == NULL) {
1679     goto err;
1680   }
1681 
1682   ret->default_passwd_callback = 0;
1683   ret->default_passwd_callback_userdata = NULL;
1684   ret->client_cert_cb = 0;
1685 
1686   ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
1687   if (ret->sessions == NULL) {
1688     goto err;
1689   }
1690   ret->cert_store = X509_STORE_new();
1691   if (ret->cert_store == NULL) {
1692     goto err;
1693   }
1694 
1695   ssl_create_cipher_list(ret->method, &ret->cipher_list,
1696                          &ret->cipher_list_by_id, SSL_DEFAULT_CIPHER_LIST);
1697   if (ret->cipher_list == NULL ||
1698       sk_SSL_CIPHER_num(ret->cipher_list->ciphers) <= 0) {
1699     OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, SSL_R_LIBRARY_HAS_NO_CIPHERS);
1700     goto err2;
1701   }
1702 
1703   ret->param = X509_VERIFY_PARAM_new();
1704   if (!ret->param) {
1705     goto err;
1706   }
1707 
1708   ret->client_CA = sk_X509_NAME_new_null();
1709   if (ret->client_CA == NULL) {
1710     goto err;
1711   }
1712 
1713   CRYPTO_new_ex_data(&g_ex_data_class_ssl_ctx, ret, &ret->ex_data);
1714 
1715   ret->extra_certs = NULL;
1716 
1717   ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1718 
1719   ret->tlsext_servername_callback = 0;
1720   ret->tlsext_servername_arg = NULL;
1721   /* Setup RFC4507 ticket keys */
1722   if (!RAND_bytes(ret->tlsext_tick_key_name, 16) ||
1723       !RAND_bytes(ret->tlsext_tick_hmac_key, 16) ||
1724       !RAND_bytes(ret->tlsext_tick_aes_key, 16)) {
1725     ret->options |= SSL_OP_NO_TICKET;
1726   }
1727 
1728   ret->next_protos_advertised_cb = 0;
1729   ret->next_proto_select_cb = 0;
1730   ret->psk_identity_hint = NULL;
1731   ret->psk_client_callback = NULL;
1732   ret->psk_server_callback = NULL;
1733 
1734   /* Default is to connect to non-RI servers. When RI is more widely deployed
1735    * might change this. */
1736   ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
1737 
1738   /* Lock the SSL_CTX to the specified version, for compatibility with legacy
1739    * uses of SSL_METHOD. */
1740   if (method->version != 0) {
1741     SSL_CTX_set_max_version(ret, method->version);
1742     SSL_CTX_set_min_version(ret, method->version);
1743   }
1744 
1745   return ret;
1746 
1747 err:
1748   OPENSSL_PUT_ERROR(SSL, SSL_CTX_new, ERR_R_MALLOC_FAILURE);
1749 err2:
1750   SSL_CTX_free(ret);
1751   return NULL;
1752 }
1753 
SSL_CTX_free(SSL_CTX * ctx)1754 void SSL_CTX_free(SSL_CTX *ctx) {
1755   if (ctx == NULL ||
1756       !CRYPTO_refcount_dec_and_test_zero(&ctx->references)) {
1757     return;
1758   }
1759 
1760   X509_VERIFY_PARAM_free(ctx->param);
1761 
1762   /* Free internal session cache. However: the remove_cb() may reference the
1763    * ex_data of SSL_CTX, thus the ex_data store can only be removed after the
1764    * sessions were flushed. As the ex_data handling routines might also touch
1765    * the session cache, the most secure solution seems to be: empty (flush) the
1766    * cache, then free ex_data, then finally free the cache. (See ticket
1767    * [openssl.org #212].) */
1768   SSL_CTX_flush_sessions(ctx, 0);
1769 
1770   CRYPTO_free_ex_data(&g_ex_data_class_ssl_ctx, ctx, &ctx->ex_data);
1771 
1772   CRYPTO_MUTEX_cleanup(&ctx->lock);
1773   lh_SSL_SESSION_free(ctx->sessions);
1774   X509_STORE_free(ctx->cert_store);
1775   ssl_cipher_preference_list_free(ctx->cipher_list);
1776   sk_SSL_CIPHER_free(ctx->cipher_list_by_id);
1777   ssl_cipher_preference_list_free(ctx->cipher_list_tls11);
1778   ssl_cert_free(ctx->cert);
1779   sk_X509_NAME_pop_free(ctx->client_CA, X509_NAME_free);
1780   sk_X509_pop_free(ctx->extra_certs, X509_free);
1781   sk_SRTP_PROTECTION_PROFILE_free(ctx->srtp_profiles);
1782   OPENSSL_free(ctx->psk_identity_hint);
1783   OPENSSL_free(ctx->tlsext_ecpointformatlist);
1784   OPENSSL_free(ctx->tlsext_ellipticcurvelist);
1785   OPENSSL_free(ctx->alpn_client_proto_list);
1786   EVP_PKEY_free(ctx->tlsext_channel_id_private);
1787   BIO_free(ctx->keylog_bio);
1788 
1789   OPENSSL_free(ctx);
1790 }
1791 
SSL_CTX_set_default_passwd_cb(SSL_CTX * ctx,pem_password_cb * cb)1792 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb) {
1793   ctx->default_passwd_callback = cb;
1794 }
1795 
SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX * ctx,void * u)1796 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u) {
1797   ctx->default_passwd_callback_userdata = u;
1798 }
1799 
SSL_CTX_set_cert_verify_callback(SSL_CTX * ctx,int (* cb)(X509_STORE_CTX *,void *),void * arg)1800 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
1801                                       int (*cb)(X509_STORE_CTX *, void *),
1802                                       void *arg) {
1803   ctx->app_verify_callback = cb;
1804   ctx->app_verify_arg = arg;
1805 }
1806 
SSL_CTX_set_verify(SSL_CTX * ctx,int mode,int (* cb)(int,X509_STORE_CTX *))1807 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
1808                         int (*cb)(int, X509_STORE_CTX *)) {
1809   ctx->verify_mode = mode;
1810   ctx->default_verify_callback = cb;
1811 }
1812 
SSL_CTX_set_verify_depth(SSL_CTX * ctx,int depth)1813 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth) {
1814   X509_VERIFY_PARAM_set_depth(ctx->param, depth);
1815 }
1816 
SSL_CTX_set_cert_cb(SSL_CTX * c,int (* cb)(SSL * ssl,void * arg),void * arg)1817 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb)(SSL *ssl, void *arg),
1818                          void *arg) {
1819   ssl_cert_set_cert_cb(c->cert, cb, arg);
1820 }
1821 
SSL_set_cert_cb(SSL * s,int (* cb)(SSL * ssl,void * arg),void * arg)1822 void SSL_set_cert_cb(SSL *s, int (*cb)(SSL *ssl, void *arg), void *arg) {
1823   ssl_cert_set_cert_cb(s->cert, cb, arg);
1824 }
1825 
ssl_has_key(SSL * s,size_t idx)1826 static int ssl_has_key(SSL *s, size_t idx) {
1827   CERT_PKEY *cpk = &s->cert->pkeys[idx];
1828   return cpk->x509 && cpk->privatekey;
1829 }
1830 
ssl_get_compatible_server_ciphers(SSL * s,uint32_t * out_mask_k,uint32_t * out_mask_a)1831 void ssl_get_compatible_server_ciphers(SSL *s, uint32_t *out_mask_k,
1832                                        uint32_t *out_mask_a) {
1833   CERT *c = s->cert;
1834   int rsa_enc, rsa_sign, dh_tmp;
1835   uint32_t mask_k, mask_a;
1836   int have_ecc_cert, ecdsa_ok;
1837   X509 *x;
1838 
1839   if (c == NULL) {
1840     /* TODO(davidben): Is this codepath possible? */
1841     *out_mask_k = 0;
1842     *out_mask_a = 0;
1843     return;
1844   }
1845 
1846   dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL);
1847 
1848   rsa_enc = ssl_has_key(s, SSL_PKEY_RSA_ENC);
1849   rsa_sign = ssl_has_key(s, SSL_PKEY_RSA_SIGN);
1850   have_ecc_cert = ssl_has_key(s, SSL_PKEY_ECC);
1851   mask_k = 0;
1852   mask_a = 0;
1853 
1854   if (rsa_enc) {
1855     mask_k |= SSL_kRSA;
1856   }
1857   if (dh_tmp) {
1858     mask_k |= SSL_kDHE;
1859   }
1860   if (rsa_enc || rsa_sign) {
1861     mask_a |= SSL_aRSA;
1862   }
1863 
1864   /* An ECC certificate may be usable for ECDSA cipher suites depending on the
1865    * key usage extension and on the client's curve preferences. */
1866   if (have_ecc_cert) {
1867     x = c->pkeys[SSL_PKEY_ECC].x509;
1868     /* This call populates extension flags (ex_flags). */
1869     X509_check_purpose(x, -1, 0);
1870     ecdsa_ok = (x->ex_flags & EXFLAG_KUSAGE)
1871                    ? (x->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)
1872                    : 1;
1873     if (!tls1_check_ec_cert(s, x)) {
1874       ecdsa_ok = 0;
1875     }
1876     if (ecdsa_ok) {
1877       mask_a |= SSL_aECDSA;
1878     }
1879   }
1880 
1881   /* If we are considering an ECC cipher suite that uses an ephemeral EC
1882    * key, check it. */
1883   if (tls1_check_ec_tmp_key(s)) {
1884     mask_k |= SSL_kECDHE;
1885   }
1886 
1887   /* PSK requires a server callback. */
1888   if (s->psk_server_callback != NULL) {
1889     mask_k |= SSL_kPSK;
1890     mask_a |= SSL_aPSK;
1891   }
1892 
1893   *out_mask_k = mask_k;
1894   *out_mask_a = mask_a;
1895 }
1896 
1897 /* This handy macro borrowed from crypto/x509v3/v3_purp.c */
1898 #define ku_reject(x, usage) \
1899   (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
1900 
ssl_check_srvr_ecc_cert_and_alg(X509 * x,SSL * s)1901 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s) {
1902   const SSL_CIPHER *cs = s->s3->tmp.new_cipher;
1903   uint32_t alg_a = cs->algorithm_auth;
1904   int signature_nid = 0, md_nid = 0, pk_nid = 0;
1905 
1906   /* This call populates the ex_flags field correctly */
1907   X509_check_purpose(x, -1, 0);
1908   if (x->sig_alg && x->sig_alg->algorithm) {
1909     signature_nid = OBJ_obj2nid(x->sig_alg->algorithm);
1910     OBJ_find_sigid_algs(signature_nid, &md_nid, &pk_nid);
1911   }
1912   if (alg_a & SSL_aECDSA) {
1913     /* key usage, if present, must allow signing */
1914     if (ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE)) {
1915       OPENSSL_PUT_ERROR(SSL, ssl_check_srvr_ecc_cert_and_alg,
1916                         SSL_R_ECC_CERT_NOT_FOR_SIGNING);
1917       return 0;
1918     }
1919   }
1920 
1921   return 1; /* all checks are ok */
1922 }
1923 
ssl_get_server_cert_index(const SSL * s)1924 static int ssl_get_server_cert_index(const SSL *s) {
1925   int idx;
1926   idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
1927   if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509) {
1928     idx = SSL_PKEY_RSA_SIGN;
1929   }
1930   if (idx == -1) {
1931     OPENSSL_PUT_ERROR(SSL, ssl_get_server_cert_index, ERR_R_INTERNAL_ERROR);
1932   }
1933   return idx;
1934 }
1935 
ssl_get_server_send_pkey(const SSL * s)1936 CERT_PKEY *ssl_get_server_send_pkey(const SSL *s) {
1937   int i = ssl_get_server_cert_index(s);
1938 
1939   /* This may or may not be an error. */
1940   if (i < 0) {
1941     return NULL;
1942   }
1943 
1944   /* May be NULL. */
1945   return &s->cert->pkeys[i];
1946 }
1947 
ssl_get_sign_pkey(SSL * s,const SSL_CIPHER * cipher)1948 EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher) {
1949   uint32_t alg_a = cipher->algorithm_auth;
1950   CERT *c = s->cert;
1951   int idx = -1;
1952 
1953   if (alg_a & SSL_aRSA) {
1954     if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL) {
1955       idx = SSL_PKEY_RSA_SIGN;
1956     } else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL) {
1957       idx = SSL_PKEY_RSA_ENC;
1958     }
1959   } else if ((alg_a & SSL_aECDSA) &&
1960              (c->pkeys[SSL_PKEY_ECC].privatekey != NULL)) {
1961     idx = SSL_PKEY_ECC;
1962   }
1963 
1964   if (idx == -1) {
1965     OPENSSL_PUT_ERROR(SSL, ssl_get_sign_pkey, ERR_R_INTERNAL_ERROR);
1966     return NULL;
1967   }
1968 
1969   return c->pkeys[idx].privatekey;
1970 }
1971 
ssl_update_cache(SSL * s,int mode)1972 void ssl_update_cache(SSL *s, int mode) {
1973   /* Never cache sessions with empty session IDs. */
1974   if (s->session->session_id_length == 0) {
1975     return;
1976   }
1977 
1978   SSL_CTX *ctx = s->initial_ctx;
1979   if ((ctx->session_cache_mode & mode) == mode && !s->hit &&
1980       ((ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE) ||
1981        SSL_CTX_add_session(ctx, s->session)) &&
1982       ctx->new_session_cb != NULL) {
1983     /* Note: |new_session_cb| is called whether the internal session cache is
1984      * used or not. */
1985     if (!ctx->new_session_cb(s, SSL_SESSION_up_ref(s->session))) {
1986       SSL_SESSION_free(s->session);
1987     }
1988   }
1989 
1990   if (!(ctx->session_cache_mode & SSL_SESS_CACHE_NO_AUTO_CLEAR) &&
1991       !(ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE) &&
1992       (ctx->session_cache_mode & mode) == mode) {
1993     /* Automatically flush the internal session cache every 255 connections. */
1994     int flush_cache = 0;
1995     CRYPTO_MUTEX_lock_write(&ctx->lock);
1996     ctx->handshakes_since_cache_flush++;
1997     if (ctx->handshakes_since_cache_flush >= 255) {
1998       flush_cache = 1;
1999       ctx->handshakes_since_cache_flush = 0;
2000     }
2001     CRYPTO_MUTEX_unlock(&ctx->lock);
2002 
2003     if (flush_cache) {
2004       SSL_CTX_flush_sessions(ctx, (unsigned long)time(NULL));
2005     }
2006   }
2007 }
2008 
SSL_get_error(const SSL * s,int ret_code)2009 int SSL_get_error(const SSL *s, int ret_code) {
2010   int reason;
2011   uint32_t err;
2012   BIO *bio;
2013 
2014   if (ret_code > 0) {
2015     return SSL_ERROR_NONE;
2016   }
2017 
2018   /* Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
2019    * where we do encode the error */
2020   err = ERR_peek_error();
2021   if (err != 0) {
2022     if (ERR_GET_LIB(err) == ERR_LIB_SYS) {
2023       return SSL_ERROR_SYSCALL;
2024     }
2025     return SSL_ERROR_SSL;
2026   }
2027 
2028   if (ret_code == 0) {
2029     if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2030         (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY)) {
2031       /* The socket was cleanly shut down with a close_notify. */
2032       return SSL_ERROR_ZERO_RETURN;
2033     }
2034     /* An EOF was observed which violates the protocol, and the underlying
2035      * transport does not participate in the error queue. Bubble up to the
2036      * caller. */
2037     return SSL_ERROR_SYSCALL;
2038   }
2039 
2040   if (SSL_want_session(s)) {
2041     return SSL_ERROR_PENDING_SESSION;
2042   }
2043 
2044   if (SSL_want_certificate(s)) {
2045     return SSL_ERROR_PENDING_CERTIFICATE;
2046   }
2047 
2048   if (SSL_want_read(s)) {
2049     bio = SSL_get_rbio(s);
2050     if (BIO_should_read(bio)) {
2051       return SSL_ERROR_WANT_READ;
2052     }
2053 
2054     if (BIO_should_write(bio)) {
2055       /* This one doesn't make too much sense ... We never try to write to the
2056        * rbio, and an application program where rbio and wbio are separate
2057        * couldn't even know what it should wait for. However if we ever set
2058        * s->rwstate incorrectly (so that we have SSL_want_read(s) instead of
2059        * SSL_want_write(s)) and rbio and wbio *are* the same, this test works
2060        * around that bug; so it might be safer to keep it. */
2061       return SSL_ERROR_WANT_WRITE;
2062     }
2063 
2064     if (BIO_should_io_special(bio)) {
2065       reason = BIO_get_retry_reason(bio);
2066       if (reason == BIO_RR_CONNECT) {
2067         return SSL_ERROR_WANT_CONNECT;
2068       }
2069 
2070       if (reason == BIO_RR_ACCEPT) {
2071         return SSL_ERROR_WANT_ACCEPT;
2072       }
2073 
2074       return SSL_ERROR_SYSCALL; /* unknown */
2075     }
2076   }
2077 
2078   if (SSL_want_write(s)) {
2079     bio = SSL_get_wbio(s);
2080     if (BIO_should_write(bio)) {
2081       return SSL_ERROR_WANT_WRITE;
2082     }
2083 
2084     if (BIO_should_read(bio)) {
2085       /* See above (SSL_want_read(s) with BIO_should_write(bio)) */
2086       return SSL_ERROR_WANT_READ;
2087     }
2088 
2089     if (BIO_should_io_special(bio)) {
2090       reason = BIO_get_retry_reason(bio);
2091       if (reason == BIO_RR_CONNECT) {
2092         return SSL_ERROR_WANT_CONNECT;
2093       }
2094 
2095       if (reason == BIO_RR_ACCEPT) {
2096         return SSL_ERROR_WANT_ACCEPT;
2097       }
2098 
2099       return SSL_ERROR_SYSCALL;
2100     }
2101   }
2102 
2103   if (SSL_want_x509_lookup(s)) {
2104     return SSL_ERROR_WANT_X509_LOOKUP;
2105   }
2106 
2107   if (SSL_want_channel_id_lookup(s)) {
2108     return SSL_ERROR_WANT_CHANNEL_ID_LOOKUP;
2109   }
2110 
2111   return SSL_ERROR_SYSCALL;
2112 }
2113 
SSL_do_handshake(SSL * s)2114 int SSL_do_handshake(SSL *s) {
2115   int ret = 1;
2116 
2117   if (s->handshake_func == NULL) {
2118     OPENSSL_PUT_ERROR(SSL, SSL_do_handshake, SSL_R_CONNECTION_TYPE_NOT_SET);
2119     return -1;
2120   }
2121 
2122   if (SSL_in_init(s)) {
2123     ret = s->handshake_func(s);
2124   }
2125   return ret;
2126 }
2127 
SSL_set_accept_state(SSL * ssl)2128 void SSL_set_accept_state(SSL *ssl) {
2129   ssl->server = 1;
2130   ssl->shutdown = 0;
2131   ssl->state = SSL_ST_ACCEPT;
2132   ssl->handshake_func = ssl->method->ssl_accept;
2133   /* clear the current cipher */
2134   ssl_clear_cipher_ctx(ssl);
2135 }
2136 
SSL_set_connect_state(SSL * ssl)2137 void SSL_set_connect_state(SSL *ssl) {
2138   ssl->server = 0;
2139   ssl->shutdown = 0;
2140   ssl->state = SSL_ST_CONNECT;
2141   ssl->handshake_func = ssl->method->ssl_connect;
2142   /* clear the current cipher */
2143   ssl_clear_cipher_ctx(ssl);
2144 }
2145 
ssl_get_version(int version)2146 static const char *ssl_get_version(int version) {
2147   switch (version) {
2148     case TLS1_2_VERSION:
2149       return "TLSv1.2";
2150 
2151     case TLS1_1_VERSION:
2152       return "TLSv1.1";
2153 
2154     case TLS1_VERSION:
2155       return "TLSv1";
2156 
2157     case SSL3_VERSION:
2158       return "SSLv3";
2159 
2160     case DTLS1_VERSION:
2161       return "DTLSv1";
2162 
2163     case DTLS1_2_VERSION:
2164       return "DTLSv1.2";
2165 
2166     default:
2167       return "unknown";
2168   }
2169 }
2170 
SSL_get_version(const SSL * s)2171 const char *SSL_get_version(const SSL *s) {
2172   return ssl_get_version(s->version);
2173 }
2174 
SSL_SESSION_get_version(const SSL_SESSION * sess)2175 const char *SSL_SESSION_get_version(const SSL_SESSION *sess) {
2176   return ssl_get_version(sess->ssl_version);
2177 }
2178 
ssl_clear_cipher_ctx(SSL * s)2179 void ssl_clear_cipher_ctx(SSL *s) {
2180   SSL_AEAD_CTX_free(s->aead_read_ctx);
2181   s->aead_read_ctx = NULL;
2182   SSL_AEAD_CTX_free(s->aead_write_ctx);
2183   s->aead_write_ctx = NULL;
2184 }
2185 
SSL_get_certificate(const SSL * s)2186 X509 *SSL_get_certificate(const SSL *s) {
2187   if (s->cert != NULL) {
2188     return s->cert->key->x509;
2189   }
2190 
2191   return NULL;
2192 }
2193 
SSL_get_privatekey(const SSL * s)2194 EVP_PKEY *SSL_get_privatekey(const SSL *s) {
2195   if (s->cert != NULL) {
2196     return s->cert->key->privatekey;
2197   }
2198 
2199   return NULL;
2200 }
2201 
SSL_CTX_get0_certificate(const SSL_CTX * ctx)2202 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx) {
2203   if (ctx->cert != NULL) {
2204     return ctx->cert->key->x509;
2205   }
2206 
2207   return NULL;
2208 }
2209 
SSL_CTX_get0_privatekey(const SSL_CTX * ctx)2210 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx) {
2211   if (ctx->cert != NULL) {
2212     return ctx->cert->key->privatekey;
2213   }
2214 
2215   return NULL;
2216 }
2217 
SSL_get_current_cipher(const SSL * s)2218 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s) {
2219   if (s->aead_write_ctx == NULL) {
2220     return NULL;
2221   }
2222   return s->aead_write_ctx->cipher;
2223 }
2224 
SSL_get_current_compression(SSL * s)2225 const void *SSL_get_current_compression(SSL *s) { return NULL; }
2226 
SSL_get_current_expansion(SSL * s)2227 const void *SSL_get_current_expansion(SSL *s) { return NULL; }
2228 
ssl_init_wbio_buffer(SSL * s,int push)2229 int ssl_init_wbio_buffer(SSL *s, int push) {
2230   BIO *bbio;
2231 
2232   if (s->bbio == NULL) {
2233     bbio = BIO_new(BIO_f_buffer());
2234     if (bbio == NULL) {
2235       return 0;
2236     }
2237     s->bbio = bbio;
2238   } else {
2239     bbio = s->bbio;
2240     if (s->bbio == s->wbio) {
2241       s->wbio = BIO_pop(s->wbio);
2242     }
2243   }
2244 
2245   BIO_reset(bbio);
2246   if (!BIO_set_read_buffer_size(bbio, 1)) {
2247     OPENSSL_PUT_ERROR(SSL, ssl_init_wbio_buffer, ERR_R_BUF_LIB);
2248     return 0;
2249   }
2250 
2251   if (push) {
2252     if (s->wbio != bbio) {
2253       s->wbio = BIO_push(bbio, s->wbio);
2254     }
2255   } else {
2256     if (s->wbio == bbio) {
2257       s->wbio = BIO_pop(bbio);
2258     }
2259   }
2260 
2261   return 1;
2262 }
2263 
ssl_free_wbio_buffer(SSL * s)2264 void ssl_free_wbio_buffer(SSL *s) {
2265   if (s->bbio == NULL) {
2266     return;
2267   }
2268 
2269   if (s->bbio == s->wbio) {
2270     /* remove buffering */
2271     s->wbio = BIO_pop(s->wbio);
2272   }
2273 
2274   BIO_free(s->bbio);
2275   s->bbio = NULL;
2276 }
2277 
SSL_CTX_set_quiet_shutdown(SSL_CTX * ctx,int mode)2278 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode) {
2279   ctx->quiet_shutdown = mode;
2280 }
2281 
SSL_CTX_get_quiet_shutdown(const SSL_CTX * ctx)2282 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx) {
2283   return ctx->quiet_shutdown;
2284 }
2285 
SSL_set_quiet_shutdown(SSL * s,int mode)2286 void SSL_set_quiet_shutdown(SSL *s, int mode) { s->quiet_shutdown = mode; }
2287 
SSL_get_quiet_shutdown(const SSL * s)2288 int SSL_get_quiet_shutdown(const SSL *s) { return s->quiet_shutdown; }
2289 
SSL_set_shutdown(SSL * s,int mode)2290 void SSL_set_shutdown(SSL *s, int mode) { s->shutdown = mode; }
2291 
SSL_get_shutdown(const SSL * s)2292 int SSL_get_shutdown(const SSL *s) { return s->shutdown; }
2293 
SSL_version(const SSL * s)2294 int SSL_version(const SSL *s) { return s->version; }
2295 
SSL_get_SSL_CTX(const SSL * ssl)2296 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl) { return ssl->ctx; }
2297 
SSL_set_SSL_CTX(SSL * ssl,SSL_CTX * ctx)2298 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx) {
2299   if (ssl->ctx == ctx) {
2300     return ssl->ctx;
2301   }
2302 
2303   if (ctx == NULL) {
2304     ctx = ssl->initial_ctx;
2305   }
2306 
2307   ssl_cert_free(ssl->cert);
2308   ssl->cert = ssl_cert_dup(ctx->cert);
2309 
2310   CRYPTO_refcount_inc(&ctx->references);
2311   SSL_CTX_free(ssl->ctx); /* decrement reference count */
2312   ssl->ctx = ctx;
2313 
2314   ssl->sid_ctx_length = ctx->sid_ctx_length;
2315   assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
2316   memcpy(ssl->sid_ctx, ctx->sid_ctx, sizeof(ssl->sid_ctx));
2317 
2318   return ssl->ctx;
2319 }
2320 
SSL_CTX_set_default_verify_paths(SSL_CTX * ctx)2321 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx) {
2322   return X509_STORE_set_default_paths(ctx->cert_store);
2323 }
2324 
SSL_CTX_load_verify_locations(SSL_CTX * ctx,const char * CAfile,const char * CApath)2325 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
2326                                   const char *CApath) {
2327   return X509_STORE_load_locations(ctx->cert_store, CAfile, CApath);
2328 }
2329 
SSL_set_info_callback(SSL * ssl,void (* cb)(const SSL * ssl,int type,int val))2330 void SSL_set_info_callback(SSL *ssl,
2331                            void (*cb)(const SSL *ssl, int type, int val)) {
2332   ssl->info_callback = cb;
2333 }
2334 
SSL_get_info_callback(const SSL * ssl)2335 void (*SSL_get_info_callback(const SSL *ssl))(const SSL * /*ssl*/, int /*type*/,
2336                                               int /*val*/) {
2337   return ssl->info_callback;
2338 }
2339 
SSL_state(const SSL * ssl)2340 int SSL_state(const SSL *ssl) { return ssl->state; }
2341 
SSL_set_state(SSL * ssl,int state)2342 void SSL_set_state(SSL *ssl, int state) { }
2343 
SSL_set_verify_result(SSL * ssl,long arg)2344 void SSL_set_verify_result(SSL *ssl, long arg) { ssl->verify_result = arg; }
2345 
SSL_get_verify_result(const SSL * ssl)2346 long SSL_get_verify_result(const SSL *ssl) { return ssl->verify_result; }
2347 
SSL_get_ex_new_index(long argl,void * argp,CRYPTO_EX_new * new_func,CRYPTO_EX_dup * dup_func,CRYPTO_EX_free * free_func)2348 int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2349                          CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) {
2350   int index;
2351   if (!CRYPTO_get_ex_new_index(&g_ex_data_class_ssl, &index, argl, argp,
2352                                new_func, dup_func, free_func)) {
2353     return -1;
2354   }
2355   return index;
2356 }
2357 
SSL_set_ex_data(SSL * s,int idx,void * arg)2358 int SSL_set_ex_data(SSL *s, int idx, void *arg) {
2359   return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
2360 }
2361 
SSL_get_ex_data(const SSL * s,int idx)2362 void *SSL_get_ex_data(const SSL *s, int idx) {
2363   return CRYPTO_get_ex_data(&s->ex_data, idx);
2364 }
2365 
SSL_CTX_get_ex_new_index(long argl,void * argp,CRYPTO_EX_new * new_func,CRYPTO_EX_dup * dup_func,CRYPTO_EX_free * free_func)2366 int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
2367                              CRYPTO_EX_dup *dup_func,
2368                              CRYPTO_EX_free *free_func) {
2369   int index;
2370   if (!CRYPTO_get_ex_new_index(&g_ex_data_class_ssl_ctx, &index, argl, argp,
2371                                new_func, dup_func, free_func)) {
2372     return -1;
2373   }
2374   return index;
2375 }
2376 
SSL_CTX_set_ex_data(SSL_CTX * s,int idx,void * arg)2377 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg) {
2378   return CRYPTO_set_ex_data(&s->ex_data, idx, arg);
2379 }
2380 
SSL_CTX_get_ex_data(const SSL_CTX * s,int idx)2381 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx) {
2382   return CRYPTO_get_ex_data(&s->ex_data, idx);
2383 }
2384 
SSL_CTX_get_cert_store(const SSL_CTX * ctx)2385 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx) {
2386   return ctx->cert_store;
2387 }
2388 
SSL_CTX_set_cert_store(SSL_CTX * ctx,X509_STORE * store)2389 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store) {
2390   X509_STORE_free(ctx->cert_store);
2391   ctx->cert_store = store;
2392 }
2393 
SSL_want(const SSL * s)2394 int SSL_want(const SSL *s) { return s->rwstate; }
2395 
SSL_CTX_set_tmp_rsa_callback(SSL_CTX * ctx,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2396 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,
2397                                   RSA *(*cb)(SSL *ssl, int is_export,
2398                                              int keylength)) {
2399 }
2400 
SSL_set_tmp_rsa_callback(SSL * ssl,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2401 void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
2402                                                    int keylength)) {
2403 }
2404 
SSL_CTX_set_tmp_dh_callback(SSL_CTX * ctx,DH * (* callback)(SSL * ssl,int is_export,int keylength))2405 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
2406                                  DH *(*callback)(SSL *ssl, int is_export,
2407                                                  int keylength)) {
2408   ctx->cert->dh_tmp_cb = callback;
2409 }
2410 
SSL_set_tmp_dh_callback(SSL * ssl,DH * (* callback)(SSL * ssl,int is_export,int keylength))2411 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*callback)(SSL *ssl, int is_export,
2412                                                        int keylength)) {
2413   ssl->cert->dh_tmp_cb = callback;
2414 }
2415 
SSL_CTX_set_tmp_ecdh_callback(SSL_CTX * ctx,EC_KEY * (* callback)(SSL * ssl,int is_export,int keylength))2416 void SSL_CTX_set_tmp_ecdh_callback(SSL_CTX *ctx,
2417                                    EC_KEY *(*callback)(SSL *ssl, int is_export,
2418                                                        int keylength)) {
2419   ctx->cert->ecdh_tmp_cb = callback;
2420 }
2421 
SSL_set_tmp_ecdh_callback(SSL * ssl,EC_KEY * (* callback)(SSL * ssl,int is_export,int keylength))2422 void SSL_set_tmp_ecdh_callback(SSL *ssl,
2423                                EC_KEY *(*callback)(SSL *ssl, int is_export,
2424                                                    int keylength)) {
2425   ssl->cert->ecdh_tmp_cb = callback;
2426 }
2427 
SSL_CTX_use_psk_identity_hint(SSL_CTX * ctx,const char * identity_hint)2428 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint) {
2429   if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
2430     OPENSSL_PUT_ERROR(SSL, SSL_CTX_use_psk_identity_hint,
2431                       SSL_R_DATA_LENGTH_TOO_LONG);
2432     return 0;
2433   }
2434 
2435   OPENSSL_free(ctx->psk_identity_hint);
2436 
2437   if (identity_hint != NULL) {
2438     ctx->psk_identity_hint = BUF_strdup(identity_hint);
2439     if (ctx->psk_identity_hint == NULL) {
2440       return 0;
2441     }
2442   } else {
2443     ctx->psk_identity_hint = NULL;
2444   }
2445 
2446   return 1;
2447 }
2448 
SSL_use_psk_identity_hint(SSL * s,const char * identity_hint)2449 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint) {
2450   if (s == NULL) {
2451     return 0;
2452   }
2453 
2454   if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
2455     OPENSSL_PUT_ERROR(SSL, SSL_use_psk_identity_hint,
2456                       SSL_R_DATA_LENGTH_TOO_LONG);
2457     return 0;
2458   }
2459 
2460   /* Clear currently configured hint, if any. */
2461   OPENSSL_free(s->psk_identity_hint);
2462   s->psk_identity_hint = NULL;
2463 
2464   if (identity_hint != NULL) {
2465     s->psk_identity_hint = BUF_strdup(identity_hint);
2466     if (s->psk_identity_hint == NULL) {
2467       return 0;
2468     }
2469   }
2470 
2471   return 1;
2472 }
2473 
SSL_get_psk_identity_hint(const SSL * s)2474 const char *SSL_get_psk_identity_hint(const SSL *s) {
2475   if (s == NULL) {
2476     return NULL;
2477   }
2478   return s->psk_identity_hint;
2479 }
2480 
SSL_get_psk_identity(const SSL * s)2481 const char *SSL_get_psk_identity(const SSL *s) {
2482   if (s == NULL || s->session == NULL) {
2483     return NULL;
2484   }
2485 
2486   return s->session->psk_identity;
2487 }
2488 
SSL_set_psk_client_callback(SSL * s,unsigned int (* cb)(SSL * ssl,const char * hint,char * identity,unsigned int max_identity_len,uint8_t * psk,unsigned int max_psk_len))2489 void SSL_set_psk_client_callback(
2490     SSL *s, unsigned int (*cb)(SSL *ssl, const char *hint, char *identity,
2491                                unsigned int max_identity_len, uint8_t *psk,
2492                                unsigned int max_psk_len)) {
2493   s->psk_client_callback = cb;
2494 }
2495 
SSL_CTX_set_psk_client_callback(SSL_CTX * ctx,unsigned int (* cb)(SSL * ssl,const char * hint,char * identity,unsigned int max_identity_len,uint8_t * psk,unsigned int max_psk_len))2496 void SSL_CTX_set_psk_client_callback(
2497     SSL_CTX *ctx, unsigned int (*cb)(SSL *ssl, const char *hint, char *identity,
2498                                      unsigned int max_identity_len,
2499                                      uint8_t *psk, unsigned int max_psk_len)) {
2500   ctx->psk_client_callback = cb;
2501 }
2502 
SSL_set_psk_server_callback(SSL * s,unsigned int (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned int max_psk_len))2503 void SSL_set_psk_server_callback(
2504     SSL *s, unsigned int (*cb)(SSL *ssl, const char *identity, uint8_t *psk,
2505                                unsigned int max_psk_len)) {
2506   s->psk_server_callback = cb;
2507 }
2508 
SSL_CTX_set_psk_server_callback(SSL_CTX * ctx,unsigned int (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned int max_psk_len))2509 void SSL_CTX_set_psk_server_callback(
2510     SSL_CTX *ctx, unsigned int (*cb)(SSL *ssl, const char *identity,
2511                                      uint8_t *psk, unsigned int max_psk_len)) {
2512   ctx->psk_server_callback = cb;
2513 }
2514 
SSL_CTX_set_min_version(SSL_CTX * ctx,uint16_t version)2515 void SSL_CTX_set_min_version(SSL_CTX *ctx, uint16_t version) {
2516   ctx->min_version = version;
2517 }
2518 
SSL_CTX_set_max_version(SSL_CTX * ctx,uint16_t version)2519 void SSL_CTX_set_max_version(SSL_CTX *ctx, uint16_t version) {
2520   ctx->max_version = version;
2521 }
2522 
SSL_set_min_version(SSL * ssl,uint16_t version)2523 void SSL_set_min_version(SSL *ssl, uint16_t version) {
2524   ssl->min_version = version;
2525 }
2526 
SSL_set_max_version(SSL * ssl,uint16_t version)2527 void SSL_set_max_version(SSL *ssl, uint16_t version) {
2528   ssl->max_version = version;
2529 }
2530 
SSL_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))2531 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
2532                               void (*cb)(int write_p, int version,
2533                                          int content_type, const void *buf,
2534                                          size_t len, SSL *ssl, void *arg)) {
2535   ctx->msg_callback = cb;
2536 }
2537 
SSL_CTX_set_msg_callback_arg(SSL_CTX * ctx,void * arg)2538 void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg) {
2539   ctx->msg_callback_arg = arg;
2540 }
2541 
SSL_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))2542 void SSL_set_msg_callback(SSL *ssl,
2543                           void (*cb)(int write_p, int version, int content_type,
2544                                      const void *buf, size_t len, SSL *ssl,
2545                                      void *arg)) {
2546   ssl->msg_callback = cb;
2547 }
2548 
SSL_set_msg_callback_arg(SSL * ssl,void * arg)2549 void SSL_set_msg_callback_arg(SSL *ssl, void *arg) {
2550   ssl->msg_callback_arg = arg;
2551 }
2552 
SSL_CTX_set_keylog_bio(SSL_CTX * ctx,BIO * keylog_bio)2553 void SSL_CTX_set_keylog_bio(SSL_CTX *ctx, BIO *keylog_bio) {
2554   BIO_free(ctx->keylog_bio);
2555   ctx->keylog_bio = keylog_bio;
2556 }
2557 
cbb_add_hex(CBB * cbb,const uint8_t * in,size_t in_len)2558 static int cbb_add_hex(CBB *cbb, const uint8_t *in, size_t in_len) {
2559   static const char hextable[] = "0123456789abcdef";
2560   uint8_t *out;
2561   size_t i;
2562 
2563   if (!CBB_add_space(cbb, &out, in_len * 2)) {
2564     return 0;
2565   }
2566 
2567   for (i = 0; i < in_len; i++) {
2568     *(out++) = (uint8_t)hextable[in[i] >> 4];
2569     *(out++) = (uint8_t)hextable[in[i] & 0xf];
2570   }
2571 
2572   return 1;
2573 }
2574 
ssl_ctx_log_rsa_client_key_exchange(SSL_CTX * ctx,const uint8_t * encrypted_premaster,size_t encrypted_premaster_len,const uint8_t * premaster,size_t premaster_len)2575 int ssl_ctx_log_rsa_client_key_exchange(SSL_CTX *ctx,
2576                                         const uint8_t *encrypted_premaster,
2577                                         size_t encrypted_premaster_len,
2578                                         const uint8_t *premaster,
2579                                         size_t premaster_len) {
2580   BIO *bio = ctx->keylog_bio;
2581   CBB cbb;
2582   uint8_t *out;
2583   size_t out_len;
2584   int ret;
2585 
2586   if (bio == NULL) {
2587     return 1;
2588   }
2589 
2590   if (encrypted_premaster_len < 8) {
2591     OPENSSL_PUT_ERROR(SSL, ssl_ctx_log_rsa_client_key_exchange,
2592                       ERR_R_INTERNAL_ERROR);
2593     return 0;
2594   }
2595 
2596   if (!CBB_init(&cbb, 4 + 16 + 1 + premaster_len * 2 + 1)) {
2597     return 0;
2598   }
2599 
2600   if (!CBB_add_bytes(&cbb, (const uint8_t *)"RSA ", 4) ||
2601       /* Only the first 8 bytes of the encrypted premaster secret are
2602        * logged. */
2603       !cbb_add_hex(&cbb, encrypted_premaster, 8) ||
2604       !CBB_add_bytes(&cbb, (const uint8_t *)" ", 1) ||
2605       !cbb_add_hex(&cbb, premaster, premaster_len) ||
2606       !CBB_add_bytes(&cbb, (const uint8_t *)"\n", 1) ||
2607       !CBB_finish(&cbb, &out, &out_len)) {
2608     CBB_cleanup(&cbb);
2609     return 0;
2610   }
2611 
2612   CRYPTO_MUTEX_lock_write(&ctx->lock);
2613   ret = BIO_write(bio, out, out_len) >= 0 && BIO_flush(bio);
2614   CRYPTO_MUTEX_unlock(&ctx->lock);
2615 
2616   OPENSSL_free(out);
2617   return ret;
2618 }
2619 
ssl_ctx_log_master_secret(SSL_CTX * ctx,const uint8_t * client_random,size_t client_random_len,const uint8_t * master,size_t master_len)2620 int ssl_ctx_log_master_secret(SSL_CTX *ctx, const uint8_t *client_random,
2621                               size_t client_random_len, const uint8_t *master,
2622                               size_t master_len) {
2623   BIO *bio = ctx->keylog_bio;
2624   CBB cbb;
2625   uint8_t *out;
2626   size_t out_len;
2627   int ret;
2628 
2629   if (bio == NULL) {
2630     return 1;
2631   }
2632 
2633   if (client_random_len != 32) {
2634     OPENSSL_PUT_ERROR(SSL, ssl_ctx_log_master_secret, ERR_R_INTERNAL_ERROR);
2635     return 0;
2636   }
2637 
2638   if (!CBB_init(&cbb, 14 + 64 + 1 + master_len * 2 + 1)) {
2639     return 0;
2640   }
2641 
2642   if (!CBB_add_bytes(&cbb, (const uint8_t *)"CLIENT_RANDOM ", 14) ||
2643       !cbb_add_hex(&cbb, client_random, 32) ||
2644       !CBB_add_bytes(&cbb, (const uint8_t *)" ", 1) ||
2645       !cbb_add_hex(&cbb, master, master_len) ||
2646       !CBB_add_bytes(&cbb, (const uint8_t *)"\n", 1) ||
2647       !CBB_finish(&cbb, &out, &out_len)) {
2648     CBB_cleanup(&cbb);
2649     return 0;
2650   }
2651 
2652   CRYPTO_MUTEX_lock_write(&ctx->lock);
2653   ret = BIO_write(bio, out, out_len) >= 0 && BIO_flush(bio);
2654   CRYPTO_MUTEX_unlock(&ctx->lock);
2655 
2656   OPENSSL_free(out);
2657   return ret;
2658 }
2659 
SSL_in_false_start(const SSL * s)2660 int SSL_in_false_start(const SSL *s) {
2661   return s->s3->tmp.in_false_start;
2662 }
2663 
SSL_cutthrough_complete(const SSL * s)2664 int SSL_cutthrough_complete(const SSL *s) {
2665   return SSL_in_false_start(s);
2666 }
2667 
SSL_get_structure_sizes(size_t * ssl_size,size_t * ssl_ctx_size,size_t * ssl_session_size)2668 void SSL_get_structure_sizes(size_t *ssl_size, size_t *ssl_ctx_size,
2669                              size_t *ssl_session_size) {
2670   *ssl_size = sizeof(SSL);
2671   *ssl_ctx_size = sizeof(SSL_CTX);
2672   *ssl_session_size = sizeof(SSL_SESSION);
2673 }
2674 
ssl3_can_false_start(const SSL * s)2675 int ssl3_can_false_start(const SSL *s) {
2676   const SSL_CIPHER *const cipher = SSL_get_current_cipher(s);
2677 
2678   /* False Start only for TLS 1.2 with an ECDHE+AEAD cipher and ALPN or NPN. */
2679   return !SSL_IS_DTLS(s) &&
2680       SSL_version(s) >= TLS1_2_VERSION &&
2681       (s->s3->alpn_selected || s->s3->next_proto_neg_seen) &&
2682       cipher != NULL &&
2683       cipher->algorithm_mkey == SSL_kECDHE &&
2684       (cipher->algorithm_enc == SSL_AES128GCM ||
2685        cipher->algorithm_enc == SSL_AES256GCM ||
2686        cipher->algorithm_enc == SSL_CHACHA20POLY1305);
2687 }
2688 
ssl3_get_enc_method(uint16_t version)2689 const SSL3_ENC_METHOD *ssl3_get_enc_method(uint16_t version) {
2690   switch (version) {
2691     case SSL3_VERSION:
2692       return &SSLv3_enc_data;
2693 
2694     case TLS1_VERSION:
2695       return &TLSv1_enc_data;
2696 
2697     case DTLS1_VERSION:
2698     case TLS1_1_VERSION:
2699       return &TLSv1_1_enc_data;
2700 
2701     case DTLS1_2_VERSION:
2702     case TLS1_2_VERSION:
2703       return &TLSv1_2_enc_data;
2704 
2705     default:
2706       return NULL;
2707   }
2708 }
2709 
ssl3_get_max_server_version(const SSL * s)2710 uint16_t ssl3_get_max_server_version(const SSL *s) {
2711   uint16_t max_version;
2712 
2713   if (SSL_IS_DTLS(s)) {
2714     max_version = (s->max_version != 0) ? s->max_version : DTLS1_2_VERSION;
2715     if (!(s->options & SSL_OP_NO_DTLSv1_2) && DTLS1_2_VERSION >= max_version) {
2716       return DTLS1_2_VERSION;
2717     }
2718     if (!(s->options & SSL_OP_NO_DTLSv1) && DTLS1_VERSION >= max_version) {
2719       return DTLS1_VERSION;
2720     }
2721     return 0;
2722   }
2723 
2724   max_version = (s->max_version != 0) ? s->max_version : TLS1_2_VERSION;
2725   if (!(s->options & SSL_OP_NO_TLSv1_2) && TLS1_2_VERSION <= max_version) {
2726     return TLS1_2_VERSION;
2727   }
2728   if (!(s->options & SSL_OP_NO_TLSv1_1) && TLS1_1_VERSION <= max_version) {
2729     return TLS1_1_VERSION;
2730   }
2731   if (!(s->options & SSL_OP_NO_TLSv1) && TLS1_VERSION <= max_version) {
2732     return TLS1_VERSION;
2733   }
2734   if (!(s->options & SSL_OP_NO_SSLv3) && SSL3_VERSION <= max_version) {
2735     return SSL3_VERSION;
2736   }
2737   return 0;
2738 }
2739 
ssl3_get_mutual_version(SSL * s,uint16_t client_version)2740 uint16_t ssl3_get_mutual_version(SSL *s, uint16_t client_version) {
2741   uint16_t version = 0;
2742 
2743   if (SSL_IS_DTLS(s)) {
2744     /* Clamp client_version to max_version. */
2745     if (s->max_version != 0 && client_version < s->max_version) {
2746       client_version = s->max_version;
2747     }
2748 
2749     if (client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) {
2750       version = DTLS1_2_VERSION;
2751     } else if (client_version <= DTLS1_VERSION &&
2752                !(s->options & SSL_OP_NO_DTLSv1)) {
2753       version = DTLS1_VERSION;
2754     }
2755 
2756     /* Check against min_version. */
2757     if (version != 0 && s->min_version != 0 && version > s->min_version) {
2758       return 0;
2759     }
2760     return version;
2761   } else {
2762     /* Clamp client_version to max_version. */
2763     if (s->max_version != 0 && client_version > s->max_version) {
2764       client_version = s->max_version;
2765     }
2766 
2767     if (client_version >= TLS1_2_VERSION && !(s->options & SSL_OP_NO_TLSv1_2)) {
2768       version = TLS1_2_VERSION;
2769     } else if (client_version >= TLS1_1_VERSION &&
2770              !(s->options & SSL_OP_NO_TLSv1_1)) {
2771       version = TLS1_1_VERSION;
2772     } else if (client_version >= TLS1_VERSION && !(s->options & SSL_OP_NO_TLSv1)) {
2773       version = TLS1_VERSION;
2774     } else if (client_version >= SSL3_VERSION && !(s->options & SSL_OP_NO_SSLv3)) {
2775       version = SSL3_VERSION;
2776     }
2777 
2778     /* Check against min_version. */
2779     if (version != 0 && s->min_version != 0 && version < s->min_version) {
2780       return 0;
2781     }
2782     return version;
2783   }
2784 }
2785 
ssl3_get_max_client_version(SSL * s)2786 uint16_t ssl3_get_max_client_version(SSL *s) {
2787   uint32_t options = s->options;
2788   uint16_t version = 0;
2789 
2790   /* OpenSSL's API for controlling versions entails blacklisting individual
2791    * protocols. This has two problems. First, on the client, the protocol can
2792    * only express a contiguous range of versions. Second, a library consumer
2793    * trying to set a maximum version cannot disable protocol versions that get
2794    * added in a future version of the library.
2795    *
2796    * To account for both of these, OpenSSL interprets the client-side bitmask
2797    * as a min/max range by picking the lowest contiguous non-empty range of
2798    * enabled protocols. Note that this means it is impossible to set a maximum
2799    * version of TLS 1.2 in a future-proof way.
2800    *
2801    * By this scheme, the maximum version is the lowest version V such that V is
2802    * enabled and V+1 is disabled or unimplemented. */
2803   if (SSL_IS_DTLS(s)) {
2804     if (!(options & SSL_OP_NO_DTLSv1_2)) {
2805       version = DTLS1_2_VERSION;
2806     }
2807     if (!(options & SSL_OP_NO_DTLSv1) && (options & SSL_OP_NO_DTLSv1_2)) {
2808       version = DTLS1_VERSION;
2809     }
2810     if (s->max_version != 0 && version < s->max_version) {
2811       version = s->max_version;
2812     }
2813   } else {
2814     if (!(options & SSL_OP_NO_TLSv1_2)) {
2815       version = TLS1_2_VERSION;
2816     }
2817     if (!(options & SSL_OP_NO_TLSv1_1) && (options & SSL_OP_NO_TLSv1_2)) {
2818       version = TLS1_1_VERSION;
2819     }
2820     if (!(options & SSL_OP_NO_TLSv1) && (options & SSL_OP_NO_TLSv1_1)) {
2821       version = TLS1_VERSION;
2822     }
2823     if (!(options & SSL_OP_NO_SSLv3) && (options & SSL_OP_NO_TLSv1)) {
2824       version = SSL3_VERSION;
2825     }
2826     if (s->max_version != 0 && version > s->max_version) {
2827       version = s->max_version;
2828     }
2829   }
2830 
2831   return version;
2832 }
2833 
ssl3_is_version_enabled(SSL * s,uint16_t version)2834 int ssl3_is_version_enabled(SSL *s, uint16_t version) {
2835   if (SSL_IS_DTLS(s)) {
2836     if (s->max_version != 0 && version < s->max_version) {
2837       return 0;
2838     }
2839     if (s->min_version != 0 && version > s->min_version) {
2840       return 0;
2841     }
2842 
2843     switch (version) {
2844       case DTLS1_VERSION:
2845         return !(s->options & SSL_OP_NO_DTLSv1);
2846 
2847       case DTLS1_2_VERSION:
2848         return !(s->options & SSL_OP_NO_DTLSv1_2);
2849 
2850       default:
2851         return 0;
2852     }
2853   } else {
2854     if (s->max_version != 0 && version > s->max_version) {
2855       return 0;
2856     }
2857     if (s->min_version != 0 && version < s->min_version) {
2858       return 0;
2859     }
2860 
2861     switch (version) {
2862       case SSL3_VERSION:
2863         return !(s->options & SSL_OP_NO_SSLv3);
2864 
2865       case TLS1_VERSION:
2866         return !(s->options & SSL_OP_NO_TLSv1);
2867 
2868       case TLS1_1_VERSION:
2869         return !(s->options & SSL_OP_NO_TLSv1_1);
2870 
2871       case TLS1_2_VERSION:
2872         return !(s->options & SSL_OP_NO_TLSv1_2);
2873 
2874       default:
2875         return 0;
2876     }
2877   }
2878 }
2879 
ssl3_version_from_wire(SSL * s,uint16_t wire_version)2880 uint16_t ssl3_version_from_wire(SSL *s, uint16_t wire_version) {
2881   if (!SSL_IS_DTLS(s)) {
2882     return wire_version;
2883   }
2884 
2885   uint16_t tls_version = ~wire_version;
2886   uint16_t version = tls_version + 0x0201;
2887   /* If either component overflowed, clamp it so comparisons still work. */
2888   if ((version >> 8) < (tls_version >> 8)) {
2889     version = 0xff00 | (version & 0xff);
2890   }
2891   if ((version & 0xff) < (tls_version & 0xff)) {
2892     version = (version & 0xff00) | 0xff;
2893   }
2894   /* DTLS 1.0 maps to TLS 1.1, not TLS 1.0. */
2895   if (version == TLS1_VERSION) {
2896     version = TLS1_1_VERSION;
2897   }
2898   return version;
2899 }
2900 
SSL_cache_hit(SSL * s)2901 int SSL_cache_hit(SSL *s) { return s->hit; }
2902 
SSL_is_server(SSL * s)2903 int SSL_is_server(SSL *s) { return s->server; }
2904 
SSL_CTX_set_dos_protection_cb(SSL_CTX * ctx,int (* cb)(const struct ssl_early_callback_ctx *))2905 void SSL_CTX_set_dos_protection_cb(
2906     SSL_CTX *ctx, int (*cb)(const struct ssl_early_callback_ctx *)) {
2907   ctx->dos_protection_cb = cb;
2908 }
2909 
SSL_enable_fastradio_padding(SSL * s,char on_off)2910 void SSL_enable_fastradio_padding(SSL *s, char on_off) {
2911   s->fastradio_padding = on_off;
2912 }
2913 
SSL_set_reject_peer_renegotiations(SSL * s,int reject)2914 void SSL_set_reject_peer_renegotiations(SSL *s, int reject) {
2915   s->accept_peer_renegotiations = !reject;
2916 }
2917 
SSL_get_rc4_state(const SSL * ssl,const RC4_KEY ** read_key,const RC4_KEY ** write_key)2918 int SSL_get_rc4_state(const SSL *ssl, const RC4_KEY **read_key,
2919                       const RC4_KEY **write_key) {
2920   if (ssl->aead_read_ctx == NULL || ssl->aead_write_ctx == NULL) {
2921     return 0;
2922   }
2923 
2924   return EVP_AEAD_CTX_get_rc4_state(&ssl->aead_read_ctx->ctx, read_key) &&
2925          EVP_AEAD_CTX_get_rc4_state(&ssl->aead_write_ctx->ctx, write_key);
2926 }
2927 
SSL_get_tls_unique(const SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)2928 int SSL_get_tls_unique(const SSL *ssl, uint8_t *out, size_t *out_len,
2929                        size_t max_out) {
2930   /* The tls-unique value is the first Finished message in the handshake, which
2931    * is the client's in a full handshake and the server's for a resumption. See
2932    * https://tools.ietf.org/html/rfc5929#section-3.1. */
2933   const uint8_t *finished = ssl->s3->previous_client_finished;
2934   size_t finished_len = ssl->s3->previous_client_finished_len;
2935   if (ssl->hit) {
2936     /* tls-unique is broken for resumed sessions unless EMS is used. */
2937     if (!ssl->session->extended_master_secret) {
2938       goto err;
2939     }
2940     finished = ssl->s3->previous_server_finished;
2941     finished_len = ssl->s3->previous_server_finished_len;
2942   }
2943 
2944   if (!ssl->s3->initial_handshake_complete ||
2945       ssl->version < TLS1_VERSION) {
2946     goto err;
2947   }
2948 
2949   *out_len = finished_len;
2950   if (finished_len > max_out) {
2951     *out_len = max_out;
2952   }
2953 
2954   memcpy(out, finished, *out_len);
2955   return 1;
2956 
2957 err:
2958   *out_len = 0;
2959   memset(out, 0, max_out);
2960   return 0;
2961 }
2962 
SSL_CTX_sess_connect(const SSL_CTX * ctx)2963 int SSL_CTX_sess_connect(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_good(const SSL_CTX * ctx)2964 int SSL_CTX_sess_connect_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_renegotiate(const SSL_CTX * ctx)2965 int SSL_CTX_sess_connect_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept(const SSL_CTX * ctx)2966 int SSL_CTX_sess_accept(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_renegotiate(const SSL_CTX * ctx)2967 int SSL_CTX_sess_accept_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_good(const SSL_CTX * ctx)2968 int SSL_CTX_sess_accept_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_hits(const SSL_CTX * ctx)2969 int SSL_CTX_sess_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cb_hits(const SSL_CTX * ctx)2970 int SSL_CTX_sess_cb_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_misses(const SSL_CTX * ctx)2971 int SSL_CTX_sess_misses(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_timeouts(const SSL_CTX * ctx)2972 int SSL_CTX_sess_timeouts(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cache_full(const SSL_CTX * ctx)2973 int SSL_CTX_sess_cache_full(const SSL_CTX *ctx) { return 0; }
2974