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