• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
114  */
115 /* ====================================================================
116  * Copyright 2005 Nokia. All rights reserved.
117  *
118  * The portions of the attached software ("Contribution") is developed by
119  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
120  * license.
121  *
122  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
123  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
124  * support (see RFC 4279) to OpenSSL.
125  *
126  * No patent licenses or other rights except those expressly stated in
127  * the OpenSSL open source license shall be deemed granted or received
128  * expressly, by implication, estoppel, or otherwise.
129  *
130  * No assurances are provided by Nokia that the Contribution does not
131  * infringe the patent or other intellectual property rights of any third
132  * party or that the license provides you with all the necessary rights
133  * to make use of the Contribution.
134  *
135  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
136  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
137  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
138  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139  * OTHERWISE.
140  */
141 
142 #ifndef OPENSSL_HEADER_SSL_INTERNAL_H
143 #define OPENSSL_HEADER_SSL_INTERNAL_H
144 
145 #include <openssl/base.h>
146 
147 #include <stdlib.h>
148 
149 #include <initializer_list>
150 #include <limits>
151 #include <new>
152 #include <type_traits>
153 #include <utility>
154 
155 #include <openssl/aead.h>
156 #include <openssl/curve25519.h>
157 #include <openssl/err.h>
158 #include <openssl/hpke.h>
159 #include <openssl/lhash.h>
160 #include <openssl/mem.h>
161 #include <openssl/span.h>
162 #include <openssl/ssl.h>
163 #include <openssl/stack.h>
164 
165 #include "../crypto/err/internal.h"
166 #include "../crypto/internal.h"
167 #include "../crypto/lhash/internal.h"
168 
169 
170 #if defined(OPENSSL_WINDOWS)
171 // Windows defines struct timeval in winsock2.h.
172 OPENSSL_MSVC_PRAGMA(warning(push, 3))
173 #include <winsock2.h>
174 OPENSSL_MSVC_PRAGMA(warning(pop))
175 #else
176 #include <sys/time.h>
177 #endif
178 
179 
180 BSSL_NAMESPACE_BEGIN
181 
182 struct SSL_CONFIG;
183 struct SSL_HANDSHAKE;
184 struct SSL_PROTOCOL_METHOD;
185 struct SSL_X509_METHOD;
186 
187 // C++ utilities.
188 
189 // New behaves like |new| but uses |OPENSSL_malloc| for memory allocation. It
190 // returns nullptr on allocation error. It only implements single-object
191 // allocation and not new T[n].
192 //
193 // Note: unlike |new|, this does not support non-public constructors.
194 template <typename T, typename... Args>
New(Args &&...args)195 T *New(Args &&... args) {
196   void *t = OPENSSL_malloc(sizeof(T));
197   if (t == nullptr) {
198     return nullptr;
199   }
200   return new (t) T(std::forward<Args>(args)...);
201 }
202 
203 // Delete behaves like |delete| but uses |OPENSSL_free| to release memory.
204 //
205 // Note: unlike |delete| this does not support non-public destructors.
206 template <typename T>
Delete(T * t)207 void Delete(T *t) {
208   if (t != nullptr) {
209     t->~T();
210     OPENSSL_free(t);
211   }
212 }
213 
214 // All types with kAllowUniquePtr set may be used with UniquePtr. Other types
215 // may be C structs which require a |BORINGSSL_MAKE_DELETER| registration.
216 namespace internal {
217 template <typename T>
218 struct DeleterImpl<T, std::enable_if_t<T::kAllowUniquePtr>> {
219   static void Free(T *t) { Delete(t); }
220 };
221 }  // namespace internal
222 
223 // MakeUnique behaves like |std::make_unique| but returns nullptr on allocation
224 // error.
225 template <typename T, typename... Args>
226 UniquePtr<T> MakeUnique(Args &&... args) {
227   return UniquePtr<T>(New<T>(std::forward<Args>(args)...));
228 }
229 
230 #if defined(BORINGSSL_ALLOW_CXX_RUNTIME)
231 #define HAS_VIRTUAL_DESTRUCTOR
232 #define PURE_VIRTUAL = 0
233 #else
234 // HAS_VIRTUAL_DESTRUCTOR should be declared in any base class which defines a
235 // virtual destructor. This avoids a dependency on |_ZdlPv| and prevents the
236 // class from being used with |delete|.
237 #define HAS_VIRTUAL_DESTRUCTOR \
238   void operator delete(void *) { abort(); }
239 
240 // PURE_VIRTUAL should be used instead of = 0 when defining pure-virtual
241 // functions. This avoids a dependency on |__cxa_pure_virtual| but loses
242 // compile-time checking.
243 #define PURE_VIRTUAL \
244   { abort(); }
245 #endif
246 
247 // Array<T> is an owning array of elements of |T|.
248 template <typename T>
249 class Array {
250  public:
251   // Array's default constructor creates an empty array.
252   Array() {}
253   Array(const Array &) = delete;
254   Array(Array &&other) { *this = std::move(other); }
255 
256   ~Array() { Reset(); }
257 
258   Array &operator=(const Array &) = delete;
259   Array &operator=(Array &&other) {
260     Reset();
261     other.Release(&data_, &size_);
262     return *this;
263   }
264 
265   const T *data() const { return data_; }
266   T *data() { return data_; }
267   size_t size() const { return size_; }
268   bool empty() const { return size_ == 0; }
269 
270   const T &operator[](size_t i) const { return data_[i]; }
271   T &operator[](size_t i) { return data_[i]; }
272 
273   T *begin() { return data_; }
274   const T *begin() const { return data_; }
275   T *end() { return data_ + size_; }
276   const T *end() const { return data_ + size_; }
277 
278   void Reset() { Reset(nullptr, 0); }
279 
280   // Reset releases the current contents of the array and takes ownership of the
281   // raw pointer supplied by the caller.
282   void Reset(T *new_data, size_t new_size) {
283     for (size_t i = 0; i < size_; i++) {
284       data_[i].~T();
285     }
286     OPENSSL_free(data_);
287     data_ = new_data;
288     size_ = new_size;
289   }
290 
291   // Release releases ownership of the array to a raw pointer supplied by the
292   // caller.
293   void Release(T **out, size_t *out_size) {
294     *out = data_;
295     *out_size = size_;
296     data_ = nullptr;
297     size_ = 0;
298   }
299 
300   // Init replaces the array with a newly-allocated array of |new_size|
301   // default-constructed copies of |T|. It returns true on success and false on
302   // error.
303   //
304   // Note that if |T| is a primitive type like |uint8_t|, it is uninitialized.
305   bool Init(size_t new_size) {
306     Reset();
307     if (new_size == 0) {
308       return true;
309     }
310 
311     if (new_size > std::numeric_limits<size_t>::max() / sizeof(T)) {
312       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
313       return false;
314     }
315     data_ = reinterpret_cast<T *>(OPENSSL_malloc(new_size * sizeof(T)));
316     if (data_ == nullptr) {
317       return false;
318     }
319     size_ = new_size;
320     for (size_t i = 0; i < size_; i++) {
321       new (&data_[i]) T;
322     }
323     return true;
324   }
325 
326   // CopyFrom replaces the array with a newly-allocated copy of |in|. It returns
327   // true on success and false on error.
328   bool CopyFrom(Span<const T> in) {
329     if (!Init(in.size())) {
330       return false;
331     }
332     OPENSSL_memcpy(data_, in.data(), sizeof(T) * in.size());
333     return true;
334   }
335 
336   // Shrink shrinks the stored size of the array to |new_size|. It crashes if
337   // the new size is larger. Note this does not shrink the allocation itself.
338   void Shrink(size_t new_size) {
339     if (new_size > size_) {
340       abort();
341     }
342     for (size_t i = new_size; i < size_; i++) {
343       data_[i].~T();
344     }
345     size_ = new_size;
346   }
347 
348  private:
349   T *data_ = nullptr;
350   size_t size_ = 0;
351 };
352 
353 // GrowableArray<T> is an array that owns elements of |T|, backed by an
354 // Array<T>. When necessary, pushing will automatically trigger a resize.
355 //
356 // Note, for simplicity, this class currently differs from |std::vector| in that
357 // |T| must be efficiently default-constructible. Allocated elements beyond the
358 // end of the array are constructed and destructed.
359 template <typename T>
360 class GrowableArray {
361  public:
362   GrowableArray() = default;
363   GrowableArray(const GrowableArray &) = delete;
364   GrowableArray(GrowableArray &&other) { *this = std::move(other); }
365   ~GrowableArray() {}
366 
367   GrowableArray &operator=(const GrowableArray &) = delete;
368   GrowableArray &operator=(GrowableArray &&other) {
369     size_ = other.size_;
370     other.size_ = 0;
371     array_ = std::move(other.array_);
372     return *this;
373   }
374 
375   const T *data() const { return array_.data(); }
376   T *data() { return array_.data(); }
377   size_t size() const { return size_; }
378   bool empty() const { return size_ == 0; }
379 
380   const T &operator[](size_t i) const { return array_[i]; }
381   T &operator[](size_t i) { return array_[i]; }
382 
383   T *begin() { return array_.data(); }
384   const T *begin() const { return array_.data(); }
385   T *end() { return array_.data() + size_; }
386   const T *end() const { return array_.data() + size_; }
387 
388   void clear() {
389     size_ = 0;
390     array_.Reset();
391   }
392 
393   // Push adds |elem| at the end of the internal array, growing if necessary. It
394   // returns false when allocation fails.
395   bool Push(T elem) {
396     if (!MaybeGrow()) {
397       return false;
398     }
399     array_[size_] = std::move(elem);
400     size_++;
401     return true;
402   }
403 
404   // CopyFrom replaces the contents of the array with a copy of |in|. It returns
405   // true on success and false on allocation error.
406   bool CopyFrom(Span<const T> in) {
407     if (!array_.CopyFrom(in)) {
408       return false;
409     }
410     size_ = in.size();
411     return true;
412   }
413 
414  private:
415   // If there is no room for one more element, creates a new backing array with
416   // double the size of the old one and copies elements over.
417   bool MaybeGrow() {
418     if (array_.size() == 0) {
419       return array_.Init(kDefaultSize);
420     }
421     // No need to grow if we have room for one more T.
422     if (size_ < array_.size()) {
423       return true;
424     }
425     // Double the array's size if it's safe to do so.
426     if (array_.size() > std::numeric_limits<size_t>::max() / 2) {
427       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
428       return false;
429     }
430     Array<T> new_array;
431     if (!new_array.Init(array_.size() * 2)) {
432       return false;
433     }
434     for (size_t i = 0; i < array_.size(); i++) {
435       new_array[i] = std::move(array_[i]);
436     }
437     array_ = std::move(new_array);
438 
439     return true;
440   }
441 
442   // |size_| is the number of elements stored in this GrowableArray.
443   size_t size_ = 0;
444   // |array_| is the backing array. Note that |array_.size()| is this
445   // GrowableArray's current capacity and that |size_ <= array_.size()|.
446   Array<T> array_;
447   // |kDefaultSize| is the default initial size of the backing array.
448   static constexpr size_t kDefaultSize = 16;
449 };
450 
451 // CBBFinishArray behaves like |CBB_finish| but stores the result in an Array.
452 OPENSSL_EXPORT bool CBBFinishArray(CBB *cbb, Array<uint8_t> *out);
453 
454 
455 // Protocol versions.
456 //
457 // Due to DTLS's historical wire version differences, we maintain two notions of
458 // version.
459 //
460 // The "version" or "wire version" is the actual 16-bit value that appears on
461 // the wire. It uniquely identifies a version and is also used at API
462 // boundaries. The set of supported versions differs between TLS and DTLS. Wire
463 // versions are opaque values and may not be compared numerically.
464 //
465 // The "protocol version" identifies the high-level handshake variant being
466 // used. DTLS versions map to the corresponding TLS versions. Protocol versions
467 // are sequential and may be compared numerically.
468 
469 // ssl_protocol_version_from_wire sets |*out| to the protocol version
470 // corresponding to wire version |version| and returns true. If |version| is not
471 // a valid TLS or DTLS version, it returns false.
472 //
473 // Note this simultaneously handles both DTLS and TLS. Use one of the
474 // higher-level functions below for most operations.
475 bool ssl_protocol_version_from_wire(uint16_t *out, uint16_t version);
476 
477 // ssl_get_version_range sets |*out_min_version| and |*out_max_version| to the
478 // minimum and maximum enabled protocol versions, respectively.
479 bool ssl_get_version_range(const SSL_HANDSHAKE *hs, uint16_t *out_min_version,
480                            uint16_t *out_max_version);
481 
482 // ssl_supports_version returns whether |hs| supports |version|.
483 bool ssl_supports_version(const SSL_HANDSHAKE *hs, uint16_t version);
484 
485 // ssl_method_supports_version returns whether |method| supports |version|.
486 bool ssl_method_supports_version(const SSL_PROTOCOL_METHOD *method,
487                                  uint16_t version);
488 
489 // ssl_add_supported_versions writes the supported versions of |hs| to |cbb|, in
490 // decreasing preference order. The version list is filtered to those whose
491 // protocol version is at least |extra_min_version|.
492 bool ssl_add_supported_versions(const SSL_HANDSHAKE *hs, CBB *cbb,
493                                 uint16_t extra_min_version);
494 
495 // ssl_negotiate_version negotiates a common version based on |hs|'s preferences
496 // and the peer preference list in |peer_versions|. On success, it returns true
497 // and sets |*out_version| to the selected version. Otherwise, it returns false
498 // and sets |*out_alert| to an alert to send.
499 bool ssl_negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
500                            uint16_t *out_version, const CBS *peer_versions);
501 
502 // ssl_protocol_version returns |ssl|'s protocol version. It is an error to
503 // call this function before the version is determined.
504 uint16_t ssl_protocol_version(const SSL *ssl);
505 
506 // Cipher suites.
507 
508 BSSL_NAMESPACE_END
509 
510 struct ssl_cipher_st {
511   // name is the OpenSSL name for the cipher.
512   const char *name;
513   // standard_name is the IETF name for the cipher.
514   const char *standard_name;
515   // id is the cipher suite value bitwise OR-d with 0x03000000.
516   uint32_t id;
517 
518   // algorithm_* determine the cipher suite. See constants below for the values.
519   uint32_t algorithm_mkey;
520   uint32_t algorithm_auth;
521   uint32_t algorithm_enc;
522   uint32_t algorithm_mac;
523   uint32_t algorithm_prf;
524 };
525 
526 BSSL_NAMESPACE_BEGIN
527 
528 // Bits for |algorithm_mkey| (key exchange algorithm).
529 #define SSL_kRSA 0x00000001u
530 #define SSL_kECDHE 0x00000002u
531 // SSL_kPSK is only set for plain PSK, not ECDHE_PSK.
532 #define SSL_kPSK 0x00000004u
533 #define SSL_kGENERIC 0x00000008u
534 
535 // Bits for |algorithm_auth| (server authentication).
536 #define SSL_aRSA 0x00000001u
537 #define SSL_aECDSA 0x00000002u
538 // SSL_aPSK is set for both PSK and ECDHE_PSK.
539 #define SSL_aPSK 0x00000004u
540 #define SSL_aGENERIC 0x00000008u
541 
542 #define SSL_aCERT (SSL_aRSA | SSL_aECDSA)
543 
544 // Bits for |algorithm_enc| (symmetric encryption).
545 #define SSL_3DES 0x00000001u
546 #define SSL_AES128 0x00000002u
547 #define SSL_AES256 0x00000004u
548 #define SSL_AES128GCM 0x00000008u
549 #define SSL_AES256GCM 0x00000010u
550 #define SSL_CHACHA20POLY1305 0x00000020u
551 
552 #define SSL_AES (SSL_AES128 | SSL_AES256 | SSL_AES128GCM | SSL_AES256GCM)
553 
554 // Bits for |algorithm_mac| (symmetric authentication).
555 #define SSL_SHA1 0x00000001u
556 // SSL_AEAD is set for all AEADs.
557 #define SSL_AEAD 0x00000002u
558 
559 // Bits for |algorithm_prf| (handshake digest).
560 #define SSL_HANDSHAKE_MAC_DEFAULT 0x1
561 #define SSL_HANDSHAKE_MAC_SHA256 0x2
562 #define SSL_HANDSHAKE_MAC_SHA384 0x4
563 
564 // SSL_MAX_MD_SIZE is size of the largest hash function used in TLS, SHA-384.
565 #define SSL_MAX_MD_SIZE 48
566 
567 // An SSLCipherPreferenceList contains a list of SSL_CIPHERs with equal-
568 // preference groups. For TLS clients, the groups are moot because the server
569 // picks the cipher and groups cannot be expressed on the wire. However, for
570 // servers, the equal-preference groups allow the client's preferences to be
571 // partially respected. (This only has an effect with
572 // SSL_OP_CIPHER_SERVER_PREFERENCE).
573 //
574 // The equal-preference groups are expressed by grouping SSL_CIPHERs together.
575 // All elements of a group have the same priority: no ordering is expressed
576 // within a group.
577 //
578 // The values in |ciphers| are in one-to-one correspondence with
579 // |in_group_flags|. (That is, sk_SSL_CIPHER_num(ciphers) is the number of
580 // bytes in |in_group_flags|.) The bytes in |in_group_flags| are either 1, to
581 // indicate that the corresponding SSL_CIPHER is not the last element of a
582 // group, or 0 to indicate that it is.
583 //
584 // For example, if |in_group_flags| contains all zeros then that indicates a
585 // traditional, fully-ordered preference. Every SSL_CIPHER is the last element
586 // of the group (i.e. they are all in a one-element group).
587 //
588 // For a more complex example, consider:
589 //   ciphers:        A  B  C  D  E  F
590 //   in_group_flags: 1  1  0  0  1  0
591 //
592 // That would express the following, order:
593 //
594 //    A         E
595 //    B -> D -> F
596 //    C
597 struct SSLCipherPreferenceList {
598   static constexpr bool kAllowUniquePtr = true;
599 
600   SSLCipherPreferenceList() = default;
601   ~SSLCipherPreferenceList();
602 
603   bool Init(UniquePtr<STACK_OF(SSL_CIPHER)> ciphers,
604             Span<const bool> in_group_flags);
605   bool Init(const SSLCipherPreferenceList &);
606 
607   void Remove(const SSL_CIPHER *cipher);
608 
609   UniquePtr<STACK_OF(SSL_CIPHER)> ciphers;
610   bool *in_group_flags = nullptr;
611 };
612 
613 // AllCiphers returns an array of all supported ciphers, sorted by id.
614 Span<const SSL_CIPHER> AllCiphers();
615 
616 // ssl_cipher_get_evp_aead sets |*out_aead| to point to the correct EVP_AEAD
617 // object for |cipher| protocol version |version|. It sets |*out_mac_secret_len|
618 // and |*out_fixed_iv_len| to the MAC key length and fixed IV length,
619 // respectively. The MAC key length is zero except for legacy block and stream
620 // ciphers. It returns true on success and false on error.
621 bool ssl_cipher_get_evp_aead(const EVP_AEAD **out_aead,
622                              size_t *out_mac_secret_len,
623                              size_t *out_fixed_iv_len, const SSL_CIPHER *cipher,
624                              uint16_t version, bool is_dtls);
625 
626 // ssl_get_handshake_digest returns the |EVP_MD| corresponding to |version| and
627 // |cipher|.
628 const EVP_MD *ssl_get_handshake_digest(uint16_t version,
629                                        const SSL_CIPHER *cipher);
630 
631 // ssl_create_cipher_list evaluates |rule_str|. It sets |*out_cipher_list| to a
632 // newly-allocated |SSLCipherPreferenceList| containing the result. It returns
633 // true on success and false on failure. If |strict| is true, nonsense will be
634 // rejected. If false, nonsense will be silently ignored. An empty result is
635 // considered an error regardless of |strict|. |has_aes_hw| indicates if the
636 // list should be ordered based on having support for AES in hardware or not.
637 bool ssl_create_cipher_list(UniquePtr<SSLCipherPreferenceList> *out_cipher_list,
638                             const bool has_aes_hw, const char *rule_str,
639                             bool strict);
640 
641 // ssl_cipher_auth_mask_for_key returns the mask of cipher |algorithm_auth|
642 // values suitable for use with |key| in TLS 1.2 and below.
643 uint32_t ssl_cipher_auth_mask_for_key(const EVP_PKEY *key);
644 
645 // ssl_cipher_uses_certificate_auth returns whether |cipher| authenticates the
646 // server and, optionally, the client with a certificate.
647 bool ssl_cipher_uses_certificate_auth(const SSL_CIPHER *cipher);
648 
649 // ssl_cipher_requires_server_key_exchange returns whether |cipher| requires a
650 // ServerKeyExchange message.
651 //
652 // This function may return false while still allowing |cipher| an optional
653 // ServerKeyExchange. This is the case for plain PSK ciphers.
654 bool ssl_cipher_requires_server_key_exchange(const SSL_CIPHER *cipher);
655 
656 // ssl_cipher_get_record_split_len, for TLS 1.0 CBC mode ciphers, returns the
657 // length of an encrypted 1-byte record, for use in record-splitting. Otherwise
658 // it returns zero.
659 size_t ssl_cipher_get_record_split_len(const SSL_CIPHER *cipher);
660 
661 // ssl_choose_tls13_cipher returns an |SSL_CIPHER| corresponding with the best
662 // available from |cipher_suites| compatible with |version|, |group_id|, and
663 // |only_fips|. It returns NULL if there isn't a compatible cipher. |has_aes_hw|
664 // indicates if the choice should be made as if support for AES in hardware
665 // is available.
666 const SSL_CIPHER *ssl_choose_tls13_cipher(CBS cipher_suites, bool has_aes_hw,
667                                           uint16_t version, uint16_t group_id,
668                                           bool only_fips);
669 
670 // ssl_tls13_cipher_meets_policy returns true if |cipher_id| is acceptable given
671 // |only_fips|. (For now there's only a single policy and so the policy argument
672 // is just a bool.)
673 bool ssl_tls13_cipher_meets_policy(uint16_t cipher_id, bool only_fips);
674 
675 
676 // Transcript layer.
677 
678 // SSLTranscript maintains the handshake transcript as a combination of a
679 // buffer and running hash.
680 class SSLTranscript {
681  public:
682   SSLTranscript();
683   ~SSLTranscript();
684 
685   SSLTranscript(SSLTranscript &&other) = default;
686   SSLTranscript &operator=(SSLTranscript &&other) = default;
687 
688   // Init initializes the handshake transcript. If called on an existing
689   // transcript, it resets the transcript and hash. It returns true on success
690   // and false on failure.
691   bool Init();
692 
693   // InitHash initializes the handshake hash based on the PRF and contents of
694   // the handshake transcript. Subsequent calls to |Update| will update the
695   // rolling hash. It returns one on success and zero on failure. It is an error
696   // to call this function after the handshake buffer is released. This may be
697   // called multiple times to change the hash function.
698   bool InitHash(uint16_t version, const SSL_CIPHER *cipher);
699 
700   // UpdateForHelloRetryRequest resets the rolling hash with the
701   // HelloRetryRequest construction. It returns true on success and false on
702   // failure. It is an error to call this function before the handshake buffer
703   // is released.
704   bool UpdateForHelloRetryRequest();
705 
706   // CopyToHashContext initializes |ctx| with |digest| and the data thus far in
707   // the transcript. It returns true on success and false on failure. If the
708   // handshake buffer is still present, |digest| may be any supported digest.
709   // Otherwise, |digest| must match the transcript hash.
710   bool CopyToHashContext(EVP_MD_CTX *ctx, const EVP_MD *digest) const;
711 
712   Span<const uint8_t> buffer() const {
713     return MakeConstSpan(reinterpret_cast<const uint8_t *>(buffer_->data),
714                          buffer_->length);
715   }
716 
717   // FreeBuffer releases the handshake buffer. Subsequent calls to
718   // |Update| will not update the handshake buffer.
719   void FreeBuffer();
720 
721   // DigestLen returns the length of the PRF hash.
722   size_t DigestLen() const;
723 
724   // Digest returns the PRF hash. For TLS 1.1 and below, this is
725   // |EVP_md5_sha1|.
726   const EVP_MD *Digest() const;
727 
728   // Update adds |in| to the handshake buffer and handshake hash, whichever is
729   // enabled. It returns true on success and false on failure.
730   bool Update(Span<const uint8_t> in);
731 
732   // GetHash writes the handshake hash to |out| which must have room for at
733   // least |DigestLen| bytes. On success, it returns true and sets |*out_len| to
734   // the number of bytes written. Otherwise, it returns false.
735   bool GetHash(uint8_t *out, size_t *out_len) const;
736 
737   // GetFinishedMAC computes the MAC for the Finished message into the bytes
738   // pointed by |out| and writes the number of bytes to |*out_len|. |out| must
739   // have room for |EVP_MAX_MD_SIZE| bytes. It returns true on success and false
740   // on failure.
741   bool GetFinishedMAC(uint8_t *out, size_t *out_len, const SSL_SESSION *session,
742                       bool from_server) const;
743 
744  private:
745   // buffer_, if non-null, contains the handshake transcript.
746   UniquePtr<BUF_MEM> buffer_;
747   // hash, if initialized with an |EVP_MD|, maintains the handshake hash.
748   ScopedEVP_MD_CTX hash_;
749 };
750 
751 // tls1_prf computes the PRF function for |ssl|. It fills |out|, using |secret|
752 // as the secret and |label| as the label. |seed1| and |seed2| are concatenated
753 // to form the seed parameter. It returns true on success and false on failure.
754 bool tls1_prf(const EVP_MD *digest, Span<uint8_t> out,
755               Span<const uint8_t> secret, Span<const char> label,
756               Span<const uint8_t> seed1, Span<const uint8_t> seed2);
757 
758 
759 // Encryption layer.
760 
761 // SSLAEADContext contains information about an AEAD that is being used to
762 // encrypt an SSL connection.
763 class SSLAEADContext {
764  public:
765   SSLAEADContext(uint16_t version, bool is_dtls, const SSL_CIPHER *cipher);
766   ~SSLAEADContext();
767   static constexpr bool kAllowUniquePtr = true;
768 
769   SSLAEADContext(const SSLAEADContext &&) = delete;
770   SSLAEADContext &operator=(const SSLAEADContext &&) = delete;
771 
772   // CreateNullCipher creates an |SSLAEADContext| for the null cipher.
773   static UniquePtr<SSLAEADContext> CreateNullCipher(bool is_dtls);
774 
775   // Create creates an |SSLAEADContext| using the supplied key material. It
776   // returns nullptr on error. Only one of |Open| or |Seal| may be used with the
777   // resulting object, depending on |direction|. |version| is the normalized
778   // protocol version, so DTLS 1.0 is represented as 0x0301, not 0xffef.
779   static UniquePtr<SSLAEADContext> Create(enum evp_aead_direction_t direction,
780                                           uint16_t version, bool is_dtls,
781                                           const SSL_CIPHER *cipher,
782                                           Span<const uint8_t> enc_key,
783                                           Span<const uint8_t> mac_key,
784                                           Span<const uint8_t> fixed_iv);
785 
786   // CreatePlaceholderForQUIC creates a placeholder |SSLAEADContext| for the
787   // given cipher and version. The resulting object can be queried for various
788   // properties but cannot encrypt or decrypt data.
789   static UniquePtr<SSLAEADContext> CreatePlaceholderForQUIC(
790       uint16_t version, const SSL_CIPHER *cipher);
791 
792   // SetVersionIfNullCipher sets the version the SSLAEADContext for the null
793   // cipher, to make version-specific determinations in the record layer prior
794   // to a cipher being selected.
795   void SetVersionIfNullCipher(uint16_t version);
796 
797   // ProtocolVersion returns the protocol version associated with this
798   // SSLAEADContext. It can only be called once |version_| has been set to a
799   // valid value.
800   uint16_t ProtocolVersion() const;
801 
802   // RecordVersion returns the record version that should be used with this
803   // SSLAEADContext for record construction and crypto.
804   uint16_t RecordVersion() const;
805 
806   const SSL_CIPHER *cipher() const { return cipher_; }
807 
808   // is_null_cipher returns true if this is the null cipher.
809   bool is_null_cipher() const { return !cipher_; }
810 
811   // ExplicitNonceLen returns the length of the explicit nonce.
812   size_t ExplicitNonceLen() const;
813 
814   // MaxOverhead returns the maximum overhead of calling |Seal|.
815   size_t MaxOverhead() const;
816 
817   // SuffixLen calculates the suffix length written by |SealScatter| and writes
818   // it to |*out_suffix_len|. It returns true on success and false on error.
819   // |in_len| and |extra_in_len| should equal the argument of the same names
820   // passed to |SealScatter|.
821   bool SuffixLen(size_t *out_suffix_len, size_t in_len,
822                  size_t extra_in_len) const;
823 
824   // CiphertextLen calculates the total ciphertext length written by
825   // |SealScatter| and writes it to |*out_len|. It returns true on success and
826   // false on error. |in_len| and |extra_in_len| should equal the argument of
827   // the same names passed to |SealScatter|.
828   bool CiphertextLen(size_t *out_len, size_t in_len, size_t extra_in_len) const;
829 
830   // Open authenticates and decrypts |in| in-place. On success, it sets |*out|
831   // to the plaintext in |in| and returns true.  Otherwise, it returns
832   // false. The output will always be |ExplicitNonceLen| bytes ahead of |in|.
833   bool Open(Span<uint8_t> *out, uint8_t type, uint16_t record_version,
834             uint64_t seqnum, Span<const uint8_t> header, Span<uint8_t> in);
835 
836   // Seal encrypts and authenticates |in_len| bytes from |in| and writes the
837   // result to |out|. It returns true on success and false on error.
838   //
839   // If |in| and |out| alias then |out| + |ExplicitNonceLen| must be == |in|.
840   bool Seal(uint8_t *out, size_t *out_len, size_t max_out, uint8_t type,
841             uint16_t record_version, uint64_t seqnum,
842             Span<const uint8_t> header, const uint8_t *in, size_t in_len);
843 
844   // SealScatter encrypts and authenticates |in_len| bytes from |in| and splits
845   // the result between |out_prefix|, |out| and |out_suffix|. It returns one on
846   // success and zero on error.
847   //
848   // On successful return, exactly |ExplicitNonceLen| bytes are written to
849   // |out_prefix|, |in_len| bytes to |out|, and |SuffixLen| bytes to
850   // |out_suffix|.
851   //
852   // |extra_in| may point to an additional plaintext buffer. If present,
853   // |extra_in_len| additional bytes are encrypted and authenticated, and the
854   // ciphertext is written to the beginning of |out_suffix|. |SuffixLen| should
855   // be used to size |out_suffix| accordingly.
856   //
857   // If |in| and |out| alias then |out| must be == |in|. Other arguments may not
858   // alias anything.
859   bool SealScatter(uint8_t *out_prefix, uint8_t *out, uint8_t *out_suffix,
860                    uint8_t type, uint16_t record_version, uint64_t seqnum,
861                    Span<const uint8_t> header, const uint8_t *in, size_t in_len,
862                    const uint8_t *extra_in, size_t extra_in_len);
863 
864   bool GetIV(const uint8_t **out_iv, size_t *out_iv_len) const;
865 
866  private:
867   // GetAdditionalData returns the additional data, writing into |storage| if
868   // necessary.
869   Span<const uint8_t> GetAdditionalData(uint8_t storage[13], uint8_t type,
870                                         uint16_t record_version,
871                                         uint64_t seqnum, size_t plaintext_len,
872                                         Span<const uint8_t> header);
873 
874   const SSL_CIPHER *cipher_;
875   ScopedEVP_AEAD_CTX ctx_;
876   // fixed_nonce_ contains any bytes of the nonce that are fixed for all
877   // records.
878   uint8_t fixed_nonce_[12];
879   uint8_t fixed_nonce_len_ = 0, variable_nonce_len_ = 0;
880   // version_ is the wire version that should be used with this AEAD.
881   uint16_t version_;
882   // is_dtls_ is whether DTLS is being used with this AEAD.
883   bool is_dtls_;
884   // variable_nonce_included_in_record_ is true if the variable nonce
885   // for a record is included as a prefix before the ciphertext.
886   bool variable_nonce_included_in_record_ : 1;
887   // random_variable_nonce_ is true if the variable nonce is
888   // randomly generated, rather than derived from the sequence
889   // number.
890   bool random_variable_nonce_ : 1;
891   // xor_fixed_nonce_ is true if the fixed nonce should be XOR'd into the
892   // variable nonce rather than prepended.
893   bool xor_fixed_nonce_ : 1;
894   // omit_length_in_ad_ is true if the length should be omitted in the
895   // AEAD's ad parameter.
896   bool omit_length_in_ad_ : 1;
897   // ad_is_header_ is true if the AEAD's ad parameter is the record header.
898   bool ad_is_header_ : 1;
899 };
900 
901 
902 // DTLS replay bitmap.
903 
904 // DTLS1_BITMAP maintains a sliding window of 64 sequence numbers to detect
905 // replayed packets. It should be initialized by zeroing every field.
906 struct DTLS1_BITMAP {
907   // map is a bit mask of the last 64 sequence numbers. Bit
908   // |1<<i| corresponds to |max_seq_num - i|.
909   uint64_t map = 0;
910   // max_seq_num is the largest sequence number seen so far as a 64-bit
911   // integer.
912   uint64_t max_seq_num = 0;
913 };
914 
915 
916 // Record layer.
917 
918 // ssl_record_prefix_len returns the length of the prefix before the ciphertext
919 // of a record for |ssl|.
920 //
921 // TODO(davidben): Expose this as part of public API once the high-level
922 // buffer-free APIs are available.
923 size_t ssl_record_prefix_len(const SSL *ssl);
924 
925 enum ssl_open_record_t {
926   ssl_open_record_success,
927   ssl_open_record_discard,
928   ssl_open_record_partial,
929   ssl_open_record_close_notify,
930   ssl_open_record_error,
931 };
932 
933 // tls_open_record decrypts a record from |in| in-place.
934 //
935 // If the input did not contain a complete record, it returns
936 // |ssl_open_record_partial|. It sets |*out_consumed| to the total number of
937 // bytes necessary. It is guaranteed that a successful call to |tls_open_record|
938 // will consume at least that many bytes.
939 //
940 // Otherwise, it sets |*out_consumed| to the number of bytes of input
941 // consumed. Note that input may be consumed on all return codes if a record was
942 // decrypted.
943 //
944 // On success, it returns |ssl_open_record_success|. It sets |*out_type| to the
945 // record type and |*out| to the record body in |in|. Note that |*out| may be
946 // empty.
947 //
948 // If a record was successfully processed but should be discarded, it returns
949 // |ssl_open_record_discard|.
950 //
951 // If a record was successfully processed but is a close_notify, it returns
952 // |ssl_open_record_close_notify|.
953 //
954 // On failure or fatal alert, it returns |ssl_open_record_error| and sets
955 // |*out_alert| to an alert to emit, or zero if no alert should be emitted.
956 enum ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type,
957                                        Span<uint8_t> *out, size_t *out_consumed,
958                                        uint8_t *out_alert, Span<uint8_t> in);
959 
960 // dtls_open_record implements |tls_open_record| for DTLS. It only returns
961 // |ssl_open_record_partial| if |in| was empty and sets |*out_consumed| to
962 // zero. The caller should read one packet and try again.
963 enum ssl_open_record_t dtls_open_record(SSL *ssl, uint8_t *out_type,
964                                         Span<uint8_t> *out,
965                                         size_t *out_consumed,
966                                         uint8_t *out_alert, Span<uint8_t> in);
967 
968 // ssl_seal_align_prefix_len returns the length of the prefix before the start
969 // of the bulk of the ciphertext when sealing a record with |ssl|. Callers may
970 // use this to align buffers.
971 //
972 // Note when TLS 1.0 CBC record-splitting is enabled, this includes the one byte
973 // record and is the offset into second record's ciphertext. Thus sealing a
974 // small record may result in a smaller output than this value.
975 //
976 // TODO(davidben): Is this alignment valuable? Record-splitting makes this a
977 // mess.
978 size_t ssl_seal_align_prefix_len(const SSL *ssl);
979 
980 // tls_seal_record seals a new record of type |type| and body |in| and writes it
981 // to |out|. At most |max_out| bytes will be written. It returns true on success
982 // and false on error. If enabled, |tls_seal_record| implements TLS 1.0 CBC
983 // 1/n-1 record splitting and may write two records concatenated.
984 //
985 // For a large record, the bulk of the ciphertext will begin
986 // |ssl_seal_align_prefix_len| bytes into out. Aligning |out| appropriately may
987 // improve performance. It writes at most |in_len| + |SSL_max_seal_overhead|
988 // bytes to |out|.
989 //
990 // |in| and |out| may not alias.
991 bool tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
992                      uint8_t type, const uint8_t *in, size_t in_len);
993 
994 enum dtls1_use_epoch_t {
995   dtls1_use_previous_epoch,
996   dtls1_use_current_epoch,
997 };
998 
999 // dtls_max_seal_overhead returns the maximum overhead, in bytes, of sealing a
1000 // record.
1001 size_t dtls_max_seal_overhead(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
1002 
1003 // dtls_seal_prefix_len returns the number of bytes of prefix to reserve in
1004 // front of the plaintext when sealing a record in-place.
1005 size_t dtls_seal_prefix_len(const SSL *ssl, enum dtls1_use_epoch_t use_epoch);
1006 
1007 // dtls_seal_record implements |tls_seal_record| for DTLS. |use_epoch| selects
1008 // which epoch's cipher state to use. Unlike |tls_seal_record|, |in| and |out|
1009 // may alias but, if they do, |in| must be exactly |dtls_seal_prefix_len| bytes
1010 // ahead of |out|.
1011 bool dtls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
1012                       uint8_t type, const uint8_t *in, size_t in_len,
1013                       enum dtls1_use_epoch_t use_epoch);
1014 
1015 // ssl_process_alert processes |in| as an alert and updates |ssl|'s shutdown
1016 // state. It returns one of |ssl_open_record_discard|, |ssl_open_record_error|,
1017 // |ssl_open_record_close_notify|, or |ssl_open_record_fatal_alert| as
1018 // appropriate.
1019 enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert,
1020                                          Span<const uint8_t> in);
1021 
1022 
1023 // Private key operations.
1024 
1025 // ssl_has_private_key returns whether |hs| has a private key configured.
1026 bool ssl_has_private_key(const SSL_HANDSHAKE *hs);
1027 
1028 // ssl_private_key_* perform the corresponding operation on
1029 // |SSL_PRIVATE_KEY_METHOD|. If there is a custom private key configured, they
1030 // call the corresponding function or |complete| depending on whether there is a
1031 // pending operation. Otherwise, they implement the operation with
1032 // |EVP_PKEY|.
1033 
1034 enum ssl_private_key_result_t ssl_private_key_sign(
1035     SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len, size_t max_out,
1036     uint16_t sigalg, Span<const uint8_t> in);
1037 
1038 enum ssl_private_key_result_t ssl_private_key_decrypt(SSL_HANDSHAKE *hs,
1039                                                       uint8_t *out,
1040                                                       size_t *out_len,
1041                                                       size_t max_out,
1042                                                       Span<const uint8_t> in);
1043 
1044 // ssl_private_key_supports_signature_algorithm returns whether |hs|'s private
1045 // key supports |sigalg|.
1046 bool ssl_private_key_supports_signature_algorithm(SSL_HANDSHAKE *hs,
1047                                                   uint16_t sigalg);
1048 
1049 // ssl_public_key_verify verifies that the |signature| is valid for the public
1050 // key |pkey| and input |in|, using the signature algorithm |sigalg|.
1051 bool ssl_public_key_verify(SSL *ssl, Span<const uint8_t> signature,
1052                            uint16_t sigalg, EVP_PKEY *pkey,
1053                            Span<const uint8_t> in);
1054 
1055 
1056 // Key shares.
1057 
1058 // SSLKeyShare abstracts over KEM-like constructions, for use with TLS 1.2 ECDHE
1059 // cipher suites and the TLS 1.3 key_share extension.
1060 //
1061 // TODO(davidben): This class is named SSLKeyShare after the TLS 1.3 key_share
1062 // extension, but it really implements a KEM abstraction. Additionally, we use
1063 // the same type for Encap, which is a one-off, stateless operation, as Generate
1064 // and Decap. Slightly tidier would be for Generate to return a new SSLKEMKey
1065 // (or we introduce EVP_KEM and EVP_KEM_KEY), with a Decap method, and for Encap
1066 // to be static function.
1067 class SSLKeyShare {
1068  public:
1069   virtual ~SSLKeyShare() {}
1070   static constexpr bool kAllowUniquePtr = true;
1071   HAS_VIRTUAL_DESTRUCTOR
1072 
1073   // Create returns a SSLKeyShare instance for use with group |group_id| or
1074   // nullptr on error.
1075   static UniquePtr<SSLKeyShare> Create(uint16_t group_id);
1076 
1077   // GroupID returns the group ID.
1078   virtual uint16_t GroupID() const PURE_VIRTUAL;
1079 
1080   // Generate generates a keypair and writes the public key to |out_public_key|.
1081   // It returns true on success and false on error.
1082   virtual bool Generate(CBB *out_public_key) PURE_VIRTUAL;
1083 
1084   // Encap generates an ephemeral, symmetric secret and encapsulates it with
1085   // |peer_key|. On success, it returns true, writes the encapsulated secret to
1086   // |out_ciphertext|, and sets |*out_secret| to the shared secret. On failure,
1087   // it returns false and sets |*out_alert| to an alert to send to the peer.
1088   virtual bool Encap(CBB *out_ciphertext, Array<uint8_t> *out_secret,
1089                      uint8_t *out_alert,
1090                      Span<const uint8_t> peer_key) PURE_VIRTUAL;
1091 
1092   // Decap decapsulates the symmetric secret in |ciphertext|. On success, it
1093   // returns true and sets |*out_secret| to the shared secret. On failure, it
1094   // returns false and sets |*out_alert| to an alert to send to the peer.
1095   virtual bool Decap(Array<uint8_t> *out_secret, uint8_t *out_alert,
1096                      Span<const uint8_t> ciphertext) PURE_VIRTUAL;
1097 
1098   // SerializePrivateKey writes the private key to |out|, returning true if
1099   // successful and false otherwise. It should be called after |Generate|.
1100   virtual bool SerializePrivateKey(CBB *out) { return false; }
1101 
1102   // DeserializePrivateKey initializes the state of the key exchange from |in|,
1103   // returning true if successful and false otherwise.
1104   virtual bool DeserializePrivateKey(CBS *in) { return false; }
1105 };
1106 
1107 struct NamedGroup {
1108   int nid;
1109   uint16_t group_id;
1110   const char name[12], alias[12];
1111 };
1112 
1113 // NamedGroups returns all supported groups.
1114 Span<const NamedGroup> NamedGroups();
1115 
1116 // ssl_nid_to_group_id looks up the group corresponding to |nid|. On success, it
1117 // sets |*out_group_id| to the group ID and returns true. Otherwise, it returns
1118 // false.
1119 bool ssl_nid_to_group_id(uint16_t *out_group_id, int nid);
1120 
1121 // ssl_name_to_group_id looks up the group corresponding to the |name| string of
1122 // length |len|. On success, it sets |*out_group_id| to the group ID and returns
1123 // true. Otherwise, it returns false.
1124 bool ssl_name_to_group_id(uint16_t *out_group_id, const char *name, size_t len);
1125 
1126 
1127 // Handshake messages.
1128 
1129 struct SSLMessage {
1130   bool is_v2_hello;
1131   uint8_t type;
1132   CBS body;
1133   // raw is the entire serialized handshake message, including the TLS or DTLS
1134   // message header.
1135   CBS raw;
1136 };
1137 
1138 // SSL_MAX_HANDSHAKE_FLIGHT is the number of messages, including
1139 // ChangeCipherSpec, in the longest handshake flight. Currently this is the
1140 // client's second leg in a full handshake when client certificates, NPN, and
1141 // Channel ID, are all enabled.
1142 #define SSL_MAX_HANDSHAKE_FLIGHT 7
1143 
1144 extern const uint8_t kHelloRetryRequest[SSL3_RANDOM_SIZE];
1145 extern const uint8_t kTLS12DowngradeRandom[8];
1146 extern const uint8_t kTLS13DowngradeRandom[8];
1147 extern const uint8_t kJDK11DowngradeRandom[8];
1148 
1149 // ssl_max_handshake_message_len returns the maximum number of bytes permitted
1150 // in a handshake message for |ssl|.
1151 size_t ssl_max_handshake_message_len(const SSL *ssl);
1152 
1153 // tls_can_accept_handshake_data returns whether |ssl| is able to accept more
1154 // data into handshake buffer.
1155 bool tls_can_accept_handshake_data(const SSL *ssl, uint8_t *out_alert);
1156 
1157 // tls_has_unprocessed_handshake_data returns whether there is buffered
1158 // handshake data that has not been consumed by |get_message|.
1159 bool tls_has_unprocessed_handshake_data(const SSL *ssl);
1160 
1161 // tls_append_handshake_data appends |data| to the handshake buffer. It returns
1162 // true on success and false on allocation failure.
1163 bool tls_append_handshake_data(SSL *ssl, Span<const uint8_t> data);
1164 
1165 // dtls_has_unprocessed_handshake_data behaves like
1166 // |tls_has_unprocessed_handshake_data| for DTLS.
1167 bool dtls_has_unprocessed_handshake_data(const SSL *ssl);
1168 
1169 // tls_flush_pending_hs_data flushes any handshake plaintext data.
1170 bool tls_flush_pending_hs_data(SSL *ssl);
1171 
1172 struct DTLS_OUTGOING_MESSAGE {
1173   DTLS_OUTGOING_MESSAGE() {}
1174   DTLS_OUTGOING_MESSAGE(const DTLS_OUTGOING_MESSAGE &) = delete;
1175   DTLS_OUTGOING_MESSAGE &operator=(const DTLS_OUTGOING_MESSAGE &) = delete;
1176 
1177   void Clear();
1178 
1179   Array<uint8_t> data;
1180   uint16_t epoch = 0;
1181   bool is_ccs = false;
1182 };
1183 
1184 // dtls_clear_outgoing_messages releases all buffered outgoing messages.
1185 void dtls_clear_outgoing_messages(SSL *ssl);
1186 
1187 
1188 // Callbacks.
1189 
1190 // ssl_do_info_callback calls |ssl|'s info callback, if set.
1191 void ssl_do_info_callback(const SSL *ssl, int type, int value);
1192 
1193 // ssl_do_msg_callback calls |ssl|'s message callback, if set.
1194 void ssl_do_msg_callback(const SSL *ssl, int is_write, int content_type,
1195                          Span<const uint8_t> in);
1196 
1197 
1198 // Transport buffers.
1199 
1200 class SSLBuffer {
1201  public:
1202   SSLBuffer() {}
1203   ~SSLBuffer() { Clear(); }
1204 
1205   SSLBuffer(const SSLBuffer &) = delete;
1206   SSLBuffer &operator=(const SSLBuffer &) = delete;
1207 
1208   uint8_t *data() { return buf_ + offset_; }
1209   size_t size() const { return size_; }
1210   bool empty() const { return size_ == 0; }
1211   size_t cap() const { return cap_; }
1212 
1213   Span<uint8_t> span() { return MakeSpan(data(), size()); }
1214 
1215   Span<uint8_t> remaining() {
1216     return MakeSpan(data() + size(), cap() - size());
1217   }
1218 
1219   // Clear releases the buffer.
1220   void Clear();
1221 
1222   // EnsureCap ensures the buffer has capacity at least |new_cap|, aligned such
1223   // that data written after |header_len| is aligned to a
1224   // |SSL3_ALIGN_PAYLOAD|-byte boundary. It returns true on success and false
1225   // on error.
1226   bool EnsureCap(size_t header_len, size_t new_cap);
1227 
1228   // DidWrite extends the buffer by |len|. The caller must have filled in to
1229   // this point.
1230   void DidWrite(size_t len);
1231 
1232   // Consume consumes |len| bytes from the front of the buffer.  The memory
1233   // consumed will remain valid until the next call to |DiscardConsumed| or
1234   // |Clear|.
1235   void Consume(size_t len);
1236 
1237   // DiscardConsumed discards the consumed bytes from the buffer. If the buffer
1238   // is now empty, it releases memory used by it.
1239   void DiscardConsumed();
1240 
1241  private:
1242   // buf_ is the memory allocated for this buffer.
1243   uint8_t *buf_ = nullptr;
1244   // offset_ is the offset into |buf_| which the buffer contents start at.
1245   uint16_t offset_ = 0;
1246   // size_ is the size of the buffer contents from |buf_| + |offset_|.
1247   uint16_t size_ = 0;
1248   // cap_ is how much memory beyond |buf_| + |offset_| is available.
1249   uint16_t cap_ = 0;
1250   // inline_buf_ is a static buffer for short reads.
1251   uint8_t inline_buf_[SSL3_RT_HEADER_LENGTH];
1252   // buf_allocated_ is true if |buf_| points to allocated data and must be freed
1253   // or false if it points into |inline_buf_|.
1254   bool buf_allocated_ = false;
1255 };
1256 
1257 // ssl_read_buffer_extend_to extends the read buffer to the desired length. For
1258 // TLS, it reads to the end of the buffer until the buffer is |len| bytes
1259 // long. For DTLS, it reads a new packet and ignores |len|. It returns one on
1260 // success, zero on EOF, and a negative number on error.
1261 //
1262 // It is an error to call |ssl_read_buffer_extend_to| in DTLS when the buffer is
1263 // non-empty.
1264 int ssl_read_buffer_extend_to(SSL *ssl, size_t len);
1265 
1266 // ssl_handle_open_record handles the result of passing |ssl->s3->read_buffer|
1267 // to a record-processing function. If |ret| is a success or if the caller
1268 // should retry, it returns one and sets |*out_retry|. Otherwise, it returns <=
1269 // 0.
1270 int ssl_handle_open_record(SSL *ssl, bool *out_retry, ssl_open_record_t ret,
1271                            size_t consumed, uint8_t alert);
1272 
1273 // ssl_write_buffer_flush flushes the write buffer to the transport. It returns
1274 // one on success and <= 0 on error. For DTLS, whether or not the write
1275 // succeeds, the write buffer will be cleared.
1276 int ssl_write_buffer_flush(SSL *ssl);
1277 
1278 
1279 // Certificate functions.
1280 
1281 // ssl_has_certificate returns whether a certificate and private key are
1282 // configured.
1283 bool ssl_has_certificate(const SSL_HANDSHAKE *hs);
1284 
1285 // ssl_parse_cert_chain parses a certificate list from |cbs| in the format used
1286 // by a TLS Certificate message. On success, it advances |cbs| and returns
1287 // true. Otherwise, it returns false and sets |*out_alert| to an alert to send
1288 // to the peer.
1289 //
1290 // If the list is non-empty then |*out_chain| and |*out_pubkey| will be set to
1291 // the certificate chain and the leaf certificate's public key
1292 // respectively. Otherwise, both will be set to nullptr.
1293 //
1294 // If the list is non-empty and |out_leaf_sha256| is non-NULL, it writes the
1295 // SHA-256 hash of the leaf to |out_leaf_sha256|.
1296 bool ssl_parse_cert_chain(uint8_t *out_alert,
1297                           UniquePtr<STACK_OF(CRYPTO_BUFFER)> *out_chain,
1298                           UniquePtr<EVP_PKEY> *out_pubkey,
1299                           uint8_t *out_leaf_sha256, CBS *cbs,
1300                           CRYPTO_BUFFER_POOL *pool);
1301 
1302 // ssl_add_cert_chain adds |hs->ssl|'s certificate chain to |cbb| in the format
1303 // used by a TLS Certificate message. If there is no certificate chain, it emits
1304 // an empty certificate list. It returns true on success and false on error.
1305 bool ssl_add_cert_chain(SSL_HANDSHAKE *hs, CBB *cbb);
1306 
1307 enum ssl_key_usage_t {
1308   key_usage_digital_signature = 0,
1309   key_usage_encipherment = 2,
1310 };
1311 
1312 // ssl_cert_check_key_usage parses the DER-encoded, X.509 certificate in |in|
1313 // and returns true if doesn't specify a key usage or, if it does, if it
1314 // includes |bit|. Otherwise it pushes to the error queue and returns false.
1315 OPENSSL_EXPORT bool ssl_cert_check_key_usage(const CBS *in,
1316                                              enum ssl_key_usage_t bit);
1317 
1318 // ssl_cert_parse_pubkey extracts the public key from the DER-encoded, X.509
1319 // certificate in |in|. It returns an allocated |EVP_PKEY| or else returns
1320 // nullptr and pushes to the error queue.
1321 UniquePtr<EVP_PKEY> ssl_cert_parse_pubkey(const CBS *in);
1322 
1323 // ssl_parse_client_CA_list parses a CA list from |cbs| in the format used by a
1324 // TLS CertificateRequest message. On success, it returns a newly-allocated
1325 // |CRYPTO_BUFFER| list and advances |cbs|. Otherwise, it returns nullptr and
1326 // sets |*out_alert| to an alert to send to the peer.
1327 UniquePtr<STACK_OF(CRYPTO_BUFFER)> ssl_parse_client_CA_list(SSL *ssl,
1328                                                             uint8_t *out_alert,
1329                                                             CBS *cbs);
1330 
1331 // ssl_has_client_CAs returns there are configured CAs.
1332 bool ssl_has_client_CAs(const SSL_CONFIG *cfg);
1333 
1334 // ssl_add_client_CA_list adds the configured CA list to |cbb| in the format
1335 // used by a TLS CertificateRequest message. It returns true on success and
1336 // false on error.
1337 bool ssl_add_client_CA_list(SSL_HANDSHAKE *hs, CBB *cbb);
1338 
1339 // ssl_check_leaf_certificate returns one if |pkey| and |leaf| are suitable as
1340 // a server's leaf certificate for |hs|. Otherwise, it returns zero and pushes
1341 // an error on the error queue.
1342 bool ssl_check_leaf_certificate(SSL_HANDSHAKE *hs, EVP_PKEY *pkey,
1343                                const CRYPTO_BUFFER *leaf);
1344 
1345 // ssl_on_certificate_selected is called once the certificate has been selected.
1346 // It finalizes the certificate and initializes |hs->local_pubkey|. It returns
1347 // true on success and false on error.
1348 bool ssl_on_certificate_selected(SSL_HANDSHAKE *hs);
1349 
1350 
1351 // TLS 1.3 key derivation.
1352 
1353 // tls13_init_key_schedule initializes the handshake hash and key derivation
1354 // state, and incorporates the PSK. The cipher suite and PRF hash must have been
1355 // selected at this point. It returns true on success and false on error.
1356 bool tls13_init_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> psk);
1357 
1358 // tls13_init_early_key_schedule initializes the handshake hash and key
1359 // derivation state from |session| for use with 0-RTT. It returns one on success
1360 // and zero on error.
1361 bool tls13_init_early_key_schedule(SSL_HANDSHAKE *hs,
1362                                    const SSL_SESSION *session);
1363 
1364 // tls13_advance_key_schedule incorporates |in| into the key schedule with
1365 // HKDF-Extract. It returns true on success and false on error.
1366 bool tls13_advance_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> in);
1367 
1368 // tls13_set_traffic_key sets the read or write traffic keys to
1369 // |traffic_secret|. The version and cipher suite are determined from |session|.
1370 // It returns true on success and false on error.
1371 bool tls13_set_traffic_key(SSL *ssl, enum ssl_encryption_level_t level,
1372                            enum evp_aead_direction_t direction,
1373                            const SSL_SESSION *session,
1374                            Span<const uint8_t> traffic_secret);
1375 
1376 // tls13_derive_early_secret derives the early traffic secret. It returns true
1377 // on success and false on error.
1378 bool tls13_derive_early_secret(SSL_HANDSHAKE *hs);
1379 
1380 // tls13_derive_handshake_secrets derives the handshake traffic secret. It
1381 // returns true on success and false on error.
1382 bool tls13_derive_handshake_secrets(SSL_HANDSHAKE *hs);
1383 
1384 // tls13_rotate_traffic_key derives the next read or write traffic secret. It
1385 // returns true on success and false on error.
1386 bool tls13_rotate_traffic_key(SSL *ssl, enum evp_aead_direction_t direction);
1387 
1388 // tls13_derive_application_secrets derives the initial application data traffic
1389 // and exporter secrets based on the handshake transcripts and |master_secret|.
1390 // It returns true on success and false on error.
1391 bool tls13_derive_application_secrets(SSL_HANDSHAKE *hs);
1392 
1393 // tls13_derive_resumption_secret derives the |resumption_secret|.
1394 bool tls13_derive_resumption_secret(SSL_HANDSHAKE *hs);
1395 
1396 // tls13_export_keying_material provides an exporter interface to use the
1397 // |exporter_secret|.
1398 bool tls13_export_keying_material(SSL *ssl, Span<uint8_t> out,
1399                                   Span<const uint8_t> secret,
1400                                   Span<const char> label,
1401                                   Span<const uint8_t> context);
1402 
1403 // tls13_finished_mac calculates the MAC of the handshake transcript to verify
1404 // the integrity of the Finished message, and stores the result in |out| and
1405 // length in |out_len|. |is_server| is true if this is for the Server Finished
1406 // and false for the Client Finished.
1407 bool tls13_finished_mac(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len,
1408                         bool is_server);
1409 
1410 // tls13_derive_session_psk calculates the PSK for this session based on the
1411 // resumption master secret and |nonce|. It returns true on success, and false
1412 // on failure.
1413 bool tls13_derive_session_psk(SSL_SESSION *session, Span<const uint8_t> nonce);
1414 
1415 // tls13_write_psk_binder calculates the PSK binder value over |transcript| and
1416 // |msg|, and replaces the last bytes of |msg| with the resulting value. It
1417 // returns true on success, and false on failure. If |out_binder_len| is
1418 // non-NULL, it sets |*out_binder_len| to the length of the value computed.
1419 bool tls13_write_psk_binder(const SSL_HANDSHAKE *hs,
1420                             const SSLTranscript &transcript, Span<uint8_t> msg,
1421                             size_t *out_binder_len);
1422 
1423 // tls13_verify_psk_binder verifies that the handshake transcript, truncated up
1424 // to the binders has a valid signature using the value of |session|'s
1425 // resumption secret. It returns true on success, and false on failure.
1426 bool tls13_verify_psk_binder(const SSL_HANDSHAKE *hs,
1427                              const SSL_SESSION *session, const SSLMessage &msg,
1428                              CBS *binders);
1429 
1430 
1431 // Encrypted ClientHello.
1432 
1433 struct ECHConfig {
1434   static constexpr bool kAllowUniquePtr = true;
1435   // raw contains the serialized ECHConfig.
1436   Array<uint8_t> raw;
1437   // The following fields alias into |raw|.
1438   Span<const uint8_t> public_key;
1439   Span<const uint8_t> public_name;
1440   Span<const uint8_t> cipher_suites;
1441   uint16_t kem_id = 0;
1442   uint8_t maximum_name_length = 0;
1443   uint8_t config_id = 0;
1444 };
1445 
1446 class ECHServerConfig {
1447  public:
1448   static constexpr bool kAllowUniquePtr = true;
1449   ECHServerConfig() = default;
1450   ECHServerConfig(const ECHServerConfig &other) = delete;
1451   ECHServerConfig &operator=(ECHServerConfig &&) = delete;
1452 
1453   // Init parses |ech_config| as an ECHConfig and saves a copy of |key|.
1454   // It returns true on success and false on error.
1455   bool Init(Span<const uint8_t> ech_config, const EVP_HPKE_KEY *key,
1456             bool is_retry_config);
1457 
1458   // SetupContext sets up |ctx| for a new connection, given the specified
1459   // HPKE ciphersuite and encapsulated KEM key. It returns true on success and
1460   // false on error. This function may only be called on an initialized object.
1461   bool SetupContext(EVP_HPKE_CTX *ctx, uint16_t kdf_id, uint16_t aead_id,
1462                     Span<const uint8_t> enc) const;
1463 
1464   const ECHConfig &ech_config() const { return ech_config_; }
1465   bool is_retry_config() const { return is_retry_config_; }
1466 
1467  private:
1468   ECHConfig ech_config_;
1469   ScopedEVP_HPKE_KEY key_;
1470   bool is_retry_config_ = false;
1471 };
1472 
1473 enum ssl_client_hello_type_t {
1474   ssl_client_hello_unencrypted,
1475   ssl_client_hello_inner,
1476   ssl_client_hello_outer,
1477 };
1478 
1479 // ECH_CLIENT_* are types for the ClientHello encrypted_client_hello extension.
1480 #define ECH_CLIENT_OUTER 0
1481 #define ECH_CLIENT_INNER 1
1482 
1483 // ssl_decode_client_hello_inner recovers the full ClientHelloInner from the
1484 // EncodedClientHelloInner |encoded_client_hello_inner| by replacing its
1485 // outer_extensions extension with the referenced extensions from the
1486 // ClientHelloOuter |client_hello_outer|. If successful, it writes the recovered
1487 // ClientHelloInner to |out_client_hello_inner|. It returns true on success and
1488 // false on failure.
1489 //
1490 // This function is exported for fuzzing.
1491 OPENSSL_EXPORT bool ssl_decode_client_hello_inner(
1492     SSL *ssl, uint8_t *out_alert, Array<uint8_t> *out_client_hello_inner,
1493     Span<const uint8_t> encoded_client_hello_inner,
1494     const SSL_CLIENT_HELLO *client_hello_outer);
1495 
1496 // ssl_client_hello_decrypt attempts to decrypt and decode the |payload|. It
1497 // writes the result to |*out|. |payload| must point into |client_hello_outer|.
1498 // It returns true on success and false on error. On error, it sets
1499 // |*out_is_decrypt_error| to whether the failure was due to a bad ciphertext.
1500 bool ssl_client_hello_decrypt(SSL_HANDSHAKE *hs, uint8_t *out_alert,
1501                               bool *out_is_decrypt_error, Array<uint8_t> *out,
1502                               const SSL_CLIENT_HELLO *client_hello_outer,
1503                               Span<const uint8_t> payload);
1504 
1505 #define ECH_CONFIRMATION_SIGNAL_LEN 8
1506 
1507 // ssl_ech_confirmation_signal_hello_offset returns the offset of the ECH
1508 // confirmation signal in a ServerHello message, including the handshake header.
1509 size_t ssl_ech_confirmation_signal_hello_offset(const SSL *ssl);
1510 
1511 // ssl_ech_accept_confirmation computes the server's ECH acceptance signal,
1512 // writing it to |out|. The transcript portion is the concatenation of
1513 // |transcript| with |msg|. The |ECH_CONFIRMATION_SIGNAL_LEN| bytes from
1514 // |offset| in |msg| are replaced with zeros before hashing. This function
1515 // returns true on success, and false on failure.
1516 bool ssl_ech_accept_confirmation(const SSL_HANDSHAKE *hs, Span<uint8_t> out,
1517                                  Span<const uint8_t> client_random,
1518                                  const SSLTranscript &transcript, bool is_hrr,
1519                                  Span<const uint8_t> msg, size_t offset);
1520 
1521 // ssl_is_valid_ech_public_name returns true if |public_name| is a valid ECH
1522 // public name and false otherwise. It is exported for testing.
1523 OPENSSL_EXPORT bool ssl_is_valid_ech_public_name(
1524     Span<const uint8_t> public_name);
1525 
1526 // ssl_is_valid_ech_config_list returns true if |ech_config_list| is a valid
1527 // ECHConfigList structure and false otherwise.
1528 bool ssl_is_valid_ech_config_list(Span<const uint8_t> ech_config_list);
1529 
1530 // ssl_select_ech_config selects an ECHConfig and associated parameters to offer
1531 // on the client and updates |hs|. It returns true on success, whether an
1532 // ECHConfig was found or not, and false on internal error. On success, the
1533 // encapsulated key is written to |out_enc| and |*out_enc_len| is set to the
1534 // number of bytes written. If the function did not select an ECHConfig, the
1535 // encapsulated key is the empty string.
1536 bool ssl_select_ech_config(SSL_HANDSHAKE *hs, Span<uint8_t> out_enc,
1537                            size_t *out_enc_len);
1538 
1539 // ssl_ech_extension_body_length returns the length of the body of a ClientHello
1540 // ECH extension that encrypts |in_len| bytes with |aead| and an 'enc' value of
1541 // length |enc_len|. The result does not include the four-byte extension header.
1542 size_t ssl_ech_extension_body_length(const EVP_HPKE_AEAD *aead, size_t enc_len,
1543                                      size_t in_len);
1544 
1545 // ssl_encrypt_client_hello constructs a new ClientHelloInner, adds it to the
1546 // inner transcript, and encrypts for inclusion in the ClientHelloOuter. |enc|
1547 // is the encapsulated key to include in the extension. It returns true on
1548 // success and false on error. If not offering ECH, |enc| is ignored and the
1549 // function will compute a GREASE ECH extension if necessary, and otherwise
1550 // return success while doing nothing.
1551 //
1552 // Encrypting the ClientHelloInner incorporates all extensions in the
1553 // ClientHelloOuter, so all other state necessary for |ssl_add_client_hello|
1554 // must already be computed.
1555 bool ssl_encrypt_client_hello(SSL_HANDSHAKE *hs, Span<const uint8_t> enc);
1556 
1557 
1558 // Delegated credentials.
1559 
1560 // This structure stores a delegated credential (DC) as defined by
1561 // draft-ietf-tls-subcerts-03.
1562 struct DC {
1563   static constexpr bool kAllowUniquePtr = true;
1564   ~DC();
1565 
1566   // Dup returns a copy of this DC and takes references to |raw| and |pkey|.
1567   UniquePtr<DC> Dup();
1568 
1569   // Parse parses the delegated credential stored in |in|. If successful it
1570   // returns the parsed structure, otherwise it returns |nullptr| and sets
1571   // |*out_alert|.
1572   static UniquePtr<DC> Parse(CRYPTO_BUFFER *in, uint8_t *out_alert);
1573 
1574   // raw is the delegated credential encoded as specified in draft-ietf-tls-
1575   // subcerts-03.
1576   UniquePtr<CRYPTO_BUFFER> raw;
1577 
1578   // expected_cert_verify_algorithm is the signature scheme of the DC public
1579   // key.
1580   uint16_t expected_cert_verify_algorithm = 0;
1581 
1582   // pkey is the public key parsed from |public_key|.
1583   UniquePtr<EVP_PKEY> pkey;
1584 
1585  private:
1586   friend DC* New<DC>();
1587   DC();
1588 };
1589 
1590 // ssl_signing_with_dc returns true if the peer has indicated support for
1591 // delegated credentials and this host has sent a delegated credential in
1592 // response. If this is true then we've committed to using the DC in the
1593 // handshake.
1594 bool ssl_signing_with_dc(const SSL_HANDSHAKE *hs);
1595 
1596 
1597 // Handshake functions.
1598 
1599 enum ssl_hs_wait_t {
1600   ssl_hs_error,
1601   ssl_hs_ok,
1602   ssl_hs_read_server_hello,
1603   ssl_hs_read_message,
1604   ssl_hs_flush,
1605   ssl_hs_certificate_selection_pending,
1606   ssl_hs_handoff,
1607   ssl_hs_handback,
1608   ssl_hs_x509_lookup,
1609   ssl_hs_private_key_operation,
1610   ssl_hs_pending_session,
1611   ssl_hs_pending_ticket,
1612   ssl_hs_early_return,
1613   ssl_hs_early_data_rejected,
1614   ssl_hs_read_end_of_early_data,
1615   ssl_hs_read_change_cipher_spec,
1616   ssl_hs_certificate_verify,
1617   ssl_hs_hints_ready,
1618 };
1619 
1620 enum ssl_grease_index_t {
1621   ssl_grease_cipher = 0,
1622   ssl_grease_group,
1623   ssl_grease_extension1,
1624   ssl_grease_extension2,
1625   ssl_grease_version,
1626   ssl_grease_ticket_extension,
1627   ssl_grease_ech_config_id,
1628   ssl_grease_last_index = ssl_grease_ech_config_id,
1629 };
1630 
1631 enum tls12_server_hs_state_t {
1632   state12_start_accept = 0,
1633   state12_read_client_hello,
1634   state12_read_client_hello_after_ech,
1635   state12_select_certificate,
1636   state12_tls13,
1637   state12_select_parameters,
1638   state12_send_server_hello,
1639   state12_send_server_certificate,
1640   state12_send_server_key_exchange,
1641   state12_send_server_hello_done,
1642   state12_read_client_certificate,
1643   state12_verify_client_certificate,
1644   state12_read_client_key_exchange,
1645   state12_read_client_certificate_verify,
1646   state12_read_change_cipher_spec,
1647   state12_process_change_cipher_spec,
1648   state12_read_next_proto,
1649   state12_read_channel_id,
1650   state12_read_client_finished,
1651   state12_send_server_finished,
1652   state12_finish_server_handshake,
1653   state12_done,
1654 };
1655 
1656 enum tls13_server_hs_state_t {
1657   state13_select_parameters = 0,
1658   state13_select_session,
1659   state13_send_hello_retry_request,
1660   state13_read_second_client_hello,
1661   state13_send_server_hello,
1662   state13_send_server_certificate_verify,
1663   state13_send_server_finished,
1664   state13_send_half_rtt_ticket,
1665   state13_read_second_client_flight,
1666   state13_process_end_of_early_data,
1667   state13_read_client_encrypted_extensions,
1668   state13_read_client_certificate,
1669   state13_read_client_certificate_verify,
1670   state13_read_channel_id,
1671   state13_read_client_finished,
1672   state13_send_new_session_ticket,
1673   state13_done,
1674 };
1675 
1676 // handback_t lists the points in the state machine where a handback can occur.
1677 // These are the different points at which key material is no longer needed.
1678 enum handback_t {
1679   handback_after_session_resumption = 0,
1680   handback_after_ecdhe = 1,
1681   handback_after_handshake = 2,
1682   handback_tls13 = 3,
1683   handback_max_value = handback_tls13,
1684 };
1685 
1686 // SSL_HANDSHAKE_HINTS contains handshake hints for a connection. See
1687 // |SSL_request_handshake_hints| and related functions.
1688 struct SSL_HANDSHAKE_HINTS {
1689   static constexpr bool kAllowUniquePtr = true;
1690 
1691   Array<uint8_t> server_random_tls12;
1692   Array<uint8_t> server_random_tls13;
1693 
1694   uint16_t key_share_group_id = 0;
1695   Array<uint8_t> key_share_ciphertext;
1696   Array<uint8_t> key_share_secret;
1697 
1698   uint16_t signature_algorithm = 0;
1699   Array<uint8_t> signature_input;
1700   Array<uint8_t> signature_spki;
1701   Array<uint8_t> signature;
1702 
1703   Array<uint8_t> decrypted_psk;
1704   bool ignore_psk = false;
1705 
1706   uint16_t cert_compression_alg_id = 0;
1707   Array<uint8_t> cert_compression_input;
1708   Array<uint8_t> cert_compression_output;
1709 
1710   uint16_t ecdhe_group_id = 0;
1711   Array<uint8_t> ecdhe_public_key;
1712   Array<uint8_t> ecdhe_private_key;
1713 
1714   Array<uint8_t> decrypted_ticket;
1715   bool renew_ticket = false;
1716   bool ignore_ticket = false;
1717 };
1718 
1719 struct SSL_HANDSHAKE {
1720   explicit SSL_HANDSHAKE(SSL *ssl);
1721   ~SSL_HANDSHAKE();
1722   static constexpr bool kAllowUniquePtr = true;
1723 
1724   // ssl is a non-owning pointer to the parent |SSL| object.
1725   SSL *ssl;
1726 
1727   // config is a non-owning pointer to the handshake configuration.
1728   SSL_CONFIG *config;
1729 
1730   // wait contains the operation the handshake is currently blocking on or
1731   // |ssl_hs_ok| if none.
1732   enum ssl_hs_wait_t wait = ssl_hs_ok;
1733 
1734   // state is the internal state for the TLS 1.2 and below handshake. Its
1735   // values depend on |do_handshake| but the starting state is always zero.
1736   int state = 0;
1737 
1738   // tls13_state is the internal state for the TLS 1.3 handshake. Its values
1739   // depend on |do_handshake| but the starting state is always zero.
1740   int tls13_state = 0;
1741 
1742   // min_version is the minimum accepted protocol version, taking account both
1743   // |SSL_OP_NO_*| and |SSL_CTX_set_min_proto_version| APIs.
1744   uint16_t min_version = 0;
1745 
1746   // max_version is the maximum accepted protocol version, taking account both
1747   // |SSL_OP_NO_*| and |SSL_CTX_set_max_proto_version| APIs.
1748   uint16_t max_version = 0;
1749 
1750  private:
1751   size_t hash_len_ = 0;
1752   uint8_t secret_[SSL_MAX_MD_SIZE] = {0};
1753   uint8_t early_traffic_secret_[SSL_MAX_MD_SIZE] = {0};
1754   uint8_t client_handshake_secret_[SSL_MAX_MD_SIZE] = {0};
1755   uint8_t server_handshake_secret_[SSL_MAX_MD_SIZE] = {0};
1756   uint8_t client_traffic_secret_0_[SSL_MAX_MD_SIZE] = {0};
1757   uint8_t server_traffic_secret_0_[SSL_MAX_MD_SIZE] = {0};
1758   uint8_t expected_client_finished_[SSL_MAX_MD_SIZE] = {0};
1759 
1760  public:
1761   void ResizeSecrets(size_t hash_len);
1762 
1763   // GetClientHello, on the server, returns either the normal ClientHello
1764   // message or the ClientHelloInner if it has been serialized to
1765   // |ech_client_hello_buf|. This function should only be called when the
1766   // current message is a ClientHello. It returns true on success and false on
1767   // error.
1768   //
1769   // Note that fields of the returned |out_msg| and |out_client_hello| point
1770   // into a handshake-owned buffer, so their lifetimes should not exceed this
1771   // SSL_HANDSHAKE.
1772   bool GetClientHello(SSLMessage *out_msg, SSL_CLIENT_HELLO *out_client_hello);
1773 
1774   Span<uint8_t> secret() { return MakeSpan(secret_, hash_len_); }
1775   Span<const uint8_t> secret() const {
1776     return MakeConstSpan(secret_, hash_len_);
1777   }
1778   Span<uint8_t> early_traffic_secret() {
1779     return MakeSpan(early_traffic_secret_, hash_len_);
1780   }
1781   Span<uint8_t> client_handshake_secret() {
1782     return MakeSpan(client_handshake_secret_, hash_len_);
1783   }
1784   Span<uint8_t> server_handshake_secret() {
1785     return MakeSpan(server_handshake_secret_, hash_len_);
1786   }
1787   Span<uint8_t> client_traffic_secret_0() {
1788     return MakeSpan(client_traffic_secret_0_, hash_len_);
1789   }
1790   Span<uint8_t> server_traffic_secret_0() {
1791     return MakeSpan(server_traffic_secret_0_, hash_len_);
1792   }
1793   Span<uint8_t> expected_client_finished() {
1794     return MakeSpan(expected_client_finished_, hash_len_);
1795   }
1796 
1797   union {
1798     // sent is a bitset where the bits correspond to elements of kExtensions
1799     // in extensions.cc. Each bit is set if that extension was sent in a
1800     // ClientHello. It's not used by servers.
1801     uint32_t sent = 0;
1802     // received is a bitset, like |sent|, but is used by servers to record
1803     // which extensions were received from a client.
1804     uint32_t received;
1805   } extensions;
1806 
1807   // inner_extensions_sent, on clients that offer ECH, is |extensions.sent| for
1808   // the ClientHelloInner.
1809   uint32_t inner_extensions_sent = 0;
1810 
1811   // error, if |wait| is |ssl_hs_error|, is the error the handshake failed on.
1812   UniquePtr<ERR_SAVE_STATE> error;
1813 
1814   // key_shares are the current key exchange instances. The second is only used
1815   // as a client if we believe that we should offer two key shares in a
1816   // ClientHello.
1817   UniquePtr<SSLKeyShare> key_shares[2];
1818 
1819   // transcript is the current handshake transcript.
1820   SSLTranscript transcript;
1821 
1822   // inner_transcript, on the client, is the handshake transcript for the
1823   // ClientHelloInner handshake. It is moved to |transcript| if the server
1824   // accepts ECH.
1825   SSLTranscript inner_transcript;
1826 
1827   // inner_client_random is the ClientHello random value used with
1828   // ClientHelloInner.
1829   uint8_t inner_client_random[SSL3_RANDOM_SIZE] = {0};
1830 
1831   // cookie is the value of the cookie in HelloRetryRequest, or empty if none
1832   // was received.
1833   Array<uint8_t> cookie;
1834 
1835   // dtls_cookie is the value of the cookie in DTLS HelloVerifyRequest. If
1836   // empty, either none was received or HelloVerifyRequest contained an empty
1837   // cookie.
1838   Array<uint8_t> dtls_cookie;
1839 
1840   // ech_client_outer contains the outer ECH extension to send in the
1841   // ClientHello, excluding the header and type byte.
1842   Array<uint8_t> ech_client_outer;
1843 
1844   // ech_retry_configs, on the client, contains the retry configs from the
1845   // server as a serialized ECHConfigList.
1846   Array<uint8_t> ech_retry_configs;
1847 
1848   // ech_client_hello_buf, on the server, contains the bytes of the
1849   // reconstructed ClientHelloInner message.
1850   Array<uint8_t> ech_client_hello_buf;
1851 
1852   // key_share_bytes is the key_share extension that the client should send.
1853   Array<uint8_t> key_share_bytes;
1854 
1855   // key_share_ciphertext, for servers, is encapsulated shared secret to be sent
1856   // to the client in the TLS 1.3 key_share extension.
1857   Array<uint8_t> key_share_ciphertext;
1858 
1859   // peer_sigalgs are the signature algorithms that the peer supports. These are
1860   // taken from the contents of the signature algorithms extension for a server
1861   // or from the CertificateRequest for a client.
1862   Array<uint16_t> peer_sigalgs;
1863 
1864   // peer_supported_group_list contains the supported group IDs advertised by
1865   // the peer. This is only set on the server's end. The server does not
1866   // advertise this extension to the client.
1867   Array<uint16_t> peer_supported_group_list;
1868 
1869   // peer_delegated_credential_sigalgs are the signature algorithms the peer
1870   // supports with delegated credentials.
1871   Array<uint16_t> peer_delegated_credential_sigalgs;
1872 
1873   // peer_key is the peer's ECDH key for a TLS 1.2 client.
1874   Array<uint8_t> peer_key;
1875 
1876   // extension_permutation is the permutation to apply to ClientHello
1877   // extensions. It maps indices into the |kExtensions| table into other
1878   // indices.
1879   Array<uint8_t> extension_permutation;
1880 
1881   // cert_compression_alg_id, for a server, contains the negotiated certificate
1882   // compression algorithm for this client. It is only valid if
1883   // |cert_compression_negotiated| is true.
1884   uint16_t cert_compression_alg_id;
1885 
1886   // ech_hpke_ctx is the HPKE context used in ECH. On the server, it is
1887   // initialized if |ech_status| is |ssl_ech_accepted|. On the client, it is
1888   // initialized if |selected_ech_config| is not nullptr.
1889   ScopedEVP_HPKE_CTX ech_hpke_ctx;
1890 
1891   // server_params, in a TLS 1.2 server, stores the ServerKeyExchange
1892   // parameters. It has client and server randoms prepended for signing
1893   // convenience.
1894   Array<uint8_t> server_params;
1895 
1896   // peer_psk_identity_hint, on the client, is the psk_identity_hint sent by the
1897   // server when using a TLS 1.2 PSK key exchange.
1898   UniquePtr<char> peer_psk_identity_hint;
1899 
1900   // ca_names, on the client, contains the list of CAs received in a
1901   // CertificateRequest message.
1902   UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names;
1903 
1904   // cached_x509_ca_names contains a cache of parsed versions of the elements of
1905   // |ca_names|. This pointer is left non-owning so only
1906   // |ssl_crypto_x509_method| needs to link against crypto/x509.
1907   STACK_OF(X509_NAME) *cached_x509_ca_names = nullptr;
1908 
1909   // certificate_types, on the client, contains the set of certificate types
1910   // received in a CertificateRequest message.
1911   Array<uint8_t> certificate_types;
1912 
1913   // local_pubkey is the public key we are authenticating as.
1914   UniquePtr<EVP_PKEY> local_pubkey;
1915 
1916   // peer_pubkey is the public key parsed from the peer's leaf certificate.
1917   UniquePtr<EVP_PKEY> peer_pubkey;
1918 
1919   // new_session is the new mutable session being established by the current
1920   // handshake. It should not be cached.
1921   UniquePtr<SSL_SESSION> new_session;
1922 
1923   // early_session is the session corresponding to the current 0-RTT state on
1924   // the client if |in_early_data| is true.
1925   UniquePtr<SSL_SESSION> early_session;
1926 
1927   // ssl_ech_keys, for servers, is the set of ECH keys to use with this
1928   // handshake. This is copied from |SSL_CTX| to ensure consistent behavior as
1929   // |SSL_CTX| rotates keys.
1930   UniquePtr<SSL_ECH_KEYS> ech_keys;
1931 
1932   // selected_ech_config, for clients, is the ECHConfig the client uses to offer
1933   // ECH, or nullptr if ECH is not being offered. If non-NULL, |ech_hpke_ctx|
1934   // will be initialized.
1935   UniquePtr<ECHConfig> selected_ech_config;
1936 
1937   // new_cipher is the cipher being negotiated in this handshake.
1938   const SSL_CIPHER *new_cipher = nullptr;
1939 
1940   // key_block is the record-layer key block for TLS 1.2 and earlier.
1941   Array<uint8_t> key_block;
1942 
1943   // hints contains the handshake hints for this connection. If
1944   // |hints_requested| is true, this field is non-null and contains the pending
1945   // hints to filled as the predicted handshake progresses. Otherwise, this
1946   // field, if non-null, contains hints configured by the caller and will
1947   // influence the handshake on match.
1948   UniquePtr<SSL_HANDSHAKE_HINTS> hints;
1949 
1950   // ech_is_inner, on the server, indicates whether the ClientHello contained an
1951   // inner ECH extension.
1952   bool ech_is_inner : 1;
1953 
1954   // ech_authenticated_reject, on the client, indicates whether an ECH rejection
1955   // handshake has been authenticated.
1956   bool ech_authenticated_reject : 1;
1957 
1958   // scts_requested is true if the SCT extension is in the ClientHello.
1959   bool scts_requested : 1;
1960 
1961   // handshake_finalized is true once the handshake has completed, at which
1962   // point accessors should use the established state.
1963   bool handshake_finalized : 1;
1964 
1965   // accept_psk_mode stores whether the client's PSK mode is compatible with our
1966   // preferences.
1967   bool accept_psk_mode : 1;
1968 
1969   // cert_request is true if a client certificate was requested.
1970   bool cert_request : 1;
1971 
1972   // certificate_status_expected is true if OCSP stapling was negotiated and the
1973   // server is expected to send a CertificateStatus message. (This is used on
1974   // both the client and server sides.)
1975   bool certificate_status_expected : 1;
1976 
1977   // ocsp_stapling_requested is true if a client requested OCSP stapling.
1978   bool ocsp_stapling_requested : 1;
1979 
1980   // delegated_credential_requested is true if the peer indicated support for
1981   // the delegated credential extension.
1982   bool delegated_credential_requested : 1;
1983 
1984   // should_ack_sni is used by a server and indicates that the SNI extension
1985   // should be echoed in the ServerHello.
1986   bool should_ack_sni : 1;
1987 
1988   // in_false_start is true if there is a pending client handshake in False
1989   // Start. The client may write data at this point.
1990   bool in_false_start : 1;
1991 
1992   // in_early_data is true if there is a pending handshake that has progressed
1993   // enough to send and receive early data.
1994   bool in_early_data : 1;
1995 
1996   // early_data_offered is true if the client sent the early_data extension.
1997   bool early_data_offered : 1;
1998 
1999   // can_early_read is true if application data may be read at this point in the
2000   // handshake.
2001   bool can_early_read : 1;
2002 
2003   // can_early_write is true if application data may be written at this point in
2004   // the handshake.
2005   bool can_early_write : 1;
2006 
2007   // next_proto_neg_seen is one of NPN was negotiated.
2008   bool next_proto_neg_seen : 1;
2009 
2010   // ticket_expected is true if a TLS 1.2 NewSessionTicket message is to be sent
2011   // or received.
2012   bool ticket_expected : 1;
2013 
2014   // extended_master_secret is true if the extended master secret extension is
2015   // negotiated in this handshake.
2016   bool extended_master_secret : 1;
2017 
2018   // pending_private_key_op is true if there is a pending private key operation
2019   // in progress.
2020   bool pending_private_key_op : 1;
2021 
2022   // handback indicates that a server should pause the handshake after
2023   // finishing operations that require private key material, in such a way that
2024   // |SSL_get_error| returns |SSL_ERROR_HANDBACK|.  It is set by
2025   // |SSL_apply_handoff|.
2026   bool handback : 1;
2027 
2028   // hints_requested indicates the caller has requested handshake hints. Only
2029   // the first round-trip of the handshake will complete, after which the
2030   // |hints| structure can be serialized.
2031   bool hints_requested : 1;
2032 
2033   // cert_compression_negotiated is true iff |cert_compression_alg_id| is valid.
2034   bool cert_compression_negotiated : 1;
2035 
2036   // apply_jdk11_workaround is true if the peer is probably a JDK 11 client
2037   // which implemented TLS 1.3 incorrectly.
2038   bool apply_jdk11_workaround : 1;
2039 
2040   // can_release_private_key is true if the private key will no longer be used
2041   // in this handshake.
2042   bool can_release_private_key : 1;
2043 
2044   // channel_id_negotiated is true if Channel ID should be used in this
2045   // handshake.
2046   bool channel_id_negotiated : 1;
2047 
2048   // client_version is the value sent or received in the ClientHello version.
2049   uint16_t client_version = 0;
2050 
2051   // early_data_read is the amount of early data that has been read by the
2052   // record layer.
2053   uint16_t early_data_read = 0;
2054 
2055   // early_data_written is the amount of early data that has been written by the
2056   // record layer.
2057   uint16_t early_data_written = 0;
2058 
2059   // ech_config_id is the ECH config sent by the client.
2060   uint8_t ech_config_id = 0;
2061 
2062   // session_id is the session ID in the ClientHello.
2063   uint8_t session_id[SSL_MAX_SSL_SESSION_ID_LENGTH] = {0};
2064   uint8_t session_id_len = 0;
2065 
2066   // grease_seed is the entropy for GREASE values.
2067   uint8_t grease_seed[ssl_grease_last_index + 1] = {0};
2068 };
2069 
2070 // kMaxTickets is the maximum number of tickets to send immediately after the
2071 // handshake. We use a one-byte ticket nonce, and there is no point in sending
2072 // so many tickets.
2073 constexpr size_t kMaxTickets = 16;
2074 
2075 UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl);
2076 
2077 // ssl_check_message_type checks if |msg| has type |type|. If so it returns
2078 // one. Otherwise, it sends an alert and returns zero.
2079 bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type);
2080 
2081 // ssl_run_handshake runs the TLS handshake. It returns one on success and <= 0
2082 // on error. It sets |out_early_return| to one if we've completed the handshake
2083 // early.
2084 int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return);
2085 
2086 // The following are implementations of |do_handshake| for the client and
2087 // server.
2088 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs);
2089 enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs);
2090 enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs);
2091 enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs);
2092 
2093 // The following functions return human-readable representations of the TLS
2094 // handshake states for debugging.
2095 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs);
2096 const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs);
2097 const char *tls13_client_handshake_state(SSL_HANDSHAKE *hs);
2098 const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs);
2099 
2100 // tls13_add_key_update queues a KeyUpdate message on |ssl|. The
2101 // |update_requested| argument must be one of |SSL_KEY_UPDATE_REQUESTED| or
2102 // |SSL_KEY_UPDATE_NOT_REQUESTED|.
2103 bool tls13_add_key_update(SSL *ssl, int update_requested);
2104 
2105 // tls13_post_handshake processes a post-handshake message. It returns true on
2106 // success and false on failure.
2107 bool tls13_post_handshake(SSL *ssl, const SSLMessage &msg);
2108 
2109 bool tls13_process_certificate(SSL_HANDSHAKE *hs, const SSLMessage &msg,
2110                                bool allow_anonymous);
2111 bool tls13_process_certificate_verify(SSL_HANDSHAKE *hs, const SSLMessage &msg);
2112 
2113 // tls13_process_finished processes |msg| as a Finished message from the
2114 // peer. If |use_saved_value| is true, the verify_data is compared against
2115 // |hs->expected_client_finished| rather than computed fresh.
2116 bool tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg,
2117                             bool use_saved_value);
2118 
2119 bool tls13_add_certificate(SSL_HANDSHAKE *hs);
2120 
2121 // tls13_add_certificate_verify adds a TLS 1.3 CertificateVerify message to the
2122 // handshake. If it returns |ssl_private_key_retry|, it should be called again
2123 // to retry when the signing operation is completed.
2124 enum ssl_private_key_result_t tls13_add_certificate_verify(SSL_HANDSHAKE *hs);
2125 
2126 bool tls13_add_finished(SSL_HANDSHAKE *hs);
2127 bool tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg);
2128 bssl::UniquePtr<SSL_SESSION> tls13_create_session_with_ticket(SSL *ssl,
2129                                                               CBS *body);
2130 
2131 // ssl_setup_extension_permutation computes a ClientHello extension permutation
2132 // for |hs|, if applicable. It returns true on success and false on error.
2133 bool ssl_setup_extension_permutation(SSL_HANDSHAKE *hs);
2134 
2135 // ssl_setup_key_shares computes client key shares and saves them in |hs|. It
2136 // returns true on success and false on failure. If |override_group_id| is zero,
2137 // it offers the default groups, including GREASE. If it is non-zero, it offers
2138 // a single key share of the specified group.
2139 bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id);
2140 
2141 bool ssl_ext_key_share_parse_serverhello(SSL_HANDSHAKE *hs,
2142                                          Array<uint8_t> *out_secret,
2143                                          uint8_t *out_alert, CBS *contents);
2144 bool ssl_ext_key_share_parse_clienthello(SSL_HANDSHAKE *hs, bool *out_found,
2145                                          Span<const uint8_t> *out_peer_key,
2146                                          uint8_t *out_alert,
2147                                          const SSL_CLIENT_HELLO *client_hello);
2148 bool ssl_ext_key_share_add_serverhello(SSL_HANDSHAKE *hs, CBB *out);
2149 
2150 bool ssl_ext_pre_shared_key_parse_serverhello(SSL_HANDSHAKE *hs,
2151                                               uint8_t *out_alert,
2152                                               CBS *contents);
2153 bool ssl_ext_pre_shared_key_parse_clienthello(
2154     SSL_HANDSHAKE *hs, CBS *out_ticket, CBS *out_binders,
2155     uint32_t *out_obfuscated_ticket_age, uint8_t *out_alert,
2156     const SSL_CLIENT_HELLO *client_hello, CBS *contents);
2157 bool ssl_ext_pre_shared_key_add_serverhello(SSL_HANDSHAKE *hs, CBB *out);
2158 
2159 // ssl_is_sct_list_valid does a shallow parse of the SCT list in |contents| and
2160 // returns whether it's valid.
2161 bool ssl_is_sct_list_valid(const CBS *contents);
2162 
2163 // ssl_write_client_hello_without_extensions writes a ClientHello to |out|,
2164 // up to the extensions field. |type| determines the type of ClientHello to
2165 // write. If |omit_session_id| is true, the session ID is empty.
2166 bool ssl_write_client_hello_without_extensions(const SSL_HANDSHAKE *hs,
2167                                                CBB *cbb,
2168                                                ssl_client_hello_type_t type,
2169                                                bool empty_session_id);
2170 
2171 // ssl_add_client_hello constructs a ClientHello and adds it to the outgoing
2172 // flight. It returns true on success and false on error.
2173 bool ssl_add_client_hello(SSL_HANDSHAKE *hs);
2174 
2175 struct ParsedServerHello {
2176   CBS raw;
2177   uint16_t legacy_version = 0;
2178   CBS random;
2179   CBS session_id;
2180   uint16_t cipher_suite = 0;
2181   uint8_t compression_method = 0;
2182   CBS extensions;
2183 };
2184 
2185 // ssl_parse_server_hello parses |msg| as a ServerHello. On success, it writes
2186 // the result to |*out| and returns true. Otherwise, it returns false and sets
2187 // |*out_alert| to an alert to send to the peer.
2188 bool ssl_parse_server_hello(ParsedServerHello *out, uint8_t *out_alert,
2189                             const SSLMessage &msg);
2190 
2191 enum ssl_cert_verify_context_t {
2192   ssl_cert_verify_server,
2193   ssl_cert_verify_client,
2194   ssl_cert_verify_channel_id,
2195 };
2196 
2197 // tls13_get_cert_verify_signature_input generates the message to be signed for
2198 // TLS 1.3's CertificateVerify message. |cert_verify_context| determines the
2199 // type of signature. It sets |*out| to a newly allocated buffer containing the
2200 // result. This function returns true on success and false on failure.
2201 bool tls13_get_cert_verify_signature_input(
2202     SSL_HANDSHAKE *hs, Array<uint8_t> *out,
2203     enum ssl_cert_verify_context_t cert_verify_context);
2204 
2205 // ssl_is_valid_alpn_list returns whether |in| is a valid ALPN protocol list.
2206 bool ssl_is_valid_alpn_list(Span<const uint8_t> in);
2207 
2208 // ssl_is_alpn_protocol_allowed returns whether |protocol| is a valid server
2209 // selection for |hs->ssl|'s client preferences.
2210 bool ssl_is_alpn_protocol_allowed(const SSL_HANDSHAKE *hs,
2211                                   Span<const uint8_t> protocol);
2212 
2213 // ssl_negotiate_alpn negotiates the ALPN extension, if applicable. It returns
2214 // true on successful negotiation or if nothing was negotiated. It returns false
2215 // and sets |*out_alert| to an alert on error.
2216 bool ssl_negotiate_alpn(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2217                         const SSL_CLIENT_HELLO *client_hello);
2218 
2219 // ssl_get_local_application_settings looks up the configured ALPS value for
2220 // |protocol|. If found, it sets |*out_settings| to the value and returns true.
2221 // Otherwise, it returns false.
2222 bool ssl_get_local_application_settings(const SSL_HANDSHAKE *hs,
2223                                         Span<const uint8_t> *out_settings,
2224                                         Span<const uint8_t> protocol);
2225 
2226 // ssl_negotiate_alps negotiates the ALPS extension, if applicable. It returns
2227 // true on successful negotiation or if nothing was negotiated. It returns false
2228 // and sets |*out_alert| to an alert on error.
2229 bool ssl_negotiate_alps(SSL_HANDSHAKE *hs, uint8_t *out_alert,
2230                         const SSL_CLIENT_HELLO *client_hello);
2231 
2232 struct SSLExtension {
2233   SSLExtension(uint16_t type_arg, bool allowed_arg = true)
2234       : type(type_arg), allowed(allowed_arg), present(false) {
2235     CBS_init(&data, nullptr, 0);
2236   }
2237 
2238   uint16_t type;
2239   bool allowed;
2240   bool present;
2241   CBS data;
2242 };
2243 
2244 // ssl_parse_extensions parses a TLS extensions block out of |cbs| and advances
2245 // it. It writes the parsed extensions to pointers in |extensions|. On success,
2246 // it fills in the |present| and |data| fields and returns true. Otherwise, it
2247 // sets |*out_alert| to an alert to send and returns false. Unknown extensions
2248 // are rejected unless |ignore_unknown| is true.
2249 bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
2250                           std::initializer_list<SSLExtension *> extensions,
2251                           bool ignore_unknown);
2252 
2253 // ssl_verify_peer_cert verifies the peer certificate for |hs|.
2254 enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs);
2255 // ssl_reverify_peer_cert verifies the peer certificate for |hs| when resuming a
2256 // session.
2257 enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs,
2258                                                 bool send_alert);
2259 
2260 enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs);
2261 bool ssl_send_finished(SSL_HANDSHAKE *hs);
2262 bool ssl_output_cert_chain(SSL_HANDSHAKE *hs);
2263 
2264 // ssl_handshake_session returns the |SSL_SESSION| corresponding to the current
2265 // handshake. Note, in TLS 1.2 resumptions, this session is immutable.
2266 const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs);
2267 
2268 // ssl_done_writing_client_hello is called after the last ClientHello is written
2269 // by |hs|. It releases some memory that is no longer needed.
2270 void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs);
2271 
2272 
2273 // SSLKEYLOGFILE functions.
2274 
2275 // ssl_log_secret logs |secret| with label |label|, if logging is enabled for
2276 // |ssl|. It returns true on success and false on failure.
2277 bool ssl_log_secret(const SSL *ssl, const char *label,
2278                     Span<const uint8_t> secret);
2279 
2280 
2281 // ClientHello functions.
2282 
2283 // ssl_client_hello_init parses |body| as a ClientHello message, excluding the
2284 // message header, and writes the result to |*out|. It returns true on success
2285 // and false on error. This function is exported for testing.
2286 OPENSSL_EXPORT bool ssl_client_hello_init(const SSL *ssl, SSL_CLIENT_HELLO *out,
2287                                           Span<const uint8_t> body);
2288 
2289 bool ssl_parse_client_hello_with_trailing_data(const SSL *ssl, CBS *cbs,
2290                                                SSL_CLIENT_HELLO *out);
2291 
2292 bool ssl_client_hello_get_extension(const SSL_CLIENT_HELLO *client_hello,
2293                                     CBS *out, uint16_t extension_type);
2294 
2295 bool ssl_client_cipher_list_contains_cipher(
2296     const SSL_CLIENT_HELLO *client_hello, uint16_t id);
2297 
2298 
2299 // GREASE.
2300 
2301 // ssl_get_grease_value returns a GREASE value for |hs|. For a given
2302 // connection, the values for each index will be deterministic. This allows the
2303 // same ClientHello be sent twice for a HelloRetryRequest or the same group be
2304 // advertised in both supported_groups and key_shares.
2305 uint16_t ssl_get_grease_value(const SSL_HANDSHAKE *hs,
2306                               enum ssl_grease_index_t index);
2307 
2308 
2309 // Signature algorithms.
2310 
2311 // tls1_parse_peer_sigalgs parses |sigalgs| as the list of peer signature
2312 // algorithms and saves them on |hs|. It returns true on success and false on
2313 // error.
2314 bool tls1_parse_peer_sigalgs(SSL_HANDSHAKE *hs, const CBS *sigalgs);
2315 
2316 // tls1_get_legacy_signature_algorithm sets |*out| to the signature algorithm
2317 // that should be used with |pkey| in TLS 1.1 and earlier. It returns true on
2318 // success and false if |pkey| may not be used at those versions.
2319 bool tls1_get_legacy_signature_algorithm(uint16_t *out, const EVP_PKEY *pkey);
2320 
2321 // tls1_choose_signature_algorithm sets |*out| to a signature algorithm for use
2322 // with |hs|'s private key based on the peer's preferences and the algorithms
2323 // supported. It returns true on success and false on error.
2324 bool tls1_choose_signature_algorithm(SSL_HANDSHAKE *hs, uint16_t *out);
2325 
2326 // tls1_get_peer_verify_algorithms returns the signature schemes for which the
2327 // peer indicated support.
2328 //
2329 // NOTE: The related function |SSL_get0_peer_verify_algorithms| only has
2330 // well-defined behavior during the callbacks set by |SSL_CTX_set_cert_cb| and
2331 // |SSL_CTX_set_client_cert_cb|, or when the handshake is paused because of
2332 // them.
2333 Span<const uint16_t> tls1_get_peer_verify_algorithms(const SSL_HANDSHAKE *hs);
2334 
2335 // tls12_add_verify_sigalgs adds the signature algorithms acceptable for the
2336 // peer signature to |out|. It returns true on success and false on error.
2337 bool tls12_add_verify_sigalgs(const SSL_HANDSHAKE *hs, CBB *out);
2338 
2339 // tls12_check_peer_sigalg checks if |sigalg| is acceptable for the peer
2340 // signature. It returns true on success and false on error, setting
2341 // |*out_alert| to an alert to send.
2342 bool tls12_check_peer_sigalg(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
2343                              uint16_t sigalg);
2344 
2345 
2346 // Underdocumented functions.
2347 //
2348 // Functions below here haven't been touched up and may be underdocumented.
2349 
2350 #define TLSEXT_CHANNEL_ID_SIZE 128
2351 
2352 // From RFC 4492, used in encoding the curve type in ECParameters
2353 #define NAMED_CURVE_TYPE 3
2354 
2355 struct CERT {
2356   static constexpr bool kAllowUniquePtr = true;
2357 
2358   explicit CERT(const SSL_X509_METHOD *x509_method);
2359   ~CERT();
2360 
2361   UniquePtr<EVP_PKEY> privatekey;
2362 
2363   // chain contains the certificate chain, with the leaf at the beginning. The
2364   // first element of |chain| may be NULL to indicate that the leaf certificate
2365   // has not yet been set.
2366   //   If |chain| != NULL -> len(chain) >= 1
2367   //   If |chain[0]| == NULL -> len(chain) >= 2.
2368   //   |chain[1..]| != NULL
2369   UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain;
2370 
2371   // x509_chain may contain a parsed copy of |chain[1..]|. This is only used as
2372   // a cache in order to implement “get0” functions that return a non-owning
2373   // pointer to the certificate chain.
2374   STACK_OF(X509) *x509_chain = nullptr;
2375 
2376   // x509_leaf may contain a parsed copy of the first element of |chain|. This
2377   // is only used as a cache in order to implement “get0” functions that return
2378   // a non-owning pointer to the certificate chain.
2379   X509 *x509_leaf = nullptr;
2380 
2381   // x509_stash contains the last |X509| object append to the chain. This is a
2382   // workaround for some third-party code that continue to use an |X509| object
2383   // even after passing ownership with an “add0” function.
2384   X509 *x509_stash = nullptr;
2385 
2386   // key_method, if non-NULL, is a set of callbacks to call for private key
2387   // operations.
2388   const SSL_PRIVATE_KEY_METHOD *key_method = nullptr;
2389 
2390   // x509_method contains pointers to functions that might deal with |X509|
2391   // compatibility, or might be a no-op, depending on the application.
2392   const SSL_X509_METHOD *x509_method = nullptr;
2393 
2394   // sigalgs, if non-empty, is the set of signature algorithms supported by
2395   // |privatekey| in decreasing order of preference.
2396   Array<uint16_t> sigalgs;
2397 
2398   // Certificate setup callback: if set is called whenever a
2399   // certificate may be required (client or server). the callback
2400   // can then examine any appropriate parameters and setup any
2401   // certificates required. This allows advanced applications
2402   // to select certificates on the fly: for example based on
2403   // supported signature algorithms or curves.
2404   int (*cert_cb)(SSL *ssl, void *arg) = nullptr;
2405   void *cert_cb_arg = nullptr;
2406 
2407   // Optional X509_STORE for certificate validation. If NULL the parent SSL_CTX
2408   // store is used instead.
2409   X509_STORE *verify_store = nullptr;
2410 
2411   // Signed certificate timestamp list to be sent to the client, if requested
2412   UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list;
2413 
2414   // OCSP response to be sent to the client, if requested.
2415   UniquePtr<CRYPTO_BUFFER> ocsp_response;
2416 
2417   // sid_ctx partitions the session space within a shared session cache or
2418   // ticket key. Only sessions with a matching value will be accepted.
2419   uint8_t sid_ctx_length = 0;
2420   uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH] = {0};
2421 
2422   // Delegated credentials.
2423 
2424   // dc is the delegated credential to send to the peer (if requested).
2425   UniquePtr<DC> dc = nullptr;
2426 
2427   // dc_privatekey is used instead of |privatekey| or |key_method| to
2428   // authenticate the host if a delegated credential is used in the handshake.
2429   UniquePtr<EVP_PKEY> dc_privatekey = nullptr;
2430 
2431   // dc_key_method, if not NULL, is used instead of |dc_privatekey| to
2432   // authenticate the host.
2433   const SSL_PRIVATE_KEY_METHOD *dc_key_method = nullptr;
2434 };
2435 
2436 // |SSL_PROTOCOL_METHOD| abstracts between TLS and DTLS.
2437 struct SSL_PROTOCOL_METHOD {
2438   bool is_dtls;
2439   bool (*ssl_new)(SSL *ssl);
2440   void (*ssl_free)(SSL *ssl);
2441   // get_message sets |*out| to the current handshake message and returns true
2442   // if one has been received. It returns false if more input is needed.
2443   bool (*get_message)(const SSL *ssl, SSLMessage *out);
2444   // next_message is called to release the current handshake message.
2445   void (*next_message)(SSL *ssl);
2446   // has_unprocessed_handshake_data returns whether there is buffered
2447   // handshake data that has not been consumed by |get_message|.
2448   bool (*has_unprocessed_handshake_data)(const SSL *ssl);
2449   // Use the |ssl_open_handshake| wrapper.
2450   ssl_open_record_t (*open_handshake)(SSL *ssl, size_t *out_consumed,
2451                                       uint8_t *out_alert, Span<uint8_t> in);
2452   // Use the |ssl_open_change_cipher_spec| wrapper.
2453   ssl_open_record_t (*open_change_cipher_spec)(SSL *ssl, size_t *out_consumed,
2454                                                uint8_t *out_alert,
2455                                                Span<uint8_t> in);
2456   // Use the |ssl_open_app_data| wrapper.
2457   ssl_open_record_t (*open_app_data)(SSL *ssl, Span<uint8_t> *out,
2458                                      size_t *out_consumed, uint8_t *out_alert,
2459                                      Span<uint8_t> in);
2460   // write_app_data encrypts and writes |in| as application data. On success, it
2461   // returns one and sets |*out_bytes_written| to the number of bytes of |in|
2462   // written. Otherwise, it returns <= 0 and sets |*out_needs_handshake| to
2463   // whether the operation failed because the caller needs to drive the
2464   // handshake.
2465   int (*write_app_data)(SSL *ssl, bool *out_needs_handshake,
2466                         size_t *out_bytes_written, Span<const uint8_t> in);
2467   int (*dispatch_alert)(SSL *ssl);
2468   // init_message begins a new handshake message of type |type|. |cbb| is the
2469   // root CBB to be passed into |finish_message|. |*body| is set to a child CBB
2470   // the caller should write to. It returns true on success and false on error.
2471   bool (*init_message)(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
2472   // finish_message finishes a handshake message. It sets |*out_msg| to the
2473   // serialized message. It returns true on success and false on error.
2474   bool (*finish_message)(const SSL *ssl, CBB *cbb,
2475                          bssl::Array<uint8_t> *out_msg);
2476   // add_message adds a handshake message to the pending flight. It returns
2477   // true on success and false on error.
2478   bool (*add_message)(SSL *ssl, bssl::Array<uint8_t> msg);
2479   // add_change_cipher_spec adds a ChangeCipherSpec record to the pending
2480   // flight. It returns true on success and false on error.
2481   bool (*add_change_cipher_spec)(SSL *ssl);
2482   // flush_flight flushes the pending flight to the transport. It returns one on
2483   // success and <= 0 on error.
2484   int (*flush_flight)(SSL *ssl);
2485   // on_handshake_complete is called when the handshake is complete.
2486   void (*on_handshake_complete)(SSL *ssl);
2487   // set_read_state sets |ssl|'s read cipher state and level to |aead_ctx| and
2488   // |level|. In QUIC, |aead_ctx| is a placeholder object and |secret_for_quic|
2489   // is the original secret. This function returns true on success and false on
2490   // error.
2491   bool (*set_read_state)(SSL *ssl, ssl_encryption_level_t level,
2492                          UniquePtr<SSLAEADContext> aead_ctx,
2493                          Span<const uint8_t> secret_for_quic);
2494   // set_write_state sets |ssl|'s write cipher state and level to |aead_ctx| and
2495   // |level|. In QUIC, |aead_ctx| is a placeholder object and |secret_for_quic|
2496   // is the original secret. This function returns true on success and false on
2497   // error.
2498   bool (*set_write_state)(SSL *ssl, ssl_encryption_level_t level,
2499                           UniquePtr<SSLAEADContext> aead_ctx,
2500                           Span<const uint8_t> secret_for_quic);
2501 };
2502 
2503 // The following wrappers call |open_*| but handle |read_shutdown| correctly.
2504 
2505 // ssl_open_handshake processes a record from |in| for reading a handshake
2506 // message.
2507 ssl_open_record_t ssl_open_handshake(SSL *ssl, size_t *out_consumed,
2508                                      uint8_t *out_alert, Span<uint8_t> in);
2509 
2510 // ssl_open_change_cipher_spec processes a record from |in| for reading a
2511 // ChangeCipherSpec.
2512 ssl_open_record_t ssl_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
2513                                               uint8_t *out_alert,
2514                                               Span<uint8_t> in);
2515 
2516 // ssl_open_app_data processes a record from |in| for reading application data.
2517 // On success, it returns |ssl_open_record_success| and sets |*out| to the
2518 // input. If it encounters a post-handshake message, it returns
2519 // |ssl_open_record_discard|. The caller should then retry, after processing any
2520 // messages received with |get_message|.
2521 ssl_open_record_t ssl_open_app_data(SSL *ssl, Span<uint8_t> *out,
2522                                     size_t *out_consumed, uint8_t *out_alert,
2523                                     Span<uint8_t> in);
2524 
2525 struct SSL_X509_METHOD {
2526   // check_client_CA_list returns one if |names| is a good list of X.509
2527   // distinguished names and zero otherwise. This is used to ensure that we can
2528   // reject unparsable values at handshake time when using crypto/x509.
2529   bool (*check_client_CA_list)(STACK_OF(CRYPTO_BUFFER) *names);
2530 
2531   // cert_clear frees and NULLs all X509 certificate-related state.
2532   void (*cert_clear)(CERT *cert);
2533   // cert_free frees all X509-related state.
2534   void (*cert_free)(CERT *cert);
2535   // cert_flush_cached_chain drops any cached |X509|-based certificate chain
2536   // from |cert|.
2537   // cert_dup duplicates any needed fields from |cert| to |new_cert|.
2538   void (*cert_dup)(CERT *new_cert, const CERT *cert);
2539   void (*cert_flush_cached_chain)(CERT *cert);
2540   // cert_flush_cached_chain drops any cached |X509|-based leaf certificate
2541   // from |cert|.
2542   void (*cert_flush_cached_leaf)(CERT *cert);
2543 
2544   // session_cache_objects fills out |sess->x509_peer| and |sess->x509_chain|
2545   // from |sess->certs| and erases |sess->x509_chain_without_leaf|. It returns
2546   // true on success or false on error.
2547   bool (*session_cache_objects)(SSL_SESSION *session);
2548   // session_dup duplicates any needed fields from |session| to |new_session|.
2549   // It returns true on success or false on error.
2550   bool (*session_dup)(SSL_SESSION *new_session, const SSL_SESSION *session);
2551   // session_clear frees any X509-related state from |session|.
2552   void (*session_clear)(SSL_SESSION *session);
2553   // session_verify_cert_chain verifies the certificate chain in |session|,
2554   // sets |session->verify_result| and returns true on success or false on
2555   // error.
2556   bool (*session_verify_cert_chain)(SSL_SESSION *session, SSL_HANDSHAKE *ssl,
2557                                     uint8_t *out_alert);
2558 
2559   // hs_flush_cached_ca_names drops any cached |X509_NAME|s from |hs|.
2560   void (*hs_flush_cached_ca_names)(SSL_HANDSHAKE *hs);
2561   // ssl_new does any necessary initialisation of |hs|. It returns true on
2562   // success or false on error.
2563   bool (*ssl_new)(SSL_HANDSHAKE *hs);
2564   // ssl_free frees anything created by |ssl_new|.
2565   void (*ssl_config_free)(SSL_CONFIG *cfg);
2566   // ssl_flush_cached_client_CA drops any cached |X509_NAME|s from |ssl|.
2567   void (*ssl_flush_cached_client_CA)(SSL_CONFIG *cfg);
2568   // ssl_auto_chain_if_needed runs the deprecated auto-chaining logic if
2569   // necessary. On success, it updates |ssl|'s certificate configuration as
2570   // needed and returns true. Otherwise, it returns false.
2571   bool (*ssl_auto_chain_if_needed)(SSL_HANDSHAKE *hs);
2572   // ssl_ctx_new does any necessary initialisation of |ctx|. It returns true on
2573   // success or false on error.
2574   bool (*ssl_ctx_new)(SSL_CTX *ctx);
2575   // ssl_ctx_free frees anything created by |ssl_ctx_new|.
2576   void (*ssl_ctx_free)(SSL_CTX *ctx);
2577   // ssl_ctx_flush_cached_client_CA drops any cached |X509_NAME|s from |ctx|.
2578   void (*ssl_ctx_flush_cached_client_CA)(SSL_CTX *ssl);
2579 };
2580 
2581 // ssl_crypto_x509_method provides the |SSL_X509_METHOD| functions using
2582 // crypto/x509.
2583 extern const SSL_X509_METHOD ssl_crypto_x509_method;
2584 
2585 // ssl_noop_x509_method provides the |SSL_X509_METHOD| functions that avoid
2586 // crypto/x509.
2587 extern const SSL_X509_METHOD ssl_noop_x509_method;
2588 
2589 struct TicketKey {
2590   static constexpr bool kAllowUniquePtr = true;
2591 
2592   uint8_t name[SSL_TICKET_KEY_NAME_LEN] = {0};
2593   uint8_t hmac_key[16] = {0};
2594   uint8_t aes_key[16] = {0};
2595   // next_rotation_tv_sec is the time (in seconds from the epoch) when the
2596   // current key should be superseded by a new key, or the time when a previous
2597   // key should be dropped. If zero, then the key should not be automatically
2598   // rotated.
2599   uint64_t next_rotation_tv_sec = 0;
2600 };
2601 
2602 struct CertCompressionAlg {
2603   static constexpr bool kAllowUniquePtr = true;
2604 
2605   ssl_cert_compression_func_t compress = nullptr;
2606   ssl_cert_decompression_func_t decompress = nullptr;
2607   uint16_t alg_id = 0;
2608 };
2609 
2610 BSSL_NAMESPACE_END
2611 
2612 DEFINE_LHASH_OF(SSL_SESSION)
2613 
2614 BSSL_NAMESPACE_BEGIN
2615 
2616 // An ssl_shutdown_t describes the shutdown state of one end of the connection,
2617 // whether it is alive or has been shutdown via close_notify or fatal alert.
2618 enum ssl_shutdown_t {
2619   ssl_shutdown_none = 0,
2620   ssl_shutdown_close_notify = 1,
2621   ssl_shutdown_error = 2,
2622 };
2623 
2624 enum ssl_ech_status_t {
2625   // ssl_ech_none indicates ECH was not offered, or we have not gotten far
2626   // enough in the handshake to determine the status.
2627   ssl_ech_none,
2628   // ssl_ech_accepted indicates the server accepted ECH.
2629   ssl_ech_accepted,
2630   // ssl_ech_rejected indicates the server was offered ECH but rejected it.
2631   ssl_ech_rejected,
2632 };
2633 
2634 struct SSL3_STATE {
2635   static constexpr bool kAllowUniquePtr = true;
2636 
2637   SSL3_STATE();
2638   ~SSL3_STATE();
2639 
2640   uint64_t read_sequence = 0;
2641   uint64_t write_sequence = 0;
2642 
2643   uint8_t server_random[SSL3_RANDOM_SIZE] = {0};
2644   uint8_t client_random[SSL3_RANDOM_SIZE] = {0};
2645 
2646   // read_buffer holds data from the transport to be processed.
2647   SSLBuffer read_buffer;
2648   // write_buffer holds data to be written to the transport.
2649   SSLBuffer write_buffer;
2650 
2651   // pending_app_data is the unconsumed application data. It points into
2652   // |read_buffer|.
2653   Span<uint8_t> pending_app_data;
2654 
2655   // unreported_bytes_written is the number of bytes successfully written to the
2656   // transport, but not yet reported to the caller. The next |SSL_write| will
2657   // skip this many bytes from the input. This is used if
2658   // |SSL_MODE_ENABLE_PARTIAL_WRITE| is disabled, in which case |SSL_write| only
2659   // reports bytes written when the full caller input is written.
2660   size_t unreported_bytes_written = 0;
2661 
2662   // pending_write, if |has_pending_write| is true, is the caller-supplied data
2663   // corresponding to the current pending write. This is used to check the
2664   // caller retried with a compatible buffer.
2665   Span<const uint8_t> pending_write;
2666 
2667   // pending_write_type, if |has_pending_write| is true, is the record type
2668   // for the current pending write.
2669   //
2670   // TODO(davidben): Remove this when alerts are moved out of this write path.
2671   uint8_t pending_write_type = 0;
2672 
2673   // read_shutdown is the shutdown state for the read half of the connection.
2674   enum ssl_shutdown_t read_shutdown = ssl_shutdown_none;
2675 
2676   // write_shutdown is the shutdown state for the write half of the connection.
2677   enum ssl_shutdown_t write_shutdown = ssl_shutdown_none;
2678 
2679   // read_error, if |read_shutdown| is |ssl_shutdown_error|, is the error for
2680   // the receive half of the connection.
2681   UniquePtr<ERR_SAVE_STATE> read_error;
2682 
2683   int total_renegotiations = 0;
2684 
2685   // This holds a variable that indicates what we were doing when a 0 or -1 is
2686   // returned.  This is needed for non-blocking IO so we know what request
2687   // needs re-doing when in SSL_accept or SSL_connect
2688   int rwstate = SSL_ERROR_NONE;
2689 
2690   enum ssl_encryption_level_t read_level = ssl_encryption_initial;
2691   enum ssl_encryption_level_t write_level = ssl_encryption_initial;
2692 
2693   // early_data_skipped is the amount of early data that has been skipped by the
2694   // record layer.
2695   uint16_t early_data_skipped = 0;
2696 
2697   // empty_record_count is the number of consecutive empty records received.
2698   uint8_t empty_record_count = 0;
2699 
2700   // warning_alert_count is the number of consecutive warning alerts
2701   // received.
2702   uint8_t warning_alert_count = 0;
2703 
2704   // key_update_count is the number of consecutive KeyUpdates received.
2705   uint8_t key_update_count = 0;
2706 
2707   // ech_status indicates whether ECH was accepted by the server.
2708   ssl_ech_status_t ech_status = ssl_ech_none;
2709 
2710   // skip_early_data instructs the record layer to skip unexpected early data
2711   // messages when 0RTT is rejected.
2712   bool skip_early_data : 1;
2713 
2714   // have_version is true if the connection's final version is known. Otherwise
2715   // the version has not been negotiated yet.
2716   bool have_version : 1;
2717 
2718   // v2_hello_done is true if the peer's V2ClientHello, if any, has been handled
2719   // and future messages should use the record layer.
2720   bool v2_hello_done : 1;
2721 
2722   // is_v2_hello is true if the current handshake message was derived from a
2723   // V2ClientHello rather than received from the peer directly.
2724   bool is_v2_hello : 1;
2725 
2726   // has_message is true if the current handshake message has been returned
2727   // at least once by |get_message| and false otherwise.
2728   bool has_message : 1;
2729 
2730   // initial_handshake_complete is true if the initial handshake has
2731   // completed.
2732   bool initial_handshake_complete : 1;
2733 
2734   // session_reused indicates whether a session was resumed.
2735   bool session_reused : 1;
2736 
2737   // delegated_credential_used is whether we presented a delegated credential to
2738   // the peer.
2739   bool delegated_credential_used : 1;
2740 
2741   bool send_connection_binding : 1;
2742 
2743   // channel_id_valid is true if, on the server, the client has negotiated a
2744   // Channel ID and the |channel_id| field is filled in.
2745   bool channel_id_valid : 1;
2746 
2747   // key_update_pending is true if we have a KeyUpdate acknowledgment
2748   // outstanding.
2749   bool key_update_pending : 1;
2750 
2751   // early_data_accepted is true if early data was accepted by the server.
2752   bool early_data_accepted : 1;
2753 
2754   // alert_dispatch is true there is an alert in |send_alert| to be sent.
2755   bool alert_dispatch : 1;
2756 
2757   // renegotiate_pending is whether the read half of the channel is blocked on a
2758   // HelloRequest.
2759   bool renegotiate_pending : 1;
2760 
2761   // used_hello_retry_request is whether the handshake used a TLS 1.3
2762   // HelloRetryRequest message.
2763   bool used_hello_retry_request : 1;
2764 
2765   // was_key_usage_invalid is whether the handshake succeeded despite using a
2766   // TLS mode which was incompatible with the leaf certificate's keyUsage
2767   // extension.
2768   bool was_key_usage_invalid : 1;
2769 
2770   // hs_buf is the buffer of handshake data to process.
2771   UniquePtr<BUF_MEM> hs_buf;
2772 
2773   // pending_hs_data contains the pending handshake data that has not yet
2774   // been encrypted to |pending_flight|. This allows packing the handshake into
2775   // fewer records.
2776   UniquePtr<BUF_MEM> pending_hs_data;
2777 
2778   // pending_flight is the pending outgoing flight. This is used to flush each
2779   // handshake flight in a single write. |write_buffer| must be written out
2780   // before this data.
2781   UniquePtr<BUF_MEM> pending_flight;
2782 
2783   // pending_flight_offset is the number of bytes of |pending_flight| which have
2784   // been successfully written.
2785   uint32_t pending_flight_offset = 0;
2786 
2787   // ticket_age_skew is the difference, in seconds, between the client-sent
2788   // ticket age and the server-computed value in TLS 1.3 server connections
2789   // which resumed a session.
2790   int32_t ticket_age_skew = 0;
2791 
2792   // ssl_early_data_reason stores details on why 0-RTT was accepted or rejected.
2793   enum ssl_early_data_reason_t early_data_reason = ssl_early_data_unknown;
2794 
2795   // aead_read_ctx is the current read cipher state.
2796   UniquePtr<SSLAEADContext> aead_read_ctx;
2797 
2798   // aead_write_ctx is the current write cipher state.
2799   UniquePtr<SSLAEADContext> aead_write_ctx;
2800 
2801   // hs is the handshake state for the current handshake or NULL if there isn't
2802   // one.
2803   UniquePtr<SSL_HANDSHAKE> hs;
2804 
2805   uint8_t write_traffic_secret[SSL_MAX_MD_SIZE] = {0};
2806   uint8_t read_traffic_secret[SSL_MAX_MD_SIZE] = {0};
2807   uint8_t exporter_secret[SSL_MAX_MD_SIZE] = {0};
2808   uint8_t write_traffic_secret_len = 0;
2809   uint8_t read_traffic_secret_len = 0;
2810   uint8_t exporter_secret_len = 0;
2811 
2812   // Connection binding to prevent renegotiation attacks
2813   uint8_t previous_client_finished[12] = {0};
2814   uint8_t previous_client_finished_len = 0;
2815   uint8_t previous_server_finished_len = 0;
2816   uint8_t previous_server_finished[12] = {0};
2817 
2818   uint8_t send_alert[2] = {0};
2819 
2820   // established_session is the session established by the connection. This
2821   // session is only filled upon the completion of the handshake and is
2822   // immutable.
2823   UniquePtr<SSL_SESSION> established_session;
2824 
2825   // Next protocol negotiation. For the client, this is the protocol that we
2826   // sent in NextProtocol and is set when handling ServerHello extensions.
2827   //
2828   // For a server, this is the client's selected_protocol from NextProtocol and
2829   // is set when handling the NextProtocol message, before the Finished
2830   // message.
2831   Array<uint8_t> next_proto_negotiated;
2832 
2833   // ALPN information
2834   // (we are in the process of transitioning from NPN to ALPN.)
2835 
2836   // In a server these point to the selected ALPN protocol after the
2837   // ClientHello has been processed. In a client these contain the protocol
2838   // that the server selected once the ServerHello has been processed.
2839   Array<uint8_t> alpn_selected;
2840 
2841   // hostname, on the server, is the value of the SNI extension.
2842   UniquePtr<char> hostname;
2843 
2844   // For a server:
2845   //     If |channel_id_valid| is true, then this contains the
2846   //     verified Channel ID from the client: a P256 point, (x,y), where
2847   //     each are big-endian values.
2848   uint8_t channel_id[64] = {0};
2849 
2850   // Contains the QUIC transport params received by the peer.
2851   Array<uint8_t> peer_quic_transport_params;
2852 
2853   // srtp_profile is the selected SRTP protection profile for
2854   // DTLS-SRTP.
2855   const SRTP_PROTECTION_PROFILE *srtp_profile = nullptr;
2856 };
2857 
2858 // lengths of messages
2859 #define DTLS1_RT_HEADER_LENGTH 13
2860 
2861 #define DTLS1_HM_HEADER_LENGTH 12
2862 
2863 #define DTLS1_CCS_HEADER_LENGTH 1
2864 
2865 #define DTLS1_AL_HEADER_LENGTH 2
2866 
2867 struct hm_header_st {
2868   uint8_t type;
2869   uint32_t msg_len;
2870   uint16_t seq;
2871   uint32_t frag_off;
2872   uint32_t frag_len;
2873 };
2874 
2875 // An hm_fragment is an incoming DTLS message, possibly not yet assembled.
2876 struct hm_fragment {
2877   static constexpr bool kAllowUniquePtr = true;
2878 
2879   hm_fragment() {}
2880   hm_fragment(const hm_fragment &) = delete;
2881   hm_fragment &operator=(const hm_fragment &) = delete;
2882 
2883   ~hm_fragment();
2884 
2885   // type is the type of the message.
2886   uint8_t type = 0;
2887   // seq is the sequence number of this message.
2888   uint16_t seq = 0;
2889   // msg_len is the length of the message body.
2890   uint32_t msg_len = 0;
2891   // data is a pointer to the message, including message header. It has length
2892   // |DTLS1_HM_HEADER_LENGTH| + |msg_len|.
2893   uint8_t *data = nullptr;
2894   // reassembly is a bitmask of |msg_len| bits corresponding to which parts of
2895   // the message have been received. It is NULL if the message is complete.
2896   uint8_t *reassembly = nullptr;
2897 };
2898 
2899 struct OPENSSL_timeval {
2900   uint64_t tv_sec;
2901   uint32_t tv_usec;
2902 };
2903 
2904 struct DTLS1_STATE {
2905   static constexpr bool kAllowUniquePtr = true;
2906 
2907   DTLS1_STATE();
2908   ~DTLS1_STATE();
2909 
2910   // has_change_cipher_spec is true if we have received a ChangeCipherSpec from
2911   // the peer in this epoch.
2912   bool has_change_cipher_spec : 1;
2913 
2914   // outgoing_messages_complete is true if |outgoing_messages| has been
2915   // completed by an attempt to flush it. Future calls to |add_message| and
2916   // |add_change_cipher_spec| will start a new flight.
2917   bool outgoing_messages_complete : 1;
2918 
2919   // flight_has_reply is true if the current outgoing flight is complete and has
2920   // processed at least one message. This is used to detect whether we or the
2921   // peer sent the final flight.
2922   bool flight_has_reply : 1;
2923 
2924   // The current data and handshake epoch.  This is initially undefined, and
2925   // starts at zero once the initial handshake is completed.
2926   uint16_t r_epoch = 0;
2927   uint16_t w_epoch = 0;
2928 
2929   // records being received in the current epoch
2930   DTLS1_BITMAP bitmap;
2931 
2932   uint16_t handshake_write_seq = 0;
2933   uint16_t handshake_read_seq = 0;
2934 
2935   // save last sequence number for retransmissions
2936   uint64_t last_write_sequence = 0;
2937   UniquePtr<SSLAEADContext> last_aead_write_ctx;
2938 
2939   // incoming_messages is a ring buffer of incoming handshake messages that have
2940   // yet to be processed. The front of the ring buffer is message number
2941   // |handshake_read_seq|, at position |handshake_read_seq| %
2942   // |SSL_MAX_HANDSHAKE_FLIGHT|.
2943   UniquePtr<hm_fragment> incoming_messages[SSL_MAX_HANDSHAKE_FLIGHT];
2944 
2945   // outgoing_messages is the queue of outgoing messages from the last handshake
2946   // flight.
2947   DTLS_OUTGOING_MESSAGE outgoing_messages[SSL_MAX_HANDSHAKE_FLIGHT];
2948   uint8_t outgoing_messages_len = 0;
2949 
2950   // outgoing_written is the number of outgoing messages that have been
2951   // written.
2952   uint8_t outgoing_written = 0;
2953   // outgoing_offset is the number of bytes of the next outgoing message have
2954   // been written.
2955   uint32_t outgoing_offset = 0;
2956 
2957   unsigned mtu = 0;  // max DTLS packet size
2958 
2959   // num_timeouts is the number of times the retransmit timer has fired since
2960   // the last time it was reset.
2961   unsigned num_timeouts = 0;
2962 
2963   // Indicates when the last handshake msg or heartbeat sent will
2964   // timeout.
2965   struct OPENSSL_timeval next_timeout = {0, 0};
2966 
2967   // timeout_duration_ms is the timeout duration in milliseconds.
2968   unsigned timeout_duration_ms = 0;
2969 };
2970 
2971 // An ALPSConfig is a pair of ALPN protocol and settings value to use with ALPS.
2972 struct ALPSConfig {
2973   Array<uint8_t> protocol;
2974   Array<uint8_t> settings;
2975 };
2976 
2977 // SSL_CONFIG contains configuration bits that can be shed after the handshake
2978 // completes.  Objects of this type are not shared; they are unique to a
2979 // particular |SSL|.
2980 //
2981 // See SSL_shed_handshake_config() for more about the conditions under which
2982 // configuration can be shed.
2983 struct SSL_CONFIG {
2984   static constexpr bool kAllowUniquePtr = true;
2985 
2986   explicit SSL_CONFIG(SSL *ssl_arg);
2987   ~SSL_CONFIG();
2988 
2989   // ssl is a non-owning pointer to the parent |SSL| object.
2990   SSL *const ssl = nullptr;
2991 
2992   // conf_max_version is the maximum acceptable version configured by
2993   // |SSL_set_max_proto_version|. Note this version is not normalized in DTLS
2994   // and is further constrained by |SSL_OP_NO_*|.
2995   uint16_t conf_max_version = 0;
2996 
2997   // conf_min_version is the minimum acceptable version configured by
2998   // |SSL_set_min_proto_version|. Note this version is not normalized in DTLS
2999   // and is further constrained by |SSL_OP_NO_*|.
3000   uint16_t conf_min_version = 0;
3001 
3002   X509_VERIFY_PARAM *param = nullptr;
3003 
3004   // crypto
3005   UniquePtr<SSLCipherPreferenceList> cipher_list;
3006 
3007   // This is used to hold the local certificate used (i.e. the server
3008   // certificate for a server or the client certificate for a client).
3009   UniquePtr<CERT> cert;
3010 
3011   int (*verify_callback)(int ok,
3012                          X509_STORE_CTX *ctx) =
3013       nullptr;  // fail if callback returns 0
3014 
3015   enum ssl_verify_result_t (*custom_verify_callback)(
3016       SSL *ssl, uint8_t *out_alert) = nullptr;
3017   // Server-only: psk_identity_hint is the identity hint to send in
3018   // PSK-based key exchanges.
3019   UniquePtr<char> psk_identity_hint;
3020 
3021   unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity,
3022                                   unsigned max_identity_len, uint8_t *psk,
3023                                   unsigned max_psk_len) = nullptr;
3024   unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk,
3025                                   unsigned max_psk_len) = nullptr;
3026 
3027   // for server side, keep the list of CA_dn we can use
3028   UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA;
3029 
3030   // cached_x509_client_CA is a cache of parsed versions of the elements of
3031   // |client_CA|.
3032   STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr;
3033 
3034   Array<uint16_t> supported_group_list;  // our list
3035 
3036   // channel_id_private is the client's Channel ID private key, or null if
3037   // Channel ID should not be offered on this connection.
3038   UniquePtr<EVP_PKEY> channel_id_private;
3039 
3040   // For a client, this contains the list of supported protocols in wire
3041   // format.
3042   Array<uint8_t> alpn_client_proto_list;
3043 
3044   // alps_configs contains the list of supported protocols to use with ALPS,
3045   // along with their corresponding ALPS values.
3046   GrowableArray<ALPSConfig> alps_configs;
3047 
3048   // Contains the QUIC transport params that this endpoint will send.
3049   Array<uint8_t> quic_transport_params;
3050 
3051   // Contains the context used to decide whether to accept early data in QUIC.
3052   Array<uint8_t> quic_early_data_context;
3053 
3054   // verify_sigalgs, if not empty, is the set of signature algorithms
3055   // accepted from the peer in decreasing order of preference.
3056   Array<uint16_t> verify_sigalgs;
3057 
3058   // srtp_profiles is the list of configured SRTP protection profiles for
3059   // DTLS-SRTP.
3060   UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles;
3061 
3062   // client_ech_config_list, if not empty, is a serialized ECHConfigList
3063   // structure for the client to use when negotiating ECH.
3064   Array<uint8_t> client_ech_config_list;
3065 
3066   // verify_mode is a bitmask of |SSL_VERIFY_*| values.
3067   uint8_t verify_mode = SSL_VERIFY_NONE;
3068 
3069   // ech_grease_enabled controls whether ECH GREASE may be sent in the
3070   // ClientHello.
3071   bool ech_grease_enabled : 1;
3072 
3073   // Enable signed certificate time stamps. Currently client only.
3074   bool signed_cert_timestamps_enabled : 1;
3075 
3076   // ocsp_stapling_enabled is only used by client connections and indicates
3077   // whether OCSP stapling will be requested.
3078   bool ocsp_stapling_enabled : 1;
3079 
3080   // channel_id_enabled is copied from the |SSL_CTX|. For a server, it means
3081   // that we'll accept Channel IDs from clients. It is ignored on the client.
3082   bool channel_id_enabled : 1;
3083 
3084   // If enforce_rsa_key_usage is true, the handshake will fail if the
3085   // keyUsage extension is present and incompatible with the TLS usage.
3086   // This field is not read until after certificate verification.
3087   bool enforce_rsa_key_usage : 1;
3088 
3089   // retain_only_sha256_of_client_certs is true if we should compute the SHA256
3090   // hash of the peer's certificate and then discard it to save memory and
3091   // session space. Only effective on the server side.
3092   bool retain_only_sha256_of_client_certs : 1;
3093 
3094   // handoff indicates that a server should stop after receiving the
3095   // ClientHello and pause the handshake in such a way that |SSL_get_error|
3096   // returns |SSL_ERROR_HANDOFF|. This is copied in |SSL_new| from the |SSL_CTX|
3097   // element of the same name and may be cleared if the handoff is declined.
3098   bool handoff : 1;
3099 
3100   // shed_handshake_config indicates that the handshake config (this object!)
3101   // should be freed after the handshake completes.
3102   bool shed_handshake_config : 1;
3103 
3104   // jdk11_workaround is whether to disable TLS 1.3 for JDK 11 clients, as a
3105   // workaround for https://bugs.openjdk.java.net/browse/JDK-8211806.
3106   bool jdk11_workaround : 1;
3107 
3108   // QUIC drafts up to and including 32 used a different TLS extension
3109   // codepoint to convey QUIC's transport parameters.
3110   bool quic_use_legacy_codepoint : 1;
3111 
3112   // permute_extensions is whether to permute extensions when sending messages.
3113   bool permute_extensions : 1;
3114 
3115   // only_fips_cipher_suites_in_tls13 constrains the selection of cipher suites
3116   // in TLS 1.3 such that only FIPS approved ones will be selected.
3117   bool only_fips_cipher_suites_in_tls13 : 1;
3118 
3119   // aes_hw_override if set indicates we should override checking for aes
3120   // hardware support, and use the value in aes_hw_override_value instead.
3121   bool aes_hw_override : 1;
3122 
3123   // aes_hw_override_value is used for testing to indicate the support or lack
3124   // of support for AES hw. The value is only considered if |aes_hw_override| is
3125   // true.
3126   bool aes_hw_override_value : 1;
3127 };
3128 
3129 // From RFC 8446, used in determining PSK modes.
3130 #define SSL_PSK_DHE_KE 0x1
3131 
3132 // kMaxEarlyDataAccepted is the advertised number of plaintext bytes of early
3133 // data that will be accepted. This value should be slightly below
3134 // kMaxEarlyDataSkipped in tls_record.c, which is measured in ciphertext.
3135 static const size_t kMaxEarlyDataAccepted = 14336;
3136 
3137 UniquePtr<CERT> ssl_cert_dup(CERT *cert);
3138 void ssl_cert_clear_certs(CERT *cert);
3139 bool ssl_set_cert(CERT *cert, UniquePtr<CRYPTO_BUFFER> buffer);
3140 bool ssl_is_key_type_supported(int key_type);
3141 // ssl_compare_public_and_private_key returns true if |pubkey| is the public
3142 // counterpart to |privkey|. Otherwise it returns false and pushes a helpful
3143 // message on the error queue.
3144 bool ssl_compare_public_and_private_key(const EVP_PKEY *pubkey,
3145                                        const EVP_PKEY *privkey);
3146 bool ssl_cert_check_private_key(const CERT *cert, const EVP_PKEY *privkey);
3147 bool ssl_get_new_session(SSL_HANDSHAKE *hs);
3148 bool ssl_encrypt_ticket(SSL_HANDSHAKE *hs, CBB *out,
3149                         const SSL_SESSION *session);
3150 bool ssl_ctx_rotate_ticket_encryption_key(SSL_CTX *ctx);
3151 
3152 // ssl_session_new returns a newly-allocated blank |SSL_SESSION| or nullptr on
3153 // error.
3154 UniquePtr<SSL_SESSION> ssl_session_new(const SSL_X509_METHOD *x509_method);
3155 
3156 // ssl_hash_session_id returns a hash of |session_id|, suitable for a hash table
3157 // keyed on session IDs.
3158 uint32_t ssl_hash_session_id(Span<const uint8_t> session_id);
3159 
3160 // SSL_SESSION_parse parses an |SSL_SESSION| from |cbs| and advances |cbs| over
3161 // the parsed data.
3162 OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_parse(
3163     CBS *cbs, const SSL_X509_METHOD *x509_method, CRYPTO_BUFFER_POOL *pool);
3164 
3165 // ssl_session_serialize writes |in| to |cbb| as if it were serialising a
3166 // session for Session-ID resumption. It returns true on success and false on
3167 // error.
3168 OPENSSL_EXPORT bool ssl_session_serialize(const SSL_SESSION *in, CBB *cbb);
3169 
3170 // ssl_session_is_context_valid returns whether |session|'s session ID context
3171 // matches the one set on |hs|.
3172 bool ssl_session_is_context_valid(const SSL_HANDSHAKE *hs,
3173                                   const SSL_SESSION *session);
3174 
3175 // ssl_session_is_time_valid returns true if |session| is still valid and false
3176 // if it has expired.
3177 bool ssl_session_is_time_valid(const SSL *ssl, const SSL_SESSION *session);
3178 
3179 // ssl_session_is_resumable returns whether |session| is resumable for |hs|.
3180 bool ssl_session_is_resumable(const SSL_HANDSHAKE *hs,
3181                               const SSL_SESSION *session);
3182 
3183 // ssl_session_protocol_version returns the protocol version associated with
3184 // |session|. Note that despite the name, this is not the same as
3185 // |SSL_SESSION_get_protocol_version|. The latter is based on upstream's name.
3186 uint16_t ssl_session_protocol_version(const SSL_SESSION *session);
3187 
3188 // ssl_session_get_digest returns the digest used in |session|.
3189 const EVP_MD *ssl_session_get_digest(const SSL_SESSION *session);
3190 
3191 void ssl_set_session(SSL *ssl, SSL_SESSION *session);
3192 
3193 // ssl_get_prev_session looks up the previous session based on |client_hello|.
3194 // On success, it sets |*out_session| to the session or nullptr if none was
3195 // found. If the session could not be looked up synchronously, it returns
3196 // |ssl_hs_pending_session| and should be called again. If a ticket could not be
3197 // decrypted immediately it returns |ssl_hs_pending_ticket| and should also
3198 // be called again. Otherwise, it returns |ssl_hs_error|.
3199 enum ssl_hs_wait_t ssl_get_prev_session(SSL_HANDSHAKE *hs,
3200                                         UniquePtr<SSL_SESSION> *out_session,
3201                                         bool *out_tickets_supported,
3202                                         bool *out_renew_ticket,
3203                                         const SSL_CLIENT_HELLO *client_hello);
3204 
3205 // The following flags determine which parts of the session are duplicated.
3206 #define SSL_SESSION_DUP_AUTH_ONLY 0x0
3207 #define SSL_SESSION_INCLUDE_TICKET 0x1
3208 #define SSL_SESSION_INCLUDE_NONAUTH 0x2
3209 #define SSL_SESSION_DUP_ALL \
3210   (SSL_SESSION_INCLUDE_TICKET | SSL_SESSION_INCLUDE_NONAUTH)
3211 
3212 // SSL_SESSION_dup returns a newly-allocated |SSL_SESSION| with a copy of the
3213 // fields in |session| or nullptr on error. The new session is non-resumable and
3214 // must be explicitly marked resumable once it has been filled in.
3215 OPENSSL_EXPORT UniquePtr<SSL_SESSION> SSL_SESSION_dup(SSL_SESSION *session,
3216                                                       int dup_flags);
3217 
3218 // ssl_session_rebase_time updates |session|'s start time to the current time,
3219 // adjusting the timeout so the expiration time is unchanged.
3220 void ssl_session_rebase_time(SSL *ssl, SSL_SESSION *session);
3221 
3222 // ssl_session_renew_timeout calls |ssl_session_rebase_time| and renews
3223 // |session|'s timeout to |timeout| (measured from the current time). The
3224 // renewal is clamped to the session's auth_timeout.
3225 void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session,
3226                                uint32_t timeout);
3227 
3228 void ssl_update_cache(SSL *ssl);
3229 
3230 void ssl_send_alert(SSL *ssl, int level, int desc);
3231 int ssl_send_alert_impl(SSL *ssl, int level, int desc);
3232 bool tls_get_message(const SSL *ssl, SSLMessage *out);
3233 ssl_open_record_t tls_open_handshake(SSL *ssl, size_t *out_consumed,
3234                                      uint8_t *out_alert, Span<uint8_t> in);
3235 void tls_next_message(SSL *ssl);
3236 
3237 int tls_dispatch_alert(SSL *ssl);
3238 ssl_open_record_t tls_open_app_data(SSL *ssl, Span<uint8_t> *out,
3239                                     size_t *out_consumed, uint8_t *out_alert,
3240                                     Span<uint8_t> in);
3241 ssl_open_record_t tls_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
3242                                               uint8_t *out_alert,
3243                                               Span<uint8_t> in);
3244 int tls_write_app_data(SSL *ssl, bool *out_needs_handshake,
3245                        size_t *out_bytes_written, Span<const uint8_t> in);
3246 
3247 bool tls_new(SSL *ssl);
3248 void tls_free(SSL *ssl);
3249 
3250 bool tls_init_message(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
3251 bool tls_finish_message(const SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg);
3252 bool tls_add_message(SSL *ssl, Array<uint8_t> msg);
3253 bool tls_add_change_cipher_spec(SSL *ssl);
3254 int tls_flush_flight(SSL *ssl);
3255 
3256 bool dtls1_init_message(const SSL *ssl, CBB *cbb, CBB *body, uint8_t type);
3257 bool dtls1_finish_message(const SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg);
3258 bool dtls1_add_message(SSL *ssl, Array<uint8_t> msg);
3259 bool dtls1_add_change_cipher_spec(SSL *ssl);
3260 int dtls1_flush_flight(SSL *ssl);
3261 
3262 // ssl_add_message_cbb finishes the handshake message in |cbb| and adds it to
3263 // the pending flight. It returns true on success and false on error.
3264 bool ssl_add_message_cbb(SSL *ssl, CBB *cbb);
3265 
3266 // ssl_hash_message incorporates |msg| into the handshake hash. It returns true
3267 // on success and false on allocation failure.
3268 bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg);
3269 
3270 ssl_open_record_t dtls1_open_app_data(SSL *ssl, Span<uint8_t> *out,
3271                                       size_t *out_consumed, uint8_t *out_alert,
3272                                       Span<uint8_t> in);
3273 ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
3274                                                 uint8_t *out_alert,
3275                                                 Span<uint8_t> in);
3276 
3277 int dtls1_write_app_data(SSL *ssl, bool *out_needs_handshake,
3278                          size_t *out_bytes_written, Span<const uint8_t> in);
3279 
3280 // dtls1_write_record sends a record. It returns one on success and <= 0 on
3281 // error.
3282 int dtls1_write_record(SSL *ssl, int type, Span<const uint8_t> in,
3283                        enum dtls1_use_epoch_t use_epoch);
3284 
3285 int dtls1_retransmit_outgoing_messages(SSL *ssl);
3286 bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
3287                           CBS *out_body);
3288 bool dtls1_check_timeout_num(SSL *ssl);
3289 
3290 void dtls1_start_timer(SSL *ssl);
3291 void dtls1_stop_timer(SSL *ssl);
3292 bool dtls1_is_timer_expired(SSL *ssl);
3293 unsigned int dtls1_min_mtu(void);
3294 
3295 bool dtls1_new(SSL *ssl);
3296 void dtls1_free(SSL *ssl);
3297 
3298 bool dtls1_get_message(const SSL *ssl, SSLMessage *out);
3299 ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed,
3300                                        uint8_t *out_alert, Span<uint8_t> in);
3301 void dtls1_next_message(SSL *ssl);
3302 int dtls1_dispatch_alert(SSL *ssl);
3303 
3304 // tls1_configure_aead configures either the read or write direction AEAD (as
3305 // determined by |direction|) using the keys generated by the TLS KDF. The
3306 // |key_block_cache| argument is used to store the generated key block, if
3307 // empty. Otherwise it's assumed that the key block is already contained within
3308 // it. It returns true on success or false on error.
3309 bool tls1_configure_aead(SSL *ssl, evp_aead_direction_t direction,
3310                          Array<uint8_t> *key_block_cache,
3311                          const SSL_SESSION *session,
3312                          Span<const uint8_t> iv_override);
3313 
3314 bool tls1_change_cipher_state(SSL_HANDSHAKE *hs,
3315                               evp_aead_direction_t direction);
3316 int tls1_generate_master_secret(SSL_HANDSHAKE *hs, uint8_t *out,
3317                                 Span<const uint8_t> premaster);
3318 
3319 // tls1_get_grouplist returns the locally-configured group preference list.
3320 Span<const uint16_t> tls1_get_grouplist(const SSL_HANDSHAKE *ssl);
3321 
3322 // tls1_check_group_id returns whether |group_id| is consistent with locally-
3323 // configured group preferences.
3324 bool tls1_check_group_id(const SSL_HANDSHAKE *ssl, uint16_t group_id);
3325 
3326 // tls1_get_shared_group sets |*out_group_id| to the first preferred shared
3327 // group between client and server preferences and returns true. If none may be
3328 // found, it returns false.
3329 bool tls1_get_shared_group(SSL_HANDSHAKE *hs, uint16_t *out_group_id);
3330 
3331 // tls1_set_curves converts the array of NIDs in |curves| into a newly allocated
3332 // array of TLS group IDs. On success, the function returns true and writes the
3333 // array to |*out_group_ids|. Otherwise, it returns false.
3334 bool tls1_set_curves(Array<uint16_t> *out_group_ids, Span<const int> curves);
3335 
3336 // tls1_set_curves_list converts the string of curves pointed to by |curves|
3337 // into a newly allocated array of TLS group IDs. On success, the function
3338 // returns true and writes the array to |*out_group_ids|. Otherwise, it returns
3339 // false.
3340 bool tls1_set_curves_list(Array<uint16_t> *out_group_ids, const char *curves);
3341 
3342 // ssl_add_clienthello_tlsext writes ClientHello extensions to |out| for |type|.
3343 // It returns true on success and false on failure. The |header_len| argument is
3344 // the length of the ClientHello written so far and is used to compute the
3345 // padding length. (It does not include the record header or handshake headers.)
3346 //
3347 // If |type| is |ssl_client_hello_inner|, this function also writes the
3348 // compressed extensions to |out_encoded|. Otherwise, |out_encoded| should be
3349 // nullptr.
3350 //
3351 // On success, the function sets |*out_needs_psk_binder| to whether the last
3352 // ClientHello extension was the pre_shared_key extension and needs a PSK binder
3353 // filled in. The caller should then update |out| and, if applicable,
3354 // |out_encoded| with the binder after completing the whole message.
3355 bool ssl_add_clienthello_tlsext(SSL_HANDSHAKE *hs, CBB *out, CBB *out_encoded,
3356                                 bool *out_needs_psk_binder,
3357                                 ssl_client_hello_type_t type,
3358                                 size_t header_len);
3359 
3360 bool ssl_add_serverhello_tlsext(SSL_HANDSHAKE *hs, CBB *out);
3361 bool ssl_parse_clienthello_tlsext(SSL_HANDSHAKE *hs,
3362                                   const SSL_CLIENT_HELLO *client_hello);
3363 bool ssl_parse_serverhello_tlsext(SSL_HANDSHAKE *hs, const CBS *extensions);
3364 
3365 #define tlsext_tick_md EVP_sha256
3366 
3367 // ssl_process_ticket processes a session ticket from the client. It returns
3368 // one of:
3369 //   |ssl_ticket_aead_success|: |*out_session| is set to the parsed session and
3370 //       |*out_renew_ticket| is set to whether the ticket should be renewed.
3371 //   |ssl_ticket_aead_ignore_ticket|: |*out_renew_ticket| is set to whether a
3372 //       fresh ticket should be sent, but the given ticket cannot be used.
3373 //   |ssl_ticket_aead_retry|: the ticket could not be immediately decrypted.
3374 //       Retry later.
3375 //   |ssl_ticket_aead_error|: an error occured that is fatal to the connection.
3376 enum ssl_ticket_aead_result_t ssl_process_ticket(
3377     SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
3378     bool *out_renew_ticket, Span<const uint8_t> ticket,
3379     Span<const uint8_t> session_id);
3380 
3381 // tls1_verify_channel_id processes |msg| as a Channel ID message, and verifies
3382 // the signature. If the key is valid, it saves the Channel ID and returns true.
3383 // Otherwise, it returns false.
3384 bool tls1_verify_channel_id(SSL_HANDSHAKE *hs, const SSLMessage &msg);
3385 
3386 // tls1_write_channel_id generates a Channel ID message and puts the output in
3387 // |cbb|. |ssl->channel_id_private| must already be set before calling.  This
3388 // function returns true on success and false on error.
3389 bool tls1_write_channel_id(SSL_HANDSHAKE *hs, CBB *cbb);
3390 
3391 // tls1_channel_id_hash computes the hash to be signed by Channel ID and writes
3392 // it to |out|, which must contain at least |EVP_MAX_MD_SIZE| bytes. It returns
3393 // true on success and false on failure.
3394 bool tls1_channel_id_hash(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len);
3395 
3396 // tls1_record_handshake_hashes_for_channel_id records the current handshake
3397 // hashes in |hs->new_session| so that Channel ID resumptions can sign that
3398 // data.
3399 bool tls1_record_handshake_hashes_for_channel_id(SSL_HANDSHAKE *hs);
3400 
3401 // ssl_can_write returns whether |ssl| is allowed to write.
3402 bool ssl_can_write(const SSL *ssl);
3403 
3404 // ssl_can_read returns wheter |ssl| is allowed to read.
3405 bool ssl_can_read(const SSL *ssl);
3406 
3407 void ssl_get_current_time(const SSL *ssl, struct OPENSSL_timeval *out_clock);
3408 void ssl_ctx_get_current_time(const SSL_CTX *ctx,
3409                               struct OPENSSL_timeval *out_clock);
3410 
3411 // ssl_reset_error_state resets state for |SSL_get_error|.
3412 void ssl_reset_error_state(SSL *ssl);
3413 
3414 // ssl_set_read_error sets |ssl|'s read half into an error state, saving the
3415 // current state of the error queue.
3416 void ssl_set_read_error(SSL *ssl);
3417 
3418 BSSL_NAMESPACE_END
3419 
3420 
3421 // Opaque C types.
3422 //
3423 // The following types are exported to C code as public typedefs, so they must
3424 // be defined outside of the namespace.
3425 
3426 // ssl_method_st backs the public |SSL_METHOD| type. It is a compatibility
3427 // structure to support the legacy version-locked methods.
3428 struct ssl_method_st {
3429   // version, if non-zero, is the only protocol version acceptable to an
3430   // SSL_CTX initialized from this method.
3431   uint16_t version;
3432   // method is the underlying SSL_PROTOCOL_METHOD that initializes the
3433   // SSL_CTX.
3434   const bssl::SSL_PROTOCOL_METHOD *method;
3435   // x509_method contains pointers to functions that might deal with |X509|
3436   // compatibility, or might be a no-op, depending on the application.
3437   const bssl::SSL_X509_METHOD *x509_method;
3438 };
3439 
3440 struct ssl_ctx_st {
3441   explicit ssl_ctx_st(const SSL_METHOD *ssl_method);
3442   ssl_ctx_st(const ssl_ctx_st &) = delete;
3443   ssl_ctx_st &operator=(const ssl_ctx_st &) = delete;
3444 
3445   const bssl::SSL_PROTOCOL_METHOD *method = nullptr;
3446   const bssl::SSL_X509_METHOD *x509_method = nullptr;
3447 
3448   // lock is used to protect various operations on this object.
3449   CRYPTO_MUTEX lock;
3450 
3451   // conf_max_version is the maximum acceptable protocol version configured by
3452   // |SSL_CTX_set_max_proto_version|. Note this version is normalized in DTLS
3453   // and is further constrainted by |SSL_OP_NO_*|.
3454   uint16_t conf_max_version = 0;
3455 
3456   // conf_min_version is the minimum acceptable protocol version configured by
3457   // |SSL_CTX_set_min_proto_version|. Note this version is normalized in DTLS
3458   // and is further constrainted by |SSL_OP_NO_*|.
3459   uint16_t conf_min_version = 0;
3460 
3461   // num_tickets is the number of tickets to send immediately after the TLS 1.3
3462   // handshake. TLS 1.3 recommends single-use tickets so, by default, issue two
3463   /// in case the client makes several connections before getting a renewal.
3464   uint8_t num_tickets = 2;
3465 
3466   // quic_method is the method table corresponding to the QUIC hooks.
3467   const SSL_QUIC_METHOD *quic_method = nullptr;
3468 
3469   bssl::UniquePtr<bssl::SSLCipherPreferenceList> cipher_list;
3470 
3471   X509_STORE *cert_store = nullptr;
3472   LHASH_OF(SSL_SESSION) *sessions = nullptr;
3473   // Most session-ids that will be cached, default is
3474   // SSL_SESSION_CACHE_MAX_SIZE_DEFAULT. 0 is unlimited.
3475   unsigned long session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
3476   SSL_SESSION *session_cache_head = nullptr;
3477   SSL_SESSION *session_cache_tail = nullptr;
3478 
3479   // handshakes_since_cache_flush is the number of successful handshakes since
3480   // the last cache flush.
3481   int handshakes_since_cache_flush = 0;
3482 
3483   // This can have one of 2 values, ored together,
3484   // SSL_SESS_CACHE_CLIENT,
3485   // SSL_SESS_CACHE_SERVER,
3486   // Default is SSL_SESSION_CACHE_SERVER, which means only
3487   // SSL_accept which cache SSL_SESSIONS.
3488   int session_cache_mode = SSL_SESS_CACHE_SERVER;
3489 
3490   // session_timeout is the default lifetime for new sessions in TLS 1.2 and
3491   // earlier, in seconds.
3492   uint32_t session_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
3493 
3494   // session_psk_dhe_timeout is the default lifetime for new sessions in TLS
3495   // 1.3, in seconds.
3496   uint32_t session_psk_dhe_timeout = SSL_DEFAULT_SESSION_PSK_DHE_TIMEOUT;
3497 
3498   // If this callback is not null, it will be called each time a session id is
3499   // added to the cache.  If this function returns 1, it means that the
3500   // callback will do a SSL_SESSION_free() when it has finished using it.
3501   // Otherwise, on 0, it means the callback has finished with it. If
3502   // remove_session_cb is not null, it will be called when a session-id is
3503   // removed from the cache.  After the call, OpenSSL will SSL_SESSION_free()
3504   // it.
3505   int (*new_session_cb)(SSL *ssl, SSL_SESSION *sess) = nullptr;
3506   void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *sess) = nullptr;
3507   SSL_SESSION *(*get_session_cb)(SSL *ssl, const uint8_t *data, int len,
3508                                  int *copy) = nullptr;
3509 
3510   CRYPTO_refcount_t references = 1;
3511 
3512   // if defined, these override the X509_verify_cert() calls
3513   int (*app_verify_callback)(X509_STORE_CTX *store_ctx, void *arg) = nullptr;
3514   void *app_verify_arg = nullptr;
3515 
3516   ssl_verify_result_t (*custom_verify_callback)(SSL *ssl,
3517                                                 uint8_t *out_alert) = nullptr;
3518 
3519   // Default password callback.
3520   pem_password_cb *default_passwd_callback = nullptr;
3521 
3522   // Default password callback user data.
3523   void *default_passwd_callback_userdata = nullptr;
3524 
3525   // get client cert callback
3526   int (*client_cert_cb)(SSL *ssl, X509 **out_x509,
3527                         EVP_PKEY **out_pkey) = nullptr;
3528 
3529   CRYPTO_EX_DATA ex_data;
3530 
3531   // Default values used when no per-SSL value is defined follow
3532 
3533   void (*info_callback)(const SSL *ssl, int type, int value) = nullptr;
3534 
3535   // what we put in client cert requests
3536   bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> client_CA;
3537 
3538   // cached_x509_client_CA is a cache of parsed versions of the elements of
3539   // |client_CA|.
3540   STACK_OF(X509_NAME) *cached_x509_client_CA = nullptr;
3541 
3542 
3543   // Default values to use in SSL structures follow (these are copied by
3544   // SSL_new)
3545 
3546   uint32_t options = 0;
3547   // Disable the auto-chaining feature by default. wpa_supplicant relies on this
3548   // feature, but require callers opt into it.
3549   uint32_t mode = SSL_MODE_NO_AUTO_CHAIN;
3550   uint32_t max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
3551 
3552   bssl::UniquePtr<bssl::CERT> cert;
3553 
3554   // callback that allows applications to peek at protocol messages
3555   void (*msg_callback)(int is_write, int version, int content_type,
3556                        const void *buf, size_t len, SSL *ssl,
3557                        void *arg) = nullptr;
3558   void *msg_callback_arg = nullptr;
3559 
3560   int verify_mode = SSL_VERIFY_NONE;
3561   int (*default_verify_callback)(int ok, X509_STORE_CTX *ctx) =
3562       nullptr;  // called 'verify_callback' in the SSL
3563 
3564   X509_VERIFY_PARAM *param = nullptr;
3565 
3566   // select_certificate_cb is called before most ClientHello processing and
3567   // before the decision whether to resume a session is made. See
3568   // |ssl_select_cert_result_t| for details of the return values.
3569   ssl_select_cert_result_t (*select_certificate_cb)(const SSL_CLIENT_HELLO *) =
3570       nullptr;
3571 
3572   // dos_protection_cb is called once the resumption decision for a ClientHello
3573   // has been made. It returns one to continue the handshake or zero to
3574   // abort.
3575   int (*dos_protection_cb)(const SSL_CLIENT_HELLO *) = nullptr;
3576 
3577   // Controls whether to verify certificates when resuming connections. They
3578   // were already verified when the connection was first made, so the default is
3579   // false. For now, this is only respected on clients, not servers.
3580   bool reverify_on_resume = false;
3581 
3582   // Maximum amount of data to send in one fragment. actual record size can be
3583   // more than this due to padding and MAC overheads.
3584   uint16_t max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
3585 
3586   // TLS extensions servername callback
3587   int (*servername_callback)(SSL *, int *, void *) = nullptr;
3588   void *servername_arg = nullptr;
3589 
3590   // RFC 4507 session ticket keys. |ticket_key_current| may be NULL before the
3591   // first handshake and |ticket_key_prev| may be NULL at any time.
3592   // Automatically generated ticket keys are rotated as needed at handshake
3593   // time. Hence, all access must be synchronized through |lock|.
3594   bssl::UniquePtr<bssl::TicketKey> ticket_key_current;
3595   bssl::UniquePtr<bssl::TicketKey> ticket_key_prev;
3596 
3597   // Callback to support customisation of ticket key setting
3598   int (*ticket_key_cb)(SSL *ssl, uint8_t *name, uint8_t *iv,
3599                        EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc) = nullptr;
3600 
3601   // Server-only: psk_identity_hint is the default identity hint to send in
3602   // PSK-based key exchanges.
3603   bssl::UniquePtr<char> psk_identity_hint;
3604 
3605   unsigned (*psk_client_callback)(SSL *ssl, const char *hint, char *identity,
3606                                   unsigned max_identity_len, uint8_t *psk,
3607                                   unsigned max_psk_len) = nullptr;
3608   unsigned (*psk_server_callback)(SSL *ssl, const char *identity, uint8_t *psk,
3609                                   unsigned max_psk_len) = nullptr;
3610 
3611 
3612   // Next protocol negotiation information
3613   // (for experimental NPN extension).
3614 
3615   // For a server, this contains a callback function by which the set of
3616   // advertised protocols can be provided.
3617   int (*next_protos_advertised_cb)(SSL *ssl, const uint8_t **out,
3618                                    unsigned *out_len, void *arg) = nullptr;
3619   void *next_protos_advertised_cb_arg = nullptr;
3620   // For a client, this contains a callback function that selects the
3621   // next protocol from the list provided by the server.
3622   int (*next_proto_select_cb)(SSL *ssl, uint8_t **out, uint8_t *out_len,
3623                               const uint8_t *in, unsigned in_len,
3624                               void *arg) = nullptr;
3625   void *next_proto_select_cb_arg = nullptr;
3626 
3627   // ALPN information
3628   // (we are in the process of transitioning from NPN to ALPN.)
3629 
3630   // For a server, this contains a callback function that allows the
3631   // server to select the protocol for the connection.
3632   //   out: on successful return, this must point to the raw protocol
3633   //        name (without the length prefix).
3634   //   outlen: on successful return, this contains the length of |*out|.
3635   //   in: points to the client's list of supported protocols in
3636   //       wire-format.
3637   //   inlen: the length of |in|.
3638   int (*alpn_select_cb)(SSL *ssl, const uint8_t **out, uint8_t *out_len,
3639                         const uint8_t *in, unsigned in_len,
3640                         void *arg) = nullptr;
3641   void *alpn_select_cb_arg = nullptr;
3642 
3643   // For a client, this contains the list of supported protocols in wire
3644   // format.
3645   bssl::Array<uint8_t> alpn_client_proto_list;
3646 
3647   // SRTP profiles we are willing to do from RFC 5764
3648   bssl::UniquePtr<STACK_OF(SRTP_PROTECTION_PROFILE)> srtp_profiles;
3649 
3650   // Defined compression algorithms for certificates.
3651   bssl::GrowableArray<bssl::CertCompressionAlg> cert_compression_algs;
3652 
3653   // Supported group values inherited by SSL structure
3654   bssl::Array<uint16_t> supported_group_list;
3655 
3656   // channel_id_private is the client's Channel ID private key, or null if
3657   // Channel ID should not be offered on this connection.
3658   bssl::UniquePtr<EVP_PKEY> channel_id_private;
3659 
3660   // ech_keys contains the server's list of ECHConfig values and associated
3661   // private keys. This list may be swapped out at any time, so all access must
3662   // be synchronized through |lock|.
3663   bssl::UniquePtr<SSL_ECH_KEYS> ech_keys;
3664 
3665   // keylog_callback, if not NULL, is the key logging callback. See
3666   // |SSL_CTX_set_keylog_callback|.
3667   void (*keylog_callback)(const SSL *ssl, const char *line) = nullptr;
3668 
3669   // current_time_cb, if not NULL, is the function to use to get the current
3670   // time. It sets |*out_clock| to the current time. The |ssl| argument is
3671   // always NULL. See |SSL_CTX_set_current_time_cb|.
3672   void (*current_time_cb)(const SSL *ssl, struct timeval *out_clock) = nullptr;
3673 
3674   // pool is used for all |CRYPTO_BUFFER|s in case we wish to share certificate
3675   // memory.
3676   CRYPTO_BUFFER_POOL *pool = nullptr;
3677 
3678   // ticket_aead_method contains function pointers for opening and sealing
3679   // session tickets.
3680   const SSL_TICKET_AEAD_METHOD *ticket_aead_method = nullptr;
3681 
3682   // legacy_ocsp_callback implements an OCSP-related callback for OpenSSL
3683   // compatibility.
3684   int (*legacy_ocsp_callback)(SSL *ssl, void *arg) = nullptr;
3685   void *legacy_ocsp_callback_arg = nullptr;
3686 
3687   // verify_sigalgs, if not empty, is the set of signature algorithms
3688   // accepted from the peer in decreasing order of preference.
3689   bssl::Array<uint16_t> verify_sigalgs;
3690 
3691   // retain_only_sha256_of_client_certs is true if we should compute the SHA256
3692   // hash of the peer's certificate and then discard it to save memory and
3693   // session space. Only effective on the server side.
3694   bool retain_only_sha256_of_client_certs : 1;
3695 
3696   // quiet_shutdown is true if the connection should not send a close_notify on
3697   // shutdown.
3698   bool quiet_shutdown : 1;
3699 
3700   // ocsp_stapling_enabled is only used by client connections and indicates
3701   // whether OCSP stapling will be requested.
3702   bool ocsp_stapling_enabled : 1;
3703 
3704   // If true, a client will request certificate timestamps.
3705   bool signed_cert_timestamps_enabled : 1;
3706 
3707   // channel_id_enabled is whether Channel ID is enabled. For a server, means
3708   // that we'll accept Channel IDs from clients.  For a client, means that we'll
3709   // advertise support.
3710   bool channel_id_enabled : 1;
3711 
3712   // grease_enabled is whether GREASE (RFC 8701) is enabled.
3713   bool grease_enabled : 1;
3714 
3715   // permute_extensions is whether to permute extensions when sending messages.
3716   bool permute_extensions : 1;
3717 
3718   // allow_unknown_alpn_protos is whether the client allows unsolicited ALPN
3719   // protocols from the peer.
3720   bool allow_unknown_alpn_protos : 1;
3721 
3722   // false_start_allowed_without_alpn is whether False Start (if
3723   // |SSL_MODE_ENABLE_FALSE_START| is enabled) is allowed without ALPN.
3724   bool false_start_allowed_without_alpn : 1;
3725 
3726   // handoff indicates that a server should stop after receiving the
3727   // ClientHello and pause the handshake in such a way that |SSL_get_error|
3728   // returns |SSL_ERROR_HANDOFF|.
3729   bool handoff : 1;
3730 
3731   // If enable_early_data is true, early data can be sent and accepted.
3732   bool enable_early_data : 1;
3733 
3734   // only_fips_cipher_suites_in_tls13 constrains the selection of cipher suites
3735   // in TLS 1.3 such that only FIPS approved ones will be selected.
3736   bool only_fips_cipher_suites_in_tls13 : 1;
3737 
3738   // aes_hw_override if set indicates we should override checking for AES
3739   // hardware support, and use the value in aes_hw_override_value instead.
3740   bool aes_hw_override : 1;
3741 
3742   // aes_hw_override_value is used for testing to indicate the support or lack
3743   // of support for AES hardware. The value is only considered if
3744   // |aes_hw_override| is true.
3745   bool aes_hw_override_value : 1;
3746 
3747  private:
3748   ~ssl_ctx_st();
3749   friend OPENSSL_EXPORT void SSL_CTX_free(SSL_CTX *);
3750 };
3751 
3752 struct ssl_st {
3753   explicit ssl_st(SSL_CTX *ctx_arg);
3754   ssl_st(const ssl_st &) = delete;
3755   ssl_st &operator=(const ssl_st &) = delete;
3756   ~ssl_st();
3757 
3758   // method is the method table corresponding to the current protocol (DTLS or
3759   // TLS).
3760   const bssl::SSL_PROTOCOL_METHOD *method = nullptr;
3761 
3762   // config is a container for handshake configuration.  Accesses to this field
3763   // should check for nullptr, since configuration may be shed after the
3764   // handshake completes.  (If you have the |SSL_HANDSHAKE| object at hand, use
3765   // that instead, and skip the null check.)
3766   bssl::UniquePtr<bssl::SSL_CONFIG> config;
3767 
3768   // version is the protocol version.
3769   uint16_t version = 0;
3770 
3771   uint16_t max_send_fragment = 0;
3772 
3773   // There are 2 BIO's even though they are normally both the same. This is so
3774   // data can be read and written to different handlers
3775 
3776   bssl::UniquePtr<BIO> rbio;  // used by SSL_read
3777   bssl::UniquePtr<BIO> wbio;  // used by SSL_write
3778 
3779   // do_handshake runs the handshake. On completion, it returns |ssl_hs_ok|.
3780   // Otherwise, it returns a value corresponding to what operation is needed to
3781   // progress.
3782   bssl::ssl_hs_wait_t (*do_handshake)(bssl::SSL_HANDSHAKE *hs) = nullptr;
3783 
3784   bssl::SSL3_STATE *s3 = nullptr;   // TLS variables
3785   bssl::DTLS1_STATE *d1 = nullptr;  // DTLS variables
3786 
3787   // callback that allows applications to peek at protocol messages
3788   void (*msg_callback)(int write_p, int version, int content_type,
3789                        const void *buf, size_t len, SSL *ssl,
3790                        void *arg) = nullptr;
3791   void *msg_callback_arg = nullptr;
3792 
3793   // session info
3794 
3795   // initial_timeout_duration_ms is the default DTLS timeout duration in
3796   // milliseconds. It's used to initialize the timer any time it's restarted.
3797   //
3798   // RFC 6347 states that implementations SHOULD use an initial timer value of 1
3799   // second.
3800   unsigned initial_timeout_duration_ms = 1000;
3801 
3802   // session is the configured session to be offered by the client. This session
3803   // is immutable.
3804   bssl::UniquePtr<SSL_SESSION> session;
3805 
3806   void (*info_callback)(const SSL *ssl, int type, int value) = nullptr;
3807 
3808   bssl::UniquePtr<SSL_CTX> ctx;
3809 
3810   // session_ctx is the |SSL_CTX| used for the session cache and related
3811   // settings.
3812   bssl::UniquePtr<SSL_CTX> session_ctx;
3813 
3814   // extra application data
3815   CRYPTO_EX_DATA ex_data;
3816 
3817   uint32_t options = 0;  // protocol behaviour
3818   uint32_t mode = 0;     // API behaviour
3819   uint32_t max_cert_list = 0;
3820   bssl::UniquePtr<char> hostname;
3821 
3822   // quic_method is the method table corresponding to the QUIC hooks.
3823   const SSL_QUIC_METHOD *quic_method = nullptr;
3824 
3825   // renegotiate_mode controls how peer renegotiation attempts are handled.
3826   ssl_renegotiate_mode_t renegotiate_mode = ssl_renegotiate_never;
3827 
3828   // server is true iff the this SSL* is the server half. Note: before the SSL*
3829   // is initialized by either SSL_set_accept_state or SSL_set_connect_state,
3830   // the side is not determined. In this state, server is always false.
3831   bool server : 1;
3832 
3833   // quiet_shutdown is true if the connection should not send a close_notify on
3834   // shutdown.
3835   bool quiet_shutdown : 1;
3836 
3837   // If enable_early_data is true, early data can be sent and accepted.
3838   bool enable_early_data : 1;
3839 };
3840 
3841 struct ssl_session_st {
3842   explicit ssl_session_st(const bssl::SSL_X509_METHOD *method);
3843   ssl_session_st(const ssl_session_st &) = delete;
3844   ssl_session_st &operator=(const ssl_session_st &) = delete;
3845 
3846   CRYPTO_refcount_t references = 1;
3847 
3848   // ssl_version is the (D)TLS version that established the session.
3849   uint16_t ssl_version = 0;
3850 
3851   // group_id is the ID of the ECDH group used to establish this session or zero
3852   // if not applicable or unknown.
3853   uint16_t group_id = 0;
3854 
3855   // peer_signature_algorithm is the signature algorithm used to authenticate
3856   // the peer, or zero if not applicable or unknown.
3857   uint16_t peer_signature_algorithm = 0;
3858 
3859   // secret, in TLS 1.2 and below, is the master secret associated with the
3860   // session. In TLS 1.3 and up, it is the resumption PSK for sessions handed to
3861   // the caller, but it stores the resumption secret when stored on |SSL|
3862   // objects.
3863   uint8_t secret_length = 0;
3864   uint8_t secret[SSL_MAX_MASTER_KEY_LENGTH] = {0};
3865 
3866   // session_id - valid?
3867   uint8_t session_id_length = 0;
3868   uint8_t session_id[SSL_MAX_SSL_SESSION_ID_LENGTH] = {0};
3869   // this is used to determine whether the session is being reused in
3870   // the appropriate context. It is up to the application to set this,
3871   // via SSL_new
3872   uint8_t sid_ctx_length = 0;
3873   uint8_t sid_ctx[SSL_MAX_SID_CTX_LENGTH] = {0};
3874 
3875   bssl::UniquePtr<char> psk_identity;
3876 
3877   // certs contains the certificate chain from the peer, starting with the leaf
3878   // certificate.
3879   bssl::UniquePtr<STACK_OF(CRYPTO_BUFFER)> certs;
3880 
3881   const bssl::SSL_X509_METHOD *x509_method = nullptr;
3882 
3883   // x509_peer is the peer's certificate.
3884   X509 *x509_peer = nullptr;
3885 
3886   // x509_chain is the certificate chain sent by the peer. NOTE: for historical
3887   // reasons, when a client (so the peer is a server), the chain includes
3888   // |peer|, but when a server it does not.
3889   STACK_OF(X509) *x509_chain = nullptr;
3890 
3891   // x509_chain_without_leaf is a lazily constructed copy of |x509_chain| that
3892   // omits the leaf certificate. This exists because OpenSSL, historically,
3893   // didn't include the leaf certificate in the chain for a server, but did for
3894   // a client. The |x509_chain| always includes it and, if an API call requires
3895   // a chain without, it is stored here.
3896   STACK_OF(X509) *x509_chain_without_leaf = nullptr;
3897 
3898   // verify_result is the result of certificate verification in the case of
3899   // non-fatal certificate errors.
3900   long verify_result = X509_V_ERR_INVALID_CALL;
3901 
3902   // timeout is the lifetime of the session in seconds, measured from |time|.
3903   // This is renewable up to |auth_timeout|.
3904   uint32_t timeout = SSL_DEFAULT_SESSION_TIMEOUT;
3905 
3906   // auth_timeout is the non-renewable lifetime of the session in seconds,
3907   // measured from |time|.
3908   uint32_t auth_timeout = SSL_DEFAULT_SESSION_TIMEOUT;
3909 
3910   // time is the time the session was issued, measured in seconds from the UNIX
3911   // epoch.
3912   uint64_t time = 0;
3913 
3914   const SSL_CIPHER *cipher = nullptr;
3915 
3916   CRYPTO_EX_DATA ex_data;  // application specific data
3917 
3918   // These are used to make removal of session-ids more efficient and to
3919   // implement a maximum cache size.
3920   SSL_SESSION *prev = nullptr, *next = nullptr;
3921 
3922   bssl::Array<uint8_t> ticket;
3923 
3924   bssl::UniquePtr<CRYPTO_BUFFER> signed_cert_timestamp_list;
3925 
3926   // The OCSP response that came with the session.
3927   bssl::UniquePtr<CRYPTO_BUFFER> ocsp_response;
3928 
3929   // peer_sha256 contains the SHA-256 hash of the peer's certificate if
3930   // |peer_sha256_valid| is true.
3931   uint8_t peer_sha256[SHA256_DIGEST_LENGTH] = {0};
3932 
3933   // original_handshake_hash contains the handshake hash (either SHA-1+MD5 or
3934   // SHA-2, depending on TLS version) for the original, full handshake that
3935   // created a session. This is used by Channel IDs during resumption.
3936   uint8_t original_handshake_hash[EVP_MAX_MD_SIZE] = {0};
3937   uint8_t original_handshake_hash_len = 0;
3938 
3939   uint32_t ticket_lifetime_hint = 0;  // Session lifetime hint in seconds
3940 
3941   uint32_t ticket_age_add = 0;
3942 
3943   // ticket_max_early_data is the maximum amount of data allowed to be sent as
3944   // early data. If zero, 0-RTT is disallowed.
3945   uint32_t ticket_max_early_data = 0;
3946 
3947   // early_alpn is the ALPN protocol from the initial handshake. This is only
3948   // stored for TLS 1.3 and above in order to enforce ALPN matching for 0-RTT
3949   // resumptions. For the current connection's ALPN protocol, see
3950   // |alpn_selected| on |SSL3_STATE|.
3951   bssl::Array<uint8_t> early_alpn;
3952 
3953   // local_application_settings, if |has_application_settings| is true, is the
3954   // local ALPS value for this connection.
3955   bssl::Array<uint8_t> local_application_settings;
3956 
3957   // peer_application_settings, if |has_application_settings| is true, is the
3958   // peer ALPS value for this connection.
3959   bssl::Array<uint8_t> peer_application_settings;
3960 
3961   // extended_master_secret is whether the master secret in this session was
3962   // generated using EMS and thus isn't vulnerable to the Triple Handshake
3963   // attack.
3964   bool extended_master_secret : 1;
3965 
3966   // peer_sha256_valid is whether |peer_sha256| is valid.
3967   bool peer_sha256_valid : 1;  // Non-zero if peer_sha256 is valid
3968 
3969   // not_resumable is used to indicate that session resumption is disallowed.
3970   bool not_resumable : 1;
3971 
3972   // ticket_age_add_valid is whether |ticket_age_add| is valid.
3973   bool ticket_age_add_valid : 1;
3974 
3975   // is_server is whether this session was created by a server.
3976   bool is_server : 1;
3977 
3978   // is_quic indicates whether this session was created using QUIC.
3979   bool is_quic : 1;
3980 
3981   // has_application_settings indicates whether ALPS was negotiated in this
3982   // session.
3983   bool has_application_settings : 1;
3984 
3985   // quic_early_data_context is used to determine whether early data must be
3986   // rejected when performing a QUIC handshake.
3987   bssl::Array<uint8_t> quic_early_data_context;
3988 
3989  private:
3990   ~ssl_session_st();
3991   friend OPENSSL_EXPORT void SSL_SESSION_free(SSL_SESSION *);
3992 };
3993 
3994 struct ssl_ech_keys_st {
3995   ssl_ech_keys_st() = default;
3996   ssl_ech_keys_st(const ssl_ech_keys_st &) = delete;
3997   ssl_ech_keys_st &operator=(const ssl_ech_keys_st &) = delete;
3998 
3999   bssl::GrowableArray<bssl::UniquePtr<bssl::ECHServerConfig>> configs;
4000   CRYPTO_refcount_t references = 1;
4001 
4002  private:
4003   ~ssl_ech_keys_st() = default;
4004   friend OPENSSL_EXPORT void SSL_ECH_KEYS_free(SSL_ECH_KEYS *);
4005 };
4006 
4007 #endif  // OPENSSL_HEADER_SSL_INTERNAL_H
4008