Coverage Report

Created: 2023-06-07 07:11

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