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