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