xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/ssl/ssl_lib.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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  *    [email protected].
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  * ([email protected]).  This product includes software written by Tim
107  * Hudson ([email protected]).
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 <algorithm>
144 
145 #include <assert.h>
146 #include <limits.h>
147 #include <stdlib.h>
148 #include <string.h>
149 
150 #include <openssl/bytestring.h>
151 #include <openssl/crypto.h>
152 #include <openssl/err.h>
153 #include <openssl/lhash.h>
154 #include <openssl/mem.h>
155 #include <openssl/rand.h>
156 
157 #include "internal.h"
158 #include "../crypto/internal.h"
159 
160 #if defined(OPENSSL_WINDOWS)
161 #include <sys/timeb.h>
162 #else
163 #include <sys/socket.h>
164 #include <sys/time.h>
165 #endif
166 
167 
168 BSSL_NAMESPACE_BEGIN
169 
170 static_assert(SSL3_RT_MAX_ENCRYPTED_OVERHEAD >=
171                   SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD,
172               "max overheads are inconsistent");
173 
174 // |SSL_R_UNKNOWN_PROTOCOL| is no longer emitted, but continue to define it
175 // to avoid downstream churn.
176 OPENSSL_DECLARE_ERROR_REASON(SSL, UNKNOWN_PROTOCOL)
177 
178 // The following errors are no longer emitted, but are used in nginx without
179 // #ifdefs.
180 OPENSSL_DECLARE_ERROR_REASON(SSL, BLOCK_CIPHER_PAD_IS_WRONG)
181 OPENSSL_DECLARE_ERROR_REASON(SSL, NO_CIPHERS_SPECIFIED)
182 
183 // Some error codes are special. Ensure the make_errors.go script never
184 // regresses this.
185 static_assert(SSL_R_TLSV1_ALERT_NO_RENEGOTIATION ==
186                   SSL_AD_NO_RENEGOTIATION + SSL_AD_REASON_OFFSET,
187               "alert reason code mismatch");
188 
189 // kMaxHandshakeSize is the maximum size, in bytes, of a handshake message.
190 static const size_t kMaxHandshakeSize = (1u << 24) - 1;
191 
192 static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl =
193     CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
194 static CRYPTO_EX_DATA_CLASS g_ex_data_class_ssl_ctx =
195     CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
196 
CBBFinishArray(CBB * cbb,Array<uint8_t> * out)197 bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out) {
198   uint8_t *ptr;
199   size_t len;
200   if (!CBB_finish(cbb, &ptr, &len)) {
201     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
202     return false;
203   }
204   out->Reset(ptr, len);
205   return true;
206 }
207 
ssl_reset_error_state(SSL * ssl)208 void ssl_reset_error_state(SSL *ssl) {
209   // Functions which use |SSL_get_error| must reset I/O and error state on
210   // entry.
211   ssl->s3->rwstate = SSL_ERROR_NONE;
212   ERR_clear_error();
213   ERR_clear_system_error();
214 }
215 
ssl_set_read_error(SSL * ssl)216 void ssl_set_read_error(SSL* ssl) {
217   ssl->s3->read_shutdown = ssl_shutdown_error;
218   ssl->s3->read_error.reset(ERR_save_state());
219 }
220 
check_read_error(const SSL * ssl)221 static bool check_read_error(const SSL *ssl) {
222   if (ssl->s3->read_shutdown == ssl_shutdown_error) {
223     ERR_restore_state(ssl->s3->read_error.get());
224     return false;
225   }
226   return true;
227 }
228 
ssl_can_write(const SSL * ssl)229 bool ssl_can_write(const SSL *ssl) {
230   return !SSL_in_init(ssl) || ssl->s3->hs->can_early_write;
231 }
232 
ssl_can_read(const SSL * ssl)233 bool ssl_can_read(const SSL *ssl) {
234   return !SSL_in_init(ssl) || ssl->s3->hs->can_early_read;
235 }
236 
ssl_open_handshake(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)237 ssl_open_record_t ssl_open_handshake(SSL *ssl, size_t *out_consumed,
238                                      uint8_t *out_alert, Span<uint8_t> in) {
239   *out_consumed = 0;
240   if (!check_read_error(ssl)) {
241     *out_alert = 0;
242     return ssl_open_record_error;
243   }
244   auto ret = ssl->method->open_handshake(ssl, out_consumed, out_alert, in);
245   if (ret == ssl_open_record_error) {
246     ssl_set_read_error(ssl);
247   }
248   return ret;
249 }
250 
ssl_open_change_cipher_spec(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)251 ssl_open_record_t ssl_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
252                                               uint8_t *out_alert,
253                                               Span<uint8_t> in) {
254   *out_consumed = 0;
255   if (!check_read_error(ssl)) {
256     *out_alert = 0;
257     return ssl_open_record_error;
258   }
259   auto ret =
260       ssl->method->open_change_cipher_spec(ssl, out_consumed, out_alert, in);
261   if (ret == ssl_open_record_error) {
262     ssl_set_read_error(ssl);
263   }
264   return ret;
265 }
266 
ssl_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)267 ssl_open_record_t ssl_open_app_data(SSL *ssl, Span<uint8_t> *out,
268                                     size_t *out_consumed, uint8_t *out_alert,
269                                     Span<uint8_t> in) {
270   *out_consumed = 0;
271   if (!check_read_error(ssl)) {
272     *out_alert = 0;
273     return ssl_open_record_error;
274   }
275   auto ret = ssl->method->open_app_data(ssl, out, out_consumed, out_alert, in);
276   if (ret == ssl_open_record_error) {
277     ssl_set_read_error(ssl);
278   }
279   return ret;
280 }
281 
cbb_add_hex(CBB * cbb,Span<const uint8_t> in)282 static bool cbb_add_hex(CBB *cbb, Span<const uint8_t> in) {
283   static const char hextable[] = "0123456789abcdef";
284   uint8_t *out;
285 
286   if (!CBB_add_space(cbb, &out, in.size() * 2)) {
287     return false;
288   }
289 
290   for (uint8_t b : in) {
291     *(out++) = (uint8_t)hextable[b >> 4];
292     *(out++) = (uint8_t)hextable[b & 0xf];
293   }
294 
295   return true;
296 }
297 
ssl_log_secret(const SSL * ssl,const char * label,Span<const uint8_t> secret)298 bool ssl_log_secret(const SSL *ssl, const char *label,
299                     Span<const uint8_t> secret) {
300   if (ssl->ctx->keylog_callback == NULL) {
301     return true;
302   }
303 
304   ScopedCBB cbb;
305   Array<uint8_t> line;
306   if (!CBB_init(cbb.get(), strlen(label) + 1 + SSL3_RANDOM_SIZE * 2 + 1 +
307                                secret.size() * 2 + 1) ||
308       !CBB_add_bytes(cbb.get(), reinterpret_cast<const uint8_t *>(label),
309                      strlen(label)) ||
310       !CBB_add_u8(cbb.get(), ' ') ||
311       !cbb_add_hex(cbb.get(), ssl->s3->client_random) ||
312       !CBB_add_u8(cbb.get(), ' ') ||
313       !cbb_add_hex(cbb.get(), secret) ||
314       !CBB_add_u8(cbb.get(), 0 /* NUL */) ||
315       !CBBFinishArray(cbb.get(), &line)) {
316     return false;
317   }
318 
319   ssl->ctx->keylog_callback(ssl, reinterpret_cast<const char *>(line.data()));
320   return true;
321 }
322 
ssl_do_info_callback(const SSL * ssl,int type,int value)323 void ssl_do_info_callback(const SSL *ssl, int type, int value) {
324   void (*cb)(const SSL *ssl, int type, int value) = NULL;
325   if (ssl->info_callback != NULL) {
326     cb = ssl->info_callback;
327   } else if (ssl->ctx->info_callback != NULL) {
328     cb = ssl->ctx->info_callback;
329   }
330 
331   if (cb != NULL) {
332     cb(ssl, type, value);
333   }
334 }
335 
ssl_do_msg_callback(const SSL * ssl,int is_write,int content_type,Span<const uint8_t> in)336 void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type,
337                          Span<const uint8_t> in) {
338   if (ssl->msg_callback == NULL) {
339     return;
340   }
341 
342   // |version| is zero when calling for |SSL3_RT_HEADER| and |SSL2_VERSION| for
343   // a V2ClientHello.
344   int version;
345   switch (content_type) {
346     case 0:
347       // V2ClientHello
348       version = SSL2_VERSION;
349       break;
350     case SSL3_RT_HEADER:
351       version = 0;
352       break;
353     default:
354       version = SSL_version(ssl);
355   }
356 
357   ssl->msg_callback(is_write, version, content_type, in.data(), in.size(),
358                     const_cast<SSL *>(ssl), ssl->msg_callback_arg);
359 }
360 
ssl_get_current_time(const SSL * ssl,struct OPENSSL_timeval * out_clock)361 void ssl_get_current_time(const SSL *ssl, struct OPENSSL_timeval *out_clock) {
362   // TODO(martinkr): Change callers to |ssl_ctx_get_current_time| and drop the
363   // |ssl| arg from |current_time_cb| if possible.
364   ssl_ctx_get_current_time(ssl->ctx.get(), out_clock);
365 }
366 
ssl_ctx_get_current_time(const SSL_CTX * ctx,struct OPENSSL_timeval * out_clock)367 void ssl_ctx_get_current_time(const SSL_CTX *ctx,
368                               struct OPENSSL_timeval *out_clock) {
369   if (ctx->current_time_cb != NULL) {
370     // TODO(davidben): Update current_time_cb to use OPENSSL_timeval. See
371     // https://crbug.com/boringssl/155.
372     struct timeval clock;
373     ctx->current_time_cb(nullptr /* ssl */, &clock);
374     if (clock.tv_sec < 0) {
375       assert(0);
376       out_clock->tv_sec = 0;
377       out_clock->tv_usec = 0;
378     } else {
379       out_clock->tv_sec = (uint64_t)clock.tv_sec;
380       out_clock->tv_usec = (uint32_t)clock.tv_usec;
381     }
382     return;
383   }
384 
385 #if defined(BORINGSSL_UNSAFE_DETERMINISTIC_MODE)
386   out_clock->tv_sec = 1234;
387   out_clock->tv_usec = 1234;
388 #elif defined(OPENSSL_WINDOWS)
389   struct _timeb time;
390   _ftime(&time);
391   if (time.time < 0) {
392     assert(0);
393     out_clock->tv_sec = 0;
394     out_clock->tv_usec = 0;
395   } else {
396     out_clock->tv_sec = time.time;
397     out_clock->tv_usec = time.millitm * 1000;
398   }
399 #else
400   struct timeval clock;
401   gettimeofday(&clock, NULL);
402   if (clock.tv_sec < 0) {
403     assert(0);
404     out_clock->tv_sec = 0;
405     out_clock->tv_usec = 0;
406   } else {
407     out_clock->tv_sec = (uint64_t)clock.tv_sec;
408     out_clock->tv_usec = (uint32_t)clock.tv_usec;
409   }
410 #endif
411 }
412 
SSL_CTX_set_handoff_mode(SSL_CTX * ctx,bool on)413 void SSL_CTX_set_handoff_mode(SSL_CTX *ctx, bool on) {
414   ctx->handoff = on;
415 }
416 
ssl_can_renegotiate(const SSL * ssl)417 static bool ssl_can_renegotiate(const SSL *ssl) {
418   if (ssl->server || SSL_is_dtls(ssl)) {
419     return false;
420   }
421 
422   if (ssl->s3->have_version &&
423       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
424     return false;
425   }
426 
427   // The config has already been shed.
428   if (!ssl->config) {
429     return false;
430   }
431 
432   switch (ssl->renegotiate_mode) {
433     case ssl_renegotiate_ignore:
434     case ssl_renegotiate_never:
435       return false;
436 
437     case ssl_renegotiate_freely:
438     case ssl_renegotiate_explicit:
439       return true;
440     case ssl_renegotiate_once:
441       return ssl->s3->total_renegotiations == 0;
442   }
443 
444   assert(0);
445   return false;
446 }
447 
ssl_maybe_shed_handshake_config(SSL * ssl)448 static void ssl_maybe_shed_handshake_config(SSL *ssl) {
449   if (ssl->s3->hs != nullptr ||
450       ssl->config == nullptr ||
451       !ssl->config->shed_handshake_config ||
452       ssl_can_renegotiate(ssl)) {
453     return;
454   }
455 
456   ssl->config.reset();
457 }
458 
SSL_set_handoff_mode(SSL * ssl,bool on)459 void SSL_set_handoff_mode(SSL *ssl, bool on) {
460   if (!ssl->config) {
461     return;
462   }
463   ssl->config->handoff = on;
464 }
465 
SSL_get_traffic_secrets(const SSL * ssl,Span<const uint8_t> * out_read_traffic_secret,Span<const uint8_t> * out_write_traffic_secret)466 bool SSL_get_traffic_secrets(const SSL *ssl,
467                              Span<const uint8_t> *out_read_traffic_secret,
468                              Span<const uint8_t> *out_write_traffic_secret) {
469   if (SSL_version(ssl) < TLS1_3_VERSION) {
470     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
471     return false;
472   }
473 
474   if (!ssl->s3->initial_handshake_complete) {
475     OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_NOT_COMPLETE);
476     return false;
477   }
478 
479   *out_read_traffic_secret = Span<const uint8_t>(
480       ssl->s3->read_traffic_secret, ssl->s3->read_traffic_secret_len);
481   *out_write_traffic_secret = Span<const uint8_t>(
482       ssl->s3->write_traffic_secret, ssl->s3->write_traffic_secret_len);
483 
484   return true;
485 }
486 
SSL_CTX_set_aes_hw_override_for_testing(SSL_CTX * ctx,bool override_value)487 void SSL_CTX_set_aes_hw_override_for_testing(SSL_CTX *ctx,
488                                              bool override_value) {
489   ctx->aes_hw_override = true;
490   ctx->aes_hw_override_value = override_value;
491 }
492 
SSL_set_aes_hw_override_for_testing(SSL * ssl,bool override_value)493 void SSL_set_aes_hw_override_for_testing(SSL *ssl, bool override_value) {
494   ssl->config->aes_hw_override = true;
495   ssl->config->aes_hw_override_value = override_value;
496 }
497 
498 BSSL_NAMESPACE_END
499 
500 using namespace bssl;
501 
SSL_library_init(void)502 int SSL_library_init(void) {
503   CRYPTO_library_init();
504   return 1;
505 }
506 
OPENSSL_init_ssl(uint64_t opts,const OPENSSL_INIT_SETTINGS * settings)507 int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) {
508   CRYPTO_library_init();
509   return 1;
510 }
511 
ssl_session_hash(const SSL_SESSION * sess)512 static uint32_t ssl_session_hash(const SSL_SESSION *sess) {
513   return ssl_hash_session_id(
514       MakeConstSpan(sess->session_id, sess->session_id_length));
515 }
516 
ssl_session_cmp(const SSL_SESSION * a,const SSL_SESSION * b)517 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b) {
518   if (a->session_id_length != b->session_id_length) {
519     return 1;
520   }
521 
522   return OPENSSL_memcmp(a->session_id, b->session_id, a->session_id_length);
523 }
524 
ssl_ctx_st(const SSL_METHOD * ssl_method)525 ssl_ctx_st::ssl_ctx_st(const SSL_METHOD *ssl_method)
526     : RefCounted(CheckSubClass()),
527       method(ssl_method->method),
528       x509_method(ssl_method->x509_method),
529       retain_only_sha256_of_client_certs(false),
530       quiet_shutdown(false),
531       ocsp_stapling_enabled(false),
532       signed_cert_timestamps_enabled(false),
533       channel_id_enabled(false),
534       grease_enabled(false),
535       permute_extensions(false),
536       allow_unknown_alpn_protos(false),
537       false_start_allowed_without_alpn(false),
538       handoff(false),
539       enable_early_data(false),
540       aes_hw_override(false),
541       aes_hw_override_value(false) {
542   CRYPTO_MUTEX_init(&lock);
543   CRYPTO_new_ex_data(&ex_data);
544 }
545 
~ssl_ctx_st()546 ssl_ctx_st::~ssl_ctx_st() {
547   // Free the internal session cache. Note that this calls the caller-supplied
548   // remove callback, so we must do it before clearing ex_data. (See ticket
549   // [openssl.org #212].)
550   SSL_CTX_flush_sessions(this, 0);
551 
552   CRYPTO_free_ex_data(&g_ex_data_class_ssl_ctx, this, &ex_data);
553 
554   CRYPTO_MUTEX_cleanup(&lock);
555   lh_SSL_SESSION_free(sessions);
556   x509_method->ssl_ctx_free(this);
557 }
558 
SSL_CTX_new(const SSL_METHOD * method)559 SSL_CTX *SSL_CTX_new(const SSL_METHOD *method) {
560   if (method == NULL) {
561     OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_METHOD_PASSED);
562     return nullptr;
563   }
564 
565   UniquePtr<SSL_CTX> ret = MakeUnique<SSL_CTX>(method);
566   if (!ret) {
567     return nullptr;
568   }
569 
570   ret->cert = MakeUnique<CERT>(method->x509_method);
571   ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
572   ret->client_CA.reset(sk_CRYPTO_BUFFER_new_null());
573   if (ret->cert == nullptr ||       //
574       !ret->cert->is_valid() ||     //
575       ret->sessions == nullptr ||   //
576       ret->client_CA == nullptr ||  //
577       !ret->x509_method->ssl_ctx_new(ret.get())) {
578     return nullptr;
579   }
580 
581   if (!SSL_CTX_set_strict_cipher_list(ret.get(), SSL_DEFAULT_CIPHER_LIST) ||
582       // Lock the SSL_CTX to the specified version, for compatibility with
583       // legacy uses of SSL_METHOD.
584       !SSL_CTX_set_max_proto_version(ret.get(), method->version) ||
585       !SSL_CTX_set_min_proto_version(ret.get(), method->version)) {
586     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
587     return nullptr;
588   }
589 
590   return ret.release();
591 }
592 
SSL_CTX_up_ref(SSL_CTX * ctx)593 int SSL_CTX_up_ref(SSL_CTX *ctx) {
594   ctx->UpRefInternal();
595   return 1;
596 }
597 
SSL_CTX_free(SSL_CTX * ctx)598 void SSL_CTX_free(SSL_CTX *ctx) {
599   if (ctx != nullptr) {
600     ctx->DecRefInternal();
601   }
602 }
603 
ssl_st(SSL_CTX * ctx_arg)604 ssl_st::ssl_st(SSL_CTX *ctx_arg)
605     : method(ctx_arg->method),
606       max_send_fragment(ctx_arg->max_send_fragment),
607       msg_callback(ctx_arg->msg_callback),
608       msg_callback_arg(ctx_arg->msg_callback_arg),
609       ctx(UpRef(ctx_arg)),
610       session_ctx(UpRef(ctx_arg)),
611       options(ctx->options),
612       mode(ctx->mode),
613       max_cert_list(ctx->max_cert_list),
614       server(false),
615       quiet_shutdown(ctx->quiet_shutdown),
616       enable_early_data(ctx->enable_early_data) {
617   CRYPTO_new_ex_data(&ex_data);
618 }
619 
~ssl_st()620 ssl_st::~ssl_st() {
621   CRYPTO_free_ex_data(&g_ex_data_class_ssl, this, &ex_data);
622   // |config| refers to |this|, so we must release it earlier.
623   config.reset();
624   if (method != NULL) {
625     method->ssl_free(this);
626   }
627 }
628 
SSL_new(SSL_CTX * ctx)629 SSL *SSL_new(SSL_CTX *ctx) {
630   if (ctx == nullptr) {
631     OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_CTX);
632     return nullptr;
633   }
634 
635   UniquePtr<SSL> ssl = MakeUnique<SSL>(ctx);
636   if (ssl == nullptr) {
637     return nullptr;
638   }
639 
640   ssl->config = MakeUnique<SSL_CONFIG>(ssl.get());
641   if (ssl->config == nullptr) {
642     return nullptr;
643   }
644   ssl->config->conf_min_version = ctx->conf_min_version;
645   ssl->config->conf_max_version = ctx->conf_max_version;
646 
647   ssl->config->cert = ssl_cert_dup(ctx->cert.get());
648   if (ssl->config->cert == nullptr) {
649     return nullptr;
650   }
651 
652   ssl->config->verify_mode = ctx->verify_mode;
653   ssl->config->verify_callback = ctx->default_verify_callback;
654   ssl->config->custom_verify_callback = ctx->custom_verify_callback;
655   ssl->config->retain_only_sha256_of_client_certs =
656       ctx->retain_only_sha256_of_client_certs;
657   ssl->config->permute_extensions = ctx->permute_extensions;
658   ssl->config->aes_hw_override = ctx->aes_hw_override;
659   ssl->config->aes_hw_override_value = ctx->aes_hw_override_value;
660   ssl->config->tls13_cipher_policy = ctx->tls13_cipher_policy;
661 
662   if (!ssl->config->supported_group_list.CopyFrom(ctx->supported_group_list) ||
663       !ssl->config->alpn_client_proto_list.CopyFrom(
664           ctx->alpn_client_proto_list) ||
665       !ssl->config->verify_sigalgs.CopyFrom(ctx->verify_sigalgs)) {
666     return nullptr;
667   }
668 
669   if (ctx->psk_identity_hint) {
670     ssl->config->psk_identity_hint.reset(
671         OPENSSL_strdup(ctx->psk_identity_hint.get()));
672     if (ssl->config->psk_identity_hint == nullptr) {
673       return nullptr;
674     }
675   }
676   ssl->config->psk_client_callback = ctx->psk_client_callback;
677   ssl->config->psk_server_callback = ctx->psk_server_callback;
678 
679   ssl->config->channel_id_enabled = ctx->channel_id_enabled;
680   ssl->config->channel_id_private = UpRef(ctx->channel_id_private);
681 
682   ssl->config->signed_cert_timestamps_enabled =
683       ctx->signed_cert_timestamps_enabled;
684   ssl->config->ocsp_stapling_enabled = ctx->ocsp_stapling_enabled;
685   ssl->config->handoff = ctx->handoff;
686   ssl->quic_method = ctx->quic_method;
687 
688   if (!ssl->method->ssl_new(ssl.get()) ||
689       !ssl->ctx->x509_method->ssl_new(ssl->s3->hs.get())) {
690     return nullptr;
691   }
692 
693   return ssl.release();
694 }
695 
SSL_CONFIG(SSL * ssl_arg)696 SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg)
697     : ssl(ssl_arg),
698       ech_grease_enabled(false),
699       signed_cert_timestamps_enabled(false),
700       ocsp_stapling_enabled(false),
701       channel_id_enabled(false),
702       enforce_rsa_key_usage(true),
703       retain_only_sha256_of_client_certs(false),
704       handoff(false),
705       shed_handshake_config(false),
706       jdk11_workaround(false),
707       quic_use_legacy_codepoint(false),
708       permute_extensions(false),
709       alps_use_new_codepoint(false),
710       check_client_certificate_type(true),
711       check_ecdsa_curve(true) {
712   assert(ssl);
713 }
714 
~SSL_CONFIG()715 SSL_CONFIG::~SSL_CONFIG() {
716   if (ssl->ctx != nullptr) {
717     ssl->ctx->x509_method->ssl_config_free(this);
718   }
719 }
720 
SSL_free(SSL * ssl)721 void SSL_free(SSL *ssl) {
722   Delete(ssl);
723 }
724 
SSL_set_connect_state(SSL * ssl)725 void SSL_set_connect_state(SSL *ssl) {
726   ssl->server = false;
727   ssl->do_handshake = ssl_client_handshake;
728 }
729 
SSL_set_accept_state(SSL * ssl)730 void SSL_set_accept_state(SSL *ssl) {
731   ssl->server = true;
732   ssl->do_handshake = ssl_server_handshake;
733 }
734 
SSL_set0_rbio(SSL * ssl,BIO * rbio)735 void SSL_set0_rbio(SSL *ssl, BIO *rbio) {
736   ssl->rbio.reset(rbio);
737 }
738 
SSL_set0_wbio(SSL * ssl,BIO * wbio)739 void SSL_set0_wbio(SSL *ssl, BIO *wbio) {
740   ssl->wbio.reset(wbio);
741 }
742 
SSL_set_bio(SSL * ssl,BIO * rbio,BIO * wbio)743 void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio) {
744   // For historical reasons, this function has many different cases in ownership
745   // handling.
746 
747   // If nothing has changed, do nothing
748   if (rbio == SSL_get_rbio(ssl) && wbio == SSL_get_wbio(ssl)) {
749     return;
750   }
751 
752   // If the two arguments are equal, one fewer reference is granted than
753   // taken.
754   if (rbio != NULL && rbio == wbio) {
755     BIO_up_ref(rbio);
756   }
757 
758   // If only the wbio is changed, adopt only one reference.
759   if (rbio == SSL_get_rbio(ssl)) {
760     SSL_set0_wbio(ssl, wbio);
761     return;
762   }
763 
764   // There is an asymmetry here for historical reasons. If only the rbio is
765   // changed AND the rbio and wbio were originally different, then we only adopt
766   // one reference.
767   if (wbio == SSL_get_wbio(ssl) && SSL_get_rbio(ssl) != SSL_get_wbio(ssl)) {
768     SSL_set0_rbio(ssl, rbio);
769     return;
770   }
771 
772   // Otherwise, adopt both references.
773   SSL_set0_rbio(ssl, rbio);
774   SSL_set0_wbio(ssl, wbio);
775 }
776 
SSL_get_rbio(const SSL * ssl)777 BIO *SSL_get_rbio(const SSL *ssl) { return ssl->rbio.get(); }
778 
SSL_get_wbio(const SSL * ssl)779 BIO *SSL_get_wbio(const SSL *ssl) { return ssl->wbio.get(); }
780 
SSL_quic_max_handshake_flight_len(const SSL * ssl,enum ssl_encryption_level_t level)781 size_t SSL_quic_max_handshake_flight_len(const SSL *ssl,
782                                          enum ssl_encryption_level_t level) {
783   // Limits flights to 16K by default when there are no large
784   // (certificate-carrying) messages.
785   static const size_t kDefaultLimit = 16384;
786 
787   switch (level) {
788     case ssl_encryption_initial:
789       return kDefaultLimit;
790     case ssl_encryption_early_data:
791       // QUIC does not send EndOfEarlyData.
792       return 0;
793     case ssl_encryption_handshake:
794       if (ssl->server) {
795         // Servers may receive Certificate message if configured to request
796         // client certificates.
797         if (!!(ssl->config->verify_mode & SSL_VERIFY_PEER) &&
798             ssl->max_cert_list > kDefaultLimit) {
799           return ssl->max_cert_list;
800         }
801       } else {
802         // Clients may receive both Certificate message and a CertificateRequest
803         // message.
804         if (2*ssl->max_cert_list > kDefaultLimit) {
805           return 2*ssl->max_cert_list;
806         }
807       }
808       return kDefaultLimit;
809     case ssl_encryption_application:
810       // Note there is not actually a bound on the number of NewSessionTickets
811       // one may send in a row. This level may need more involved flow
812       // control. See https://github.com/quicwg/base-drafts/issues/1834.
813       return kDefaultLimit;
814   }
815 
816   return 0;
817 }
818 
SSL_quic_read_level(const SSL * ssl)819 enum ssl_encryption_level_t SSL_quic_read_level(const SSL *ssl) {
820   return ssl->s3->read_level;
821 }
822 
SSL_quic_write_level(const SSL * ssl)823 enum ssl_encryption_level_t SSL_quic_write_level(const SSL *ssl) {
824   return ssl->s3->write_level;
825 }
826 
SSL_provide_quic_data(SSL * ssl,enum ssl_encryption_level_t level,const uint8_t * data,size_t len)827 int SSL_provide_quic_data(SSL *ssl, enum ssl_encryption_level_t level,
828                           const uint8_t *data, size_t len) {
829   if (ssl->quic_method == nullptr) {
830     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
831     return 0;
832   }
833 
834   if (level != ssl->s3->read_level) {
835     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_ENCRYPTION_LEVEL_RECEIVED);
836     return 0;
837   }
838 
839   size_t new_len = (ssl->s3->hs_buf ? ssl->s3->hs_buf->length : 0) + len;
840   if (new_len < len ||
841       new_len > SSL_quic_max_handshake_flight_len(ssl, level)) {
842     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
843     return 0;
844   }
845 
846   return tls_append_handshake_data(ssl, MakeConstSpan(data, len));
847 }
848 
SSL_do_handshake(SSL * ssl)849 int SSL_do_handshake(SSL *ssl) {
850   ssl_reset_error_state(ssl);
851 
852   if (ssl->do_handshake == NULL) {
853     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_TYPE_NOT_SET);
854     return -1;
855   }
856 
857   if (!SSL_in_init(ssl)) {
858     return 1;
859   }
860 
861   // Run the handshake.
862   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
863 
864   bool early_return = false;
865   int ret = ssl_run_handshake(hs, &early_return);
866   ssl_do_info_callback(
867       ssl, ssl->server ? SSL_CB_ACCEPT_EXIT : SSL_CB_CONNECT_EXIT, ret);
868   if (ret <= 0) {
869     return ret;
870   }
871 
872   // Destroy the handshake object if the handshake has completely finished.
873   if (!early_return) {
874     ssl->s3->hs.reset();
875     ssl_maybe_shed_handshake_config(ssl);
876   }
877 
878   return 1;
879 }
880 
SSL_connect(SSL * ssl)881 int SSL_connect(SSL *ssl) {
882   if (ssl->do_handshake == NULL) {
883     // Not properly initialized yet
884     SSL_set_connect_state(ssl);
885   }
886 
887   return SSL_do_handshake(ssl);
888 }
889 
SSL_accept(SSL * ssl)890 int SSL_accept(SSL *ssl) {
891   if (ssl->do_handshake == NULL) {
892     // Not properly initialized yet
893     SSL_set_accept_state(ssl);
894   }
895 
896   return SSL_do_handshake(ssl);
897 }
898 
ssl_do_post_handshake(SSL * ssl,const SSLMessage & msg)899 static int ssl_do_post_handshake(SSL *ssl, const SSLMessage &msg) {
900   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
901     return tls13_post_handshake(ssl, msg);
902   }
903 
904   // Check for renegotiation on the server before parsing to use the correct
905   // error. Renegotiation is triggered by a different message for servers.
906   if (ssl->server) {
907     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
908     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_NO_RENEGOTIATION);
909     return 0;
910   }
911 
912   if (msg.type != SSL3_MT_HELLO_REQUEST || CBS_len(&msg.body) != 0) {
913     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
914     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HELLO_REQUEST);
915     return 0;
916   }
917 
918   if (ssl->renegotiate_mode == ssl_renegotiate_ignore) {
919     return 1;  // Ignore the HelloRequest.
920   }
921 
922   ssl->s3->renegotiate_pending = true;
923   if (ssl->renegotiate_mode == ssl_renegotiate_explicit) {
924     return 1;  // Handle it later.
925   }
926 
927   if (!SSL_renegotiate(ssl)) {
928     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_NO_RENEGOTIATION);
929     return 0;
930   }
931 
932   return 1;
933 }
934 
SSL_process_quic_post_handshake(SSL * ssl)935 int SSL_process_quic_post_handshake(SSL *ssl) {
936   ssl_reset_error_state(ssl);
937 
938   if (SSL_in_init(ssl)) {
939     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
940     return 0;
941   }
942 
943   // Replay post-handshake message errors.
944   if (!check_read_error(ssl)) {
945     return 0;
946   }
947 
948   // Process any buffered post-handshake messages.
949   SSLMessage msg;
950   while (ssl->method->get_message(ssl, &msg)) {
951     // Handle the post-handshake message and try again.
952     if (!ssl_do_post_handshake(ssl, msg)) {
953       ssl_set_read_error(ssl);
954       return 0;
955     }
956     ssl->method->next_message(ssl);
957   }
958 
959   return 1;
960 }
961 
ssl_read_impl(SSL * ssl)962 static int ssl_read_impl(SSL *ssl) {
963   ssl_reset_error_state(ssl);
964 
965   if (ssl->do_handshake == NULL) {
966     OPENSSL_PUT_ERROR(SSL, SSL_R_UNINITIALIZED);
967     return -1;
968   }
969 
970   // Replay post-handshake message errors.
971   if (!check_read_error(ssl)) {
972     return -1;
973   }
974 
975   while (ssl->s3->pending_app_data.empty()) {
976     if (ssl->s3->renegotiate_pending) {
977       ssl->s3->rwstate = SSL_ERROR_WANT_RENEGOTIATE;
978       return -1;
979     }
980 
981     // Complete the current handshake, if any. False Start will cause
982     // |SSL_do_handshake| to return mid-handshake, so this may require multiple
983     // iterations.
984     while (!ssl_can_read(ssl)) {
985       int ret = SSL_do_handshake(ssl);
986       if (ret < 0) {
987         return ret;
988       }
989       if (ret == 0) {
990         OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
991         return -1;
992       }
993     }
994 
995     // Process any buffered post-handshake messages.
996     SSLMessage msg;
997     if (ssl->method->get_message(ssl, &msg)) {
998       // If we received an interrupt in early read (EndOfEarlyData), loop again
999       // for the handshake to process it.
1000       if (SSL_in_init(ssl)) {
1001         ssl->s3->hs->can_early_read = false;
1002         continue;
1003       }
1004 
1005       // Handle the post-handshake message and try again.
1006       if (!ssl_do_post_handshake(ssl, msg)) {
1007         ssl_set_read_error(ssl);
1008         return -1;
1009       }
1010       ssl->method->next_message(ssl);
1011       continue;  // Loop again. We may have begun a new handshake.
1012     }
1013 
1014     uint8_t alert = SSL_AD_DECODE_ERROR;
1015     size_t consumed = 0;
1016     auto ret = ssl_open_app_data(ssl, &ssl->s3->pending_app_data, &consumed,
1017                                  &alert, ssl->s3->read_buffer.span());
1018     bool retry;
1019     int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
1020     if (bio_ret <= 0) {
1021       return bio_ret;
1022     }
1023     if (!retry) {
1024       assert(!ssl->s3->pending_app_data.empty());
1025       ssl->s3->key_update_count = 0;
1026     }
1027   }
1028 
1029   return 1;
1030 }
1031 
SSL_read(SSL * ssl,void * buf,int num)1032 int SSL_read(SSL *ssl, void *buf, int num) {
1033   int ret = SSL_peek(ssl, buf, num);
1034   if (ret <= 0) {
1035     return ret;
1036   }
1037   // TODO(davidben): In DTLS, should the rest of the record be discarded?  DTLS
1038   // is not a stream. See https://crbug.com/boringssl/65.
1039   ssl->s3->pending_app_data =
1040       ssl->s3->pending_app_data.subspan(static_cast<size_t>(ret));
1041   if (ssl->s3->pending_app_data.empty()) {
1042     ssl->s3->read_buffer.DiscardConsumed();
1043   }
1044   return ret;
1045 }
1046 
SSL_peek(SSL * ssl,void * buf,int num)1047 int SSL_peek(SSL *ssl, void *buf, int num) {
1048   if (ssl->quic_method != nullptr) {
1049     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1050     return -1;
1051   }
1052 
1053   int ret = ssl_read_impl(ssl);
1054   if (ret <= 0) {
1055     return ret;
1056   }
1057   if (num <= 0) {
1058     return num;
1059   }
1060   size_t todo =
1061       std::min(ssl->s3->pending_app_data.size(), static_cast<size_t>(num));
1062   OPENSSL_memcpy(buf, ssl->s3->pending_app_data.data(), todo);
1063   return static_cast<int>(todo);
1064 }
1065 
SSL_write(SSL * ssl,const void * buf,int num)1066 int SSL_write(SSL *ssl, const void *buf, int num) {
1067   ssl_reset_error_state(ssl);
1068 
1069   if (ssl->quic_method != nullptr) {
1070     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1071     return -1;
1072   }
1073 
1074   if (ssl->do_handshake == NULL) {
1075     OPENSSL_PUT_ERROR(SSL, SSL_R_UNINITIALIZED);
1076     return -1;
1077   }
1078 
1079   int ret = 0;
1080   size_t bytes_written = 0;
1081   bool needs_handshake = false;
1082   do {
1083     // If necessary, complete the handshake implicitly.
1084     if (!ssl_can_write(ssl)) {
1085       ret = SSL_do_handshake(ssl);
1086       if (ret < 0) {
1087         return ret;
1088       }
1089       if (ret == 0) {
1090         OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
1091         return -1;
1092       }
1093     }
1094 
1095     if (num < 0) {
1096       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_LENGTH);
1097       return -1;
1098     }
1099     ret = ssl->method->write_app_data(
1100         ssl, &needs_handshake, &bytes_written,
1101         MakeConstSpan(static_cast<const uint8_t *>(buf),
1102                       static_cast<size_t>(num)));
1103   } while (needs_handshake);
1104   return ret <= 0 ? ret : static_cast<int>(bytes_written);
1105 }
1106 
SSL_key_update(SSL * ssl,int request_type)1107 int SSL_key_update(SSL *ssl, int request_type) {
1108   ssl_reset_error_state(ssl);
1109 
1110   if (ssl->do_handshake == NULL) {
1111     OPENSSL_PUT_ERROR(SSL, SSL_R_UNINITIALIZED);
1112     return 0;
1113   }
1114 
1115   if (ssl->ctx->quic_method != nullptr) {
1116     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1117     return 0;
1118   }
1119 
1120   if (!ssl->s3->initial_handshake_complete) {
1121     OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_NOT_COMPLETE);
1122     return 0;
1123   }
1124 
1125   if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
1126     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
1127     return 0;
1128   }
1129 
1130   if (!ssl->s3->key_update_pending &&
1131       !tls13_add_key_update(ssl, request_type)) {
1132     return 0;
1133   }
1134 
1135   return 1;
1136 }
1137 
SSL_shutdown(SSL * ssl)1138 int SSL_shutdown(SSL *ssl) {
1139   ssl_reset_error_state(ssl);
1140 
1141   if (ssl->do_handshake == NULL) {
1142     OPENSSL_PUT_ERROR(SSL, SSL_R_UNINITIALIZED);
1143     return -1;
1144   }
1145 
1146   // If we are in the middle of a handshake, silently succeed. Consumers often
1147   // call this function before |SSL_free|, whether the handshake succeeded or
1148   // not. We assume the caller has already handled failed handshakes.
1149   if (SSL_in_init(ssl)) {
1150     return 1;
1151   }
1152 
1153   if (ssl->quiet_shutdown) {
1154     // Do nothing if configured not to send a close_notify.
1155     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
1156     ssl->s3->read_shutdown = ssl_shutdown_close_notify;
1157     return 1;
1158   }
1159 
1160   // This function completes in two stages. It sends a close_notify and then it
1161   // waits for a close_notify to come in. Perform exactly one action and return
1162   // whether or not it succeeds.
1163 
1164   if (ssl->s3->write_shutdown != ssl_shutdown_close_notify) {
1165     // Send a close_notify.
1166     if (ssl_send_alert_impl(ssl, SSL3_AL_WARNING, SSL_AD_CLOSE_NOTIFY) <= 0) {
1167       return -1;
1168     }
1169   } else if (ssl->s3->alert_dispatch) {
1170     // Finish sending the close_notify.
1171     if (ssl->method->dispatch_alert(ssl) <= 0) {
1172       return -1;
1173     }
1174   } else if (ssl->s3->read_shutdown != ssl_shutdown_close_notify) {
1175     if (SSL_is_dtls(ssl)) {
1176       // Bidirectional shutdown doesn't make sense for an unordered
1177       // transport. DTLS alerts also aren't delivered reliably, so we may even
1178       // time out because the peer never received our close_notify. Report to
1179       // the caller that the channel has fully shut down.
1180       if (ssl->s3->read_shutdown == ssl_shutdown_error) {
1181         ERR_restore_state(ssl->s3->read_error.get());
1182         return -1;
1183       }
1184       ssl->s3->read_shutdown = ssl_shutdown_close_notify;
1185     } else {
1186       // Process records until an error, close_notify, or application data.
1187       if (ssl_read_impl(ssl) > 0) {
1188         // We received some unexpected application data.
1189         OPENSSL_PUT_ERROR(SSL, SSL_R_APPLICATION_DATA_ON_SHUTDOWN);
1190         return -1;
1191       }
1192       if (ssl->s3->read_shutdown != ssl_shutdown_close_notify) {
1193         return -1;
1194       }
1195     }
1196   }
1197 
1198   // Return 0 for unidirectional shutdown and 1 for bidirectional shutdown.
1199   return ssl->s3->read_shutdown == ssl_shutdown_close_notify;
1200 }
1201 
SSL_send_fatal_alert(SSL * ssl,uint8_t alert)1202 int SSL_send_fatal_alert(SSL *ssl, uint8_t alert) {
1203   if (ssl->s3->alert_dispatch) {
1204     if (ssl->s3->send_alert[0] != SSL3_AL_FATAL ||
1205         ssl->s3->send_alert[1] != alert) {
1206       // We are already attempting to write a different alert.
1207       OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
1208       return -1;
1209     }
1210     return ssl->method->dispatch_alert(ssl);
1211   }
1212 
1213   return ssl_send_alert_impl(ssl, SSL3_AL_FATAL, alert);
1214 }
1215 
SSL_set_quic_transport_params(SSL * ssl,const uint8_t * params,size_t params_len)1216 int SSL_set_quic_transport_params(SSL *ssl, const uint8_t *params,
1217                                   size_t params_len) {
1218   return ssl->config && ssl->config->quic_transport_params.CopyFrom(
1219                             MakeConstSpan(params, params_len));
1220 }
1221 
SSL_get_peer_quic_transport_params(const SSL * ssl,const uint8_t ** out_params,size_t * out_params_len)1222 void SSL_get_peer_quic_transport_params(const SSL *ssl,
1223                                         const uint8_t **out_params,
1224                                         size_t *out_params_len) {
1225   *out_params = ssl->s3->peer_quic_transport_params.data();
1226   *out_params_len = ssl->s3->peer_quic_transport_params.size();
1227 }
1228 
SSL_set_quic_early_data_context(SSL * ssl,const uint8_t * context,size_t context_len)1229 int SSL_set_quic_early_data_context(SSL *ssl, const uint8_t *context,
1230                                     size_t context_len) {
1231   return ssl->config && ssl->config->quic_early_data_context.CopyFrom(
1232                             MakeConstSpan(context, context_len));
1233 }
1234 
SSL_CTX_set_early_data_enabled(SSL_CTX * ctx,int enabled)1235 void SSL_CTX_set_early_data_enabled(SSL_CTX *ctx, int enabled) {
1236   ctx->enable_early_data = !!enabled;
1237 }
1238 
SSL_set_early_data_enabled(SSL * ssl,int enabled)1239 void SSL_set_early_data_enabled(SSL *ssl, int enabled) {
1240   ssl->enable_early_data = !!enabled;
1241 }
1242 
SSL_in_early_data(const SSL * ssl)1243 int SSL_in_early_data(const SSL *ssl) {
1244   if (ssl->s3->hs == NULL) {
1245     return 0;
1246   }
1247   return ssl->s3->hs->in_early_data;
1248 }
1249 
SSL_early_data_accepted(const SSL * ssl)1250 int SSL_early_data_accepted(const SSL *ssl) {
1251   return ssl->s3->early_data_accepted;
1252 }
1253 
SSL_reset_early_data_reject(SSL * ssl)1254 void SSL_reset_early_data_reject(SSL *ssl) {
1255   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
1256   if (hs == NULL ||
1257       hs->wait != ssl_hs_early_data_rejected) {
1258     abort();
1259   }
1260 
1261   hs->wait = ssl_hs_ok;
1262   hs->in_early_data = false;
1263   hs->early_session.reset();
1264 
1265   // Discard any unfinished writes from the perspective of |SSL_write|'s
1266   // retry. The handshake will transparently flush out the pending record
1267   // (discarded by the server) to keep the framing correct.
1268   ssl->s3->pending_write = {};
1269 }
1270 
SSL_get_early_data_reason(const SSL * ssl)1271 enum ssl_early_data_reason_t SSL_get_early_data_reason(const SSL *ssl) {
1272   return ssl->s3->early_data_reason;
1273 }
1274 
SSL_early_data_reason_string(enum ssl_early_data_reason_t reason)1275 const char *SSL_early_data_reason_string(enum ssl_early_data_reason_t reason) {
1276   switch (reason) {
1277     case ssl_early_data_unknown:
1278       return "unknown";
1279     case ssl_early_data_disabled:
1280       return "disabled";
1281     case ssl_early_data_accepted:
1282       return "accepted";
1283     case ssl_early_data_protocol_version:
1284       return "protocol_version";
1285     case ssl_early_data_peer_declined:
1286       return "peer_declined";
1287     case ssl_early_data_no_session_offered:
1288       return "no_session_offered";
1289     case ssl_early_data_session_not_resumed:
1290       return "session_not_resumed";
1291     case ssl_early_data_unsupported_for_session:
1292       return "unsupported_for_session";
1293     case ssl_early_data_hello_retry_request:
1294       return "hello_retry_request";
1295     case ssl_early_data_alpn_mismatch:
1296       return "alpn_mismatch";
1297     case ssl_early_data_channel_id:
1298       return "channel_id";
1299     case ssl_early_data_ticket_age_skew:
1300       return "ticket_age_skew";
1301     case ssl_early_data_quic_parameter_mismatch:
1302       return "quic_parameter_mismatch";
1303     case ssl_early_data_alps_mismatch:
1304       return "alps_mismatch";
1305   }
1306 
1307   return nullptr;
1308 }
1309 
bio_retry_reason_to_error(int reason)1310 static int bio_retry_reason_to_error(int reason) {
1311   switch (reason) {
1312     case BIO_RR_CONNECT:
1313       return SSL_ERROR_WANT_CONNECT;
1314     case BIO_RR_ACCEPT:
1315       return SSL_ERROR_WANT_ACCEPT;
1316     default:
1317       return SSL_ERROR_SYSCALL;
1318   }
1319 }
1320 
SSL_get_error(const SSL * ssl,int ret_code)1321 int SSL_get_error(const SSL *ssl, int ret_code) {
1322   if (ret_code > 0) {
1323     return SSL_ERROR_NONE;
1324   }
1325 
1326   // Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
1327   // where we do encode the error
1328   uint32_t err = ERR_peek_error();
1329   if (err != 0) {
1330     if (ERR_GET_LIB(err) == ERR_LIB_SYS) {
1331       return SSL_ERROR_SYSCALL;
1332     }
1333     return SSL_ERROR_SSL;
1334   }
1335 
1336   if (ret_code == 0) {
1337     if (ssl->s3->rwstate == SSL_ERROR_ZERO_RETURN) {
1338       return SSL_ERROR_ZERO_RETURN;
1339     }
1340     // An EOF was observed which violates the protocol, and the underlying
1341     // transport does not participate in the error queue. Bubble up to the
1342     // caller.
1343     return SSL_ERROR_SYSCALL;
1344   }
1345 
1346   switch (ssl->s3->rwstate) {
1347     case SSL_ERROR_PENDING_SESSION:
1348     case SSL_ERROR_PENDING_CERTIFICATE:
1349     case SSL_ERROR_HANDOFF:
1350     case SSL_ERROR_HANDBACK:
1351     case SSL_ERROR_WANT_X509_LOOKUP:
1352     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
1353     case SSL_ERROR_PENDING_TICKET:
1354     case SSL_ERROR_EARLY_DATA_REJECTED:
1355     case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
1356     case SSL_ERROR_WANT_RENEGOTIATE:
1357     case SSL_ERROR_HANDSHAKE_HINTS_READY:
1358       return ssl->s3->rwstate;
1359 
1360     case SSL_ERROR_WANT_READ: {
1361       if (ssl->quic_method) {
1362         return SSL_ERROR_WANT_READ;
1363       }
1364       BIO *bio = SSL_get_rbio(ssl);
1365       if (BIO_should_read(bio)) {
1366         return SSL_ERROR_WANT_READ;
1367       }
1368 
1369       if (BIO_should_write(bio)) {
1370         // TODO(davidben): OpenSSL historically checked for writes on the read
1371         // BIO. Can this be removed?
1372         return SSL_ERROR_WANT_WRITE;
1373       }
1374 
1375       if (BIO_should_io_special(bio)) {
1376         return bio_retry_reason_to_error(BIO_get_retry_reason(bio));
1377       }
1378 
1379       break;
1380     }
1381 
1382     case SSL_ERROR_WANT_WRITE: {
1383       BIO *bio = SSL_get_wbio(ssl);
1384       if (BIO_should_write(bio)) {
1385         return SSL_ERROR_WANT_WRITE;
1386       }
1387 
1388       if (BIO_should_read(bio)) {
1389         // TODO(davidben): OpenSSL historically checked for reads on the write
1390         // BIO. Can this be removed?
1391         return SSL_ERROR_WANT_READ;
1392       }
1393 
1394       if (BIO_should_io_special(bio)) {
1395         return bio_retry_reason_to_error(BIO_get_retry_reason(bio));
1396       }
1397 
1398       break;
1399     }
1400   }
1401 
1402   return SSL_ERROR_SYSCALL;
1403 }
1404 
SSL_error_description(int err)1405 const char *SSL_error_description(int err) {
1406   switch (err) {
1407     case SSL_ERROR_NONE:
1408       return "NONE";
1409     case SSL_ERROR_SSL:
1410       return "SSL";
1411     case SSL_ERROR_WANT_READ:
1412       return "WANT_READ";
1413     case SSL_ERROR_WANT_WRITE:
1414       return "WANT_WRITE";
1415     case SSL_ERROR_WANT_X509_LOOKUP:
1416       return "WANT_X509_LOOKUP";
1417     case SSL_ERROR_SYSCALL:
1418       return "SYSCALL";
1419     case SSL_ERROR_ZERO_RETURN:
1420       return "ZERO_RETURN";
1421     case SSL_ERROR_WANT_CONNECT:
1422       return "WANT_CONNECT";
1423     case SSL_ERROR_WANT_ACCEPT:
1424       return "WANT_ACCEPT";
1425     case SSL_ERROR_PENDING_SESSION:
1426       return "PENDING_SESSION";
1427     case SSL_ERROR_PENDING_CERTIFICATE:
1428       return "PENDING_CERTIFICATE";
1429     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
1430       return "WANT_PRIVATE_KEY_OPERATION";
1431     case SSL_ERROR_PENDING_TICKET:
1432       return "PENDING_TICKET";
1433     case SSL_ERROR_EARLY_DATA_REJECTED:
1434       return "EARLY_DATA_REJECTED";
1435     case SSL_ERROR_WANT_CERTIFICATE_VERIFY:
1436       return "WANT_CERTIFICATE_VERIFY";
1437     case SSL_ERROR_HANDOFF:
1438       return "HANDOFF";
1439     case SSL_ERROR_HANDBACK:
1440       return "HANDBACK";
1441     case SSL_ERROR_WANT_RENEGOTIATE:
1442       return "WANT_RENEGOTIATE";
1443     case SSL_ERROR_HANDSHAKE_HINTS_READY:
1444       return "HANDSHAKE_HINTS_READY";
1445     default:
1446       return nullptr;
1447   }
1448 }
1449 
SSL_CTX_set_options(SSL_CTX * ctx,uint32_t options)1450 uint32_t SSL_CTX_set_options(SSL_CTX *ctx, uint32_t options) {
1451   ctx->options |= options;
1452   return ctx->options;
1453 }
1454 
SSL_CTX_clear_options(SSL_CTX * ctx,uint32_t options)1455 uint32_t SSL_CTX_clear_options(SSL_CTX *ctx, uint32_t options) {
1456   ctx->options &= ~options;
1457   return ctx->options;
1458 }
1459 
SSL_CTX_get_options(const SSL_CTX * ctx)1460 uint32_t SSL_CTX_get_options(const SSL_CTX *ctx) { return ctx->options; }
1461 
SSL_set_options(SSL * ssl,uint32_t options)1462 uint32_t SSL_set_options(SSL *ssl, uint32_t options) {
1463   ssl->options |= options;
1464   return ssl->options;
1465 }
1466 
SSL_clear_options(SSL * ssl,uint32_t options)1467 uint32_t SSL_clear_options(SSL *ssl, uint32_t options) {
1468   ssl->options &= ~options;
1469   return ssl->options;
1470 }
1471 
SSL_get_options(const SSL * ssl)1472 uint32_t SSL_get_options(const SSL *ssl) { return ssl->options; }
1473 
SSL_CTX_set_mode(SSL_CTX * ctx,uint32_t mode)1474 uint32_t SSL_CTX_set_mode(SSL_CTX *ctx, uint32_t mode) {
1475   ctx->mode |= mode;
1476   return ctx->mode;
1477 }
1478 
SSL_CTX_clear_mode(SSL_CTX * ctx,uint32_t mode)1479 uint32_t SSL_CTX_clear_mode(SSL_CTX *ctx, uint32_t mode) {
1480   ctx->mode &= ~mode;
1481   return ctx->mode;
1482 }
1483 
SSL_CTX_get_mode(const SSL_CTX * ctx)1484 uint32_t SSL_CTX_get_mode(const SSL_CTX *ctx) { return ctx->mode; }
1485 
SSL_set_mode(SSL * ssl,uint32_t mode)1486 uint32_t SSL_set_mode(SSL *ssl, uint32_t mode) {
1487   ssl->mode |= mode;
1488   return ssl->mode;
1489 }
1490 
SSL_clear_mode(SSL * ssl,uint32_t mode)1491 uint32_t SSL_clear_mode(SSL *ssl, uint32_t mode) {
1492   ssl->mode &= ~mode;
1493   return ssl->mode;
1494 }
1495 
SSL_get_mode(const SSL * ssl)1496 uint32_t SSL_get_mode(const SSL *ssl) { return ssl->mode; }
1497 
SSL_CTX_set0_buffer_pool(SSL_CTX * ctx,CRYPTO_BUFFER_POOL * pool)1498 void SSL_CTX_set0_buffer_pool(SSL_CTX *ctx, CRYPTO_BUFFER_POOL *pool) {
1499   ctx->pool = pool;
1500 }
1501 
SSL_get_tls_unique(const SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)1502 int SSL_get_tls_unique(const SSL *ssl, uint8_t *out, size_t *out_len,
1503                        size_t max_out) {
1504   *out_len = 0;
1505   OPENSSL_memset(out, 0, max_out);
1506 
1507   // tls-unique is not defined for TLS 1.3.
1508   if (!ssl->s3->initial_handshake_complete ||
1509       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1510     return 0;
1511   }
1512 
1513   // The tls-unique value is the first Finished message in the handshake, which
1514   // is the client's in a full handshake and the server's for a resumption. See
1515   // https://tools.ietf.org/html/rfc5929#section-3.1.
1516   const uint8_t *finished = ssl->s3->previous_client_finished;
1517   size_t finished_len = ssl->s3->previous_client_finished_len;
1518   if (ssl->session != NULL) {
1519     // tls-unique is broken for resumed sessions unless EMS is used.
1520     if (!ssl->session->extended_master_secret) {
1521       return 0;
1522     }
1523     finished = ssl->s3->previous_server_finished;
1524     finished_len = ssl->s3->previous_server_finished_len;
1525   }
1526 
1527   *out_len = finished_len;
1528   if (finished_len > max_out) {
1529     *out_len = max_out;
1530   }
1531 
1532   OPENSSL_memcpy(out, finished, *out_len);
1533   return 1;
1534 }
1535 
set_session_id_context(CERT * cert,const uint8_t * sid_ctx,size_t sid_ctx_len)1536 static int set_session_id_context(CERT *cert, const uint8_t *sid_ctx,
1537                                    size_t sid_ctx_len) {
1538   if (sid_ctx_len > sizeof(cert->sid_ctx)) {
1539     OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
1540     return 0;
1541   }
1542 
1543   static_assert(sizeof(cert->sid_ctx) < 256, "sid_ctx too large");
1544   cert->sid_ctx_length = (uint8_t)sid_ctx_len;
1545   OPENSSL_memcpy(cert->sid_ctx, sid_ctx, sid_ctx_len);
1546   return 1;
1547 }
1548 
SSL_CTX_set_session_id_context(SSL_CTX * ctx,const uint8_t * sid_ctx,size_t sid_ctx_len)1549 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const uint8_t *sid_ctx,
1550                                    size_t sid_ctx_len) {
1551   return set_session_id_context(ctx->cert.get(), sid_ctx, sid_ctx_len);
1552 }
1553 
SSL_set_session_id_context(SSL * ssl,const uint8_t * sid_ctx,size_t sid_ctx_len)1554 int SSL_set_session_id_context(SSL *ssl, const uint8_t *sid_ctx,
1555                                size_t sid_ctx_len) {
1556   if (!ssl->config) {
1557     return 0;
1558   }
1559   return set_session_id_context(ssl->config->cert.get(), sid_ctx, sid_ctx_len);
1560 }
1561 
SSL_get0_session_id_context(const SSL * ssl,size_t * out_len)1562 const uint8_t *SSL_get0_session_id_context(const SSL *ssl, size_t *out_len) {
1563   if (!ssl->config) {
1564     assert(ssl->config);
1565     *out_len = 0;
1566     return NULL;
1567   }
1568   *out_len = ssl->config->cert->sid_ctx_length;
1569   return ssl->config->cert->sid_ctx;
1570 }
1571 
SSL_get_fd(const SSL * ssl)1572 int SSL_get_fd(const SSL *ssl) { return SSL_get_rfd(ssl); }
1573 
SSL_get_rfd(const SSL * ssl)1574 int SSL_get_rfd(const SSL *ssl) {
1575   int ret = -1;
1576   BIO *b = BIO_find_type(SSL_get_rbio(ssl), BIO_TYPE_DESCRIPTOR);
1577   if (b != NULL) {
1578     BIO_get_fd(b, &ret);
1579   }
1580   return ret;
1581 }
1582 
SSL_get_wfd(const SSL * ssl)1583 int SSL_get_wfd(const SSL *ssl) {
1584   int ret = -1;
1585   BIO *b = BIO_find_type(SSL_get_wbio(ssl), BIO_TYPE_DESCRIPTOR);
1586   if (b != NULL) {
1587     BIO_get_fd(b, &ret);
1588   }
1589   return ret;
1590 }
1591 
1592 #if !defined(OPENSSL_NO_SOCK)
SSL_set_fd(SSL * ssl,int fd)1593 int SSL_set_fd(SSL *ssl, int fd) {
1594   BIO *bio = BIO_new(BIO_s_socket());
1595   if (bio == NULL) {
1596     OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1597     return 0;
1598   }
1599   BIO_set_fd(bio, fd, BIO_NOCLOSE);
1600   SSL_set_bio(ssl, bio, bio);
1601   return 1;
1602 }
1603 
SSL_set_wfd(SSL * ssl,int fd)1604 int SSL_set_wfd(SSL *ssl, int fd) {
1605   BIO *rbio = SSL_get_rbio(ssl);
1606   if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET ||
1607       BIO_get_fd(rbio, NULL) != fd) {
1608     BIO *bio = BIO_new(BIO_s_socket());
1609     if (bio == NULL) {
1610       OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1611       return 0;
1612     }
1613     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1614     SSL_set0_wbio(ssl, bio);
1615   } else {
1616     // Copy the rbio over to the wbio.
1617     BIO_up_ref(rbio);
1618     SSL_set0_wbio(ssl, rbio);
1619   }
1620 
1621   return 1;
1622 }
1623 
SSL_set_rfd(SSL * ssl,int fd)1624 int SSL_set_rfd(SSL *ssl, int fd) {
1625   BIO *wbio = SSL_get_wbio(ssl);
1626   if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET ||
1627       BIO_get_fd(wbio, NULL) != fd) {
1628     BIO *bio = BIO_new(BIO_s_socket());
1629     if (bio == NULL) {
1630       OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1631       return 0;
1632     }
1633     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1634     SSL_set0_rbio(ssl, bio);
1635   } else {
1636     // Copy the wbio over to the rbio.
1637     BIO_up_ref(wbio);
1638     SSL_set0_rbio(ssl, wbio);
1639   }
1640   return 1;
1641 }
1642 #endif  // !OPENSSL_NO_SOCK
1643 
copy_finished(void * out,size_t out_len,const uint8_t * in,size_t in_len)1644 static size_t copy_finished(void *out, size_t out_len, const uint8_t *in,
1645                             size_t in_len) {
1646   if (out_len > in_len) {
1647     out_len = in_len;
1648   }
1649   OPENSSL_memcpy(out, in, out_len);
1650   return in_len;
1651 }
1652 
SSL_get_finished(const SSL * ssl,void * buf,size_t count)1653 size_t SSL_get_finished(const SSL *ssl, void *buf, size_t count) {
1654   if (!ssl->s3->initial_handshake_complete ||
1655       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1656     return 0;
1657   }
1658 
1659   if (ssl->server) {
1660     return copy_finished(buf, count, ssl->s3->previous_server_finished,
1661                          ssl->s3->previous_server_finished_len);
1662   }
1663 
1664   return copy_finished(buf, count, ssl->s3->previous_client_finished,
1665                        ssl->s3->previous_client_finished_len);
1666 }
1667 
SSL_get_peer_finished(const SSL * ssl,void * buf,size_t count)1668 size_t SSL_get_peer_finished(const SSL *ssl, void *buf, size_t count) {
1669   if (!ssl->s3->initial_handshake_complete ||
1670       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1671     return 0;
1672   }
1673 
1674   if (ssl->server) {
1675     return copy_finished(buf, count, ssl->s3->previous_client_finished,
1676                          ssl->s3->previous_client_finished_len);
1677   }
1678 
1679   return copy_finished(buf, count, ssl->s3->previous_server_finished,
1680                        ssl->s3->previous_server_finished_len);
1681 }
1682 
SSL_get_verify_mode(const SSL * ssl)1683 int SSL_get_verify_mode(const SSL *ssl) {
1684   if (!ssl->config) {
1685     assert(ssl->config);
1686     return -1;
1687   }
1688   return ssl->config->verify_mode;
1689 }
1690 
SSL_get_extms_support(const SSL * ssl)1691 int SSL_get_extms_support(const SSL *ssl) {
1692   // TLS 1.3 does not require extended master secret and always reports as
1693   // supporting it.
1694   if (!ssl->s3->have_version) {
1695     return 0;
1696   }
1697   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1698     return 1;
1699   }
1700 
1701   // If the initial handshake completed, query the established session.
1702   if (ssl->s3->established_session != NULL) {
1703     return ssl->s3->established_session->extended_master_secret;
1704   }
1705 
1706   // Otherwise, query the in-progress handshake.
1707   if (ssl->s3->hs != NULL) {
1708     return ssl->s3->hs->extended_master_secret;
1709   }
1710   assert(0);
1711   return 0;
1712 }
1713 
SSL_CTX_get_read_ahead(const SSL_CTX * ctx)1714 int SSL_CTX_get_read_ahead(const SSL_CTX *ctx) { return 0; }
1715 
SSL_get_read_ahead(const SSL * ssl)1716 int SSL_get_read_ahead(const SSL *ssl) { return 0; }
1717 
SSL_CTX_set_read_ahead(SSL_CTX * ctx,int yes)1718 int SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes) { return 1; }
1719 
SSL_set_read_ahead(SSL * ssl,int yes)1720 int SSL_set_read_ahead(SSL *ssl, int yes) { return 1; }
1721 
SSL_pending(const SSL * ssl)1722 int SSL_pending(const SSL *ssl) {
1723   return static_cast<int>(ssl->s3->pending_app_data.size());
1724 }
1725 
SSL_has_pending(const SSL * ssl)1726 int SSL_has_pending(const SSL *ssl) {
1727   return SSL_pending(ssl) != 0 || !ssl->s3->read_buffer.empty();
1728 }
1729 
has_cert_and_key(const SSL_CREDENTIAL * cred)1730 static bool has_cert_and_key(const SSL_CREDENTIAL *cred) {
1731   // TODO(davidben): If |cred->key_method| is set, that should be fine too.
1732   if (cred->privkey == nullptr) {
1733     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1734     return false;
1735   }
1736 
1737   if (cred->chain == nullptr ||
1738       sk_CRYPTO_BUFFER_value(cred->chain.get(), 0) == nullptr) {
1739     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_ASSIGNED);
1740     return false;
1741   }
1742 
1743   return true;
1744 }
1745 
SSL_CTX_check_private_key(const SSL_CTX * ctx)1746 int SSL_CTX_check_private_key(const SSL_CTX *ctx) {
1747   // There is no need to actually check consistency because inconsistent values
1748   // can never be configured.
1749   return has_cert_and_key(ctx->cert->default_credential.get());
1750 }
1751 
SSL_check_private_key(const SSL * ssl)1752 int SSL_check_private_key(const SSL *ssl) {
1753   if (!ssl->config) {
1754     return 0;
1755   }
1756 
1757   // There is no need to actually check consistency because inconsistent values
1758   // can never be configured.
1759   return has_cert_and_key(ssl->config->cert->default_credential.get());
1760 }
1761 
SSL_get_default_timeout(const SSL * ssl)1762 long SSL_get_default_timeout(const SSL *ssl) {
1763   return SSL_DEFAULT_SESSION_TIMEOUT;
1764 }
1765 
SSL_renegotiate(SSL * ssl)1766 int SSL_renegotiate(SSL *ssl) {
1767   // Caller-initiated renegotiation is not supported.
1768   if (!ssl->s3->renegotiate_pending) {
1769     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1770     return 0;
1771   }
1772 
1773   if (!ssl_can_renegotiate(ssl)) {
1774     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
1775     return 0;
1776   }
1777 
1778   // We should not have told the caller to release the private key.
1779   assert(!SSL_can_release_private_key(ssl));
1780 
1781   // Renegotiation is only supported at quiescent points in the application
1782   // protocol, namely in HTTPS, just before reading the HTTP response.
1783   // Require the record-layer be idle and avoid complexities of sending a
1784   // handshake record while an application_data record is being written.
1785   if (!ssl->s3->write_buffer.empty() ||
1786       ssl->s3->write_shutdown != ssl_shutdown_none) {
1787     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
1788     return 0;
1789   }
1790 
1791   // Begin a new handshake.
1792   if (ssl->s3->hs != nullptr) {
1793     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1794     return 0;
1795   }
1796   ssl->s3->hs = ssl_handshake_new(ssl);
1797   if (ssl->s3->hs == nullptr) {
1798     return 0;
1799   }
1800 
1801   ssl->s3->renegotiate_pending = false;
1802   ssl->s3->total_renegotiations++;
1803   return 1;
1804 }
1805 
SSL_renegotiate_pending(SSL * ssl)1806 int SSL_renegotiate_pending(SSL *ssl) {
1807   return SSL_in_init(ssl) && ssl->s3->initial_handshake_complete;
1808 }
1809 
SSL_total_renegotiations(const SSL * ssl)1810 int SSL_total_renegotiations(const SSL *ssl) {
1811   return ssl->s3->total_renegotiations;
1812 }
1813 
SSL_CTX_get_max_cert_list(const SSL_CTX * ctx)1814 size_t SSL_CTX_get_max_cert_list(const SSL_CTX *ctx) {
1815   return ctx->max_cert_list;
1816 }
1817 
SSL_CTX_set_max_cert_list(SSL_CTX * ctx,size_t max_cert_list)1818 void SSL_CTX_set_max_cert_list(SSL_CTX *ctx, size_t max_cert_list) {
1819   if (max_cert_list > kMaxHandshakeSize) {
1820     max_cert_list = kMaxHandshakeSize;
1821   }
1822   ctx->max_cert_list = (uint32_t)max_cert_list;
1823 }
1824 
SSL_get_max_cert_list(const SSL * ssl)1825 size_t SSL_get_max_cert_list(const SSL *ssl) {
1826   return ssl->max_cert_list;
1827 }
1828 
SSL_set_max_cert_list(SSL * ssl,size_t max_cert_list)1829 void SSL_set_max_cert_list(SSL *ssl, size_t max_cert_list) {
1830   if (max_cert_list > kMaxHandshakeSize) {
1831     max_cert_list = kMaxHandshakeSize;
1832   }
1833   ssl->max_cert_list = (uint32_t)max_cert_list;
1834 }
1835 
SSL_CTX_set_max_send_fragment(SSL_CTX * ctx,size_t max_send_fragment)1836 int SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, size_t max_send_fragment) {
1837   if (max_send_fragment < 512) {
1838     max_send_fragment = 512;
1839   }
1840   if (max_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1841     max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1842   }
1843   ctx->max_send_fragment = (uint16_t)max_send_fragment;
1844 
1845   return 1;
1846 }
1847 
SSL_set_max_send_fragment(SSL * ssl,size_t max_send_fragment)1848 int SSL_set_max_send_fragment(SSL *ssl, size_t max_send_fragment) {
1849   if (max_send_fragment < 512) {
1850     max_send_fragment = 512;
1851   }
1852   if (max_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1853     max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1854   }
1855   ssl->max_send_fragment = (uint16_t)max_send_fragment;
1856 
1857   return 1;
1858 }
1859 
SSL_set_mtu(SSL * ssl,unsigned mtu)1860 int SSL_set_mtu(SSL *ssl, unsigned mtu) {
1861   if (!SSL_is_dtls(ssl) || mtu < dtls1_min_mtu()) {
1862     return 0;
1863   }
1864   ssl->d1->mtu = mtu;
1865   return 1;
1866 }
1867 
SSL_get_secure_renegotiation_support(const SSL * ssl)1868 int SSL_get_secure_renegotiation_support(const SSL *ssl) {
1869   if (!ssl->s3->have_version) {
1870     return 0;
1871   }
1872   return ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
1873          ssl->s3->send_connection_binding;
1874 }
1875 
SSL_CTX_sess_number(const SSL_CTX * ctx)1876 size_t SSL_CTX_sess_number(const SSL_CTX *ctx) {
1877   MutexReadLock lock(const_cast<CRYPTO_MUTEX *>(&ctx->lock));
1878   return lh_SSL_SESSION_num_items(ctx->sessions);
1879 }
1880 
SSL_CTX_sess_set_cache_size(SSL_CTX * ctx,unsigned long size)1881 unsigned long SSL_CTX_sess_set_cache_size(SSL_CTX *ctx, unsigned long size) {
1882   unsigned long ret = ctx->session_cache_size;
1883   ctx->session_cache_size = size;
1884   return ret;
1885 }
1886 
SSL_CTX_sess_get_cache_size(const SSL_CTX * ctx)1887 unsigned long SSL_CTX_sess_get_cache_size(const SSL_CTX *ctx) {
1888   return ctx->session_cache_size;
1889 }
1890 
SSL_CTX_set_session_cache_mode(SSL_CTX * ctx,int mode)1891 int SSL_CTX_set_session_cache_mode(SSL_CTX *ctx, int mode) {
1892   int ret = ctx->session_cache_mode;
1893   ctx->session_cache_mode = mode;
1894   return ret;
1895 }
1896 
SSL_CTX_get_session_cache_mode(const SSL_CTX * ctx)1897 int SSL_CTX_get_session_cache_mode(const SSL_CTX *ctx) {
1898   return ctx->session_cache_mode;
1899 }
1900 
1901 
SSL_CTX_get_tlsext_ticket_keys(SSL_CTX * ctx,void * out,size_t len)1902 int SSL_CTX_get_tlsext_ticket_keys(SSL_CTX *ctx, void *out, size_t len) {
1903   if (out == NULL) {
1904     return 48;
1905   }
1906   if (len != 48) {
1907     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_TICKET_KEYS_LENGTH);
1908     return 0;
1909   }
1910 
1911   // The default ticket keys are initialized lazily. Trigger a key
1912   // rotation to initialize them.
1913   if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
1914     return 0;
1915   }
1916 
1917   uint8_t *out_bytes = reinterpret_cast<uint8_t *>(out);
1918   MutexReadLock lock(&ctx->lock);
1919   OPENSSL_memcpy(out_bytes, ctx->ticket_key_current->name, 16);
1920   OPENSSL_memcpy(out_bytes + 16, ctx->ticket_key_current->hmac_key, 16);
1921   OPENSSL_memcpy(out_bytes + 32, ctx->ticket_key_current->aes_key, 16);
1922   return 1;
1923 }
1924 
SSL_CTX_set_tlsext_ticket_keys(SSL_CTX * ctx,const void * in,size_t len)1925 int SSL_CTX_set_tlsext_ticket_keys(SSL_CTX *ctx, const void *in, size_t len) {
1926   if (in == NULL) {
1927     return 48;
1928   }
1929   if (len != 48) {
1930     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_TICKET_KEYS_LENGTH);
1931     return 0;
1932   }
1933   auto key = MakeUnique<TicketKey>();
1934   if (!key) {
1935     return 0;
1936   }
1937   const uint8_t *in_bytes = reinterpret_cast<const uint8_t *>(in);
1938   OPENSSL_memcpy(key->name, in_bytes, 16);
1939   OPENSSL_memcpy(key->hmac_key, in_bytes + 16, 16);
1940   OPENSSL_memcpy(key->aes_key, in_bytes + 32, 16);
1941   // Disable automatic key rotation for manually-configured keys. This is now
1942   // the caller's responsibility.
1943   key->next_rotation_tv_sec = 0;
1944   ctx->ticket_key_current = std::move(key);
1945   ctx->ticket_key_prev.reset();
1946   return 1;
1947 }
1948 
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))1949 int SSL_CTX_set_tlsext_ticket_key_cb(
1950     SSL_CTX *ctx, int (*callback)(SSL *ssl, uint8_t *key_name, uint8_t *iv,
1951                                   EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
1952                                   int encrypt)) {
1953   ctx->ticket_key_cb = callback;
1954   return 1;
1955 }
1956 
check_group_ids(Span<const uint16_t> group_ids)1957 static bool check_group_ids(Span<const uint16_t> group_ids) {
1958   for (uint16_t group_id : group_ids) {
1959     if (ssl_group_id_to_nid(group_id) == NID_undef) {
1960       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1961       return false;
1962     }
1963   }
1964   return true;
1965 }
1966 
SSL_CTX_set1_group_ids(SSL_CTX * ctx,const uint16_t * group_ids,size_t num_group_ids)1967 int SSL_CTX_set1_group_ids(SSL_CTX *ctx, const uint16_t *group_ids,
1968                            size_t num_group_ids) {
1969   auto span = MakeConstSpan(group_ids, num_group_ids);
1970   return check_group_ids(span) && ctx->supported_group_list.CopyFrom(span);
1971 }
1972 
SSL_set1_group_ids(SSL * ssl,const uint16_t * group_ids,size_t num_group_ids)1973 int SSL_set1_group_ids(SSL *ssl, const uint16_t *group_ids,
1974                        size_t num_group_ids) {
1975   if (!ssl->config) {
1976     return 0;
1977   }
1978   auto span = MakeConstSpan(group_ids, num_group_ids);
1979   return check_group_ids(span) &&
1980          ssl->config->supported_group_list.CopyFrom(span);
1981 }
1982 
ssl_nids_to_group_ids(Array<uint16_t> * out_group_ids,Span<const int> nids)1983 static bool ssl_nids_to_group_ids(Array<uint16_t> *out_group_ids,
1984                                   Span<const int> nids) {
1985   Array<uint16_t> group_ids;
1986   if (!group_ids.Init(nids.size())) {
1987     return false;
1988   }
1989 
1990   for (size_t i = 0; i < nids.size(); i++) {
1991     if (!ssl_nid_to_group_id(&group_ids[i], nids[i])) {
1992       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1993       return false;
1994     }
1995   }
1996 
1997   *out_group_ids = std::move(group_ids);
1998   return true;
1999 }
2000 
SSL_CTX_set1_groups(SSL_CTX * ctx,const int * groups,size_t num_groups)2001 int SSL_CTX_set1_groups(SSL_CTX *ctx, const int *groups, size_t num_groups) {
2002   return ssl_nids_to_group_ids(&ctx->supported_group_list,
2003                                MakeConstSpan(groups, num_groups));
2004 }
2005 
SSL_set1_groups(SSL * ssl,const int * groups,size_t num_groups)2006 int SSL_set1_groups(SSL *ssl, const int *groups, size_t num_groups) {
2007   if (!ssl->config) {
2008     return 0;
2009   }
2010   return ssl_nids_to_group_ids(&ssl->config->supported_group_list,
2011                                MakeConstSpan(groups, num_groups));
2012 }
2013 
ssl_str_to_group_ids(Array<uint16_t> * out_group_ids,const char * str)2014 static bool ssl_str_to_group_ids(Array<uint16_t> *out_group_ids,
2015                                  const char *str) {
2016   // Count the number of groups in the list.
2017   size_t count = 0;
2018   const char *ptr = str, *col;
2019   do {
2020     col = strchr(ptr, ':');
2021     count++;
2022     if (col) {
2023       ptr = col + 1;
2024     }
2025   } while (col);
2026 
2027   Array<uint16_t> group_ids;
2028   if (!group_ids.Init(count)) {
2029     return false;
2030   }
2031 
2032   size_t i = 0;
2033   ptr = str;
2034   do {
2035     col = strchr(ptr, ':');
2036     if (!ssl_name_to_group_id(&group_ids[i++], ptr,
2037                               col ? (size_t)(col - ptr) : strlen(ptr))) {
2038       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2039       return false;
2040     }
2041     if (col) {
2042       ptr = col + 1;
2043     }
2044   } while (col);
2045 
2046   assert(i == count);
2047   *out_group_ids = std::move(group_ids);
2048   return true;
2049 }
2050 
SSL_CTX_set1_groups_list(SSL_CTX * ctx,const char * groups)2051 int SSL_CTX_set1_groups_list(SSL_CTX *ctx, const char *groups) {
2052   return ssl_str_to_group_ids(&ctx->supported_group_list, groups);
2053 }
2054 
SSL_set1_groups_list(SSL * ssl,const char * groups)2055 int SSL_set1_groups_list(SSL *ssl, const char *groups) {
2056   if (!ssl->config) {
2057     return 0;
2058   }
2059   return ssl_str_to_group_ids(&ssl->config->supported_group_list, groups);
2060 }
2061 
SSL_get_group_id(const SSL * ssl)2062 uint16_t SSL_get_group_id(const SSL *ssl) {
2063   SSL_SESSION *session = SSL_get_session(ssl);
2064   if (session == NULL) {
2065     return 0;
2066   }
2067 
2068   return session->group_id;
2069 }
2070 
SSL_get_negotiated_group(const SSL * ssl)2071 int SSL_get_negotiated_group(const SSL *ssl) {
2072   uint16_t group_id = SSL_get_group_id(ssl);
2073   if (group_id == 0) {
2074     return NID_undef;
2075   }
2076   return ssl_group_id_to_nid(group_id);
2077 }
2078 
SSL_CTX_set_tmp_dh(SSL_CTX * ctx,const DH * dh)2079 int SSL_CTX_set_tmp_dh(SSL_CTX *ctx, const DH *dh) {
2080   return 1;
2081 }
2082 
SSL_set_tmp_dh(SSL * ssl,const DH * dh)2083 int SSL_set_tmp_dh(SSL *ssl, const DH *dh) {
2084   return 1;
2085 }
2086 
STACK_OF(SSL_CIPHER)2087 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx) {
2088   return ctx->cipher_list->ciphers.get();
2089 }
2090 
SSL_CTX_cipher_in_group(const SSL_CTX * ctx,size_t i)2091 int SSL_CTX_cipher_in_group(const SSL_CTX *ctx, size_t i) {
2092   if (i >= sk_SSL_CIPHER_num(ctx->cipher_list->ciphers.get())) {
2093     return 0;
2094   }
2095   return ctx->cipher_list->in_group_flags[i];
2096 }
2097 
STACK_OF(SSL_CIPHER)2098 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *ssl) {
2099   if (ssl == NULL) {
2100     return NULL;
2101   }
2102   if (ssl->config == NULL) {
2103     assert(ssl->config);
2104     return NULL;
2105   }
2106 
2107   return ssl->config->cipher_list ? ssl->config->cipher_list->ciphers.get()
2108       : ssl->ctx->cipher_list->ciphers.get();
2109 }
2110 
SSL_get_cipher_list(const SSL * ssl,int n)2111 const char *SSL_get_cipher_list(const SSL *ssl, int n) {
2112   if (ssl == NULL) {
2113     return NULL;
2114   }
2115 
2116   STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
2117   if (sk == NULL || n < 0 || (size_t)n >= sk_SSL_CIPHER_num(sk)) {
2118     return NULL;
2119   }
2120 
2121   const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, n);
2122   if (c == NULL) {
2123     return NULL;
2124   }
2125 
2126   return c->name;
2127 }
2128 
SSL_CTX_set_cipher_list(SSL_CTX * ctx,const char * str)2129 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) {
2130   const bool has_aes_hw = ctx->aes_hw_override ? ctx->aes_hw_override_value
2131                                                : EVP_has_aes_hardware();
2132   return ssl_create_cipher_list(&ctx->cipher_list, has_aes_hw, str,
2133                                 false /* not strict */);
2134 }
2135 
SSL_CTX_set_strict_cipher_list(SSL_CTX * ctx,const char * str)2136 int SSL_CTX_set_strict_cipher_list(SSL_CTX *ctx, const char *str) {
2137   const bool has_aes_hw = ctx->aes_hw_override ? ctx->aes_hw_override_value
2138                                                : EVP_has_aes_hardware();
2139   return ssl_create_cipher_list(&ctx->cipher_list, has_aes_hw, str,
2140                                 true /* strict */);
2141 }
2142 
SSL_set_cipher_list(SSL * ssl,const char * str)2143 int SSL_set_cipher_list(SSL *ssl, const char *str) {
2144   if (!ssl->config) {
2145     return 0;
2146   }
2147   const bool has_aes_hw = ssl->config->aes_hw_override
2148                               ? ssl->config->aes_hw_override_value
2149                               : EVP_has_aes_hardware();
2150   return ssl_create_cipher_list(&ssl->config->cipher_list, has_aes_hw, str,
2151                                 false /* not strict */);
2152 }
2153 
SSL_set_strict_cipher_list(SSL * ssl,const char * str)2154 int SSL_set_strict_cipher_list(SSL *ssl, const char *str) {
2155   if (!ssl->config) {
2156     return 0;
2157   }
2158   const bool has_aes_hw = ssl->config->aes_hw_override
2159                               ? ssl->config->aes_hw_override_value
2160                               : EVP_has_aes_hardware();
2161   return ssl_create_cipher_list(&ssl->config->cipher_list, has_aes_hw, str,
2162                                 true /* strict */);
2163 }
2164 
SSL_get_servername(const SSL * ssl,const int type)2165 const char *SSL_get_servername(const SSL *ssl, const int type) {
2166   if (type != TLSEXT_NAMETYPE_host_name) {
2167     return NULL;
2168   }
2169 
2170   // Historically, |SSL_get_servername| was also the configuration getter
2171   // corresponding to |SSL_set_tlsext_host_name|.
2172   if (ssl->hostname != nullptr) {
2173     return ssl->hostname.get();
2174   }
2175 
2176   return ssl->s3->hostname.get();
2177 }
2178 
SSL_get_servername_type(const SSL * ssl)2179 int SSL_get_servername_type(const SSL *ssl) {
2180   if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) == NULL) {
2181     return -1;
2182   }
2183   return TLSEXT_NAMETYPE_host_name;
2184 }
2185 
SSL_CTX_set_custom_verify(SSL_CTX * ctx,int mode,enum ssl_verify_result_t (* callback)(SSL * ssl,uint8_t * out_alert))2186 void SSL_CTX_set_custom_verify(
2187     SSL_CTX *ctx, int mode,
2188     enum ssl_verify_result_t (*callback)(SSL *ssl, uint8_t *out_alert)) {
2189   ctx->verify_mode = mode;
2190   ctx->custom_verify_callback = callback;
2191 }
2192 
SSL_set_custom_verify(SSL * ssl,int mode,enum ssl_verify_result_t (* callback)(SSL * ssl,uint8_t * out_alert))2193 void SSL_set_custom_verify(
2194     SSL *ssl, int mode,
2195     enum ssl_verify_result_t (*callback)(SSL *ssl, uint8_t *out_alert)) {
2196   if (!ssl->config) {
2197     return;
2198   }
2199   ssl->config->verify_mode = mode;
2200   ssl->config->custom_verify_callback = callback;
2201 }
2202 
SSL_CTX_enable_signed_cert_timestamps(SSL_CTX * ctx)2203 void SSL_CTX_enable_signed_cert_timestamps(SSL_CTX *ctx) {
2204   ctx->signed_cert_timestamps_enabled = true;
2205 }
2206 
SSL_enable_signed_cert_timestamps(SSL * ssl)2207 void SSL_enable_signed_cert_timestamps(SSL *ssl) {
2208   if (!ssl->config) {
2209     return;
2210   }
2211   ssl->config->signed_cert_timestamps_enabled = true;
2212 }
2213 
SSL_CTX_enable_ocsp_stapling(SSL_CTX * ctx)2214 void SSL_CTX_enable_ocsp_stapling(SSL_CTX *ctx) {
2215   ctx->ocsp_stapling_enabled = true;
2216 }
2217 
SSL_enable_ocsp_stapling(SSL * ssl)2218 void SSL_enable_ocsp_stapling(SSL *ssl) {
2219   if (!ssl->config) {
2220     return;
2221   }
2222   ssl->config->ocsp_stapling_enabled = true;
2223 }
2224 
SSL_get0_signed_cert_timestamp_list(const SSL * ssl,const uint8_t ** out,size_t * out_len)2225 void SSL_get0_signed_cert_timestamp_list(const SSL *ssl, const uint8_t **out,
2226                                          size_t *out_len) {
2227   SSL_SESSION *session = SSL_get_session(ssl);
2228   if (ssl->server || !session || !session->signed_cert_timestamp_list) {
2229     *out_len = 0;
2230     *out = NULL;
2231     return;
2232   }
2233 
2234   *out = CRYPTO_BUFFER_data(session->signed_cert_timestamp_list.get());
2235   *out_len = CRYPTO_BUFFER_len(session->signed_cert_timestamp_list.get());
2236 }
2237 
SSL_get0_ocsp_response(const SSL * ssl,const uint8_t ** out,size_t * out_len)2238 void SSL_get0_ocsp_response(const SSL *ssl, const uint8_t **out,
2239                             size_t *out_len) {
2240   SSL_SESSION *session = SSL_get_session(ssl);
2241   if (ssl->server || !session || !session->ocsp_response) {
2242     *out_len = 0;
2243     *out = NULL;
2244     return;
2245   }
2246 
2247   *out = CRYPTO_BUFFER_data(session->ocsp_response.get());
2248   *out_len = CRYPTO_BUFFER_len(session->ocsp_response.get());
2249 }
2250 
SSL_set_tlsext_host_name(SSL * ssl,const char * name)2251 int SSL_set_tlsext_host_name(SSL *ssl, const char *name) {
2252   ssl->hostname.reset();
2253   if (name == nullptr) {
2254     return 1;
2255   }
2256 
2257   size_t len = strlen(name);
2258   if (len == 0 || len > TLSEXT_MAXLEN_host_name) {
2259     OPENSSL_PUT_ERROR(SSL, SSL_R_SSL3_EXT_INVALID_SERVERNAME);
2260     return 0;
2261   }
2262   ssl->hostname.reset(OPENSSL_strdup(name));
2263   if (ssl->hostname == nullptr) {
2264     return 0;
2265   }
2266   return 1;
2267 }
2268 
SSL_CTX_set_tlsext_servername_callback(SSL_CTX * ctx,int (* callback)(SSL * ssl,int * out_alert,void * arg))2269 int SSL_CTX_set_tlsext_servername_callback(
2270     SSL_CTX *ctx, int (*callback)(SSL *ssl, int *out_alert, void *arg)) {
2271   ctx->servername_callback = callback;
2272   return 1;
2273 }
2274 
SSL_CTX_set_tlsext_servername_arg(SSL_CTX * ctx,void * arg)2275 int SSL_CTX_set_tlsext_servername_arg(SSL_CTX *ctx, void *arg) {
2276   ctx->servername_arg = arg;
2277   return 1;
2278 }
2279 
SSL_select_next_proto(uint8_t ** out,uint8_t * out_len,const uint8_t * peer,unsigned peer_len,const uint8_t * supported,unsigned supported_len)2280 int SSL_select_next_proto(uint8_t **out, uint8_t *out_len, const uint8_t *peer,
2281                           unsigned peer_len, const uint8_t *supported,
2282                           unsigned supported_len) {
2283   const uint8_t *result;
2284   int status;
2285 
2286   // For each protocol in peer preference order, see if we support it.
2287   for (unsigned i = 0; i < peer_len;) {
2288     for (unsigned j = 0; j < supported_len;) {
2289       if (peer[i] == supported[j] &&
2290           OPENSSL_memcmp(&peer[i + 1], &supported[j + 1], peer[i]) == 0) {
2291         // We found a match
2292         result = &peer[i];
2293         status = OPENSSL_NPN_NEGOTIATED;
2294         goto found;
2295       }
2296       j += supported[j];
2297       j++;
2298     }
2299     i += peer[i];
2300     i++;
2301   }
2302 
2303   // There's no overlap between our protocols and the peer's list.
2304   result = supported;
2305   status = OPENSSL_NPN_NO_OVERLAP;
2306 
2307 found:
2308   *out = (uint8_t *)result + 1;
2309   *out_len = result[0];
2310   return status;
2311 }
2312 
SSL_get0_next_proto_negotiated(const SSL * ssl,const uint8_t ** out_data,unsigned * out_len)2313 void SSL_get0_next_proto_negotiated(const SSL *ssl, const uint8_t **out_data,
2314                                     unsigned *out_len) {
2315   // NPN protocols have one-byte lengths, so they must fit in |unsigned|.
2316   assert(ssl->s3->next_proto_negotiated.size() <= UINT_MAX);
2317   *out_data = ssl->s3->next_proto_negotiated.data();
2318   *out_len = static_cast<unsigned>(ssl->s3->next_proto_negotiated.size());
2319 }
2320 
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)2321 void SSL_CTX_set_next_protos_advertised_cb(
2322     SSL_CTX *ctx,
2323     int (*cb)(SSL *ssl, const uint8_t **out, unsigned *out_len, void *arg),
2324     void *arg) {
2325   ctx->next_protos_advertised_cb = cb;
2326   ctx->next_protos_advertised_cb_arg = arg;
2327 }
2328 
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)2329 void SSL_CTX_set_next_proto_select_cb(
2330     SSL_CTX *ctx, int (*cb)(SSL *ssl, uint8_t **out, uint8_t *out_len,
2331                             const uint8_t *in, unsigned in_len, void *arg),
2332     void *arg) {
2333   ctx->next_proto_select_cb = cb;
2334   ctx->next_proto_select_cb_arg = arg;
2335 }
2336 
SSL_CTX_set_alpn_protos(SSL_CTX * ctx,const uint8_t * protos,size_t protos_len)2337 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos,
2338                             size_t protos_len) {
2339   // Note this function's return value is backwards.
2340   auto span = MakeConstSpan(protos, protos_len);
2341   if (!span.empty() && !ssl_is_valid_alpn_list(span)) {
2342     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL_LIST);
2343     return 1;
2344   }
2345   return ctx->alpn_client_proto_list.CopyFrom(span) ? 0 : 1;
2346 }
2347 
SSL_set_alpn_protos(SSL * ssl,const uint8_t * protos,size_t protos_len)2348 int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, size_t protos_len) {
2349   // Note this function's return value is backwards.
2350   if (!ssl->config) {
2351     return 1;
2352   }
2353   auto span = MakeConstSpan(protos, protos_len);
2354   if (!span.empty() && !ssl_is_valid_alpn_list(span)) {
2355     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL_LIST);
2356     return 1;
2357   }
2358   return ssl->config->alpn_client_proto_list.CopyFrom(span) ? 0 : 1;
2359 }
2360 
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)2361 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2362                                 int (*cb)(SSL *ssl, const uint8_t **out,
2363                                           uint8_t *out_len, const uint8_t *in,
2364                                           unsigned in_len, void *arg),
2365                                 void *arg) {
2366   ctx->alpn_select_cb = cb;
2367   ctx->alpn_select_cb_arg = arg;
2368 }
2369 
SSL_get0_alpn_selected(const SSL * ssl,const uint8_t ** out_data,unsigned * out_len)2370 void SSL_get0_alpn_selected(const SSL *ssl, const uint8_t **out_data,
2371                             unsigned *out_len) {
2372   Span<const uint8_t> protocol;
2373   if (SSL_in_early_data(ssl) && !ssl->server) {
2374     protocol = ssl->s3->hs->early_session->early_alpn;
2375   } else {
2376     protocol = ssl->s3->alpn_selected;
2377   }
2378   // ALPN protocols have one-byte lengths, so they must fit in |unsigned|.
2379   assert(protocol.size() < UINT_MAX);
2380   *out_data = protocol.data();
2381   *out_len = static_cast<unsigned>(protocol.size());
2382 }
2383 
SSL_CTX_set_allow_unknown_alpn_protos(SSL_CTX * ctx,int enabled)2384 void SSL_CTX_set_allow_unknown_alpn_protos(SSL_CTX *ctx, int enabled) {
2385   ctx->allow_unknown_alpn_protos = !!enabled;
2386 }
2387 
SSL_add_application_settings(SSL * ssl,const uint8_t * proto,size_t proto_len,const uint8_t * settings,size_t settings_len)2388 int SSL_add_application_settings(SSL *ssl, const uint8_t *proto,
2389                                  size_t proto_len, const uint8_t *settings,
2390                                  size_t settings_len) {
2391   if (!ssl->config) {
2392     return 0;
2393   }
2394   ALPSConfig config;
2395   if (!config.protocol.CopyFrom(MakeConstSpan(proto, proto_len)) ||
2396       !config.settings.CopyFrom(MakeConstSpan(settings, settings_len)) ||
2397       !ssl->config->alps_configs.Push(std::move(config))) {
2398     return 0;
2399   }
2400   return 1;
2401 }
2402 
SSL_get0_peer_application_settings(const SSL * ssl,const uint8_t ** out_data,size_t * out_len)2403 void SSL_get0_peer_application_settings(const SSL *ssl,
2404                                         const uint8_t **out_data,
2405                                         size_t *out_len) {
2406   const SSL_SESSION *session = SSL_get_session(ssl);
2407   Span<const uint8_t> settings =
2408       session ? session->peer_application_settings : Span<const uint8_t>();
2409   *out_data = settings.data();
2410   *out_len = settings.size();
2411 }
2412 
SSL_has_application_settings(const SSL * ssl)2413 int SSL_has_application_settings(const SSL *ssl) {
2414   const SSL_SESSION *session = SSL_get_session(ssl);
2415   return session && session->has_application_settings;
2416 }
2417 
SSL_set_alps_use_new_codepoint(SSL * ssl,int use_new)2418 void SSL_set_alps_use_new_codepoint(SSL *ssl, int use_new) {
2419   if (!ssl->config) {
2420     return;
2421   }
2422   ssl->config->alps_use_new_codepoint = !!use_new;
2423 }
2424 
SSL_CTX_add_cert_compression_alg(SSL_CTX * ctx,uint16_t alg_id,ssl_cert_compression_func_t compress,ssl_cert_decompression_func_t decompress)2425 int SSL_CTX_add_cert_compression_alg(SSL_CTX *ctx, uint16_t alg_id,
2426                                      ssl_cert_compression_func_t compress,
2427                                      ssl_cert_decompression_func_t decompress) {
2428   assert(compress != nullptr || decompress != nullptr);
2429 
2430   for (const auto &alg : ctx->cert_compression_algs) {
2431     if (alg.alg_id == alg_id) {
2432       return 0;
2433     }
2434   }
2435 
2436   CertCompressionAlg alg;
2437   alg.alg_id = alg_id;
2438   alg.compress = compress;
2439   alg.decompress = decompress;
2440   return ctx->cert_compression_algs.Push(alg);
2441 }
2442 
SSL_CTX_set_tls_channel_id_enabled(SSL_CTX * ctx,int enabled)2443 void SSL_CTX_set_tls_channel_id_enabled(SSL_CTX *ctx, int enabled) {
2444   ctx->channel_id_enabled = !!enabled;
2445 }
2446 
SSL_CTX_enable_tls_channel_id(SSL_CTX * ctx)2447 int SSL_CTX_enable_tls_channel_id(SSL_CTX *ctx) {
2448   SSL_CTX_set_tls_channel_id_enabled(ctx, 1);
2449   return 1;
2450 }
2451 
SSL_set_tls_channel_id_enabled(SSL * ssl,int enabled)2452 void SSL_set_tls_channel_id_enabled(SSL *ssl, int enabled) {
2453   if (!ssl->config) {
2454     return;
2455   }
2456   ssl->config->channel_id_enabled = !!enabled;
2457 }
2458 
SSL_enable_tls_channel_id(SSL * ssl)2459 int SSL_enable_tls_channel_id(SSL *ssl) {
2460   SSL_set_tls_channel_id_enabled(ssl, 1);
2461   return 1;
2462 }
2463 
is_p256_key(EVP_PKEY * private_key)2464 static int is_p256_key(EVP_PKEY *private_key) {
2465   const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(private_key);
2466   return ec_key != NULL &&
2467          EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key)) ==
2468              NID_X9_62_prime256v1;
2469 }
2470 
SSL_CTX_set1_tls_channel_id(SSL_CTX * ctx,EVP_PKEY * private_key)2471 int SSL_CTX_set1_tls_channel_id(SSL_CTX *ctx, EVP_PKEY *private_key) {
2472   if (!is_p256_key(private_key)) {
2473     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
2474     return 0;
2475   }
2476 
2477   ctx->channel_id_private = UpRef(private_key);
2478   return 1;
2479 }
2480 
SSL_set1_tls_channel_id(SSL * ssl,EVP_PKEY * private_key)2481 int SSL_set1_tls_channel_id(SSL *ssl, EVP_PKEY *private_key) {
2482   if (!ssl->config) {
2483     return 0;
2484   }
2485   if (!is_p256_key(private_key)) {
2486     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
2487     return 0;
2488   }
2489 
2490   ssl->config->channel_id_private = UpRef(private_key);
2491   return 1;
2492 }
2493 
SSL_get_tls_channel_id(SSL * ssl,uint8_t * out,size_t max_out)2494 size_t SSL_get_tls_channel_id(SSL *ssl, uint8_t *out, size_t max_out) {
2495   if (!ssl->s3->channel_id_valid) {
2496     return 0;
2497   }
2498   OPENSSL_memcpy(out, ssl->s3->channel_id, (max_out < 64) ? max_out : 64);
2499   return 64;
2500 }
2501 
SSL_get0_certificate_types(const SSL * ssl,const uint8_t ** out_types)2502 size_t SSL_get0_certificate_types(const SSL *ssl, const uint8_t **out_types) {
2503   Span<const uint8_t> types;
2504   if (!ssl->server && ssl->s3->hs != nullptr) {
2505     types = ssl->s3->hs->certificate_types;
2506   }
2507   *out_types = types.data();
2508   return types.size();
2509 }
2510 
SSL_get0_peer_verify_algorithms(const SSL * ssl,const uint16_t ** out_sigalgs)2511 size_t SSL_get0_peer_verify_algorithms(const SSL *ssl,
2512                                        const uint16_t **out_sigalgs) {
2513   Span<const uint16_t> sigalgs;
2514   if (ssl->s3->hs != nullptr) {
2515     sigalgs = ssl->s3->hs->peer_sigalgs;
2516   }
2517   *out_sigalgs = sigalgs.data();
2518   return sigalgs.size();
2519 }
2520 
SSL_get0_peer_delegation_algorithms(const SSL * ssl,const uint16_t ** out_sigalgs)2521 size_t SSL_get0_peer_delegation_algorithms(const SSL *ssl,
2522                                            const uint16_t **out_sigalgs){
2523   Span<const uint16_t> sigalgs;
2524   if (ssl->s3->hs != nullptr) {
2525     sigalgs = ssl->s3->hs->peer_delegated_credential_sigalgs;
2526   }
2527   *out_sigalgs = sigalgs.data();
2528   return sigalgs.size();
2529 }
2530 
SSL_get_privatekey(const SSL * ssl)2531 EVP_PKEY *SSL_get_privatekey(const SSL *ssl) {
2532   if (!ssl->config) {
2533     assert(ssl->config);
2534     return nullptr;
2535   }
2536   return ssl->config->cert->default_credential->privkey.get();
2537 }
2538 
SSL_CTX_get0_privatekey(const SSL_CTX * ctx)2539 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx) {
2540   return ctx->cert->default_credential->privkey.get();
2541 }
2542 
SSL_get_current_cipher(const SSL * ssl)2543 const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl) {
2544   const SSL_SESSION *session = SSL_get_session(ssl);
2545   return session == nullptr ? nullptr : session->cipher;
2546 }
2547 
SSL_session_reused(const SSL * ssl)2548 int SSL_session_reused(const SSL *ssl) {
2549   return ssl->s3->session_reused || SSL_in_early_data(ssl);
2550 }
2551 
SSL_get_current_compression(SSL * ssl)2552 const COMP_METHOD *SSL_get_current_compression(SSL *ssl) { return NULL; }
2553 
SSL_get_current_expansion(SSL * ssl)2554 const COMP_METHOD *SSL_get_current_expansion(SSL *ssl) { return NULL; }
2555 
SSL_get_server_tmp_key(SSL * ssl,EVP_PKEY ** out_key)2556 int SSL_get_server_tmp_key(SSL *ssl, EVP_PKEY **out_key) { return 0; }
2557 
SSL_CTX_set_quiet_shutdown(SSL_CTX * ctx,int mode)2558 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode) {
2559   ctx->quiet_shutdown = (mode != 0);
2560 }
2561 
SSL_CTX_get_quiet_shutdown(const SSL_CTX * ctx)2562 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx) {
2563   return ctx->quiet_shutdown;
2564 }
2565 
SSL_set_quiet_shutdown(SSL * ssl,int mode)2566 void SSL_set_quiet_shutdown(SSL *ssl, int mode) {
2567   ssl->quiet_shutdown = (mode != 0);
2568 }
2569 
SSL_get_quiet_shutdown(const SSL * ssl)2570 int SSL_get_quiet_shutdown(const SSL *ssl) { return ssl->quiet_shutdown; }
2571 
SSL_set_shutdown(SSL * ssl,int mode)2572 void SSL_set_shutdown(SSL *ssl, int mode) {
2573   // It is an error to clear any bits that have already been set. (We can't try
2574   // to get a second close_notify or send two.)
2575   assert((SSL_get_shutdown(ssl) & mode) == SSL_get_shutdown(ssl));
2576 
2577   if (mode & SSL_RECEIVED_SHUTDOWN &&
2578       ssl->s3->read_shutdown == ssl_shutdown_none) {
2579     ssl->s3->read_shutdown = ssl_shutdown_close_notify;
2580   }
2581 
2582   if (mode & SSL_SENT_SHUTDOWN &&
2583       ssl->s3->write_shutdown == ssl_shutdown_none) {
2584     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
2585   }
2586 }
2587 
SSL_get_shutdown(const SSL * ssl)2588 int SSL_get_shutdown(const SSL *ssl) {
2589   int ret = 0;
2590   if (ssl->s3->read_shutdown != ssl_shutdown_none) {
2591     // Historically, OpenSSL set |SSL_RECEIVED_SHUTDOWN| on both close_notify
2592     // and fatal alert.
2593     ret |= SSL_RECEIVED_SHUTDOWN;
2594   }
2595   if (ssl->s3->write_shutdown == ssl_shutdown_close_notify) {
2596     // Historically, OpenSSL set |SSL_SENT_SHUTDOWN| on only close_notify.
2597     ret |= SSL_SENT_SHUTDOWN;
2598   }
2599   return ret;
2600 }
2601 
SSL_get_SSL_CTX(const SSL * ssl)2602 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl) { return ssl->ctx.get(); }
2603 
SSL_set_SSL_CTX(SSL * ssl,SSL_CTX * ctx)2604 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx) {
2605   if (!ssl->config) {
2606     return NULL;
2607   }
2608   if (ssl->ctx.get() == ctx) {
2609     return ssl->ctx.get();
2610   }
2611 
2612   // One cannot change the X.509 callbacks during a connection.
2613   if (ssl->ctx->x509_method != ctx->x509_method) {
2614     assert(0);
2615     return NULL;
2616   }
2617 
2618   UniquePtr<CERT> new_cert = ssl_cert_dup(ctx->cert.get());
2619   if (!new_cert) {
2620     return nullptr;
2621   }
2622 
2623   ssl->config->cert = std::move(new_cert);
2624   ssl->ctx = UpRef(ctx);
2625   ssl->enable_early_data = ssl->ctx->enable_early_data;
2626 
2627   return ssl->ctx.get();
2628 }
2629 
SSL_set_info_callback(SSL * ssl,void (* cb)(const SSL * ssl,int type,int value))2630 void SSL_set_info_callback(SSL *ssl,
2631                            void (*cb)(const SSL *ssl, int type, int value)) {
2632   ssl->info_callback = cb;
2633 }
2634 
SSL_get_info_callback(const SSL * ssl)2635 void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type,
2636                                               int value) {
2637   return ssl->info_callback;
2638 }
2639 
SSL_state(const SSL * ssl)2640 int SSL_state(const SSL *ssl) {
2641   return SSL_in_init(ssl) ? SSL_ST_INIT : SSL_ST_OK;
2642 }
2643 
SSL_set_state(SSL * ssl,int state)2644 void SSL_set_state(SSL *ssl, int state) { }
2645 
SSL_get_shared_ciphers(const SSL * ssl,char * buf,int len)2646 char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len) {
2647   if (len <= 0) {
2648     return NULL;
2649   }
2650   buf[0] = '\0';
2651   return buf;
2652 }
2653 
SSL_get_shared_sigalgs(SSL * ssl,int idx,int * psign,int * phash,int * psignandhash,uint8_t * rsig,uint8_t * rhash)2654 int SSL_get_shared_sigalgs(SSL *ssl, int idx, int *psign, int *phash,
2655                            int *psignandhash, uint8_t *rsig, uint8_t *rhash) {
2656   return 0;
2657 }
2658 
SSL_CTX_set_quic_method(SSL_CTX * ctx,const SSL_QUIC_METHOD * quic_method)2659 int SSL_CTX_set_quic_method(SSL_CTX *ctx, const SSL_QUIC_METHOD *quic_method) {
2660   if (ctx->method->is_dtls) {
2661     return 0;
2662   }
2663   ctx->quic_method = quic_method;
2664   return 1;
2665 }
2666 
SSL_set_quic_method(SSL * ssl,const SSL_QUIC_METHOD * quic_method)2667 int SSL_set_quic_method(SSL *ssl, const SSL_QUIC_METHOD *quic_method) {
2668   if (ssl->method->is_dtls) {
2669     return 0;
2670   }
2671   ssl->quic_method = quic_method;
2672   return 1;
2673 }
2674 
SSL_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)2675 int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
2676                          CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
2677   return CRYPTO_get_ex_new_index_ex(&g_ex_data_class_ssl, argl, argp,
2678                                     free_func);
2679 }
2680 
SSL_set_ex_data(SSL * ssl,int idx,void * data)2681 int SSL_set_ex_data(SSL *ssl, int idx, void *data) {
2682   return CRYPTO_set_ex_data(&ssl->ex_data, idx, data);
2683 }
2684 
SSL_get_ex_data(const SSL * ssl,int idx)2685 void *SSL_get_ex_data(const SSL *ssl, int idx) {
2686   return CRYPTO_get_ex_data(&ssl->ex_data, idx);
2687 }
2688 
SSL_CTX_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)2689 int SSL_CTX_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
2690                              CRYPTO_EX_dup *dup_unused,
2691                              CRYPTO_EX_free *free_func) {
2692   return CRYPTO_get_ex_new_index_ex(&g_ex_data_class_ssl_ctx, argl, argp,
2693                                  free_func);
2694 }
2695 
SSL_CTX_set_ex_data(SSL_CTX * ctx,int idx,void * data)2696 int SSL_CTX_set_ex_data(SSL_CTX *ctx, int idx, void *data) {
2697   return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2698 }
2699 
SSL_CTX_get_ex_data(const SSL_CTX * ctx,int idx)2700 void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx) {
2701   return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2702 }
2703 
SSL_want(const SSL * ssl)2704 int SSL_want(const SSL *ssl) {
2705   // Historically, OpenSSL did not track |SSL_ERROR_ZERO_RETURN| as an |rwstate|
2706   // value. We do, but map it back to |SSL_ERROR_NONE| to preserve the original
2707   // behavior.
2708   return ssl->s3->rwstate == SSL_ERROR_ZERO_RETURN ? SSL_ERROR_NONE
2709                                                    : ssl->s3->rwstate;
2710 }
2711 
SSL_CTX_set_tmp_rsa_callback(SSL_CTX * ctx,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2712 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,
2713                                   RSA *(*cb)(SSL *ssl, int is_export,
2714                                              int keylength)) {}
2715 
SSL_set_tmp_rsa_callback(SSL * ssl,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2716 void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
2717                                                    int keylength)) {}
2718 
SSL_CTX_set_tmp_dh_callback(SSL_CTX * ctx,DH * (* cb)(SSL * ssl,int is_export,int keylength))2719 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
2720                                  DH *(*cb)(SSL *ssl, int is_export,
2721                                            int keylength)) {}
2722 
SSL_set_tmp_dh_callback(SSL * ssl,DH * (* cb)(SSL * ssl,int is_export,int keylength))2723 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*cb)(SSL *ssl, int is_export,
2724                                                  int keylength)) {}
2725 
use_psk_identity_hint(UniquePtr<char> * out,const char * identity_hint)2726 static int use_psk_identity_hint(UniquePtr<char> *out,
2727                                  const char *identity_hint) {
2728   if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
2729     OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
2730     return 0;
2731   }
2732 
2733   // Clear currently configured hint, if any.
2734   out->reset();
2735 
2736   // Treat the empty hint as not supplying one. Plain PSK makes it possible to
2737   // send either no hint (omit ServerKeyExchange) or an empty hint, while
2738   // ECDHE_PSK can only spell empty hint. Having different capabilities is odd,
2739   // so we interpret empty and missing as identical.
2740   if (identity_hint != NULL && identity_hint[0] != '\0') {
2741     out->reset(OPENSSL_strdup(identity_hint));
2742     if (*out == nullptr) {
2743       return 0;
2744     }
2745   }
2746 
2747   return 1;
2748 }
2749 
SSL_CTX_use_psk_identity_hint(SSL_CTX * ctx,const char * identity_hint)2750 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint) {
2751   return use_psk_identity_hint(&ctx->psk_identity_hint, identity_hint);
2752 }
2753 
SSL_use_psk_identity_hint(SSL * ssl,const char * identity_hint)2754 int SSL_use_psk_identity_hint(SSL *ssl, const char *identity_hint) {
2755   if (!ssl->config) {
2756     return 0;
2757   }
2758   return use_psk_identity_hint(&ssl->config->psk_identity_hint, identity_hint);
2759 }
2760 
SSL_get_psk_identity_hint(const SSL * ssl)2761 const char *SSL_get_psk_identity_hint(const SSL *ssl) {
2762   if (ssl == NULL) {
2763     return NULL;
2764   }
2765   if (ssl->config == NULL) {
2766     assert(ssl->config);
2767     return NULL;
2768   }
2769   return ssl->config->psk_identity_hint.get();
2770 }
2771 
SSL_get_psk_identity(const SSL * ssl)2772 const char *SSL_get_psk_identity(const SSL *ssl) {
2773   if (ssl == NULL) {
2774     return NULL;
2775   }
2776   SSL_SESSION *session = SSL_get_session(ssl);
2777   if (session == NULL) {
2778     return NULL;
2779   }
2780   return session->psk_identity.get();
2781 }
2782 
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))2783 void SSL_set_psk_client_callback(
2784     SSL *ssl, unsigned (*cb)(SSL *ssl, const char *hint, char *identity,
2785                              unsigned max_identity_len, uint8_t *psk,
2786                              unsigned max_psk_len)) {
2787   if (!ssl->config) {
2788     return;
2789   }
2790   ssl->config->psk_client_callback = cb;
2791 }
2792 
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))2793 void SSL_CTX_set_psk_client_callback(
2794     SSL_CTX *ctx, unsigned (*cb)(SSL *ssl, const char *hint, char *identity,
2795                                  unsigned max_identity_len, uint8_t *psk,
2796                                  unsigned max_psk_len)) {
2797   ctx->psk_client_callback = cb;
2798 }
2799 
SSL_set_psk_server_callback(SSL * ssl,unsigned (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned max_psk_len))2800 void SSL_set_psk_server_callback(
2801     SSL *ssl, unsigned (*cb)(SSL *ssl, const char *identity, uint8_t *psk,
2802                              unsigned max_psk_len)) {
2803   if (!ssl->config) {
2804     return;
2805   }
2806   ssl->config->psk_server_callback = cb;
2807 }
2808 
SSL_CTX_set_psk_server_callback(SSL_CTX * ctx,unsigned (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned max_psk_len))2809 void SSL_CTX_set_psk_server_callback(
2810     SSL_CTX *ctx, unsigned (*cb)(SSL *ssl, const char *identity,
2811                                  uint8_t *psk, unsigned max_psk_len)) {
2812   ctx->psk_server_callback = cb;
2813 }
2814 
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))2815 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
2816                               void (*cb)(int write_p, int version,
2817                                          int content_type, const void *buf,
2818                                          size_t len, SSL *ssl, void *arg)) {
2819   ctx->msg_callback = cb;
2820 }
2821 
SSL_CTX_set_msg_callback_arg(SSL_CTX * ctx,void * arg)2822 void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg) {
2823   ctx->msg_callback_arg = arg;
2824 }
2825 
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))2826 void SSL_set_msg_callback(SSL *ssl,
2827                           void (*cb)(int write_p, int version, int content_type,
2828                                      const void *buf, size_t len, SSL *ssl,
2829                                      void *arg)) {
2830   ssl->msg_callback = cb;
2831 }
2832 
SSL_set_msg_callback_arg(SSL * ssl,void * arg)2833 void SSL_set_msg_callback_arg(SSL *ssl, void *arg) {
2834   ssl->msg_callback_arg = arg;
2835 }
2836 
SSL_CTX_set_keylog_callback(SSL_CTX * ctx,void (* cb)(const SSL * ssl,const char * line))2837 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx,
2838                                  void (*cb)(const SSL *ssl, const char *line)) {
2839   ctx->keylog_callback = cb;
2840 }
2841 
SSL_CTX_get_keylog_callback(const SSL_CTX * ctx)2842 void (*SSL_CTX_get_keylog_callback(const SSL_CTX *ctx))(const SSL *ssl,
2843                                                         const char *line) {
2844   return ctx->keylog_callback;
2845 }
2846 
SSL_CTX_set_current_time_cb(SSL_CTX * ctx,void (* cb)(const SSL * ssl,struct timeval * out_clock))2847 void SSL_CTX_set_current_time_cb(SSL_CTX *ctx,
2848                                  void (*cb)(const SSL *ssl,
2849                                             struct timeval *out_clock)) {
2850   ctx->current_time_cb = cb;
2851 }
2852 
SSL_can_release_private_key(const SSL * ssl)2853 int SSL_can_release_private_key(const SSL *ssl) {
2854   if (ssl_can_renegotiate(ssl)) {
2855     // If the connection can renegotiate (client only), the private key may be
2856     // used in a future handshake.
2857     return 0;
2858   }
2859 
2860   // Otherwise, this is determined by the current handshake.
2861   return !ssl->s3->hs || ssl->s3->hs->can_release_private_key;
2862 }
2863 
SSL_is_init_finished(const SSL * ssl)2864 int SSL_is_init_finished(const SSL *ssl) {
2865   return !SSL_in_init(ssl);
2866 }
2867 
SSL_in_init(const SSL * ssl)2868 int SSL_in_init(const SSL *ssl) {
2869   // This returns false once all the handshake state has been finalized, to
2870   // allow callbacks and getters based on SSL_in_init to return the correct
2871   // values.
2872   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
2873   return hs != nullptr && !hs->handshake_finalized;
2874 }
2875 
SSL_in_false_start(const SSL * ssl)2876 int SSL_in_false_start(const SSL *ssl) {
2877   if (ssl->s3->hs == NULL) {
2878     return 0;
2879   }
2880   return ssl->s3->hs->in_false_start;
2881 }
2882 
SSL_cutthrough_complete(const SSL * ssl)2883 int SSL_cutthrough_complete(const SSL *ssl) {
2884   return SSL_in_false_start(ssl);
2885 }
2886 
SSL_is_server(const SSL * ssl)2887 int SSL_is_server(const SSL *ssl) { return ssl->server; }
2888 
SSL_is_dtls(const SSL * ssl)2889 int SSL_is_dtls(const SSL *ssl) { return ssl->method->is_dtls; }
2890 
SSL_CTX_set_select_certificate_cb(SSL_CTX * ctx,enum ssl_select_cert_result_t (* cb)(const SSL_CLIENT_HELLO *))2891 void SSL_CTX_set_select_certificate_cb(
2892     SSL_CTX *ctx,
2893     enum ssl_select_cert_result_t (*cb)(const SSL_CLIENT_HELLO *)) {
2894   ctx->select_certificate_cb = cb;
2895 }
2896 
SSL_CTX_set_dos_protection_cb(SSL_CTX * ctx,int (* cb)(const SSL_CLIENT_HELLO *))2897 void SSL_CTX_set_dos_protection_cb(SSL_CTX *ctx,
2898                                    int (*cb)(const SSL_CLIENT_HELLO *)) {
2899   ctx->dos_protection_cb = cb;
2900 }
2901 
SSL_CTX_set_reverify_on_resume(SSL_CTX * ctx,int enabled)2902 void SSL_CTX_set_reverify_on_resume(SSL_CTX *ctx, int enabled) {
2903   ctx->reverify_on_resume = !!enabled;
2904 }
2905 
SSL_set_enforce_rsa_key_usage(SSL * ssl,int enabled)2906 void SSL_set_enforce_rsa_key_usage(SSL *ssl, int enabled) {
2907   if (!ssl->config) {
2908     return;
2909   }
2910   ssl->config->enforce_rsa_key_usage = !!enabled;
2911 }
2912 
SSL_was_key_usage_invalid(const SSL * ssl)2913 int SSL_was_key_usage_invalid(const SSL *ssl) {
2914   return ssl->s3->was_key_usage_invalid;
2915 }
2916 
SSL_set_renegotiate_mode(SSL * ssl,enum ssl_renegotiate_mode_t mode)2917 void SSL_set_renegotiate_mode(SSL *ssl, enum ssl_renegotiate_mode_t mode) {
2918   ssl->renegotiate_mode = mode;
2919 
2920   // Check if |ssl_can_renegotiate| has changed and the configuration may now be
2921   // shed. HTTP clients may initially allow renegotiation for HTTP/1.1, and then
2922   // disable after the handshake once the ALPN protocol is known to be HTTP/2.
2923   ssl_maybe_shed_handshake_config(ssl);
2924 }
2925 
SSL_get_ivs(const SSL * ssl,const uint8_t ** out_read_iv,const uint8_t ** out_write_iv,size_t * out_iv_len)2926 int SSL_get_ivs(const SSL *ssl, const uint8_t **out_read_iv,
2927                 const uint8_t **out_write_iv, size_t *out_iv_len) {
2928   size_t write_iv_len;
2929   if (!ssl->s3->aead_read_ctx->GetIV(out_read_iv, out_iv_len) ||
2930       !ssl->s3->aead_write_ctx->GetIV(out_write_iv, &write_iv_len) ||
2931       *out_iv_len != write_iv_len) {
2932     return 0;
2933   }
2934 
2935   return 1;
2936 }
2937 
SSL_get_read_sequence(const SSL * ssl)2938 uint64_t SSL_get_read_sequence(const SSL *ssl) {
2939   if (SSL_is_dtls(ssl)) {
2940     // max_seq_num already includes the epoch.
2941     assert(ssl->d1->r_epoch == (ssl->d1->bitmap.max_seq_num >> 48));
2942     return ssl->d1->bitmap.max_seq_num;
2943   }
2944   return ssl->s3->read_sequence;
2945 }
2946 
SSL_get_write_sequence(const SSL * ssl)2947 uint64_t SSL_get_write_sequence(const SSL *ssl) {
2948   uint64_t ret = ssl->s3->write_sequence;
2949   if (SSL_is_dtls(ssl)) {
2950     assert((ret >> 48) == 0);
2951     ret |= uint64_t{ssl->d1->w_epoch} << 48;
2952   }
2953   return ret;
2954 }
2955 
SSL_get_peer_signature_algorithm(const SSL * ssl)2956 uint16_t SSL_get_peer_signature_algorithm(const SSL *ssl) {
2957   SSL_SESSION *session = SSL_get_session(ssl);
2958   if (session == NULL) {
2959     return 0;
2960   }
2961 
2962   return session->peer_signature_algorithm;
2963 }
2964 
SSL_get_client_random(const SSL * ssl,uint8_t * out,size_t max_out)2965 size_t SSL_get_client_random(const SSL *ssl, uint8_t *out, size_t max_out) {
2966   if (max_out == 0) {
2967     return sizeof(ssl->s3->client_random);
2968   }
2969   if (max_out > sizeof(ssl->s3->client_random)) {
2970     max_out = sizeof(ssl->s3->client_random);
2971   }
2972   OPENSSL_memcpy(out, ssl->s3->client_random, max_out);
2973   return max_out;
2974 }
2975 
SSL_get_server_random(const SSL * ssl,uint8_t * out,size_t max_out)2976 size_t SSL_get_server_random(const SSL *ssl, uint8_t *out, size_t max_out) {
2977   if (max_out == 0) {
2978     return sizeof(ssl->s3->server_random);
2979   }
2980   if (max_out > sizeof(ssl->s3->server_random)) {
2981     max_out = sizeof(ssl->s3->server_random);
2982   }
2983   OPENSSL_memcpy(out, ssl->s3->server_random, max_out);
2984   return max_out;
2985 }
2986 
SSL_get_pending_cipher(const SSL * ssl)2987 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *ssl) {
2988   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
2989   if (hs == NULL) {
2990     return NULL;
2991   }
2992   return hs->new_cipher;
2993 }
2994 
SSL_set_retain_only_sha256_of_client_certs(SSL * ssl,int enabled)2995 void SSL_set_retain_only_sha256_of_client_certs(SSL *ssl, int enabled) {
2996   if (!ssl->config) {
2997     return;
2998   }
2999   ssl->config->retain_only_sha256_of_client_certs = !!enabled;
3000 }
3001 
SSL_CTX_set_retain_only_sha256_of_client_certs(SSL_CTX * ctx,int enabled)3002 void SSL_CTX_set_retain_only_sha256_of_client_certs(SSL_CTX *ctx, int enabled) {
3003   ctx->retain_only_sha256_of_client_certs = !!enabled;
3004 }
3005 
SSL_CTX_set_grease_enabled(SSL_CTX * ctx,int enabled)3006 void SSL_CTX_set_grease_enabled(SSL_CTX *ctx, int enabled) {
3007   ctx->grease_enabled = !!enabled;
3008 }
3009 
SSL_CTX_set_permute_extensions(SSL_CTX * ctx,int enabled)3010 void SSL_CTX_set_permute_extensions(SSL_CTX *ctx, int enabled) {
3011   ctx->permute_extensions = !!enabled;
3012 }
3013 
SSL_set_permute_extensions(SSL * ssl,int enabled)3014 void SSL_set_permute_extensions(SSL *ssl, int enabled) {
3015   if (!ssl->config) {
3016     return;
3017   }
3018   ssl->config->permute_extensions = !!enabled;
3019 }
3020 
SSL_get_ticket_age_skew(const SSL * ssl)3021 int32_t SSL_get_ticket_age_skew(const SSL *ssl) {
3022   return ssl->s3->ticket_age_skew;
3023 }
3024 
SSL_CTX_set_false_start_allowed_without_alpn(SSL_CTX * ctx,int allowed)3025 void SSL_CTX_set_false_start_allowed_without_alpn(SSL_CTX *ctx, int allowed) {
3026   ctx->false_start_allowed_without_alpn = !!allowed;
3027 }
3028 
SSL_used_hello_retry_request(const SSL * ssl)3029 int SSL_used_hello_retry_request(const SSL *ssl) {
3030   return ssl->s3->used_hello_retry_request;
3031 }
3032 
SSL_set_shed_handshake_config(SSL * ssl,int enable)3033 void SSL_set_shed_handshake_config(SSL *ssl, int enable) {
3034   if (!ssl->config) {
3035     return;
3036   }
3037   ssl->config->shed_handshake_config = !!enable;
3038 }
3039 
SSL_set_jdk11_workaround(SSL * ssl,int enable)3040 void SSL_set_jdk11_workaround(SSL *ssl, int enable) {
3041   if (!ssl->config) {
3042     return;
3043   }
3044   ssl->config->jdk11_workaround = !!enable;
3045 }
3046 
SSL_set_check_client_certificate_type(SSL * ssl,int enable)3047 void SSL_set_check_client_certificate_type(SSL *ssl, int enable) {
3048   if (!ssl->config) {
3049     return;
3050   }
3051   ssl->config->check_client_certificate_type = !!enable;
3052 }
3053 
SSL_set_check_ecdsa_curve(SSL * ssl,int enable)3054 void SSL_set_check_ecdsa_curve(SSL *ssl, int enable) {
3055   if (!ssl->config) {
3056     return;
3057   }
3058   ssl->config->check_ecdsa_curve = !!enable;
3059 }
3060 
SSL_set_quic_use_legacy_codepoint(SSL * ssl,int use_legacy)3061 void SSL_set_quic_use_legacy_codepoint(SSL *ssl, int use_legacy) {
3062   if (!ssl->config) {
3063     return;
3064   }
3065   ssl->config->quic_use_legacy_codepoint = !!use_legacy;
3066 }
3067 
SSL_clear(SSL * ssl)3068 int SSL_clear(SSL *ssl) {
3069   if (!ssl->config) {
3070     return 0;  // SSL_clear may not be used after shedding config.
3071   }
3072 
3073   // In OpenSSL, reusing a client |SSL| with |SSL_clear| causes the previously
3074   // established session to be offered the next time around. wpa_supplicant
3075   // depends on this behavior, so emulate it.
3076   UniquePtr<SSL_SESSION> session;
3077   if (!ssl->server && ssl->s3->established_session != NULL) {
3078     session = UpRef(ssl->s3->established_session);
3079   }
3080 
3081   // The ssl->d1->mtu is simultaneously configuration (preserved across
3082   // clear) and connection-specific state (gets reset).
3083   //
3084   // TODO(davidben): Avoid this.
3085   unsigned mtu = 0;
3086   if (ssl->d1 != NULL) {
3087     mtu = ssl->d1->mtu;
3088   }
3089 
3090   ssl->method->ssl_free(ssl);
3091   if (!ssl->method->ssl_new(ssl)) {
3092     return 0;
3093   }
3094 
3095   if (SSL_is_dtls(ssl) && (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
3096     ssl->d1->mtu = mtu;
3097   }
3098 
3099   if (session != nullptr) {
3100     SSL_set_session(ssl, session.get());
3101   }
3102 
3103   return 1;
3104 }
3105 
SSL_CTX_sess_connect(const SSL_CTX * ctx)3106 int SSL_CTX_sess_connect(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_good(const SSL_CTX * ctx)3107 int SSL_CTX_sess_connect_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_renegotiate(const SSL_CTX * ctx)3108 int SSL_CTX_sess_connect_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept(const SSL_CTX * ctx)3109 int SSL_CTX_sess_accept(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_renegotiate(const SSL_CTX * ctx)3110 int SSL_CTX_sess_accept_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_good(const SSL_CTX * ctx)3111 int SSL_CTX_sess_accept_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_hits(const SSL_CTX * ctx)3112 int SSL_CTX_sess_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cb_hits(const SSL_CTX * ctx)3113 int SSL_CTX_sess_cb_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_misses(const SSL_CTX * ctx)3114 int SSL_CTX_sess_misses(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_timeouts(const SSL_CTX * ctx)3115 int SSL_CTX_sess_timeouts(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cache_full(const SSL_CTX * ctx)3116 int SSL_CTX_sess_cache_full(const SSL_CTX *ctx) { return 0; }
3117 
SSL_num_renegotiations(const SSL * ssl)3118 int SSL_num_renegotiations(const SSL *ssl) {
3119   return SSL_total_renegotiations(ssl);
3120 }
3121 
SSL_CTX_need_tmp_RSA(const SSL_CTX * ctx)3122 int SSL_CTX_need_tmp_RSA(const SSL_CTX *ctx) { return 0; }
SSL_need_tmp_RSA(const SSL * ssl)3123 int SSL_need_tmp_RSA(const SSL *ssl) { return 0; }
SSL_CTX_set_tmp_rsa(SSL_CTX * ctx,const RSA * rsa)3124 int SSL_CTX_set_tmp_rsa(SSL_CTX *ctx, const RSA *rsa) { return 1; }
SSL_set_tmp_rsa(SSL * ssl,const RSA * rsa)3125 int SSL_set_tmp_rsa(SSL *ssl, const RSA *rsa) { return 1; }
ERR_load_SSL_strings(void)3126 void ERR_load_SSL_strings(void) {}
SSL_load_error_strings(void)3127 void SSL_load_error_strings(void) {}
SSL_cache_hit(SSL * ssl)3128 int SSL_cache_hit(SSL *ssl) { return SSL_session_reused(ssl); }
3129 
SSL_CTX_set_tmp_ecdh(SSL_CTX * ctx,const EC_KEY * ec_key)3130 int SSL_CTX_set_tmp_ecdh(SSL_CTX *ctx, const EC_KEY *ec_key) {
3131   if (ec_key == NULL || EC_KEY_get0_group(ec_key) == NULL) {
3132     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
3133     return 0;
3134   }
3135   int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key));
3136   return SSL_CTX_set1_groups(ctx, &nid, 1);
3137 }
3138 
SSL_set_tmp_ecdh(SSL * ssl,const EC_KEY * ec_key)3139 int SSL_set_tmp_ecdh(SSL *ssl, const EC_KEY *ec_key) {
3140   if (ec_key == NULL || EC_KEY_get0_group(ec_key) == NULL) {
3141     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
3142     return 0;
3143   }
3144   int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key));
3145   return SSL_set1_groups(ssl, &nid, 1);
3146 }
3147 
SSL_CTX_set_ticket_aead_method(SSL_CTX * ctx,const SSL_TICKET_AEAD_METHOD * aead_method)3148 void SSL_CTX_set_ticket_aead_method(SSL_CTX *ctx,
3149                                     const SSL_TICKET_AEAD_METHOD *aead_method) {
3150   ctx->ticket_aead_method = aead_method;
3151 }
3152 
SSL_process_tls13_new_session_ticket(SSL * ssl,const uint8_t * buf,size_t buf_len)3153 SSL_SESSION *SSL_process_tls13_new_session_ticket(SSL *ssl, const uint8_t *buf,
3154                                                   size_t buf_len) {
3155   if (SSL_in_init(ssl) ||
3156       ssl_protocol_version(ssl) != TLS1_3_VERSION ||
3157       ssl->server) {
3158     // Only TLS 1.3 clients are supported.
3159     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3160     return nullptr;
3161   }
3162 
3163   CBS cbs, body;
3164   CBS_init(&cbs, buf, buf_len);
3165   uint8_t type;
3166   if (!CBS_get_u8(&cbs, &type) ||
3167       !CBS_get_u24_length_prefixed(&cbs, &body) ||
3168       CBS_len(&cbs) != 0) {
3169     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3170     return nullptr;
3171   }
3172 
3173   UniquePtr<SSL_SESSION> session = tls13_create_session_with_ticket(ssl, &body);
3174   if (!session) {
3175     // |tls13_create_session_with_ticket| puts the correct error.
3176     return nullptr;
3177   }
3178   return session.release();
3179 }
3180 
SSL_CTX_set_num_tickets(SSL_CTX * ctx,size_t num_tickets)3181 int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets) {
3182   num_tickets = std::min(num_tickets, kMaxTickets);
3183   static_assert(kMaxTickets <= 0xff, "Too many tickets.");
3184   ctx->num_tickets = static_cast<uint8_t>(num_tickets);
3185   return 1;
3186 }
3187 
SSL_CTX_get_num_tickets(const SSL_CTX * ctx)3188 size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx) { return ctx->num_tickets; }
3189 
SSL_set_tlsext_status_type(SSL * ssl,int type)3190 int SSL_set_tlsext_status_type(SSL *ssl, int type) {
3191   if (!ssl->config) {
3192     return 0;
3193   }
3194   ssl->config->ocsp_stapling_enabled = type == TLSEXT_STATUSTYPE_ocsp;
3195   return 1;
3196 }
3197 
SSL_get_tlsext_status_type(const SSL * ssl)3198 int SSL_get_tlsext_status_type(const SSL *ssl) {
3199   if (ssl->server) {
3200     SSL_HANDSHAKE *hs = ssl->s3->hs.get();
3201     return hs != nullptr && hs->ocsp_stapling_requested
3202         ? TLSEXT_STATUSTYPE_ocsp
3203         : TLSEXT_STATUSTYPE_nothing;
3204   }
3205 
3206   return ssl->config != nullptr && ssl->config->ocsp_stapling_enabled
3207              ? TLSEXT_STATUSTYPE_ocsp
3208              : TLSEXT_STATUSTYPE_nothing;
3209 }
3210 
SSL_set_tlsext_status_ocsp_resp(SSL * ssl,uint8_t * resp,size_t resp_len)3211 int SSL_set_tlsext_status_ocsp_resp(SSL *ssl, uint8_t *resp, size_t resp_len) {
3212   if (SSL_set_ocsp_response(ssl, resp, resp_len)) {
3213     OPENSSL_free(resp);
3214     return 1;
3215   }
3216   return 0;
3217 }
3218 
SSL_get_tlsext_status_ocsp_resp(const SSL * ssl,const uint8_t ** out)3219 size_t SSL_get_tlsext_status_ocsp_resp(const SSL *ssl, const uint8_t **out) {
3220   size_t ret;
3221   SSL_get0_ocsp_response(ssl, out, &ret);
3222   return ret;
3223 }
3224 
SSL_CTX_set_tlsext_status_cb(SSL_CTX * ctx,int (* callback)(SSL * ssl,void * arg))3225 int SSL_CTX_set_tlsext_status_cb(SSL_CTX *ctx,
3226                                  int (*callback)(SSL *ssl, void *arg)) {
3227   ctx->legacy_ocsp_callback = callback;
3228   return 1;
3229 }
3230 
SSL_CTX_set_tlsext_status_arg(SSL_CTX * ctx,void * arg)3231 int SSL_CTX_set_tlsext_status_arg(SSL_CTX *ctx, void *arg) {
3232   ctx->legacy_ocsp_callback_arg = arg;
3233   return 1;
3234 }
3235 
SSL_get_curve_id(const SSL * ssl)3236 uint16_t SSL_get_curve_id(const SSL *ssl) { return SSL_get_group_id(ssl); }
3237 
SSL_get_curve_name(uint16_t curve_id)3238 const char *SSL_get_curve_name(uint16_t curve_id) {
3239   return SSL_get_group_name(curve_id);
3240 }
3241 
SSL_get_all_curve_names(const char ** out,size_t max_out)3242 size_t SSL_get_all_curve_names(const char **out, size_t max_out) {
3243   return SSL_get_all_group_names(out, max_out);
3244 }
3245 
SSL_CTX_set1_curves(SSL_CTX * ctx,const int * curves,size_t num_curves)3246 int SSL_CTX_set1_curves(SSL_CTX *ctx, const int *curves, size_t num_curves) {
3247   return SSL_CTX_set1_groups(ctx, curves, num_curves);
3248 }
3249 
SSL_set1_curves(SSL * ssl,const int * curves,size_t num_curves)3250 int SSL_set1_curves(SSL *ssl, const int *curves, size_t num_curves) {
3251   return SSL_set1_groups(ssl, curves, num_curves);
3252 }
3253 
SSL_CTX_set1_curves_list(SSL_CTX * ctx,const char * curves)3254 int SSL_CTX_set1_curves_list(SSL_CTX *ctx, const char *curves) {
3255   return SSL_CTX_set1_groups_list(ctx, curves);
3256 }
3257 
SSL_set1_curves_list(SSL * ssl,const char * curves)3258 int SSL_set1_curves_list(SSL *ssl, const char *curves) {
3259   return SSL_set1_groups_list(ssl, curves);
3260 }
3261 
3262 namespace fips202205 {
3263 
3264 // (References are to SP 800-52r2):
3265 
3266 // Section 3.4.2.2
3267 // "at least one of the NIST-approved curves, P-256 (secp256r1) and P384
3268 // (secp384r1), shall be supported as described in RFC 8422."
3269 //
3270 // Section 3.3.1
3271 // "The server shall be configured to only use cipher suites that are
3272 // composed entirely of NIST approved algorithms"
3273 static const uint16_t kGroups[] = {SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1};
3274 
3275 static const uint16_t kSigAlgs[] = {
3276     SSL_SIGN_RSA_PKCS1_SHA256,
3277     SSL_SIGN_RSA_PKCS1_SHA384,
3278     SSL_SIGN_RSA_PKCS1_SHA512,
3279     // Table 4.1:
3280     // "The curve should be P-256 or P-384"
3281     SSL_SIGN_ECDSA_SECP256R1_SHA256,
3282     SSL_SIGN_ECDSA_SECP384R1_SHA384,
3283     SSL_SIGN_RSA_PSS_RSAE_SHA256,
3284     SSL_SIGN_RSA_PSS_RSAE_SHA384,
3285     SSL_SIGN_RSA_PSS_RSAE_SHA512,
3286 };
3287 
3288 static const char kTLS12Ciphers[] =
3289     "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:"
3290     "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:"
3291     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:"
3292     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
3293 
Configure(SSL_CTX * ctx)3294 static int Configure(SSL_CTX *ctx) {
3295   ctx->tls13_cipher_policy = ssl_compliance_policy_fips_202205;
3296 
3297   return
3298       // Section 3.1:
3299       // "Servers that support government-only applications shall be
3300       // configured to use TLS 1.2 and should be configured to use TLS 1.3
3301       // as well. These servers should not be configured to use TLS 1.1 and
3302       // shall not use TLS 1.0, SSL 3.0, or SSL 2.0.
3303       SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION) &&
3304       SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION) &&
3305       // Sections 3.3.1.1.1 and 3.3.1.1.2 are ambiguous about whether
3306       // HMAC-SHA-1 cipher suites are permitted with TLS 1.2. However, later the
3307       // Encrypt-then-MAC extension is required for all CBC cipher suites and so
3308       // it's easier to drop them.
3309       SSL_CTX_set_strict_cipher_list(ctx, kTLS12Ciphers) &&
3310       SSL_CTX_set1_group_ids(ctx, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3311       SSL_CTX_set_signing_algorithm_prefs(ctx, kSigAlgs,
3312                                           OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3313       SSL_CTX_set_verify_algorithm_prefs(ctx, kSigAlgs,
3314                                          OPENSSL_ARRAY_SIZE(kSigAlgs));
3315 }
3316 
Configure(SSL * ssl)3317 static int Configure(SSL *ssl) {
3318   ssl->config->tls13_cipher_policy = ssl_compliance_policy_fips_202205;
3319 
3320   // See |Configure(SSL_CTX)|, above, for reasoning.
3321   return SSL_set_min_proto_version(ssl, TLS1_2_VERSION) &&
3322          SSL_set_max_proto_version(ssl, TLS1_3_VERSION) &&
3323          SSL_set_strict_cipher_list(ssl, kTLS12Ciphers) &&
3324          SSL_set1_group_ids(ssl, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3325          SSL_set_signing_algorithm_prefs(ssl, kSigAlgs,
3326                                          OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3327          SSL_set_verify_algorithm_prefs(ssl, kSigAlgs,
3328                                         OPENSSL_ARRAY_SIZE(kSigAlgs));
3329 }
3330 
3331 }  // namespace fips202205
3332 
3333 namespace wpa202304 {
3334 
3335 // See WPA version 3.1, section 3.5.
3336 
3337 static const uint16_t kGroups[] = {SSL_GROUP_SECP384R1};
3338 
3339 static const uint16_t kSigAlgs[] = {
3340     SSL_SIGN_RSA_PKCS1_SHA384,        //
3341     SSL_SIGN_RSA_PKCS1_SHA512,        //
3342     SSL_SIGN_ECDSA_SECP384R1_SHA384,  //
3343     SSL_SIGN_RSA_PSS_RSAE_SHA384,     //
3344     SSL_SIGN_RSA_PSS_RSAE_SHA512,     //
3345 };
3346 
3347 static const char kTLS12Ciphers[] =
3348     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:"
3349     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
3350 
Configure(SSL_CTX * ctx)3351 static int Configure(SSL_CTX *ctx) {
3352   ctx->tls13_cipher_policy = ssl_compliance_policy_wpa3_192_202304;
3353 
3354   return SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION) &&
3355          SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION) &&
3356          SSL_CTX_set_strict_cipher_list(ctx, kTLS12Ciphers) &&
3357          SSL_CTX_set1_group_ids(ctx, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3358          SSL_CTX_set_signing_algorithm_prefs(ctx, kSigAlgs,
3359                                              OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3360          SSL_CTX_set_verify_algorithm_prefs(ctx, kSigAlgs,
3361                                             OPENSSL_ARRAY_SIZE(kSigAlgs));
3362 }
3363 
Configure(SSL * ssl)3364 static int Configure(SSL *ssl) {
3365   ssl->config->tls13_cipher_policy = ssl_compliance_policy_wpa3_192_202304;
3366 
3367   return SSL_set_min_proto_version(ssl, TLS1_2_VERSION) &&
3368          SSL_set_max_proto_version(ssl, TLS1_3_VERSION) &&
3369          SSL_set_strict_cipher_list(ssl, kTLS12Ciphers) &&
3370          SSL_set1_group_ids(ssl, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3371          SSL_set_signing_algorithm_prefs(ssl, kSigAlgs,
3372                                          OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3373          SSL_set_verify_algorithm_prefs(ssl, kSigAlgs,
3374                                         OPENSSL_ARRAY_SIZE(kSigAlgs));
3375 }
3376 
3377 }  // namespace wpa202304
3378 
SSL_CTX_set_compliance_policy(SSL_CTX * ctx,enum ssl_compliance_policy_t policy)3379 int SSL_CTX_set_compliance_policy(SSL_CTX *ctx,
3380                                   enum ssl_compliance_policy_t policy) {
3381   switch (policy) {
3382     case ssl_compliance_policy_fips_202205:
3383       return fips202205::Configure(ctx);
3384     case ssl_compliance_policy_wpa3_192_202304:
3385       return wpa202304::Configure(ctx);
3386     default:
3387       return 0;
3388   }
3389 }
3390 
SSL_set_compliance_policy(SSL * ssl,enum ssl_compliance_policy_t policy)3391 int SSL_set_compliance_policy(SSL *ssl, enum ssl_compliance_policy_t policy) {
3392   switch (policy) {
3393     case ssl_compliance_policy_fips_202205:
3394       return fips202205::Configure(ssl);
3395     case ssl_compliance_policy_wpa3_192_202304:
3396       return wpa202304::Configure(ssl);
3397     default:
3398       return 0;
3399   }
3400 }
3401