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