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