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