• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE. */
140 
141 #include <openssl/ssl.h>
142 
143 #include <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     : method(ssl_method->method),
527       x509_method(ssl_method->x509_method),
528       retain_only_sha256_of_client_certs(false),
529       quiet_shutdown(false),
530       ocsp_stapling_enabled(false),
531       signed_cert_timestamps_enabled(false),
532       channel_id_enabled(false),
533       grease_enabled(false),
534       permute_extensions(false),
535       allow_unknown_alpn_protos(false),
536       false_start_allowed_without_alpn(false),
537       handoff(false),
538       enable_early_data(false),
539       aes_hw_override(false),
540       aes_hw_override_value(false) {
541   CRYPTO_MUTEX_init(&lock);
542   CRYPTO_new_ex_data(&ex_data);
543 }
544 
~ssl_ctx_st()545 ssl_ctx_st::~ssl_ctx_st() {
546   // Free the internal session cache. Note that this calls the caller-supplied
547   // remove callback, so we must do it before clearing ex_data. (See ticket
548   // [openssl.org #212].)
549   SSL_CTX_flush_sessions(this, 0);
550 
551   CRYPTO_free_ex_data(&g_ex_data_class_ssl_ctx, this, &ex_data);
552 
553   CRYPTO_MUTEX_cleanup(&lock);
554   lh_SSL_SESSION_free(sessions);
555   x509_method->ssl_ctx_free(this);
556 }
557 
SSL_CTX_new(const SSL_METHOD * method)558 SSL_CTX *SSL_CTX_new(const SSL_METHOD *method) {
559   if (method == NULL) {
560     OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_METHOD_PASSED);
561     return nullptr;
562   }
563 
564   UniquePtr<SSL_CTX> ret = MakeUnique<SSL_CTX>(method);
565   if (!ret) {
566     return nullptr;
567   }
568 
569   ret->cert = MakeUnique<CERT>(method->x509_method);
570   ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
571   ret->client_CA.reset(sk_CRYPTO_BUFFER_new_null());
572   if (ret->cert == nullptr ||
573       ret->sessions == nullptr ||
574       ret->client_CA == nullptr ||
575       !ret->x509_method->ssl_ctx_new(ret.get())) {
576     return nullptr;
577   }
578 
579   if (!SSL_CTX_set_strict_cipher_list(ret.get(), SSL_DEFAULT_CIPHER_LIST) ||
580       // Lock the SSL_CTX to the specified version, for compatibility with
581       // legacy uses of SSL_METHOD.
582       !SSL_CTX_set_max_proto_version(ret.get(), method->version) ||
583       !SSL_CTX_set_min_proto_version(ret.get(), method->version)) {
584     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
585     return nullptr;
586   }
587 
588   return ret.release();
589 }
590 
SSL_CTX_up_ref(SSL_CTX * ctx)591 int SSL_CTX_up_ref(SSL_CTX *ctx) {
592   CRYPTO_refcount_inc(&ctx->references);
593   return 1;
594 }
595 
SSL_CTX_free(SSL_CTX * ctx)596 void SSL_CTX_free(SSL_CTX *ctx) {
597   if (ctx == NULL ||
598       !CRYPTO_refcount_dec_and_test_zero(&ctx->references)) {
599     return;
600   }
601 
602   ctx->~ssl_ctx_st();
603   OPENSSL_free(ctx);
604 }
605 
ssl_st(SSL_CTX * ctx_arg)606 ssl_st::ssl_st(SSL_CTX *ctx_arg)
607     : method(ctx_arg->method),
608       max_send_fragment(ctx_arg->max_send_fragment),
609       msg_callback(ctx_arg->msg_callback),
610       msg_callback_arg(ctx_arg->msg_callback_arg),
611       ctx(UpRef(ctx_arg)),
612       session_ctx(UpRef(ctx_arg)),
613       options(ctx->options),
614       mode(ctx->mode),
615       max_cert_list(ctx->max_cert_list),
616       server(false),
617       quiet_shutdown(ctx->quiet_shutdown),
618       enable_early_data(ctx->enable_early_data) {
619   CRYPTO_new_ex_data(&ex_data);
620 }
621 
~ssl_st()622 ssl_st::~ssl_st() {
623   CRYPTO_free_ex_data(&g_ex_data_class_ssl, this, &ex_data);
624   // |config| refers to |this|, so we must release it earlier.
625   config.reset();
626   if (method != NULL) {
627     method->ssl_free(this);
628   }
629 }
630 
SSL_new(SSL_CTX * ctx)631 SSL *SSL_new(SSL_CTX *ctx) {
632   if (ctx == nullptr) {
633     OPENSSL_PUT_ERROR(SSL, SSL_R_NULL_SSL_CTX);
634     return nullptr;
635   }
636 
637   UniquePtr<SSL> ssl = MakeUnique<SSL>(ctx);
638   if (ssl == nullptr) {
639     return nullptr;
640   }
641 
642   ssl->config = MakeUnique<SSL_CONFIG>(ssl.get());
643   if (ssl->config == nullptr) {
644     return nullptr;
645   }
646   ssl->config->conf_min_version = ctx->conf_min_version;
647   ssl->config->conf_max_version = ctx->conf_max_version;
648 
649   ssl->config->cert = ssl_cert_dup(ctx->cert.get());
650   if (ssl->config->cert == nullptr) {
651     return nullptr;
652   }
653 
654   ssl->config->verify_mode = ctx->verify_mode;
655   ssl->config->verify_callback = ctx->default_verify_callback;
656   ssl->config->custom_verify_callback = ctx->custom_verify_callback;
657   ssl->config->retain_only_sha256_of_client_certs =
658       ctx->retain_only_sha256_of_client_certs;
659   ssl->config->permute_extensions = ctx->permute_extensions;
660   ssl->config->aes_hw_override = ctx->aes_hw_override;
661   ssl->config->aes_hw_override_value = ctx->aes_hw_override_value;
662   ssl->config->tls13_cipher_policy = ctx->tls13_cipher_policy;
663 
664   if (!ssl->config->supported_group_list.CopyFrom(ctx->supported_group_list) ||
665       !ssl->config->alpn_client_proto_list.CopyFrom(
666           ctx->alpn_client_proto_list) ||
667       !ssl->config->verify_sigalgs.CopyFrom(ctx->verify_sigalgs)) {
668     return nullptr;
669   }
670 
671   if (ctx->psk_identity_hint) {
672     ssl->config->psk_identity_hint.reset(
673         OPENSSL_strdup(ctx->psk_identity_hint.get()));
674     if (ssl->config->psk_identity_hint == nullptr) {
675       return nullptr;
676     }
677   }
678   ssl->config->psk_client_callback = ctx->psk_client_callback;
679   ssl->config->psk_server_callback = ctx->psk_server_callback;
680 
681   ssl->config->channel_id_enabled = ctx->channel_id_enabled;
682   ssl->config->channel_id_private = UpRef(ctx->channel_id_private);
683 
684   ssl->config->signed_cert_timestamps_enabled =
685       ctx->signed_cert_timestamps_enabled;
686   ssl->config->ocsp_stapling_enabled = ctx->ocsp_stapling_enabled;
687   ssl->config->handoff = ctx->handoff;
688   ssl->quic_method = ctx->quic_method;
689 
690   if (!ssl->method->ssl_new(ssl.get()) ||
691       !ssl->ctx->x509_method->ssl_new(ssl->s3->hs.get())) {
692     return nullptr;
693   }
694 
695   return ssl.release();
696 }
697 
SSL_CONFIG(SSL * ssl_arg)698 SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg)
699     : ssl(ssl_arg),
700       ech_grease_enabled(false),
701       signed_cert_timestamps_enabled(false),
702       ocsp_stapling_enabled(false),
703       channel_id_enabled(false),
704       enforce_rsa_key_usage(true),
705       retain_only_sha256_of_client_certs(false),
706       handoff(false),
707       shed_handshake_config(false),
708       jdk11_workaround(false),
709       quic_use_legacy_codepoint(false),
710       permute_extensions(false),
711       alps_use_new_codepoint(false) {
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_certs_clear(SSL * ssl)1572 void SSL_certs_clear(SSL *ssl) {
1573   if (!ssl->config) {
1574     return;
1575   }
1576   ssl_cert_clear_certs(ssl->config->cert.get());
1577 }
1578 
SSL_get_fd(const SSL * ssl)1579 int SSL_get_fd(const SSL *ssl) { return SSL_get_rfd(ssl); }
1580 
SSL_get_rfd(const SSL * ssl)1581 int SSL_get_rfd(const SSL *ssl) {
1582   int ret = -1;
1583   BIO *b = BIO_find_type(SSL_get_rbio(ssl), BIO_TYPE_DESCRIPTOR);
1584   if (b != NULL) {
1585     BIO_get_fd(b, &ret);
1586   }
1587   return ret;
1588 }
1589 
SSL_get_wfd(const SSL * ssl)1590 int SSL_get_wfd(const SSL *ssl) {
1591   int ret = -1;
1592   BIO *b = BIO_find_type(SSL_get_wbio(ssl), BIO_TYPE_DESCRIPTOR);
1593   if (b != NULL) {
1594     BIO_get_fd(b, &ret);
1595   }
1596   return ret;
1597 }
1598 
1599 #if !defined(OPENSSL_NO_SOCK)
SSL_set_fd(SSL * ssl,int fd)1600 int SSL_set_fd(SSL *ssl, int fd) {
1601   BIO *bio = BIO_new(BIO_s_socket());
1602   if (bio == NULL) {
1603     OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1604     return 0;
1605   }
1606   BIO_set_fd(bio, fd, BIO_NOCLOSE);
1607   SSL_set_bio(ssl, bio, bio);
1608   return 1;
1609 }
1610 
SSL_set_wfd(SSL * ssl,int fd)1611 int SSL_set_wfd(SSL *ssl, int fd) {
1612   BIO *rbio = SSL_get_rbio(ssl);
1613   if (rbio == NULL || BIO_method_type(rbio) != BIO_TYPE_SOCKET ||
1614       BIO_get_fd(rbio, NULL) != fd) {
1615     BIO *bio = BIO_new(BIO_s_socket());
1616     if (bio == NULL) {
1617       OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1618       return 0;
1619     }
1620     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1621     SSL_set0_wbio(ssl, bio);
1622   } else {
1623     // Copy the rbio over to the wbio.
1624     BIO_up_ref(rbio);
1625     SSL_set0_wbio(ssl, rbio);
1626   }
1627 
1628   return 1;
1629 }
1630 
SSL_set_rfd(SSL * ssl,int fd)1631 int SSL_set_rfd(SSL *ssl, int fd) {
1632   BIO *wbio = SSL_get_wbio(ssl);
1633   if (wbio == NULL || BIO_method_type(wbio) != BIO_TYPE_SOCKET ||
1634       BIO_get_fd(wbio, NULL) != fd) {
1635     BIO *bio = BIO_new(BIO_s_socket());
1636     if (bio == NULL) {
1637       OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
1638       return 0;
1639     }
1640     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1641     SSL_set0_rbio(ssl, bio);
1642   } else {
1643     // Copy the wbio over to the rbio.
1644     BIO_up_ref(wbio);
1645     SSL_set0_rbio(ssl, wbio);
1646   }
1647   return 1;
1648 }
1649 #endif  // !OPENSSL_NO_SOCK
1650 
copy_finished(void * out,size_t out_len,const uint8_t * in,size_t in_len)1651 static size_t copy_finished(void *out, size_t out_len, const uint8_t *in,
1652                             size_t in_len) {
1653   if (out_len > in_len) {
1654     out_len = in_len;
1655   }
1656   OPENSSL_memcpy(out, in, out_len);
1657   return in_len;
1658 }
1659 
SSL_get_finished(const SSL * ssl,void * buf,size_t count)1660 size_t SSL_get_finished(const SSL *ssl, void *buf, size_t count) {
1661   if (!ssl->s3->initial_handshake_complete ||
1662       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1663     return 0;
1664   }
1665 
1666   if (ssl->server) {
1667     return copy_finished(buf, count, ssl->s3->previous_server_finished,
1668                          ssl->s3->previous_server_finished_len);
1669   }
1670 
1671   return copy_finished(buf, count, ssl->s3->previous_client_finished,
1672                        ssl->s3->previous_client_finished_len);
1673 }
1674 
SSL_get_peer_finished(const SSL * ssl,void * buf,size_t count)1675 size_t SSL_get_peer_finished(const SSL *ssl, void *buf, size_t count) {
1676   if (!ssl->s3->initial_handshake_complete ||
1677       ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1678     return 0;
1679   }
1680 
1681   if (ssl->server) {
1682     return copy_finished(buf, count, ssl->s3->previous_client_finished,
1683                          ssl->s3->previous_client_finished_len);
1684   }
1685 
1686   return copy_finished(buf, count, ssl->s3->previous_server_finished,
1687                        ssl->s3->previous_server_finished_len);
1688 }
1689 
SSL_get_verify_mode(const SSL * ssl)1690 int SSL_get_verify_mode(const SSL *ssl) {
1691   if (!ssl->config) {
1692     assert(ssl->config);
1693     return -1;
1694   }
1695   return ssl->config->verify_mode;
1696 }
1697 
SSL_get_extms_support(const SSL * ssl)1698 int SSL_get_extms_support(const SSL *ssl) {
1699   // TLS 1.3 does not require extended master secret and always reports as
1700   // supporting it.
1701   if (!ssl->s3->have_version) {
1702     return 0;
1703   }
1704   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
1705     return 1;
1706   }
1707 
1708   // If the initial handshake completed, query the established session.
1709   if (ssl->s3->established_session != NULL) {
1710     return ssl->s3->established_session->extended_master_secret;
1711   }
1712 
1713   // Otherwise, query the in-progress handshake.
1714   if (ssl->s3->hs != NULL) {
1715     return ssl->s3->hs->extended_master_secret;
1716   }
1717   assert(0);
1718   return 0;
1719 }
1720 
SSL_CTX_get_read_ahead(const SSL_CTX * ctx)1721 int SSL_CTX_get_read_ahead(const SSL_CTX *ctx) { return 0; }
1722 
SSL_get_read_ahead(const SSL * ssl)1723 int SSL_get_read_ahead(const SSL *ssl) { return 0; }
1724 
SSL_CTX_set_read_ahead(SSL_CTX * ctx,int yes)1725 int SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes) { return 1; }
1726 
SSL_set_read_ahead(SSL * ssl,int yes)1727 int SSL_set_read_ahead(SSL *ssl, int yes) { return 1; }
1728 
SSL_pending(const SSL * ssl)1729 int SSL_pending(const SSL *ssl) {
1730   return static_cast<int>(ssl->s3->pending_app_data.size());
1731 }
1732 
SSL_has_pending(const SSL * ssl)1733 int SSL_has_pending(const SSL *ssl) {
1734   return SSL_pending(ssl) != 0 || !ssl->s3->read_buffer.empty();
1735 }
1736 
SSL_CTX_check_private_key(const SSL_CTX * ctx)1737 int SSL_CTX_check_private_key(const SSL_CTX *ctx) {
1738   return ssl_cert_check_private_key(ctx->cert.get(),
1739                                     ctx->cert->privatekey.get());
1740 }
1741 
SSL_check_private_key(const SSL * ssl)1742 int SSL_check_private_key(const SSL *ssl) {
1743   if (!ssl->config) {
1744     return 0;
1745   }
1746   return ssl_cert_check_private_key(ssl->config->cert.get(),
1747                                     ssl->config->cert->privatekey.get());
1748 }
1749 
SSL_get_default_timeout(const SSL * ssl)1750 long SSL_get_default_timeout(const SSL *ssl) {
1751   return SSL_DEFAULT_SESSION_TIMEOUT;
1752 }
1753 
SSL_renegotiate(SSL * ssl)1754 int SSL_renegotiate(SSL *ssl) {
1755   // Caller-initiated renegotiation is not supported.
1756   if (!ssl->s3->renegotiate_pending) {
1757     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1758     return 0;
1759   }
1760 
1761   if (!ssl_can_renegotiate(ssl)) {
1762     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
1763     return 0;
1764   }
1765 
1766   // We should not have told the caller to release the private key.
1767   assert(!SSL_can_release_private_key(ssl));
1768 
1769   // Renegotiation is only supported at quiescent points in the application
1770   // protocol, namely in HTTPS, just before reading the HTTP response.
1771   // Require the record-layer be idle and avoid complexities of sending a
1772   // handshake record while an application_data record is being written.
1773   if (!ssl->s3->write_buffer.empty() ||
1774       ssl->s3->write_shutdown != ssl_shutdown_none) {
1775     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
1776     return 0;
1777   }
1778 
1779   // Begin a new handshake.
1780   if (ssl->s3->hs != nullptr) {
1781     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1782     return 0;
1783   }
1784   ssl->s3->hs = ssl_handshake_new(ssl);
1785   if (ssl->s3->hs == nullptr) {
1786     return 0;
1787   }
1788 
1789   ssl->s3->renegotiate_pending = false;
1790   ssl->s3->total_renegotiations++;
1791   return 1;
1792 }
1793 
SSL_renegotiate_pending(SSL * ssl)1794 int SSL_renegotiate_pending(SSL *ssl) {
1795   return SSL_in_init(ssl) && ssl->s3->initial_handshake_complete;
1796 }
1797 
SSL_total_renegotiations(const SSL * ssl)1798 int SSL_total_renegotiations(const SSL *ssl) {
1799   return ssl->s3->total_renegotiations;
1800 }
1801 
SSL_CTX_get_max_cert_list(const SSL_CTX * ctx)1802 size_t SSL_CTX_get_max_cert_list(const SSL_CTX *ctx) {
1803   return ctx->max_cert_list;
1804 }
1805 
SSL_CTX_set_max_cert_list(SSL_CTX * ctx,size_t max_cert_list)1806 void SSL_CTX_set_max_cert_list(SSL_CTX *ctx, size_t max_cert_list) {
1807   if (max_cert_list > kMaxHandshakeSize) {
1808     max_cert_list = kMaxHandshakeSize;
1809   }
1810   ctx->max_cert_list = (uint32_t)max_cert_list;
1811 }
1812 
SSL_get_max_cert_list(const SSL * ssl)1813 size_t SSL_get_max_cert_list(const SSL *ssl) {
1814   return ssl->max_cert_list;
1815 }
1816 
SSL_set_max_cert_list(SSL * ssl,size_t max_cert_list)1817 void SSL_set_max_cert_list(SSL *ssl, size_t max_cert_list) {
1818   if (max_cert_list > kMaxHandshakeSize) {
1819     max_cert_list = kMaxHandshakeSize;
1820   }
1821   ssl->max_cert_list = (uint32_t)max_cert_list;
1822 }
1823 
SSL_CTX_set_max_send_fragment(SSL_CTX * ctx,size_t max_send_fragment)1824 int SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, size_t max_send_fragment) {
1825   if (max_send_fragment < 512) {
1826     max_send_fragment = 512;
1827   }
1828   if (max_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1829     max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
1830   }
1831   ctx->max_send_fragment = (uint16_t)max_send_fragment;
1832 
1833   return 1;
1834 }
1835 
SSL_set_max_send_fragment(SSL * ssl,size_t max_send_fragment)1836 int SSL_set_max_send_fragment(SSL *ssl, 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   ssl->max_send_fragment = (uint16_t)max_send_fragment;
1844 
1845   return 1;
1846 }
1847 
SSL_set_mtu(SSL * ssl,unsigned mtu)1848 int SSL_set_mtu(SSL *ssl, unsigned mtu) {
1849   if (!SSL_is_dtls(ssl) || mtu < dtls1_min_mtu()) {
1850     return 0;
1851   }
1852   ssl->d1->mtu = mtu;
1853   return 1;
1854 }
1855 
SSL_get_secure_renegotiation_support(const SSL * ssl)1856 int SSL_get_secure_renegotiation_support(const SSL *ssl) {
1857   if (!ssl->s3->have_version) {
1858     return 0;
1859   }
1860   return ssl_protocol_version(ssl) >= TLS1_3_VERSION ||
1861          ssl->s3->send_connection_binding;
1862 }
1863 
SSL_CTX_sess_number(const SSL_CTX * ctx)1864 size_t SSL_CTX_sess_number(const SSL_CTX *ctx) {
1865   MutexReadLock lock(const_cast<CRYPTO_MUTEX *>(&ctx->lock));
1866   return lh_SSL_SESSION_num_items(ctx->sessions);
1867 }
1868 
SSL_CTX_sess_set_cache_size(SSL_CTX * ctx,unsigned long size)1869 unsigned long SSL_CTX_sess_set_cache_size(SSL_CTX *ctx, unsigned long size) {
1870   unsigned long ret = ctx->session_cache_size;
1871   ctx->session_cache_size = size;
1872   return ret;
1873 }
1874 
SSL_CTX_sess_get_cache_size(const SSL_CTX * ctx)1875 unsigned long SSL_CTX_sess_get_cache_size(const SSL_CTX *ctx) {
1876   return ctx->session_cache_size;
1877 }
1878 
SSL_CTX_set_session_cache_mode(SSL_CTX * ctx,int mode)1879 int SSL_CTX_set_session_cache_mode(SSL_CTX *ctx, int mode) {
1880   int ret = ctx->session_cache_mode;
1881   ctx->session_cache_mode = mode;
1882   return ret;
1883 }
1884 
SSL_CTX_get_session_cache_mode(const SSL_CTX * ctx)1885 int SSL_CTX_get_session_cache_mode(const SSL_CTX *ctx) {
1886   return ctx->session_cache_mode;
1887 }
1888 
1889 
SSL_CTX_get_tlsext_ticket_keys(SSL_CTX * ctx,void * out,size_t len)1890 int SSL_CTX_get_tlsext_ticket_keys(SSL_CTX *ctx, void *out, size_t len) {
1891   if (out == NULL) {
1892     return 48;
1893   }
1894   if (len != 48) {
1895     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_TICKET_KEYS_LENGTH);
1896     return 0;
1897   }
1898 
1899   // The default ticket keys are initialized lazily. Trigger a key
1900   // rotation to initialize them.
1901   if (!ssl_ctx_rotate_ticket_encryption_key(ctx)) {
1902     return 0;
1903   }
1904 
1905   uint8_t *out_bytes = reinterpret_cast<uint8_t *>(out);
1906   MutexReadLock lock(&ctx->lock);
1907   OPENSSL_memcpy(out_bytes, ctx->ticket_key_current->name, 16);
1908   OPENSSL_memcpy(out_bytes + 16, ctx->ticket_key_current->hmac_key, 16);
1909   OPENSSL_memcpy(out_bytes + 32, ctx->ticket_key_current->aes_key, 16);
1910   return 1;
1911 }
1912 
SSL_CTX_set_tlsext_ticket_keys(SSL_CTX * ctx,const void * in,size_t len)1913 int SSL_CTX_set_tlsext_ticket_keys(SSL_CTX *ctx, const void *in, size_t len) {
1914   if (in == NULL) {
1915     return 48;
1916   }
1917   if (len != 48) {
1918     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_TICKET_KEYS_LENGTH);
1919     return 0;
1920   }
1921   auto key = MakeUnique<TicketKey>();
1922   if (!key) {
1923     return 0;
1924   }
1925   const uint8_t *in_bytes = reinterpret_cast<const uint8_t *>(in);
1926   OPENSSL_memcpy(key->name, in_bytes, 16);
1927   OPENSSL_memcpy(key->hmac_key, in_bytes + 16, 16);
1928   OPENSSL_memcpy(key->aes_key, in_bytes + 32, 16);
1929   // Disable automatic key rotation for manually-configured keys. This is now
1930   // the caller's responsibility.
1931   key->next_rotation_tv_sec = 0;
1932   ctx->ticket_key_current = std::move(key);
1933   ctx->ticket_key_prev.reset();
1934   return 1;
1935 }
1936 
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))1937 int SSL_CTX_set_tlsext_ticket_key_cb(
1938     SSL_CTX *ctx, int (*callback)(SSL *ssl, uint8_t *key_name, uint8_t *iv,
1939                                   EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
1940                                   int encrypt)) {
1941   ctx->ticket_key_cb = callback;
1942   return 1;
1943 }
1944 
check_group_ids(Span<const uint16_t> group_ids)1945 static bool check_group_ids(Span<const uint16_t> group_ids) {
1946   for (uint16_t group_id : group_ids) {
1947     if (ssl_group_id_to_nid(group_id) == NID_undef) {
1948       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1949       return false;
1950     }
1951   }
1952   return true;
1953 }
1954 
SSL_CTX_set1_group_ids(SSL_CTX * ctx,const uint16_t * group_ids,size_t num_group_ids)1955 int SSL_CTX_set1_group_ids(SSL_CTX *ctx, const uint16_t *group_ids,
1956                            size_t num_group_ids) {
1957   auto span = MakeConstSpan(group_ids, num_group_ids);
1958   return check_group_ids(span) && ctx->supported_group_list.CopyFrom(span);
1959 }
1960 
SSL_set1_group_ids(SSL * ssl,const uint16_t * group_ids,size_t num_group_ids)1961 int SSL_set1_group_ids(SSL *ssl, const uint16_t *group_ids,
1962                        size_t num_group_ids) {
1963   if (!ssl->config) {
1964     return 0;
1965   }
1966   auto span = MakeConstSpan(group_ids, num_group_ids);
1967   return check_group_ids(span) &&
1968          ssl->config->supported_group_list.CopyFrom(span);
1969 }
1970 
ssl_nids_to_group_ids(Array<uint16_t> * out_group_ids,Span<const int> nids)1971 static bool ssl_nids_to_group_ids(Array<uint16_t> *out_group_ids,
1972                                   Span<const int> nids) {
1973   Array<uint16_t> group_ids;
1974   if (!group_ids.Init(nids.size())) {
1975     return false;
1976   }
1977 
1978   for (size_t i = 0; i < nids.size(); i++) {
1979     if (!ssl_nid_to_group_id(&group_ids[i], nids[i])) {
1980       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1981       return false;
1982     }
1983   }
1984 
1985   *out_group_ids = std::move(group_ids);
1986   return true;
1987 }
1988 
SSL_CTX_set1_groups(SSL_CTX * ctx,const int * groups,size_t num_groups)1989 int SSL_CTX_set1_groups(SSL_CTX *ctx, const int *groups, size_t num_groups) {
1990   return ssl_nids_to_group_ids(&ctx->supported_group_list,
1991                                MakeConstSpan(groups, num_groups));
1992 }
1993 
SSL_set1_groups(SSL * ssl,const int * groups,size_t num_groups)1994 int SSL_set1_groups(SSL *ssl, const int *groups, size_t num_groups) {
1995   if (!ssl->config) {
1996     return 0;
1997   }
1998   return ssl_nids_to_group_ids(&ssl->config->supported_group_list,
1999                                MakeConstSpan(groups, num_groups));
2000 }
2001 
ssl_str_to_group_ids(Array<uint16_t> * out_group_ids,const char * str)2002 static bool ssl_str_to_group_ids(Array<uint16_t> *out_group_ids,
2003                                  const char *str) {
2004   // Count the number of groups in the list.
2005   size_t count = 0;
2006   const char *ptr = str, *col;
2007   do {
2008     col = strchr(ptr, ':');
2009     count++;
2010     if (col) {
2011       ptr = col + 1;
2012     }
2013   } while (col);
2014 
2015   Array<uint16_t> group_ids;
2016   if (!group_ids.Init(count)) {
2017     return false;
2018   }
2019 
2020   size_t i = 0;
2021   ptr = str;
2022   do {
2023     col = strchr(ptr, ':');
2024     if (!ssl_name_to_group_id(&group_ids[i++], ptr,
2025                               col ? (size_t)(col - ptr) : strlen(ptr))) {
2026       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2027       return false;
2028     }
2029     if (col) {
2030       ptr = col + 1;
2031     }
2032   } while (col);
2033 
2034   assert(i == count);
2035   *out_group_ids = std::move(group_ids);
2036   return true;
2037 }
2038 
SSL_CTX_set1_groups_list(SSL_CTX * ctx,const char * groups)2039 int SSL_CTX_set1_groups_list(SSL_CTX *ctx, const char *groups) {
2040   return ssl_str_to_group_ids(&ctx->supported_group_list, groups);
2041 }
2042 
SSL_set1_groups_list(SSL * ssl,const char * groups)2043 int SSL_set1_groups_list(SSL *ssl, const char *groups) {
2044   if (!ssl->config) {
2045     return 0;
2046   }
2047   return ssl_str_to_group_ids(&ssl->config->supported_group_list, groups);
2048 }
2049 
SSL_get_group_id(const SSL * ssl)2050 uint16_t SSL_get_group_id(const SSL *ssl) {
2051   SSL_SESSION *session = SSL_get_session(ssl);
2052   if (session == NULL) {
2053     return 0;
2054   }
2055 
2056   return session->group_id;
2057 }
2058 
SSL_get_negotiated_group(const SSL * ssl)2059 int SSL_get_negotiated_group(const SSL *ssl) {
2060   uint16_t group_id = SSL_get_group_id(ssl);
2061   if (group_id == 0) {
2062     return NID_undef;
2063   }
2064   return ssl_group_id_to_nid(group_id);
2065 }
2066 
SSL_CTX_set_tmp_dh(SSL_CTX * ctx,const DH * dh)2067 int SSL_CTX_set_tmp_dh(SSL_CTX *ctx, const DH *dh) {
2068   return 1;
2069 }
2070 
SSL_set_tmp_dh(SSL * ssl,const DH * dh)2071 int SSL_set_tmp_dh(SSL *ssl, const DH *dh) {
2072   return 1;
2073 }
2074 
STACK_OF(SSL_CIPHER)2075 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx) {
2076   return ctx->cipher_list->ciphers.get();
2077 }
2078 
SSL_CTX_cipher_in_group(const SSL_CTX * ctx,size_t i)2079 int SSL_CTX_cipher_in_group(const SSL_CTX *ctx, size_t i) {
2080   if (i >= sk_SSL_CIPHER_num(ctx->cipher_list->ciphers.get())) {
2081     return 0;
2082   }
2083   return ctx->cipher_list->in_group_flags[i];
2084 }
2085 
STACK_OF(SSL_CIPHER)2086 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *ssl) {
2087   if (ssl == NULL) {
2088     return NULL;
2089   }
2090   if (ssl->config == NULL) {
2091     assert(ssl->config);
2092     return NULL;
2093   }
2094 
2095   return ssl->config->cipher_list ? ssl->config->cipher_list->ciphers.get()
2096       : ssl->ctx->cipher_list->ciphers.get();
2097 }
2098 
SSL_get_cipher_list(const SSL * ssl,int n)2099 const char *SSL_get_cipher_list(const SSL *ssl, int n) {
2100   if (ssl == NULL) {
2101     return NULL;
2102   }
2103 
2104   STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
2105   if (sk == NULL || n < 0 || (size_t)n >= sk_SSL_CIPHER_num(sk)) {
2106     return NULL;
2107   }
2108 
2109   const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, n);
2110   if (c == NULL) {
2111     return NULL;
2112   }
2113 
2114   return c->name;
2115 }
2116 
SSL_CTX_set_cipher_list(SSL_CTX * ctx,const char * str)2117 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) {
2118   const bool has_aes_hw = ctx->aes_hw_override ? ctx->aes_hw_override_value
2119                                                : EVP_has_aes_hardware();
2120   return ssl_create_cipher_list(&ctx->cipher_list, has_aes_hw, str,
2121                                 false /* not strict */);
2122 }
2123 
SSL_CTX_set_strict_cipher_list(SSL_CTX * ctx,const char * str)2124 int SSL_CTX_set_strict_cipher_list(SSL_CTX *ctx, const char *str) {
2125   const bool has_aes_hw = ctx->aes_hw_override ? ctx->aes_hw_override_value
2126                                                : EVP_has_aes_hardware();
2127   return ssl_create_cipher_list(&ctx->cipher_list, has_aes_hw, str,
2128                                 true /* strict */);
2129 }
2130 
SSL_set_cipher_list(SSL * ssl,const char * str)2131 int SSL_set_cipher_list(SSL *ssl, const char *str) {
2132   if (!ssl->config) {
2133     return 0;
2134   }
2135   const bool has_aes_hw = ssl->config->aes_hw_override
2136                               ? ssl->config->aes_hw_override_value
2137                               : EVP_has_aes_hardware();
2138   return ssl_create_cipher_list(&ssl->config->cipher_list, has_aes_hw, str,
2139                                 false /* not strict */);
2140 }
2141 
SSL_set_strict_cipher_list(SSL * ssl,const char * str)2142 int SSL_set_strict_cipher_list(SSL *ssl, const char *str) {
2143   if (!ssl->config) {
2144     return 0;
2145   }
2146   const bool has_aes_hw = ssl->config->aes_hw_override
2147                               ? ssl->config->aes_hw_override_value
2148                               : EVP_has_aes_hardware();
2149   return ssl_create_cipher_list(&ssl->config->cipher_list, has_aes_hw, str,
2150                                 true /* strict */);
2151 }
2152 
SSL_get_servername(const SSL * ssl,const int type)2153 const char *SSL_get_servername(const SSL *ssl, const int type) {
2154   if (type != TLSEXT_NAMETYPE_host_name) {
2155     return NULL;
2156   }
2157 
2158   // Historically, |SSL_get_servername| was also the configuration getter
2159   // corresponding to |SSL_set_tlsext_host_name|.
2160   if (ssl->hostname != nullptr) {
2161     return ssl->hostname.get();
2162   }
2163 
2164   return ssl->s3->hostname.get();
2165 }
2166 
SSL_get_servername_type(const SSL * ssl)2167 int SSL_get_servername_type(const SSL *ssl) {
2168   if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name) == NULL) {
2169     return -1;
2170   }
2171   return TLSEXT_NAMETYPE_host_name;
2172 }
2173 
SSL_CTX_set_custom_verify(SSL_CTX * ctx,int mode,enum ssl_verify_result_t (* callback)(SSL * ssl,uint8_t * out_alert))2174 void SSL_CTX_set_custom_verify(
2175     SSL_CTX *ctx, int mode,
2176     enum ssl_verify_result_t (*callback)(SSL *ssl, uint8_t *out_alert)) {
2177   ctx->verify_mode = mode;
2178   ctx->custom_verify_callback = callback;
2179 }
2180 
SSL_set_custom_verify(SSL * ssl,int mode,enum ssl_verify_result_t (* callback)(SSL * ssl,uint8_t * out_alert))2181 void SSL_set_custom_verify(
2182     SSL *ssl, int mode,
2183     enum ssl_verify_result_t (*callback)(SSL *ssl, uint8_t *out_alert)) {
2184   if (!ssl->config) {
2185     return;
2186   }
2187   ssl->config->verify_mode = mode;
2188   ssl->config->custom_verify_callback = callback;
2189 }
2190 
SSL_CTX_enable_signed_cert_timestamps(SSL_CTX * ctx)2191 void SSL_CTX_enable_signed_cert_timestamps(SSL_CTX *ctx) {
2192   ctx->signed_cert_timestamps_enabled = true;
2193 }
2194 
SSL_enable_signed_cert_timestamps(SSL * ssl)2195 void SSL_enable_signed_cert_timestamps(SSL *ssl) {
2196   if (!ssl->config) {
2197     return;
2198   }
2199   ssl->config->signed_cert_timestamps_enabled = true;
2200 }
2201 
SSL_CTX_enable_ocsp_stapling(SSL_CTX * ctx)2202 void SSL_CTX_enable_ocsp_stapling(SSL_CTX *ctx) {
2203   ctx->ocsp_stapling_enabled = true;
2204 }
2205 
SSL_enable_ocsp_stapling(SSL * ssl)2206 void SSL_enable_ocsp_stapling(SSL *ssl) {
2207   if (!ssl->config) {
2208     return;
2209   }
2210   ssl->config->ocsp_stapling_enabled = true;
2211 }
2212 
SSL_get0_signed_cert_timestamp_list(const SSL * ssl,const uint8_t ** out,size_t * out_len)2213 void SSL_get0_signed_cert_timestamp_list(const SSL *ssl, const uint8_t **out,
2214                                          size_t *out_len) {
2215   SSL_SESSION *session = SSL_get_session(ssl);
2216   if (ssl->server || !session || !session->signed_cert_timestamp_list) {
2217     *out_len = 0;
2218     *out = NULL;
2219     return;
2220   }
2221 
2222   *out = CRYPTO_BUFFER_data(session->signed_cert_timestamp_list.get());
2223   *out_len = CRYPTO_BUFFER_len(session->signed_cert_timestamp_list.get());
2224 }
2225 
SSL_get0_ocsp_response(const SSL * ssl,const uint8_t ** out,size_t * out_len)2226 void SSL_get0_ocsp_response(const SSL *ssl, const uint8_t **out,
2227                             size_t *out_len) {
2228   SSL_SESSION *session = SSL_get_session(ssl);
2229   if (ssl->server || !session || !session->ocsp_response) {
2230     *out_len = 0;
2231     *out = NULL;
2232     return;
2233   }
2234 
2235   *out = CRYPTO_BUFFER_data(session->ocsp_response.get());
2236   *out_len = CRYPTO_BUFFER_len(session->ocsp_response.get());
2237 }
2238 
SSL_set_tlsext_host_name(SSL * ssl,const char * name)2239 int SSL_set_tlsext_host_name(SSL *ssl, const char *name) {
2240   ssl->hostname.reset();
2241   if (name == nullptr) {
2242     return 1;
2243   }
2244 
2245   size_t len = strlen(name);
2246   if (len == 0 || len > TLSEXT_MAXLEN_host_name) {
2247     OPENSSL_PUT_ERROR(SSL, SSL_R_SSL3_EXT_INVALID_SERVERNAME);
2248     return 0;
2249   }
2250   ssl->hostname.reset(OPENSSL_strdup(name));
2251   if (ssl->hostname == nullptr) {
2252     return 0;
2253   }
2254   return 1;
2255 }
2256 
SSL_CTX_set_tlsext_servername_callback(SSL_CTX * ctx,int (* callback)(SSL * ssl,int * out_alert,void * arg))2257 int SSL_CTX_set_tlsext_servername_callback(
2258     SSL_CTX *ctx, int (*callback)(SSL *ssl, int *out_alert, void *arg)) {
2259   ctx->servername_callback = callback;
2260   return 1;
2261 }
2262 
SSL_CTX_set_tlsext_servername_arg(SSL_CTX * ctx,void * arg)2263 int SSL_CTX_set_tlsext_servername_arg(SSL_CTX *ctx, void *arg) {
2264   ctx->servername_arg = arg;
2265   return 1;
2266 }
2267 
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)2268 int SSL_select_next_proto(uint8_t **out, uint8_t *out_len, const uint8_t *peer,
2269                           unsigned peer_len, const uint8_t *supported,
2270                           unsigned supported_len) {
2271   const uint8_t *result;
2272   int status;
2273 
2274   // For each protocol in peer preference order, see if we support it.
2275   for (unsigned i = 0; i < peer_len;) {
2276     for (unsigned j = 0; j < supported_len;) {
2277       if (peer[i] == supported[j] &&
2278           OPENSSL_memcmp(&peer[i + 1], &supported[j + 1], peer[i]) == 0) {
2279         // We found a match
2280         result = &peer[i];
2281         status = OPENSSL_NPN_NEGOTIATED;
2282         goto found;
2283       }
2284       j += supported[j];
2285       j++;
2286     }
2287     i += peer[i];
2288     i++;
2289   }
2290 
2291   // There's no overlap between our protocols and the peer's list.
2292   result = supported;
2293   status = OPENSSL_NPN_NO_OVERLAP;
2294 
2295 found:
2296   *out = (uint8_t *)result + 1;
2297   *out_len = result[0];
2298   return status;
2299 }
2300 
SSL_get0_next_proto_negotiated(const SSL * ssl,const uint8_t ** out_data,unsigned * out_len)2301 void SSL_get0_next_proto_negotiated(const SSL *ssl, const uint8_t **out_data,
2302                                     unsigned *out_len) {
2303   // NPN protocols have one-byte lengths, so they must fit in |unsigned|.
2304   assert(ssl->s3->next_proto_negotiated.size() <= UINT_MAX);
2305   *out_data = ssl->s3->next_proto_negotiated.data();
2306   *out_len = static_cast<unsigned>(ssl->s3->next_proto_negotiated.size());
2307 }
2308 
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)2309 void SSL_CTX_set_next_protos_advertised_cb(
2310     SSL_CTX *ctx,
2311     int (*cb)(SSL *ssl, const uint8_t **out, unsigned *out_len, void *arg),
2312     void *arg) {
2313   ctx->next_protos_advertised_cb = cb;
2314   ctx->next_protos_advertised_cb_arg = arg;
2315 }
2316 
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)2317 void SSL_CTX_set_next_proto_select_cb(
2318     SSL_CTX *ctx, int (*cb)(SSL *ssl, uint8_t **out, uint8_t *out_len,
2319                             const uint8_t *in, unsigned in_len, void *arg),
2320     void *arg) {
2321   ctx->next_proto_select_cb = cb;
2322   ctx->next_proto_select_cb_arg = arg;
2323 }
2324 
SSL_CTX_set_alpn_protos(SSL_CTX * ctx,const uint8_t * protos,size_t protos_len)2325 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const uint8_t *protos,
2326                             size_t protos_len) {
2327   // Note this function's return value is backwards.
2328   auto span = MakeConstSpan(protos, protos_len);
2329   if (!span.empty() && !ssl_is_valid_alpn_list(span)) {
2330     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL_LIST);
2331     return 1;
2332   }
2333   return ctx->alpn_client_proto_list.CopyFrom(span) ? 0 : 1;
2334 }
2335 
SSL_set_alpn_protos(SSL * ssl,const uint8_t * protos,size_t protos_len)2336 int SSL_set_alpn_protos(SSL *ssl, const uint8_t *protos, size_t protos_len) {
2337   // Note this function's return value is backwards.
2338   if (!ssl->config) {
2339     return 1;
2340   }
2341   auto span = MakeConstSpan(protos, protos_len);
2342   if (!span.empty() && !ssl_is_valid_alpn_list(span)) {
2343     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_ALPN_PROTOCOL_LIST);
2344     return 1;
2345   }
2346   return ssl->config->alpn_client_proto_list.CopyFrom(span) ? 0 : 1;
2347 }
2348 
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)2349 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2350                                 int (*cb)(SSL *ssl, const uint8_t **out,
2351                                           uint8_t *out_len, const uint8_t *in,
2352                                           unsigned in_len, void *arg),
2353                                 void *arg) {
2354   ctx->alpn_select_cb = cb;
2355   ctx->alpn_select_cb_arg = arg;
2356 }
2357 
SSL_get0_alpn_selected(const SSL * ssl,const uint8_t ** out_data,unsigned * out_len)2358 void SSL_get0_alpn_selected(const SSL *ssl, const uint8_t **out_data,
2359                             unsigned *out_len) {
2360   Span<const uint8_t> protocol;
2361   if (SSL_in_early_data(ssl) && !ssl->server) {
2362     protocol = ssl->s3->hs->early_session->early_alpn;
2363   } else {
2364     protocol = ssl->s3->alpn_selected;
2365   }
2366   // ALPN protocols have one-byte lengths, so they must fit in |unsigned|.
2367   assert(protocol.size() < UINT_MAX);
2368   *out_data = protocol.data();
2369   *out_len = static_cast<unsigned>(protocol.size());
2370 }
2371 
SSL_CTX_set_allow_unknown_alpn_protos(SSL_CTX * ctx,int enabled)2372 void SSL_CTX_set_allow_unknown_alpn_protos(SSL_CTX *ctx, int enabled) {
2373   ctx->allow_unknown_alpn_protos = !!enabled;
2374 }
2375 
SSL_add_application_settings(SSL * ssl,const uint8_t * proto,size_t proto_len,const uint8_t * settings,size_t settings_len)2376 int SSL_add_application_settings(SSL *ssl, const uint8_t *proto,
2377                                  size_t proto_len, const uint8_t *settings,
2378                                  size_t settings_len) {
2379   if (!ssl->config) {
2380     return 0;
2381   }
2382   ALPSConfig config;
2383   if (!config.protocol.CopyFrom(MakeConstSpan(proto, proto_len)) ||
2384       !config.settings.CopyFrom(MakeConstSpan(settings, settings_len)) ||
2385       !ssl->config->alps_configs.Push(std::move(config))) {
2386     return 0;
2387   }
2388   return 1;
2389 }
2390 
SSL_get0_peer_application_settings(const SSL * ssl,const uint8_t ** out_data,size_t * out_len)2391 void SSL_get0_peer_application_settings(const SSL *ssl,
2392                                         const uint8_t **out_data,
2393                                         size_t *out_len) {
2394   const SSL_SESSION *session = SSL_get_session(ssl);
2395   Span<const uint8_t> settings =
2396       session ? session->peer_application_settings : Span<const uint8_t>();
2397   *out_data = settings.data();
2398   *out_len = settings.size();
2399 }
2400 
SSL_has_application_settings(const SSL * ssl)2401 int SSL_has_application_settings(const SSL *ssl) {
2402   const SSL_SESSION *session = SSL_get_session(ssl);
2403   return session && session->has_application_settings;
2404 }
2405 
SSL_set_alps_use_new_codepoint(SSL * ssl,int use_new)2406 void SSL_set_alps_use_new_codepoint(SSL *ssl, int use_new) {
2407   if (!ssl->config) {
2408     return;
2409   }
2410   ssl->config->alps_use_new_codepoint = !!use_new;
2411 }
2412 
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)2413 int SSL_CTX_add_cert_compression_alg(SSL_CTX *ctx, uint16_t alg_id,
2414                                      ssl_cert_compression_func_t compress,
2415                                      ssl_cert_decompression_func_t decompress) {
2416   assert(compress != nullptr || decompress != nullptr);
2417 
2418   for (const auto &alg : ctx->cert_compression_algs) {
2419     if (alg.alg_id == alg_id) {
2420       return 0;
2421     }
2422   }
2423 
2424   CertCompressionAlg alg;
2425   alg.alg_id = alg_id;
2426   alg.compress = compress;
2427   alg.decompress = decompress;
2428   return ctx->cert_compression_algs.Push(alg);
2429 }
2430 
SSL_CTX_set_tls_channel_id_enabled(SSL_CTX * ctx,int enabled)2431 void SSL_CTX_set_tls_channel_id_enabled(SSL_CTX *ctx, int enabled) {
2432   ctx->channel_id_enabled = !!enabled;
2433 }
2434 
SSL_CTX_enable_tls_channel_id(SSL_CTX * ctx)2435 int SSL_CTX_enable_tls_channel_id(SSL_CTX *ctx) {
2436   SSL_CTX_set_tls_channel_id_enabled(ctx, 1);
2437   return 1;
2438 }
2439 
SSL_set_tls_channel_id_enabled(SSL * ssl,int enabled)2440 void SSL_set_tls_channel_id_enabled(SSL *ssl, int enabled) {
2441   if (!ssl->config) {
2442     return;
2443   }
2444   ssl->config->channel_id_enabled = !!enabled;
2445 }
2446 
SSL_enable_tls_channel_id(SSL * ssl)2447 int SSL_enable_tls_channel_id(SSL *ssl) {
2448   SSL_set_tls_channel_id_enabled(ssl, 1);
2449   return 1;
2450 }
2451 
is_p256_key(EVP_PKEY * private_key)2452 static int is_p256_key(EVP_PKEY *private_key) {
2453   const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(private_key);
2454   return ec_key != NULL &&
2455          EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key)) ==
2456              NID_X9_62_prime256v1;
2457 }
2458 
SSL_CTX_set1_tls_channel_id(SSL_CTX * ctx,EVP_PKEY * private_key)2459 int SSL_CTX_set1_tls_channel_id(SSL_CTX *ctx, EVP_PKEY *private_key) {
2460   if (!is_p256_key(private_key)) {
2461     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
2462     return 0;
2463   }
2464 
2465   ctx->channel_id_private = UpRef(private_key);
2466   return 1;
2467 }
2468 
SSL_set1_tls_channel_id(SSL * ssl,EVP_PKEY * private_key)2469 int SSL_set1_tls_channel_id(SSL *ssl, EVP_PKEY *private_key) {
2470   if (!ssl->config) {
2471     return 0;
2472   }
2473   if (!is_p256_key(private_key)) {
2474     OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
2475     return 0;
2476   }
2477 
2478   ssl->config->channel_id_private = UpRef(private_key);
2479   return 1;
2480 }
2481 
SSL_get_tls_channel_id(SSL * ssl,uint8_t * out,size_t max_out)2482 size_t SSL_get_tls_channel_id(SSL *ssl, uint8_t *out, size_t max_out) {
2483   if (!ssl->s3->channel_id_valid) {
2484     return 0;
2485   }
2486   OPENSSL_memcpy(out, ssl->s3->channel_id, (max_out < 64) ? max_out : 64);
2487   return 64;
2488 }
2489 
SSL_get0_certificate_types(const SSL * ssl,const uint8_t ** out_types)2490 size_t SSL_get0_certificate_types(const SSL *ssl, const uint8_t **out_types) {
2491   Span<const uint8_t> types;
2492   if (!ssl->server && ssl->s3->hs != nullptr) {
2493     types = ssl->s3->hs->certificate_types;
2494   }
2495   *out_types = types.data();
2496   return types.size();
2497 }
2498 
SSL_get0_peer_verify_algorithms(const SSL * ssl,const uint16_t ** out_sigalgs)2499 size_t SSL_get0_peer_verify_algorithms(const SSL *ssl,
2500                                        const uint16_t **out_sigalgs) {
2501   Span<const uint16_t> sigalgs;
2502   if (ssl->s3->hs != nullptr) {
2503     sigalgs = ssl->s3->hs->peer_sigalgs;
2504   }
2505   *out_sigalgs = sigalgs.data();
2506   return sigalgs.size();
2507 }
2508 
SSL_get0_peer_delegation_algorithms(const SSL * ssl,const uint16_t ** out_sigalgs)2509 size_t SSL_get0_peer_delegation_algorithms(const SSL *ssl,
2510                                            const uint16_t **out_sigalgs){
2511   Span<const uint16_t> sigalgs;
2512   if (ssl->s3->hs != nullptr) {
2513     sigalgs = ssl->s3->hs->peer_delegated_credential_sigalgs;
2514   }
2515   *out_sigalgs = sigalgs.data();
2516   return sigalgs.size();
2517 }
2518 
SSL_get_privatekey(const SSL * ssl)2519 EVP_PKEY *SSL_get_privatekey(const SSL *ssl) {
2520   if (!ssl->config) {
2521     assert(ssl->config);
2522     return NULL;
2523   }
2524   if (ssl->config->cert != NULL) {
2525     return ssl->config->cert->privatekey.get();
2526   }
2527 
2528   return NULL;
2529 }
2530 
SSL_CTX_get0_privatekey(const SSL_CTX * ctx)2531 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx) {
2532   if (ctx->cert != NULL) {
2533     return ctx->cert->privatekey.get();
2534   }
2535 
2536   return NULL;
2537 }
2538 
SSL_get_current_cipher(const SSL * ssl)2539 const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl) {
2540   const SSL_SESSION *session = SSL_get_session(ssl);
2541   return session == nullptr ? nullptr : session->cipher;
2542 }
2543 
SSL_session_reused(const SSL * ssl)2544 int SSL_session_reused(const SSL *ssl) {
2545   return ssl->s3->session_reused || SSL_in_early_data(ssl);
2546 }
2547 
SSL_get_current_compression(SSL * ssl)2548 const COMP_METHOD *SSL_get_current_compression(SSL *ssl) { return NULL; }
2549 
SSL_get_current_expansion(SSL * ssl)2550 const COMP_METHOD *SSL_get_current_expansion(SSL *ssl) { return NULL; }
2551 
SSL_get_server_tmp_key(SSL * ssl,EVP_PKEY ** out_key)2552 int SSL_get_server_tmp_key(SSL *ssl, EVP_PKEY **out_key) { return 0; }
2553 
SSL_CTX_set_quiet_shutdown(SSL_CTX * ctx,int mode)2554 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode) {
2555   ctx->quiet_shutdown = (mode != 0);
2556 }
2557 
SSL_CTX_get_quiet_shutdown(const SSL_CTX * ctx)2558 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx) {
2559   return ctx->quiet_shutdown;
2560 }
2561 
SSL_set_quiet_shutdown(SSL * ssl,int mode)2562 void SSL_set_quiet_shutdown(SSL *ssl, int mode) {
2563   ssl->quiet_shutdown = (mode != 0);
2564 }
2565 
SSL_get_quiet_shutdown(const SSL * ssl)2566 int SSL_get_quiet_shutdown(const SSL *ssl) { return ssl->quiet_shutdown; }
2567 
SSL_set_shutdown(SSL * ssl,int mode)2568 void SSL_set_shutdown(SSL *ssl, int mode) {
2569   // It is an error to clear any bits that have already been set. (We can't try
2570   // to get a second close_notify or send two.)
2571   assert((SSL_get_shutdown(ssl) & mode) == SSL_get_shutdown(ssl));
2572 
2573   if (mode & SSL_RECEIVED_SHUTDOWN &&
2574       ssl->s3->read_shutdown == ssl_shutdown_none) {
2575     ssl->s3->read_shutdown = ssl_shutdown_close_notify;
2576   }
2577 
2578   if (mode & SSL_SENT_SHUTDOWN &&
2579       ssl->s3->write_shutdown == ssl_shutdown_none) {
2580     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
2581   }
2582 }
2583 
SSL_get_shutdown(const SSL * ssl)2584 int SSL_get_shutdown(const SSL *ssl) {
2585   int ret = 0;
2586   if (ssl->s3->read_shutdown != ssl_shutdown_none) {
2587     // Historically, OpenSSL set |SSL_RECEIVED_SHUTDOWN| on both close_notify
2588     // and fatal alert.
2589     ret |= SSL_RECEIVED_SHUTDOWN;
2590   }
2591   if (ssl->s3->write_shutdown == ssl_shutdown_close_notify) {
2592     // Historically, OpenSSL set |SSL_SENT_SHUTDOWN| on only close_notify.
2593     ret |= SSL_SENT_SHUTDOWN;
2594   }
2595   return ret;
2596 }
2597 
SSL_get_SSL_CTX(const SSL * ssl)2598 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl) { return ssl->ctx.get(); }
2599 
SSL_set_SSL_CTX(SSL * ssl,SSL_CTX * ctx)2600 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx) {
2601   if (!ssl->config) {
2602     return NULL;
2603   }
2604   if (ssl->ctx.get() == ctx) {
2605     return ssl->ctx.get();
2606   }
2607 
2608   // One cannot change the X.509 callbacks during a connection.
2609   if (ssl->ctx->x509_method != ctx->x509_method) {
2610     assert(0);
2611     return NULL;
2612   }
2613 
2614   UniquePtr<CERT> new_cert = ssl_cert_dup(ctx->cert.get());
2615   if (!new_cert) {
2616     return nullptr;
2617   }
2618 
2619   ssl->config->cert = std::move(new_cert);
2620   ssl->ctx = UpRef(ctx);
2621   ssl->enable_early_data = ssl->ctx->enable_early_data;
2622 
2623   return ssl->ctx.get();
2624 }
2625 
SSL_set_info_callback(SSL * ssl,void (* cb)(const SSL * ssl,int type,int value))2626 void SSL_set_info_callback(SSL *ssl,
2627                            void (*cb)(const SSL *ssl, int type, int value)) {
2628   ssl->info_callback = cb;
2629 }
2630 
SSL_get_info_callback(const SSL * ssl)2631 void (*SSL_get_info_callback(const SSL *ssl))(const SSL *ssl, int type,
2632                                               int value) {
2633   return ssl->info_callback;
2634 }
2635 
SSL_state(const SSL * ssl)2636 int SSL_state(const SSL *ssl) {
2637   return SSL_in_init(ssl) ? SSL_ST_INIT : SSL_ST_OK;
2638 }
2639 
SSL_set_state(SSL * ssl,int state)2640 void SSL_set_state(SSL *ssl, int state) { }
2641 
SSL_get_shared_ciphers(const SSL * ssl,char * buf,int len)2642 char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len) {
2643   if (len <= 0) {
2644     return NULL;
2645   }
2646   buf[0] = '\0';
2647   return buf;
2648 }
2649 
SSL_get_shared_sigalgs(SSL * ssl,int idx,int * psign,int * phash,int * psignandhash,uint8_t * rsig,uint8_t * rhash)2650 int SSL_get_shared_sigalgs(SSL *ssl, int idx, int *psign, int *phash,
2651                            int *psignandhash, uint8_t *rsig, uint8_t *rhash) {
2652   return 0;
2653 }
2654 
SSL_CTX_set_quic_method(SSL_CTX * ctx,const SSL_QUIC_METHOD * quic_method)2655 int SSL_CTX_set_quic_method(SSL_CTX *ctx, const SSL_QUIC_METHOD *quic_method) {
2656   if (ctx->method->is_dtls) {
2657     return 0;
2658   }
2659   ctx->quic_method = quic_method;
2660   return 1;
2661 }
2662 
SSL_set_quic_method(SSL * ssl,const SSL_QUIC_METHOD * quic_method)2663 int SSL_set_quic_method(SSL *ssl, const SSL_QUIC_METHOD *quic_method) {
2664   if (ssl->method->is_dtls) {
2665     return 0;
2666   }
2667   ssl->quic_method = quic_method;
2668   return 1;
2669 }
2670 
SSL_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)2671 int SSL_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
2672                          CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
2673   int index;
2674   if (!CRYPTO_get_ex_new_index(&g_ex_data_class_ssl, &index, argl, argp,
2675                                free_func)) {
2676     return -1;
2677   }
2678   return index;
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   int index;
2693   if (!CRYPTO_get_ex_new_index(&g_ex_data_class_ssl_ctx, &index, argl, argp,
2694                                free_func)) {
2695     return -1;
2696   }
2697   return index;
2698 }
2699 
SSL_CTX_set_ex_data(SSL_CTX * ctx,int idx,void * data)2700 int SSL_CTX_set_ex_data(SSL_CTX *ctx, int idx, void *data) {
2701   return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2702 }
2703 
SSL_CTX_get_ex_data(const SSL_CTX * ctx,int idx)2704 void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx) {
2705   return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2706 }
2707 
SSL_want(const SSL * ssl)2708 int SSL_want(const SSL *ssl) {
2709   // Historically, OpenSSL did not track |SSL_ERROR_ZERO_RETURN| as an |rwstate|
2710   // value. We do, but map it back to |SSL_ERROR_NONE| to preserve the original
2711   // behavior.
2712   return ssl->s3->rwstate == SSL_ERROR_ZERO_RETURN ? SSL_ERROR_NONE
2713                                                    : ssl->s3->rwstate;
2714 }
2715 
SSL_CTX_set_tmp_rsa_callback(SSL_CTX * ctx,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2716 void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx,
2717                                   RSA *(*cb)(SSL *ssl, int is_export,
2718                                              int keylength)) {}
2719 
SSL_set_tmp_rsa_callback(SSL * ssl,RSA * (* cb)(SSL * ssl,int is_export,int keylength))2720 void SSL_set_tmp_rsa_callback(SSL *ssl, RSA *(*cb)(SSL *ssl, int is_export,
2721                                                    int keylength)) {}
2722 
SSL_CTX_set_tmp_dh_callback(SSL_CTX * ctx,DH * (* cb)(SSL * ssl,int is_export,int keylength))2723 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
2724                                  DH *(*cb)(SSL *ssl, int is_export,
2725                                            int keylength)) {}
2726 
SSL_set_tmp_dh_callback(SSL * ssl,DH * (* cb)(SSL * ssl,int is_export,int keylength))2727 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*cb)(SSL *ssl, int is_export,
2728                                                  int keylength)) {}
2729 
use_psk_identity_hint(UniquePtr<char> * out,const char * identity_hint)2730 static int use_psk_identity_hint(UniquePtr<char> *out,
2731                                  const char *identity_hint) {
2732   if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
2733     OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
2734     return 0;
2735   }
2736 
2737   // Clear currently configured hint, if any.
2738   out->reset();
2739 
2740   // Treat the empty hint as not supplying one. Plain PSK makes it possible to
2741   // send either no hint (omit ServerKeyExchange) or an empty hint, while
2742   // ECDHE_PSK can only spell empty hint. Having different capabilities is odd,
2743   // so we interpret empty and missing as identical.
2744   if (identity_hint != NULL && identity_hint[0] != '\0') {
2745     out->reset(OPENSSL_strdup(identity_hint));
2746     if (*out == nullptr) {
2747       return 0;
2748     }
2749   }
2750 
2751   return 1;
2752 }
2753 
SSL_CTX_use_psk_identity_hint(SSL_CTX * ctx,const char * identity_hint)2754 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint) {
2755   return use_psk_identity_hint(&ctx->psk_identity_hint, identity_hint);
2756 }
2757 
SSL_use_psk_identity_hint(SSL * ssl,const char * identity_hint)2758 int SSL_use_psk_identity_hint(SSL *ssl, const char *identity_hint) {
2759   if (!ssl->config) {
2760     return 0;
2761   }
2762   return use_psk_identity_hint(&ssl->config->psk_identity_hint, identity_hint);
2763 }
2764 
SSL_get_psk_identity_hint(const SSL * ssl)2765 const char *SSL_get_psk_identity_hint(const SSL *ssl) {
2766   if (ssl == NULL) {
2767     return NULL;
2768   }
2769   if (ssl->config == NULL) {
2770     assert(ssl->config);
2771     return NULL;
2772   }
2773   return ssl->config->psk_identity_hint.get();
2774 }
2775 
SSL_get_psk_identity(const SSL * ssl)2776 const char *SSL_get_psk_identity(const SSL *ssl) {
2777   if (ssl == NULL) {
2778     return NULL;
2779   }
2780   SSL_SESSION *session = SSL_get_session(ssl);
2781   if (session == NULL) {
2782     return NULL;
2783   }
2784   return session->psk_identity.get();
2785 }
2786 
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))2787 void SSL_set_psk_client_callback(
2788     SSL *ssl, unsigned (*cb)(SSL *ssl, const char *hint, char *identity,
2789                              unsigned max_identity_len, uint8_t *psk,
2790                              unsigned max_psk_len)) {
2791   if (!ssl->config) {
2792     return;
2793   }
2794   ssl->config->psk_client_callback = cb;
2795 }
2796 
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))2797 void SSL_CTX_set_psk_client_callback(
2798     SSL_CTX *ctx, unsigned (*cb)(SSL *ssl, const char *hint, char *identity,
2799                                  unsigned max_identity_len, uint8_t *psk,
2800                                  unsigned max_psk_len)) {
2801   ctx->psk_client_callback = cb;
2802 }
2803 
SSL_set_psk_server_callback(SSL * ssl,unsigned (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned max_psk_len))2804 void SSL_set_psk_server_callback(
2805     SSL *ssl, unsigned (*cb)(SSL *ssl, const char *identity, uint8_t *psk,
2806                              unsigned max_psk_len)) {
2807   if (!ssl->config) {
2808     return;
2809   }
2810   ssl->config->psk_server_callback = cb;
2811 }
2812 
SSL_CTX_set_psk_server_callback(SSL_CTX * ctx,unsigned (* cb)(SSL * ssl,const char * identity,uint8_t * psk,unsigned max_psk_len))2813 void SSL_CTX_set_psk_server_callback(
2814     SSL_CTX *ctx, unsigned (*cb)(SSL *ssl, const char *identity,
2815                                  uint8_t *psk, unsigned max_psk_len)) {
2816   ctx->psk_server_callback = cb;
2817 }
2818 
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))2819 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
2820                               void (*cb)(int write_p, int version,
2821                                          int content_type, const void *buf,
2822                                          size_t len, SSL *ssl, void *arg)) {
2823   ctx->msg_callback = cb;
2824 }
2825 
SSL_CTX_set_msg_callback_arg(SSL_CTX * ctx,void * arg)2826 void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg) {
2827   ctx->msg_callback_arg = arg;
2828 }
2829 
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))2830 void SSL_set_msg_callback(SSL *ssl,
2831                           void (*cb)(int write_p, int version, int content_type,
2832                                      const void *buf, size_t len, SSL *ssl,
2833                                      void *arg)) {
2834   ssl->msg_callback = cb;
2835 }
2836 
SSL_set_msg_callback_arg(SSL * ssl,void * arg)2837 void SSL_set_msg_callback_arg(SSL *ssl, void *arg) {
2838   ssl->msg_callback_arg = arg;
2839 }
2840 
SSL_CTX_set_keylog_callback(SSL_CTX * ctx,void (* cb)(const SSL * ssl,const char * line))2841 void SSL_CTX_set_keylog_callback(SSL_CTX *ctx,
2842                                  void (*cb)(const SSL *ssl, const char *line)) {
2843   ctx->keylog_callback = cb;
2844 }
2845 
SSL_CTX_get_keylog_callback(const SSL_CTX * ctx)2846 void (*SSL_CTX_get_keylog_callback(const SSL_CTX *ctx))(const SSL *ssl,
2847                                                         const char *line) {
2848   return ctx->keylog_callback;
2849 }
2850 
SSL_CTX_set_current_time_cb(SSL_CTX * ctx,void (* cb)(const SSL * ssl,struct timeval * out_clock))2851 void SSL_CTX_set_current_time_cb(SSL_CTX *ctx,
2852                                  void (*cb)(const SSL *ssl,
2853                                             struct timeval *out_clock)) {
2854   ctx->current_time_cb = cb;
2855 }
2856 
SSL_can_release_private_key(const SSL * ssl)2857 int SSL_can_release_private_key(const SSL *ssl) {
2858   if (ssl_can_renegotiate(ssl)) {
2859     // If the connection can renegotiate (client only), the private key may be
2860     // used in a future handshake.
2861     return 0;
2862   }
2863 
2864   // Otherwise, this is determined by the current handshake.
2865   return !ssl->s3->hs || ssl->s3->hs->can_release_private_key;
2866 }
2867 
SSL_is_init_finished(const SSL * ssl)2868 int SSL_is_init_finished(const SSL *ssl) {
2869   return !SSL_in_init(ssl);
2870 }
2871 
SSL_in_init(const SSL * ssl)2872 int SSL_in_init(const SSL *ssl) {
2873   // This returns false once all the handshake state has been finalized, to
2874   // allow callbacks and getters based on SSL_in_init to return the correct
2875   // values.
2876   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
2877   return hs != nullptr && !hs->handshake_finalized;
2878 }
2879 
SSL_in_false_start(const SSL * ssl)2880 int SSL_in_false_start(const SSL *ssl) {
2881   if (ssl->s3->hs == NULL) {
2882     return 0;
2883   }
2884   return ssl->s3->hs->in_false_start;
2885 }
2886 
SSL_cutthrough_complete(const SSL * ssl)2887 int SSL_cutthrough_complete(const SSL *ssl) {
2888   return SSL_in_false_start(ssl);
2889 }
2890 
SSL_is_server(const SSL * ssl)2891 int SSL_is_server(const SSL *ssl) { return ssl->server; }
2892 
SSL_is_dtls(const SSL * ssl)2893 int SSL_is_dtls(const SSL *ssl) { return ssl->method->is_dtls; }
2894 
SSL_CTX_set_select_certificate_cb(SSL_CTX * ctx,enum ssl_select_cert_result_t (* cb)(const SSL_CLIENT_HELLO *))2895 void SSL_CTX_set_select_certificate_cb(
2896     SSL_CTX *ctx,
2897     enum ssl_select_cert_result_t (*cb)(const SSL_CLIENT_HELLO *)) {
2898   ctx->select_certificate_cb = cb;
2899 }
2900 
SSL_CTX_set_dos_protection_cb(SSL_CTX * ctx,int (* cb)(const SSL_CLIENT_HELLO *))2901 void SSL_CTX_set_dos_protection_cb(SSL_CTX *ctx,
2902                                    int (*cb)(const SSL_CLIENT_HELLO *)) {
2903   ctx->dos_protection_cb = cb;
2904 }
2905 
SSL_CTX_set_reverify_on_resume(SSL_CTX * ctx,int enabled)2906 void SSL_CTX_set_reverify_on_resume(SSL_CTX *ctx, int enabled) {
2907   ctx->reverify_on_resume = !!enabled;
2908 }
2909 
SSL_set_enforce_rsa_key_usage(SSL * ssl,int enabled)2910 void SSL_set_enforce_rsa_key_usage(SSL *ssl, int enabled) {
2911   if (!ssl->config) {
2912     return;
2913   }
2914   ssl->config->enforce_rsa_key_usage = !!enabled;
2915 }
2916 
SSL_was_key_usage_invalid(const SSL * ssl)2917 int SSL_was_key_usage_invalid(const SSL *ssl) {
2918   return ssl->s3->was_key_usage_invalid;
2919 }
2920 
SSL_set_renegotiate_mode(SSL * ssl,enum ssl_renegotiate_mode_t mode)2921 void SSL_set_renegotiate_mode(SSL *ssl, enum ssl_renegotiate_mode_t mode) {
2922   ssl->renegotiate_mode = mode;
2923 
2924   // Check if |ssl_can_renegotiate| has changed and the configuration may now be
2925   // shed. HTTP clients may initially allow renegotiation for HTTP/1.1, and then
2926   // disable after the handshake once the ALPN protocol is known to be HTTP/2.
2927   ssl_maybe_shed_handshake_config(ssl);
2928 }
2929 
SSL_get_ivs(const SSL * ssl,const uint8_t ** out_read_iv,const uint8_t ** out_write_iv,size_t * out_iv_len)2930 int SSL_get_ivs(const SSL *ssl, const uint8_t **out_read_iv,
2931                 const uint8_t **out_write_iv, size_t *out_iv_len) {
2932   size_t write_iv_len;
2933   if (!ssl->s3->aead_read_ctx->GetIV(out_read_iv, out_iv_len) ||
2934       !ssl->s3->aead_write_ctx->GetIV(out_write_iv, &write_iv_len) ||
2935       *out_iv_len != write_iv_len) {
2936     return 0;
2937   }
2938 
2939   return 1;
2940 }
2941 
SSL_get_read_sequence(const SSL * ssl)2942 uint64_t SSL_get_read_sequence(const SSL *ssl) {
2943   if (SSL_is_dtls(ssl)) {
2944     // max_seq_num already includes the epoch.
2945     assert(ssl->d1->r_epoch == (ssl->d1->bitmap.max_seq_num >> 48));
2946     return ssl->d1->bitmap.max_seq_num;
2947   }
2948   return ssl->s3->read_sequence;
2949 }
2950 
SSL_get_write_sequence(const SSL * ssl)2951 uint64_t SSL_get_write_sequence(const SSL *ssl) {
2952   uint64_t ret = ssl->s3->write_sequence;
2953   if (SSL_is_dtls(ssl)) {
2954     assert((ret >> 48) == 0);
2955     ret |= uint64_t{ssl->d1->w_epoch} << 48;
2956   }
2957   return ret;
2958 }
2959 
SSL_get_peer_signature_algorithm(const SSL * ssl)2960 uint16_t SSL_get_peer_signature_algorithm(const SSL *ssl) {
2961   SSL_SESSION *session = SSL_get_session(ssl);
2962   if (session == NULL) {
2963     return 0;
2964   }
2965 
2966   return session->peer_signature_algorithm;
2967 }
2968 
SSL_get_client_random(const SSL * ssl,uint8_t * out,size_t max_out)2969 size_t SSL_get_client_random(const SSL *ssl, uint8_t *out, size_t max_out) {
2970   if (max_out == 0) {
2971     return sizeof(ssl->s3->client_random);
2972   }
2973   if (max_out > sizeof(ssl->s3->client_random)) {
2974     max_out = sizeof(ssl->s3->client_random);
2975   }
2976   OPENSSL_memcpy(out, ssl->s3->client_random, max_out);
2977   return max_out;
2978 }
2979 
SSL_get_server_random(const SSL * ssl,uint8_t * out,size_t max_out)2980 size_t SSL_get_server_random(const SSL *ssl, uint8_t *out, size_t max_out) {
2981   if (max_out == 0) {
2982     return sizeof(ssl->s3->server_random);
2983   }
2984   if (max_out > sizeof(ssl->s3->server_random)) {
2985     max_out = sizeof(ssl->s3->server_random);
2986   }
2987   OPENSSL_memcpy(out, ssl->s3->server_random, max_out);
2988   return max_out;
2989 }
2990 
SSL_get_pending_cipher(const SSL * ssl)2991 const SSL_CIPHER *SSL_get_pending_cipher(const SSL *ssl) {
2992   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
2993   if (hs == NULL) {
2994     return NULL;
2995   }
2996   return hs->new_cipher;
2997 }
2998 
SSL_set_retain_only_sha256_of_client_certs(SSL * ssl,int enabled)2999 void SSL_set_retain_only_sha256_of_client_certs(SSL *ssl, int enabled) {
3000   if (!ssl->config) {
3001     return;
3002   }
3003   ssl->config->retain_only_sha256_of_client_certs = !!enabled;
3004 }
3005 
SSL_CTX_set_retain_only_sha256_of_client_certs(SSL_CTX * ctx,int enabled)3006 void SSL_CTX_set_retain_only_sha256_of_client_certs(SSL_CTX *ctx, int enabled) {
3007   ctx->retain_only_sha256_of_client_certs = !!enabled;
3008 }
3009 
SSL_CTX_set_grease_enabled(SSL_CTX * ctx,int enabled)3010 void SSL_CTX_set_grease_enabled(SSL_CTX *ctx, int enabled) {
3011   ctx->grease_enabled = !!enabled;
3012 }
3013 
SSL_CTX_set_permute_extensions(SSL_CTX * ctx,int enabled)3014 void SSL_CTX_set_permute_extensions(SSL_CTX *ctx, int enabled) {
3015   ctx->permute_extensions = !!enabled;
3016 }
3017 
SSL_set_permute_extensions(SSL * ssl,int enabled)3018 void SSL_set_permute_extensions(SSL *ssl, int enabled) {
3019   if (!ssl->config) {
3020     return;
3021   }
3022   ssl->config->permute_extensions = !!enabled;
3023 }
3024 
SSL_get_ticket_age_skew(const SSL * ssl)3025 int32_t SSL_get_ticket_age_skew(const SSL *ssl) {
3026   return ssl->s3->ticket_age_skew;
3027 }
3028 
SSL_CTX_set_false_start_allowed_without_alpn(SSL_CTX * ctx,int allowed)3029 void SSL_CTX_set_false_start_allowed_without_alpn(SSL_CTX *ctx, int allowed) {
3030   ctx->false_start_allowed_without_alpn = !!allowed;
3031 }
3032 
SSL_used_hello_retry_request(const SSL * ssl)3033 int SSL_used_hello_retry_request(const SSL *ssl) {
3034   return ssl->s3->used_hello_retry_request;
3035 }
3036 
SSL_set_shed_handshake_config(SSL * ssl,int enable)3037 void SSL_set_shed_handshake_config(SSL *ssl, int enable) {
3038   if (!ssl->config) {
3039     return;
3040   }
3041   ssl->config->shed_handshake_config = !!enable;
3042 }
3043 
SSL_set_jdk11_workaround(SSL * ssl,int enable)3044 void SSL_set_jdk11_workaround(SSL *ssl, int enable) {
3045   if (!ssl->config) {
3046     return;
3047   }
3048   ssl->config->jdk11_workaround = !!enable;
3049 }
3050 
SSL_set_quic_use_legacy_codepoint(SSL * ssl,int use_legacy)3051 void SSL_set_quic_use_legacy_codepoint(SSL *ssl, int use_legacy) {
3052   if (!ssl->config) {
3053     return;
3054   }
3055   ssl->config->quic_use_legacy_codepoint = !!use_legacy;
3056 }
3057 
SSL_clear(SSL * ssl)3058 int SSL_clear(SSL *ssl) {
3059   if (!ssl->config) {
3060     return 0;  // SSL_clear may not be used after shedding config.
3061   }
3062 
3063   // In OpenSSL, reusing a client |SSL| with |SSL_clear| causes the previously
3064   // established session to be offered the next time around. wpa_supplicant
3065   // depends on this behavior, so emulate it.
3066   UniquePtr<SSL_SESSION> session;
3067   if (!ssl->server && ssl->s3->established_session != NULL) {
3068     session = UpRef(ssl->s3->established_session);
3069   }
3070 
3071   // The ssl->d1->mtu is simultaneously configuration (preserved across
3072   // clear) and connection-specific state (gets reset).
3073   //
3074   // TODO(davidben): Avoid this.
3075   unsigned mtu = 0;
3076   if (ssl->d1 != NULL) {
3077     mtu = ssl->d1->mtu;
3078   }
3079 
3080   ssl->method->ssl_free(ssl);
3081   if (!ssl->method->ssl_new(ssl)) {
3082     return 0;
3083   }
3084 
3085   if (SSL_is_dtls(ssl) && (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
3086     ssl->d1->mtu = mtu;
3087   }
3088 
3089   if (session != nullptr) {
3090     SSL_set_session(ssl, session.get());
3091   }
3092 
3093   return 1;
3094 }
3095 
SSL_CTX_sess_connect(const SSL_CTX * ctx)3096 int SSL_CTX_sess_connect(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_good(const SSL_CTX * ctx)3097 int SSL_CTX_sess_connect_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_connect_renegotiate(const SSL_CTX * ctx)3098 int SSL_CTX_sess_connect_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept(const SSL_CTX * ctx)3099 int SSL_CTX_sess_accept(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_renegotiate(const SSL_CTX * ctx)3100 int SSL_CTX_sess_accept_renegotiate(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_accept_good(const SSL_CTX * ctx)3101 int SSL_CTX_sess_accept_good(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_hits(const SSL_CTX * ctx)3102 int SSL_CTX_sess_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cb_hits(const SSL_CTX * ctx)3103 int SSL_CTX_sess_cb_hits(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_misses(const SSL_CTX * ctx)3104 int SSL_CTX_sess_misses(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_timeouts(const SSL_CTX * ctx)3105 int SSL_CTX_sess_timeouts(const SSL_CTX *ctx) { return 0; }
SSL_CTX_sess_cache_full(const SSL_CTX * ctx)3106 int SSL_CTX_sess_cache_full(const SSL_CTX *ctx) { return 0; }
3107 
SSL_num_renegotiations(const SSL * ssl)3108 int SSL_num_renegotiations(const SSL *ssl) {
3109   return SSL_total_renegotiations(ssl);
3110 }
3111 
SSL_CTX_need_tmp_RSA(const SSL_CTX * ctx)3112 int SSL_CTX_need_tmp_RSA(const SSL_CTX *ctx) { return 0; }
SSL_need_tmp_RSA(const SSL * ssl)3113 int SSL_need_tmp_RSA(const SSL *ssl) { return 0; }
SSL_CTX_set_tmp_rsa(SSL_CTX * ctx,const RSA * rsa)3114 int SSL_CTX_set_tmp_rsa(SSL_CTX *ctx, const RSA *rsa) { return 1; }
SSL_set_tmp_rsa(SSL * ssl,const RSA * rsa)3115 int SSL_set_tmp_rsa(SSL *ssl, const RSA *rsa) { return 1; }
ERR_load_SSL_strings(void)3116 void ERR_load_SSL_strings(void) {}
SSL_load_error_strings(void)3117 void SSL_load_error_strings(void) {}
SSL_cache_hit(SSL * ssl)3118 int SSL_cache_hit(SSL *ssl) { return SSL_session_reused(ssl); }
3119 
SSL_CTX_set_tmp_ecdh(SSL_CTX * ctx,const EC_KEY * ec_key)3120 int SSL_CTX_set_tmp_ecdh(SSL_CTX *ctx, const EC_KEY *ec_key) {
3121   if (ec_key == NULL || EC_KEY_get0_group(ec_key) == NULL) {
3122     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
3123     return 0;
3124   }
3125   int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key));
3126   return SSL_CTX_set1_groups(ctx, &nid, 1);
3127 }
3128 
SSL_set_tmp_ecdh(SSL * ssl,const EC_KEY * ec_key)3129 int SSL_set_tmp_ecdh(SSL *ssl, const EC_KEY *ec_key) {
3130   if (ec_key == NULL || EC_KEY_get0_group(ec_key) == NULL) {
3131     OPENSSL_PUT_ERROR(SSL, ERR_R_PASSED_NULL_PARAMETER);
3132     return 0;
3133   }
3134   int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key));
3135   return SSL_set1_groups(ssl, &nid, 1);
3136 }
3137 
SSL_CTX_set_ticket_aead_method(SSL_CTX * ctx,const SSL_TICKET_AEAD_METHOD * aead_method)3138 void SSL_CTX_set_ticket_aead_method(SSL_CTX *ctx,
3139                                     const SSL_TICKET_AEAD_METHOD *aead_method) {
3140   ctx->ticket_aead_method = aead_method;
3141 }
3142 
SSL_process_tls13_new_session_ticket(SSL * ssl,const uint8_t * buf,size_t buf_len)3143 SSL_SESSION *SSL_process_tls13_new_session_ticket(SSL *ssl, const uint8_t *buf,
3144                                                   size_t buf_len) {
3145   if (SSL_in_init(ssl) ||
3146       ssl_protocol_version(ssl) != TLS1_3_VERSION ||
3147       ssl->server) {
3148     // Only TLS 1.3 clients are supported.
3149     OPENSSL_PUT_ERROR(SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3150     return nullptr;
3151   }
3152 
3153   CBS cbs, body;
3154   CBS_init(&cbs, buf, buf_len);
3155   uint8_t type;
3156   if (!CBS_get_u8(&cbs, &type) ||
3157       !CBS_get_u24_length_prefixed(&cbs, &body) ||
3158       CBS_len(&cbs) != 0) {
3159     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
3160     return nullptr;
3161   }
3162 
3163   UniquePtr<SSL_SESSION> session = tls13_create_session_with_ticket(ssl, &body);
3164   if (!session) {
3165     // |tls13_create_session_with_ticket| puts the correct error.
3166     return nullptr;
3167   }
3168   return session.release();
3169 }
3170 
SSL_CTX_set_num_tickets(SSL_CTX * ctx,size_t num_tickets)3171 int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets) {
3172   num_tickets = std::min(num_tickets, kMaxTickets);
3173   static_assert(kMaxTickets <= 0xff, "Too many tickets.");
3174   ctx->num_tickets = static_cast<uint8_t>(num_tickets);
3175   return 1;
3176 }
3177 
SSL_CTX_get_num_tickets(const SSL_CTX * ctx)3178 size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx) { return ctx->num_tickets; }
3179 
SSL_set_tlsext_status_type(SSL * ssl,int type)3180 int SSL_set_tlsext_status_type(SSL *ssl, int type) {
3181   if (!ssl->config) {
3182     return 0;
3183   }
3184   ssl->config->ocsp_stapling_enabled = type == TLSEXT_STATUSTYPE_ocsp;
3185   return 1;
3186 }
3187 
SSL_get_tlsext_status_type(const SSL * ssl)3188 int SSL_get_tlsext_status_type(const SSL *ssl) {
3189   if (ssl->server) {
3190     SSL_HANDSHAKE *hs = ssl->s3->hs.get();
3191     return hs != nullptr && hs->ocsp_stapling_requested
3192         ? TLSEXT_STATUSTYPE_ocsp
3193         : TLSEXT_STATUSTYPE_nothing;
3194   }
3195 
3196   return ssl->config != nullptr && ssl->config->ocsp_stapling_enabled
3197              ? TLSEXT_STATUSTYPE_ocsp
3198              : TLSEXT_STATUSTYPE_nothing;
3199 }
3200 
SSL_set_tlsext_status_ocsp_resp(SSL * ssl,uint8_t * resp,size_t resp_len)3201 int SSL_set_tlsext_status_ocsp_resp(SSL *ssl, uint8_t *resp, size_t resp_len) {
3202   if (SSL_set_ocsp_response(ssl, resp, resp_len)) {
3203     OPENSSL_free(resp);
3204     return 1;
3205   }
3206   return 0;
3207 }
3208 
SSL_get_tlsext_status_ocsp_resp(const SSL * ssl,const uint8_t ** out)3209 size_t SSL_get_tlsext_status_ocsp_resp(const SSL *ssl, const uint8_t **out) {
3210   size_t ret;
3211   SSL_get0_ocsp_response(ssl, out, &ret);
3212   return ret;
3213 }
3214 
SSL_CTX_set_tlsext_status_cb(SSL_CTX * ctx,int (* callback)(SSL * ssl,void * arg))3215 int SSL_CTX_set_tlsext_status_cb(SSL_CTX *ctx,
3216                                  int (*callback)(SSL *ssl, void *arg)) {
3217   ctx->legacy_ocsp_callback = callback;
3218   return 1;
3219 }
3220 
SSL_CTX_set_tlsext_status_arg(SSL_CTX * ctx,void * arg)3221 int SSL_CTX_set_tlsext_status_arg(SSL_CTX *ctx, void *arg) {
3222   ctx->legacy_ocsp_callback_arg = arg;
3223   return 1;
3224 }
3225 
SSL_get_curve_id(const SSL * ssl)3226 uint16_t SSL_get_curve_id(const SSL *ssl) { return SSL_get_group_id(ssl); }
3227 
SSL_get_curve_name(uint16_t curve_id)3228 const char *SSL_get_curve_name(uint16_t curve_id) {
3229   return SSL_get_group_name(curve_id);
3230 }
3231 
SSL_get_all_curve_names(const char ** out,size_t max_out)3232 size_t SSL_get_all_curve_names(const char **out, size_t max_out) {
3233   return SSL_get_all_group_names(out, max_out);
3234 }
3235 
SSL_CTX_set1_curves(SSL_CTX * ctx,const int * curves,size_t num_curves)3236 int SSL_CTX_set1_curves(SSL_CTX *ctx, const int *curves, size_t num_curves) {
3237   return SSL_CTX_set1_groups(ctx, curves, num_curves);
3238 }
3239 
SSL_set1_curves(SSL * ssl,const int * curves,size_t num_curves)3240 int SSL_set1_curves(SSL *ssl, const int *curves, size_t num_curves) {
3241   return SSL_set1_groups(ssl, curves, num_curves);
3242 }
3243 
SSL_CTX_set1_curves_list(SSL_CTX * ctx,const char * curves)3244 int SSL_CTX_set1_curves_list(SSL_CTX *ctx, const char *curves) {
3245   return SSL_CTX_set1_groups_list(ctx, curves);
3246 }
3247 
SSL_set1_curves_list(SSL * ssl,const char * curves)3248 int SSL_set1_curves_list(SSL *ssl, const char *curves) {
3249   return SSL_set1_groups_list(ssl, curves);
3250 }
3251 
3252 namespace fips202205 {
3253 
3254 // (References are to SP 800-52r2):
3255 
3256 // Section 3.4.2.2
3257 // "at least one of the NIST-approved curves, P-256 (secp256r1) and P384
3258 // (secp384r1), shall be supported as described in RFC 8422."
3259 //
3260 // Section 3.3.1
3261 // "The server shall be configured to only use cipher suites that are
3262 // composed entirely of NIST approved algorithms"
3263 static const uint16_t kGroups[] = {SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1};
3264 
3265 static const uint16_t kSigAlgs[] = {
3266     SSL_SIGN_RSA_PKCS1_SHA256,
3267     SSL_SIGN_RSA_PKCS1_SHA384,
3268     SSL_SIGN_RSA_PKCS1_SHA512,
3269     // Table 4.1:
3270     // "The curve should be P-256 or P-384"
3271     SSL_SIGN_ECDSA_SECP256R1_SHA256,
3272     SSL_SIGN_ECDSA_SECP384R1_SHA384,
3273     SSL_SIGN_RSA_PSS_RSAE_SHA256,
3274     SSL_SIGN_RSA_PSS_RSAE_SHA384,
3275     SSL_SIGN_RSA_PSS_RSAE_SHA512,
3276 };
3277 
3278 static const char kTLS12Ciphers[] =
3279     "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:"
3280     "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:"
3281     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:"
3282     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
3283 
Configure(SSL_CTX * ctx)3284 static int Configure(SSL_CTX *ctx) {
3285   ctx->tls13_cipher_policy = ssl_compliance_policy_fips_202205;
3286 
3287   return
3288       // Section 3.1:
3289       // "Servers that support government-only applications shall be
3290       // configured to use TLS 1.2 and should be configured to use TLS 1.3
3291       // as well. These servers should not be configured to use TLS 1.1 and
3292       // shall not use TLS 1.0, SSL 3.0, or SSL 2.0.
3293       SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION) &&
3294       SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION) &&
3295       // Sections 3.3.1.1.1 and 3.3.1.1.2 are ambiguous about whether
3296       // HMAC-SHA-1 cipher suites are permitted with TLS 1.2. However, later the
3297       // Encrypt-then-MAC extension is required for all CBC cipher suites and so
3298       // it's easier to drop them.
3299       SSL_CTX_set_strict_cipher_list(ctx, kTLS12Ciphers) &&
3300       SSL_CTX_set1_group_ids(ctx, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3301       SSL_CTX_set_signing_algorithm_prefs(ctx, kSigAlgs,
3302                                           OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3303       SSL_CTX_set_verify_algorithm_prefs(ctx, kSigAlgs,
3304                                          OPENSSL_ARRAY_SIZE(kSigAlgs));
3305 }
3306 
Configure(SSL * ssl)3307 static int Configure(SSL *ssl) {
3308   ssl->config->tls13_cipher_policy = ssl_compliance_policy_fips_202205;
3309 
3310   // See |Configure(SSL_CTX)|, above, for reasoning.
3311   return SSL_set_min_proto_version(ssl, TLS1_2_VERSION) &&
3312          SSL_set_max_proto_version(ssl, TLS1_3_VERSION) &&
3313          SSL_set_strict_cipher_list(ssl, kTLS12Ciphers) &&
3314          SSL_set1_group_ids(ssl, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3315          SSL_set_signing_algorithm_prefs(ssl, kSigAlgs,
3316                                          OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3317          SSL_set_verify_algorithm_prefs(ssl, kSigAlgs,
3318                                         OPENSSL_ARRAY_SIZE(kSigAlgs));
3319 }
3320 
3321 }  // namespace fips202205
3322 
3323 namespace wpa202304 {
3324 
3325 // See WPA version 3.1, section 3.5.
3326 
3327 static const uint16_t kGroups[] = {SSL_GROUP_SECP384R1};
3328 
3329 static const uint16_t kSigAlgs[] = {
3330     SSL_SIGN_RSA_PKCS1_SHA384,        //
3331     SSL_SIGN_RSA_PKCS1_SHA512,        //
3332     SSL_SIGN_ECDSA_SECP384R1_SHA384,  //
3333     SSL_SIGN_RSA_PSS_RSAE_SHA384,     //
3334     SSL_SIGN_RSA_PSS_RSAE_SHA512,     //
3335 };
3336 
3337 static const char kTLS12Ciphers[] =
3338     "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:"
3339     "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
3340 
Configure(SSL_CTX * ctx)3341 static int Configure(SSL_CTX *ctx) {
3342   ctx->tls13_cipher_policy = ssl_compliance_policy_wpa3_192_202304;
3343 
3344   return SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION) &&
3345          SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION) &&
3346          SSL_CTX_set_strict_cipher_list(ctx, kTLS12Ciphers) &&
3347          SSL_CTX_set1_group_ids(ctx, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3348          SSL_CTX_set_signing_algorithm_prefs(ctx, kSigAlgs,
3349                                              OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3350          SSL_CTX_set_verify_algorithm_prefs(ctx, kSigAlgs,
3351                                             OPENSSL_ARRAY_SIZE(kSigAlgs));
3352 }
3353 
Configure(SSL * ssl)3354 static int Configure(SSL *ssl) {
3355   ssl->config->tls13_cipher_policy = ssl_compliance_policy_wpa3_192_202304;
3356 
3357   return SSL_set_min_proto_version(ssl, TLS1_2_VERSION) &&
3358          SSL_set_max_proto_version(ssl, TLS1_3_VERSION) &&
3359          SSL_set_strict_cipher_list(ssl, kTLS12Ciphers) &&
3360          SSL_set1_group_ids(ssl, kGroups, OPENSSL_ARRAY_SIZE(kGroups)) &&
3361          SSL_set_signing_algorithm_prefs(ssl, kSigAlgs,
3362                                          OPENSSL_ARRAY_SIZE(kSigAlgs)) &&
3363          SSL_set_verify_algorithm_prefs(ssl, kSigAlgs,
3364                                         OPENSSL_ARRAY_SIZE(kSigAlgs));
3365 }
3366 
3367 }  // namespace wpa202304
3368 
SSL_CTX_set_compliance_policy(SSL_CTX * ctx,enum ssl_compliance_policy_t policy)3369 int SSL_CTX_set_compliance_policy(SSL_CTX *ctx,
3370                                   enum ssl_compliance_policy_t policy) {
3371   switch (policy) {
3372     case ssl_compliance_policy_fips_202205:
3373       return fips202205::Configure(ctx);
3374     case ssl_compliance_policy_wpa3_192_202304:
3375       return wpa202304::Configure(ctx);
3376     default:
3377       return 0;
3378   }
3379 }
3380 
SSL_set_compliance_policy(SSL * ssl,enum ssl_compliance_policy_t policy)3381 int SSL_set_compliance_policy(SSL *ssl, enum ssl_compliance_policy_t policy) {
3382   switch (policy) {
3383     case ssl_compliance_policy_fips_202205:
3384       return fips202205::Configure(ssl);
3385     case ssl_compliance_policy_wpa3_192_202304:
3386       return wpa202304::Configure(ssl);
3387     default:
3388       return 0;
3389   }
3390 }
3391