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