Coverage Report

Created: 2026-10-19 07:10

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