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