/src/curl_fuzzer/proto_fuzzer/tls_mock_server.cc
Line | Count | Source |
1 | | /* |
2 | | * Copyright (C) Max Dymond, <cmeister2@gmail.com>, et al. |
3 | | * |
4 | | * SPDX-License-Identifier: curl |
5 | | */ |
6 | | |
7 | | /// @file |
8 | | /// @brief Nonblocking OpenSSL server transport for structured HTTPS inputs. |
9 | | |
10 | | #include "proto_fuzzer/tls_mock_server.h" |
11 | | |
12 | | #include <openssl/bio.h> |
13 | | #include <openssl/crypto.h> |
14 | | #include <openssl/ech.h> |
15 | | #include <openssl/err.h> |
16 | | #include <openssl/ocsp.h> |
17 | | #include <openssl/ssl.h> |
18 | | #include <sys/socket.h> |
19 | | |
20 | | #include <cassert> |
21 | | #include <cstddef> |
22 | | #include <cstdint> |
23 | | #include <cstring> |
24 | | #include <string> |
25 | | #include <vector> |
26 | | |
27 | | #include "proto_fuzzer/option_apply.h" |
28 | | #include "proto_fuzzer/tls_test_credential_cache.h" |
29 | | #include "proto_fuzzer/tls_test_credentials.h" |
30 | | |
31 | | namespace proto_fuzzer { |
32 | | |
33 | | namespace { |
34 | | |
35 | | constexpr std::size_t kMaxSessionExportAttempts = 8; |
36 | | constexpr std::uint32_t kMaxEarlyDataSize = 16 * 1024; |
37 | | |
38 | | /// The TLS carrier always uses OpenSSL on its server side, but the HTTPS seed |
39 | | /// corpus is also replayed by curl clients built with GnuTLS and mbedTLS. |
40 | | /// Backend-specific handshake terminals must not replace their ordinary peer. |
41 | 4.60k | bool CurlClientUsesOpenSsl() { |
42 | 4.60k | const curl_version_info_data* version = curl_version_info(CURLVERSION_NOW); |
43 | 4.60k | constexpr char kOpenSslPrefix[] = "OpenSSL/"; |
44 | 4.60k | return version != nullptr && version->ssl_version != nullptr && |
45 | 4.60k | std::strncmp(version->ssl_version, kOpenSslPrefix, sizeof(kOpenSslPrefix) - 1) == 0; |
46 | 4.60k | } |
47 | | |
48 | | /// Isolate the server and curl client even though both OpenSSL instances run |
49 | | /// on one thread. SSL_get_error requires an empty queue before its I/O call; |
50 | | /// clearing at both boundaries also prevents a server failure from changing |
51 | | /// curl's subsequent error classification. |
52 | | class OpenSslErrorQueueGuard { |
53 | | public: |
54 | 2.58M | OpenSslErrorQueueGuard() { ERR_clear_error(); } |
55 | | |
56 | 2.58M | ~OpenSslErrorQueueGuard() { ERR_clear_error(); } |
57 | | |
58 | | OpenSslErrorQueueGuard(const OpenSslErrorQueueGuard&) = delete; |
59 | | OpenSslErrorQueueGuard& operator=(const OpenSslErrorQueueGuard&) = delete; |
60 | | }; |
61 | | |
62 | | /// Select the one protocol owned by this peer. A fixed server preference keeps |
63 | | /// ordinary HTTPS scripts on HTTP/1.1 while allowing the proxy lane to prove |
64 | | /// curl installed its HTTP/2 connection filter after TLS. |
65 | | int SelectAlpn(SSL* /*ssl*/, const unsigned char** selected, unsigned char* selected_length, |
66 | 140k | const unsigned char* client_protocols, unsigned int client_protocols_length, void* userdata) { |
67 | 140k | const auto protocol = *static_cast<const TlsApplicationProtocol*>(userdata); |
68 | | // OpenSSL may return a pointer into the server preference list. Function- |
69 | | // local static storage keeps that result valid for the rest of the |
70 | | // handshake without reintroducing mutable transport policy as a global. |
71 | 140k | static constexpr unsigned char http11_alpn[] = {8, 'h', 't', 't', 'p', '/', '1', '.', '1'}; |
72 | 140k | static constexpr unsigned char http2_alpn[] = {2, 'h', '2'}; |
73 | 140k | const unsigned char* server_protocols = protocol == TlsApplicationProtocol::kHttp2 ? http2_alpn : http11_alpn; |
74 | 140k | const unsigned int server_protocols_length = |
75 | 140k | protocol == TlsApplicationProtocol::kHttp2 ? sizeof(http2_alpn) : sizeof(http11_alpn); |
76 | 140k | unsigned char* match = nullptr; |
77 | 140k | unsigned char match_length = 0; |
78 | 140k | const int result = SSL_select_next_proto(&match, &match_length, server_protocols, server_protocols_length, |
79 | 140k | client_protocols, client_protocols_length); |
80 | 140k | if (result != OPENSSL_NPN_NEGOTIATED) { |
81 | 21.4k | return SSL_TLSEXT_ERR_NOACK; |
82 | 21.4k | } |
83 | 119k | *selected = match; |
84 | 119k | *selected_length = match_length; |
85 | 119k | return SSL_TLSEXT_ERR_OK; |
86 | 140k | } |
87 | | |
88 | | using OcspBasicResponsePtr = std::unique_ptr<OCSP_BASICRESP, decltype(&OCSP_BASICRESP_free)>; |
89 | | using OcspCertIdPtr = std::unique_ptr<OCSP_CERTID, decltype(&OCSP_CERTID_free)>; |
90 | | using OcspResponsePtr = std::unique_ptr<OCSP_RESPONSE, decltype(&OCSP_RESPONSE_free)>; |
91 | | using Asn1TimePtr = std::unique_ptr<ASN1_TIME, decltype(&ASN1_TIME_free)>; |
92 | | |
93 | | /// Encode one owned OpenSSL response for the status callback. |
94 | | /// @param response Parsed response whose ownership stays with the caller. |
95 | | /// @return DER bytes, or an empty vector when encoding failed. |
96 | 24 | std::vector<unsigned char> EncodeOcspResponse(OCSP_RESPONSE* response) { |
97 | 24 | if (response == nullptr) { |
98 | 0 | return {}; |
99 | 0 | } |
100 | 24 | const int encoded_size = i2d_OCSP_RESPONSE(response, nullptr); |
101 | 24 | if (encoded_size <= 0) { |
102 | 0 | return {}; |
103 | 0 | } |
104 | 24 | std::vector<unsigned char> encoded(static_cast<std::size_t>(encoded_size)); |
105 | 24 | unsigned char* output = encoded.data(); |
106 | 24 | if (i2d_OCSP_RESPONSE(response, &output) != encoded_size) { |
107 | 0 | return {}; |
108 | 0 | } |
109 | 24 | return encoded; |
110 | 24 | } |
111 | | |
112 | | /// Build a response carrying only its top-level OCSP status. |
113 | 6 | std::vector<unsigned char> BuildTopLevelOcspResponse(int response_status) { |
114 | 6 | OcspResponsePtr response(OCSP_response_create(response_status, nullptr), &OCSP_RESPONSE_free); |
115 | 6 | return EncodeOcspResponse(response.get()); |
116 | 6 | } |
117 | | |
118 | | /// Build and sign one single-certificate OCSP response. |
119 | | std::vector<unsigned char> BuildSignedOcspResponse(X509* certificate, X509* issuer, EVP_PKEY* issuer_private_key, |
120 | | int certificate_status, bool sha256_certificate_id, bool expired, |
121 | 18 | bool bad_signature) { |
122 | 18 | OcspBasicResponsePtr basic(OCSP_BASICRESP_new(), &OCSP_BASICRESP_free); |
123 | 18 | const EVP_MD* certificate_id_digest = sha256_certificate_id ? EVP_sha256() : EVP_sha1(); |
124 | 18 | OcspCertIdPtr certificate_id(OCSP_cert_to_id(certificate_id_digest, certificate, issuer), &OCSP_CERTID_free); |
125 | 18 | const long this_update_offset = expired ? -2L * 24L * 60L * 60L : -60L; |
126 | 18 | const long next_update_offset = expired ? -24L * 60L * 60L : 24L * 60L * 60L; |
127 | 18 | Asn1TimePtr this_update(X509_gmtime_adj(nullptr, this_update_offset), &ASN1_TIME_free); |
128 | 18 | Asn1TimePtr next_update(X509_gmtime_adj(nullptr, next_update_offset), &ASN1_TIME_free); |
129 | 18 | Asn1TimePtr revocation_time( |
130 | 18 | certificate_status == V_OCSP_CERTSTATUS_REVOKED ? X509_gmtime_adj(nullptr, -60L * 60L) : nullptr, |
131 | 18 | &ASN1_TIME_free); |
132 | 18 | if (basic == nullptr || certificate_id == nullptr || this_update == nullptr || next_update == nullptr || |
133 | 18 | (certificate_status == V_OCSP_CERTSTATUS_REVOKED && revocation_time == nullptr)) { |
134 | 0 | return {}; |
135 | 0 | } |
136 | | |
137 | 18 | const int revocation_reason = certificate_status == V_OCSP_CERTSTATUS_REVOKED ? OCSP_REVOKED_STATUS_KEYCOMPROMISE : 0; |
138 | 18 | if (OCSP_basic_add1_status(basic.get(), certificate_id.get(), certificate_status, revocation_reason, |
139 | 18 | revocation_time.get(), this_update.get(), next_update.get()) == nullptr || |
140 | 18 | OCSP_basic_sign(basic.get(), issuer, issuer_private_key, EVP_sha256(), nullptr, OCSP_NOCERTS | OCSP_RESPID_KEY) != |
141 | 18 | 1) { |
142 | 0 | return {}; |
143 | 0 | } |
144 | | |
145 | 18 | OcspResponsePtr response(OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, basic.get()), &OCSP_RESPONSE_free); |
146 | 18 | std::vector<unsigned char> encoded = EncodeOcspResponse(response.get()); |
147 | | // OCSP_NOCERTS leaves the signature as the final DER value. Changing one |
148 | | // payload byte preserves the ASN.1 shape while making verification fail. |
149 | 18 | if (bad_signature && !encoded.empty()) { |
150 | 3 | encoded.back() ^= 1U; |
151 | 3 | } |
152 | 18 | return encoded; |
153 | 18 | } |
154 | | |
155 | | /// Generate each signed profile once. Per-connection callbacks copy only the |
156 | | /// selected DER, avoiding asymmetric signing work in the fuzzing hot path. |
157 | | class TlsOcspResponseCache { |
158 | | public: |
159 | | TlsOcspResponseCache(X509* certificate, X509* issuer, EVP_PKEY* issuer_private_key) |
160 | 3 | : good_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_GOOD, false, false, |
161 | 3 | false)), |
162 | 3 | revoked_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_REVOKED, false, |
163 | 3 | false, false)), |
164 | 3 | unknown_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_UNKNOWN, false, |
165 | 3 | false, false)), |
166 | 3 | try_later_(BuildTopLevelOcspResponse(OCSP_RESPONSE_STATUS_TRYLATER)), |
167 | 3 | empty_successful_(BuildTopLevelOcspResponse(OCSP_RESPONSE_STATUS_SUCCESSFUL)), |
168 | 3 | sha256_certificate_id_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_GOOD, |
169 | 3 | true, false, false)), |
170 | 3 | expired_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_GOOD, false, true, |
171 | 3 | false)), |
172 | 3 | bad_signature_(BuildSignedOcspResponse(certificate, issuer, issuer_private_key, V_OCSP_CERTSTATUS_GOOD, false, |
173 | 3 | false, true)) {} |
174 | | |
175 | 7.78k | const std::vector<unsigned char>& Get(curl::fuzzer::proto::TlsOcspStapleProfile profile) const { |
176 | 7.78k | switch (profile) { |
177 | 1.28k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_GOOD: |
178 | 1.28k | return good_; |
179 | 1.02k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_REVOKED: |
180 | 1.02k | return revoked_; |
181 | 1.23k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_UNKNOWN: |
182 | 1.23k | return unknown_; |
183 | 1.01k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_TRY_LATER: |
184 | 1.01k | return try_later_; |
185 | 754 | case curl::fuzzer::proto::TLS_OCSP_STAPLE_EMPTY_SUCCESSFUL: |
186 | 754 | return empty_successful_; |
187 | 1.32k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_SHA256_CERT_ID: |
188 | 1.32k | return sha256_certificate_id_; |
189 | 591 | case curl::fuzzer::proto::TLS_OCSP_STAPLE_EXPIRED: |
190 | 591 | return expired_; |
191 | 561 | case curl::fuzzer::proto::TLS_OCSP_STAPLE_BAD_SIGNATURE: |
192 | 561 | return bad_signature_; |
193 | 0 | case curl::fuzzer::proto::TLS_OCSP_STAPLE_NONE: |
194 | 0 | default: |
195 | 0 | return none_; |
196 | 7.78k | } |
197 | 7.78k | } |
198 | | |
199 | | private: |
200 | | const std::vector<unsigned char> none_; |
201 | | const std::vector<unsigned char> good_; |
202 | | const std::vector<unsigned char> revoked_; |
203 | | const std::vector<unsigned char> unknown_; |
204 | | const std::vector<unsigned char> try_later_; |
205 | | const std::vector<unsigned char> empty_successful_; |
206 | | const std::vector<unsigned char> sha256_certificate_id_; |
207 | | const std::vector<unsigned char> expired_; |
208 | | const std::vector<unsigned char> bad_signature_; |
209 | | }; |
210 | | |
211 | | const std::vector<unsigned char>& CachedOcspResponse(curl::fuzzer::proto::TlsOcspStapleProfile profile, |
212 | 7.78k | X509* certificate, X509* issuer, EVP_PKEY* issuer_private_key) { |
213 | 7.78k | static const TlsOcspResponseCache cache(certificate, issuer, issuer_private_key); |
214 | 7.78k | return cache.Get(profile); |
215 | 7.78k | } |
216 | | |
217 | | /// @return whether the selected value owns a generated stapled response. |
218 | 248k | bool IsKnownOcspStapleProfile(curl::fuzzer::proto::TlsOcspStapleProfile profile) { |
219 | 248k | switch (profile) { |
220 | 2.56k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_GOOD: |
221 | 4.60k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_REVOKED: |
222 | 7.07k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_UNKNOWN: |
223 | 9.10k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_TRY_LATER: |
224 | 10.6k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_EMPTY_SUCCESSFUL: |
225 | 13.2k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_SHA256_CERT_ID: |
226 | 14.4k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_EXPIRED: |
227 | 15.5k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_BAD_SIGNATURE: |
228 | 15.5k | return true; |
229 | 233k | case curl::fuzzer::proto::TLS_OCSP_STAPLE_NONE: |
230 | 233k | default: |
231 | 233k | return false; |
232 | 248k | } |
233 | 248k | } |
234 | | |
235 | | } // namespace |
236 | | |
237 | | /// Derive the correlated peer policy from the same bounded option prefix curl |
238 | | /// receives. Later duplicate options replace earlier values, matching |
239 | | /// sequential curl_easy_setopt calls. |
240 | | /// @param scenario Structured input whose retained option prefix is inspected. |
241 | | /// @return Server policy matching the effective SSL_OPTIONS value. |
242 | 60.3k | TlsEarlyDataPolicy EarlyDataPolicyForScenario(const curl::fuzzer::proto::Scenario& scenario) { |
243 | 60.3k | std::uint64_t ssl_options = 0; |
244 | 60.3k | const std::size_t option_count = RuntimeOptionCount(scenario); |
245 | 266k | for (std::size_t index = 0; index < option_count; ++index) { |
246 | 205k | const auto& option = scenario.options(static_cast<int>(index)); |
247 | 205k | if (option.option_id() == curl::fuzzer::proto::CURLOPT_SSL_OPTIONS) { |
248 | 1.82k | ssl_options = DecodeIntegralOptionValue(option); |
249 | 1.82k | } |
250 | 205k | } |
251 | 60.3k | return (ssl_options & static_cast<std::uint64_t>(CURLSSLOPT_EARLYDATA)) != 0 ? TlsEarlyDataPolicy::kAdvertiseAndReject |
252 | 60.3k | : TlsEarlyDataPolicy::kDisabled; |
253 | 60.3k | } |
254 | | |
255 | | /// Own the certificate, key, session cache, ALPN policy, and observations |
256 | | /// shared by every bounded connection in one Scenario. Keeping both session |
257 | | /// state and its measurements here makes redirects related while preventing |
258 | | /// one fuzz input from affecting the next. |
259 | | class TlsServerContext { |
260 | | public: |
261 | | // Doxygen's no-preprocessing pass would see both conditional body openings. |
262 | | // Skip this implementation-only constructor to preserve the enclosing scope. |
263 | | /// @cond |
264 | | TlsServerContext(TlsApplicationProtocol protocol, curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
265 | | TlsGroupPolicy group_policy, TlsEarlyDataPolicy early_data_policy, |
266 | | curl::fuzzer::proto::TlsOcspStapleProfile ocsp_staple_profile) |
267 | 124k | : context_(nullptr), |
268 | 124k | protocol_(protocol), |
269 | 124k | group_policy_(group_policy), |
270 | 124k | early_data_policy_(early_data_policy), |
271 | 124k | ocsp_response_(nullptr), |
272 | 124k | negotiated_tls_version_(0), |
273 | 124k | completed_handshake_count_(0), |
274 | 124k | reused_session_count_(0), |
275 | 124k | write_retry_count_(0), |
276 | | #ifndef OPENSSL_NO_ECH |
277 | 124k | ech_status_(SSL_ECH_STATUS_NOT_TRIED) { |
278 | | #else |
279 | | ech_status_(-1) { |
280 | | #endif |
281 | 124k | OpenSslErrorQueueGuard error_guard; |
282 | 124k | context_ = SSL_CTX_new(TLS_server_method()); |
283 | 124k | const bool use_issuer_signed_leaf = IsKnownOcspStapleProfile(ocsp_staple_profile); |
284 | 124k | if (context_ == nullptr || !ApplyGroupPolicy() || !ApplyEarlyDataPolicy() || |
285 | 124k | !InstallCachedTlsTestCredentials(context_, certificate_chain, use_issuer_signed_leaf) || |
286 | 124k | !ApplyOcspStapleProfile(ocsp_staple_profile) || !LoadEchConfig()) { |
287 | 0 | SSL_CTX_free(context_); |
288 | 0 | context_ = nullptr; |
289 | 0 | return; |
290 | 0 | } |
291 | | |
292 | 124k | (void)SSL_CTX_set_min_proto_version(context_, TLS1_2_VERSION); |
293 | 124k | (void)SSL_CTX_set_options(context_, SSL_OP_NO_COMPRESSION); |
294 | 124k | (void)SSL_CTX_set_session_cache_mode(context_, SSL_SESS_CACHE_SERVER); |
295 | 124k | constexpr unsigned char session_id_context[] = "curl-fuzzer"; |
296 | 124k | (void)SSL_CTX_set_session_id_context(context_, session_id_context, sizeof(session_id_context) - 1); |
297 | 124k | SSL_CTX_set_alpn_select_cb(context_, &SelectAlpn, &protocol_); |
298 | 124k | } |
299 | | /// @endcond |
300 | | |
301 | 124k | ~TlsServerContext() { |
302 | 124k | OpenSslErrorQueueGuard error_guard; |
303 | 124k | SSL_CTX_free(context_); |
304 | 124k | } |
305 | | |
306 | | TlsServerContext(const TlsServerContext&) = delete; |
307 | | TlsServerContext& operator=(const TlsServerContext&) = delete; |
308 | | |
309 | | /// @return the configured context, or nullptr when credential setup failed. |
310 | 177k | SSL_CTX* get() const { return context_; } |
311 | | |
312 | | /// Retain only scalar handshake results; SSL itself remains connection-owned. |
313 | | /// @param ssl connection that has just completed SSL_accept. |
314 | 161k | void RecordHandshake(SSL* ssl) { |
315 | 161k | if (ssl == nullptr) { |
316 | 0 | return; |
317 | 0 | } |
318 | 161k | negotiated_tls_version_ = SSL_version(ssl); |
319 | 161k | const unsigned char* alpn = nullptr; |
320 | 161k | unsigned int alpn_length = 0; |
321 | 161k | SSL_get0_alpn_selected(ssl, &alpn, &alpn_length); |
322 | 161k | if (alpn != nullptr && alpn_length != 0) { |
323 | 112k | negotiated_alpn_.assign(reinterpret_cast<const char*>(alpn), alpn_length); |
324 | 112k | } else { |
325 | 48.7k | negotiated_alpn_.clear(); |
326 | 48.7k | } |
327 | 161k | ++completed_handshake_count_; |
328 | 161k | if (SSL_session_reused(ssl) == 1) { |
329 | 32.9k | ++reused_session_count_; |
330 | 32.9k | } |
331 | 161k | const int negotiated_group = SSL_get_negotiated_group(ssl); |
332 | 161k | const char* group_name = negotiated_group == 0 ? nullptr : SSL_group_to_name(ssl, negotiated_group); |
333 | 161k | negotiated_group_ = group_name == nullptr ? std::string() : group_name; |
334 | 161k | #ifndef OPENSSL_NO_ECH |
335 | 161k | char* inner_name = nullptr; |
336 | 161k | char* outer_name = nullptr; |
337 | 161k | ech_status_ = SSL_ech_get1_status(ssl, &inner_name, &outer_name); |
338 | 161k | ech_inner_name_ = inner_name == nullptr ? std::string() : inner_name; |
339 | 161k | ech_outer_name_ = outer_name == nullptr ? std::string() : outer_name; |
340 | 161k | OPENSSL_free(inner_name); |
341 | 161k | OPENSSL_free(outer_name); |
342 | 161k | #endif |
343 | 161k | } |
344 | | |
345 | | /// Record that OpenSSL requires an identical application-write retry. |
346 | 105 | void RecordWriteRetry() { ++write_retry_count_; } |
347 | | |
348 | | /// @return protocol version from the most recent completed handshake. |
349 | 15.7k | int negotiated_tls_version() const { return negotiated_tls_version_; } |
350 | | /// @return number of connections that completed their handshake. |
351 | 966k | std::size_t completed_handshake_count() const { return completed_handshake_count_; } |
352 | | /// @return number of completed handshakes that reused a session. |
353 | 7 | std::size_t reused_session_count() const { return reused_session_count_; } |
354 | | /// @return number of application writes that OpenSSL asked to retry. |
355 | 7 | std::size_t write_retry_count() const { return write_retry_count_; } |
356 | | /// @return ALPN protocol from the most recent completed handshake. |
357 | 15.7k | const std::string& negotiated_alpn() const { return negotiated_alpn_; } |
358 | | /// @return key-exchange group from the most recent completed handshake. |
359 | 7 | const std::string& negotiated_group() const { return negotiated_group_; } |
360 | | /// @return fixed application protocol this context offers. |
361 | 159k | TlsApplicationProtocol protocol() const { return protocol_; } |
362 | | /// @return OpenSSL ECH result from the latest completed handshake. |
363 | 7 | int ech_status() const { return ech_status_; } |
364 | | /// @return latest decrypted inner SNI, if ECH was attempted. |
365 | 7 | const std::string& ech_inner_name() const { return ech_inner_name_; } |
366 | | /// @return latest public outer SNI, if ECH was attempted. |
367 | 7 | const std::string& ech_outer_name() const { return ech_outer_name_; } |
368 | | |
369 | | private: |
370 | | /// Apply the constructor-selected group policy before any SSL is created. |
371 | | /// @return true when the provider accepted the requested policy. |
372 | 124k | bool ApplyGroupPolicy() { |
373 | 124k | switch (group_policy_) { |
374 | 110k | case TlsGroupPolicy::kProviderDefault: |
375 | 110k | return true; |
376 | 14.3k | case TlsGroupPolicy::kX25519: |
377 | 14.3k | return SSL_CTX_set1_groups_list(context_, "X25519") == 1; |
378 | 124k | } |
379 | 0 | return false; |
380 | 124k | } |
381 | | |
382 | | /// Advertise a bounded TLS 1.3 allowance without consuming early data. The |
383 | | /// ordinary SSL_accept path rejects it, so curl must replay the request |
384 | | /// after completing the resumed handshake. |
385 | | /// @return true when OpenSSL accepted the selected policy. |
386 | 124k | bool ApplyEarlyDataPolicy() { |
387 | 124k | switch (early_data_policy_) { |
388 | 123k | case TlsEarlyDataPolicy::kDisabled: |
389 | 123k | return true; |
390 | 507 | case TlsEarlyDataPolicy::kAdvertiseAndReject: |
391 | 507 | return SSL_CTX_set_max_early_data(context_, kMaxEarlyDataSize) == 1; |
392 | 124k | } |
393 | 0 | return false; |
394 | 124k | } |
395 | | |
396 | | /// Install a context callback that copies one cached DER response into each |
397 | | /// SSL object whose client requested certificate status. |
398 | 124k | bool ApplyOcspStapleProfile(curl::fuzzer::proto::TlsOcspStapleProfile profile) { |
399 | 124k | if (!IsKnownOcspStapleProfile(profile)) { |
400 | 116k | return true; |
401 | 116k | } |
402 | 7.78k | X509* certificate = SSL_CTX_get0_certificate(context_); |
403 | 7.78k | X509* issuer = CachedTlsTestIssuerCertificate(); |
404 | 7.78k | EVP_PKEY* issuer_private_key = CachedTlsTestIssuerPrivateKey(); |
405 | 7.78k | const std::vector<unsigned char>& response = CachedOcspResponse(profile, certificate, issuer, issuer_private_key); |
406 | 7.78k | if (response.empty()) { |
407 | 0 | return false; |
408 | 0 | } |
409 | 7.78k | ocsp_response_ = &response; |
410 | 7.78k | return SSL_CTX_set_tlsext_status_cb(context_, &ServeOcspStaple) == 1 && |
411 | 7.78k | SSL_CTX_set_tlsext_status_arg(context_, this) == 1; |
412 | 7.78k | } |
413 | | |
414 | | /// Copy the immutable process-cached response into one connection. OpenSSL |
415 | | /// takes ownership only after SSL_set_tlsext_status_ocsp_resp succeeds. |
416 | 5.28k | static int ServeOcspStaple(SSL* ssl, void* user_data) { |
417 | 5.28k | auto* server = static_cast<TlsServerContext*>(user_data); |
418 | 5.28k | if (ssl == nullptr || server == nullptr || server->ocsp_response_ == nullptr) { |
419 | 0 | return SSL_TLSEXT_ERR_NOACK; |
420 | 0 | } |
421 | 5.28k | const std::vector<unsigned char>& response = *server->ocsp_response_; |
422 | 5.28k | auto* copy = static_cast<unsigned char*>(OPENSSL_memdup(response.data(), response.size())); |
423 | 5.28k | if (copy == nullptr) { |
424 | 0 | return SSL_TLSEXT_ERR_ALERT_FATAL; |
425 | 0 | } |
426 | 5.28k | if (SSL_set_tlsext_status_ocsp_resp(ssl, copy, response.size()) != 1) { |
427 | 0 | OPENSSL_free(copy); |
428 | 0 | return SSL_TLSEXT_ERR_ALERT_FATAL; |
429 | 0 | } |
430 | 5.28k | return SSL_TLSEXT_ERR_OK; |
431 | 5.28k | } |
432 | | |
433 | | /// Load a fixed test-only ECH private key and matching public config. This |
434 | | /// makes a successful encrypted ClientHello deterministic without DNS or |
435 | | /// filesystem state; builds configured without ECH retain the TLS mock. |
436 | 124k | bool LoadEchConfig() { |
437 | 124k | #ifndef OPENSSL_NO_ECH |
438 | 124k | BIO* ech_bio = BIO_new_mem_buf(tls_test_credentials::kEchConfigPem, -1); |
439 | 124k | OSSL_ECHSTORE* store = OSSL_ECHSTORE_new(nullptr, nullptr); |
440 | 124k | if (ech_bio == nullptr || store == nullptr) { |
441 | 0 | BIO_free(ech_bio); |
442 | 0 | OSSL_ECHSTORE_free(store); |
443 | 0 | return false; |
444 | 0 | } |
445 | 124k | const bool loaded = |
446 | 124k | OSSL_ECHSTORE_read_pem(store, ech_bio, OSSL_ECH_NO_RETRY) == 1 && SSL_CTX_set1_echstore(context_, store) == 1; |
447 | 124k | BIO_free(ech_bio); |
448 | 124k | OSSL_ECHSTORE_free(store); |
449 | 124k | return loaded; |
450 | | #else |
451 | | return true; |
452 | | #endif |
453 | 124k | } |
454 | | |
455 | | SSL_CTX* context_; |
456 | | TlsApplicationProtocol protocol_; |
457 | | const TlsGroupPolicy group_policy_; |
458 | | const TlsEarlyDataPolicy early_data_policy_; |
459 | | const std::vector<unsigned char>* ocsp_response_; |
460 | | std::string negotiated_alpn_; |
461 | | std::string negotiated_group_; |
462 | | int negotiated_tls_version_; |
463 | | std::size_t completed_handshake_count_; |
464 | | std::size_t reused_session_count_; |
465 | | std::size_t write_retry_count_; |
466 | | int ech_status_; |
467 | | std::string ech_inner_name_; |
468 | | std::string ech_outer_name_; |
469 | | }; |
470 | | |
471 | | namespace { |
472 | | |
473 | | /// TLS-aware MockConnection. Application writes are queued before the client |
474 | | /// starts, then encrypted only after SSL_accept has completed. This preserves |
475 | | /// MockServer's useful initial_response semantics without ever putting those |
476 | | /// plaintext bytes onto the TLS wire. |
477 | | class TlsMockConnection final : public MockConnection { |
478 | | public: |
479 | | explicit TlsMockConnection(TlsServerContext* context) |
480 | 177k | : ssl_(nullptr), |
481 | 177k | context_(context), |
482 | 177k | pending_offset_(0), |
483 | 177k | pending_write_end_(0), |
484 | 177k | handshake_complete_(false), |
485 | 177k | shutdown_requested_(false), |
486 | 177k | write_shutdown_(false), |
487 | 177k | failed_(false) { |
488 | 177k | InitializeSsl(); |
489 | 177k | } |
490 | | |
491 | | TlsMockConnection(TlsServerContext* context, int accepted_fd) |
492 | 514 | : MockConnection(accepted_fd), |
493 | 514 | ssl_(nullptr), |
494 | 514 | context_(context), |
495 | 514 | pending_offset_(0), |
496 | 514 | pending_write_end_(0), |
497 | 514 | handshake_complete_(false), |
498 | 514 | shutdown_requested_(false), |
499 | 514 | write_shutdown_(false), |
500 | 514 | failed_(false) { |
501 | 514 | InitializeSsl(); |
502 | 514 | } |
503 | | |
504 | 177k | ~TlsMockConnection() override { |
505 | 177k | OpenSslErrorQueueGuard error_guard; |
506 | 177k | if (ssl_ != nullptr) { |
507 | 177k | SSL_free(ssl_); |
508 | 177k | } |
509 | 177k | } |
510 | | |
511 | | /// Require both the socketpair and its OpenSSL wrapper to be usable. |
512 | 2.17M | bool ok() const override { return MockConnection::ok() && ssl_ != nullptr; } |
513 | | |
514 | | /// Queue bounded application bytes until the handshake can encrypt them. |
515 | 424k | bool WriteAll(const unsigned char* data, std::size_t size) override { |
516 | 424k | if (failed_ || (data == nullptr && size != 0) || size > pending_plaintext_.max_size() - pending_plaintext_.size()) { |
517 | 2.35k | return false; |
518 | 2.35k | } |
519 | 422k | if (size != 0) { |
520 | 422k | pending_plaintext_.append(reinterpret_cast<const char*>(data), size); |
521 | 422k | } |
522 | 422k | return true; |
523 | 424k | } |
524 | | |
525 | | /// Advance the handshake, consume encrypted request records, flush queued |
526 | | /// response records, and finish a requested close without ever waiting. |
527 | | /// @return decrypted/application bytes plus state transitions made this turn. |
528 | 1.99M | std::size_t DrainIncoming() override { |
529 | 1.99M | if (!ok() || failed_) { |
530 | 14.2k | return 0; |
531 | 14.2k | } |
532 | | |
533 | 1.98M | OpenSslErrorQueueGuard error_guard; |
534 | 1.98M | std::size_t progress = 0; |
535 | 1.98M | if (!handshake_complete_) { |
536 | 488k | const int state_before = static_cast<int>(SSL_get_state(ssl_)); |
537 | 488k | const int result = SSL_accept(ssl_); |
538 | | // SSL_get_error must be the next OpenSSL call after failed I/O. Even a |
539 | | // state query in between would make its use formally unreliable. |
540 | 488k | const int error = result == 1 ? SSL_ERROR_NONE : SSL_get_error(ssl_, result); |
541 | 488k | const int state_after = static_cast<int>(SSL_get_state(ssl_)); |
542 | 488k | if (state_after != state_before) { |
543 | 331k | ++progress; |
544 | 331k | } |
545 | 488k | if (result == 1) { |
546 | 161k | handshake_complete_ = true; |
547 | 161k | if (context_ != nullptr) { |
548 | 161k | context_->RecordHandshake(ssl_); |
549 | 161k | } |
550 | 161k | ++progress; |
551 | 326k | } else { |
552 | 326k | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) { |
553 | 324k | return progress; |
554 | 324k | } |
555 | 2.32k | failed_ = true; |
556 | 2.32k | return progress; |
557 | 326k | } |
558 | 488k | } |
559 | | |
560 | | // A WANT result leaves SSL_write_ex in flight. OpenSSL requires the next |
561 | | // I/O operation to retry that exact write, so do not interpose SSL_read_ex |
562 | | // merely because the outer driver has yielded back to us. |
563 | 1.65M | if (pending_write_end_ != 0) { |
564 | 105 | progress += FlushPendingWrites(); |
565 | 105 | if (failed_ || pending_write_end_ != 0) { |
566 | 99 | return progress; |
567 | 99 | } |
568 | 105 | } |
569 | | |
570 | 1.65M | unsigned char request[4096]; |
571 | 2.34M | while (true) { |
572 | 2.34M | std::size_t received = 0; |
573 | 2.34M | const int result = SSL_read_ex(ssl_, request, sizeof(request), &received); |
574 | 2.34M | if (result == 1 && received != 0) { |
575 | 687k | NotifyIncomingData(request, received); |
576 | 687k | progress += received; |
577 | 687k | continue; |
578 | 687k | } |
579 | 1.65M | if (result != 1) { |
580 | 1.65M | const int error = SSL_get_error(ssl_, result); |
581 | 1.65M | if (error == SSL_ERROR_ZERO_RETURN) { |
582 | | // The client sent close_notify. TLS requires a reciprocal close_notify |
583 | | // before the orderly shutdown completes; protocols such as FTP upload |
584 | | // wait for that completion even though the application data is done. |
585 | 239k | shutdown_requested_ = true; |
586 | 1.41M | } else if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { |
587 | 11.3k | failed_ = true; |
588 | 11.3k | } |
589 | 1.65M | } |
590 | 1.65M | break; |
591 | 2.34M | } |
592 | | |
593 | 1.65M | progress += FlushPendingWrites(); |
594 | | |
595 | 1.65M | if (!failed_ && shutdown_requested_ && pending_plaintext_.empty() && !write_shutdown_) { |
596 | 118k | const int result = SSL_shutdown(ssl_); |
597 | 118k | if (result >= 0) { |
598 | | // The first successful call sends close_notify. The fuzzer does not |
599 | | // need to wait for the client's reciprocal alert before exposing EOF. |
600 | 118k | (void)::shutdown(server_fd(), SHUT_WR); |
601 | 118k | write_shutdown_ = true; |
602 | 118k | ++progress; |
603 | 118k | } else { |
604 | 18 | const int error = SSL_get_error(ssl_, result); |
605 | 18 | if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { |
606 | 17 | failed_ = true; |
607 | 17 | } |
608 | 18 | } |
609 | 118k | } |
610 | 1.65M | return progress; |
611 | 1.65M | } |
612 | | |
613 | | /// Defer close_notify until every queued plaintext byte has become a record. |
614 | 159k | void ShutdownWrite() override { |
615 | | // An HTTP/2 proxy connection outlives the scripted origin response inside |
616 | | // its CONNECT stream. Half-closing TLS when the last script chunk is |
617 | | // queued would make curl observe a dead proxy rather than exercise its |
618 | | // own stream/session shutdown and GOAWAY handling. |
619 | 159k | if (context_ != nullptr && context_->protocol() == TlsApplicationProtocol::kHttp2) { |
620 | 28.6k | return; |
621 | 28.6k | } |
622 | 130k | shutdown_requested_ = true; |
623 | 130k | (void)DrainIncoming(); |
624 | 130k | } |
625 | | |
626 | | private: |
627 | | /// Bind a server-side SSL object to the already-owned transport endpoint. |
628 | 177k | void InitializeSsl() { |
629 | 177k | OpenSslErrorQueueGuard error_guard; |
630 | 177k | SSL_CTX* ssl_context = context_ == nullptr ? nullptr : context_->get(); |
631 | 177k | ssl_ = ssl_context == nullptr ? nullptr : SSL_new(ssl_context); |
632 | 177k | if (ssl_ == nullptr) { |
633 | 0 | return; |
634 | 0 | } |
635 | 177k | SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); |
636 | 177k | if (SSL_set_fd(ssl_, server_fd()) != 1) { |
637 | 0 | SSL_free(ssl_); |
638 | 0 | ssl_ = nullptr; |
639 | 0 | return; |
640 | 0 | } |
641 | 177k | SSL_set_accept_state(ssl_); |
642 | 177k | } |
643 | | |
644 | | /// Flush queued response bytes while preserving any OpenSSL retry boundary. |
645 | | /// @return plaintext bytes OpenSSL accepted during this call. |
646 | 1.65M | std::size_t FlushPendingWrites() { |
647 | 1.65M | std::size_t progress = 0; |
648 | 2.01M | while (!failed_ && pending_offset_ < pending_plaintext_.size()) { |
649 | 363k | if (pending_write_end_ == 0) { |
650 | | // Freeze one write boundary until OpenSSL accepts it. WriteAll may |
651 | | // append the next scripted chunk after WANT_READ/WANT_WRITE, but the |
652 | | // retry contract permits only pointer relocation—not changed bytes or |
653 | | // length—for the outstanding SSL_write_ex call. |
654 | 361k | pending_write_end_ = pending_plaintext_.size(); |
655 | 361k | } |
656 | 363k | std::size_t written = 0; |
657 | 363k | const int result = SSL_write_ex(ssl_, pending_plaintext_.data() + pending_offset_, |
658 | 363k | pending_write_end_ - pending_offset_, &written); |
659 | 363k | if (result == 1) { |
660 | 362k | if (written == 0) { |
661 | 0 | failed_ = true; |
662 | 0 | break; |
663 | 0 | } |
664 | 362k | pending_offset_ += written; |
665 | 362k | progress += written; |
666 | 362k | if (pending_offset_ == pending_write_end_) { |
667 | 361k | pending_write_end_ = 0; |
668 | 361k | } |
669 | 362k | continue; |
670 | 362k | } |
671 | 878 | const int error = SSL_get_error(ssl_, result); |
672 | 878 | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) { |
673 | 105 | if (context_ != nullptr) { |
674 | 105 | context_->RecordWriteRetry(); |
675 | 105 | } |
676 | 773 | } else { |
677 | 773 | failed_ = true; |
678 | 773 | } |
679 | 878 | break; |
680 | 363k | } |
681 | 1.65M | if (pending_offset_ == pending_plaintext_.size()) { |
682 | 1.65M | pending_plaintext_.clear(); |
683 | 1.65M | pending_offset_ = 0; |
684 | 1.65M | pending_write_end_ = 0; |
685 | 1.65M | } |
686 | 1.65M | return progress; |
687 | 1.65M | } |
688 | | |
689 | | SSL* ssl_; |
690 | | TlsServerContext* context_; |
691 | | std::string pending_plaintext_; |
692 | | std::size_t pending_offset_; |
693 | | /// Exclusive end of a write that OpenSSL may require us to retry exactly. |
694 | | std::size_t pending_write_end_; |
695 | | bool handshake_complete_; |
696 | | bool shutdown_requested_; |
697 | | bool write_shutdown_; |
698 | | bool failed_; |
699 | | }; |
700 | | |
701 | | /// Emit one fixed clean-shutdown alert without completing a server handshake. |
702 | | /// OpenSSL classifies this as SSL_ERROR_ZERO_RETURN with an empty error queue; |
703 | | /// ignoring scripted response bytes keeps protobuf data out of the TLS record. |
704 | | class TlsCloseNotifyConnection final : public MockConnection { |
705 | | public: |
706 | 276 | TlsCloseNotifyConnection() : alert_sent_(false) {} |
707 | | |
708 | 431 | bool WriteAll(const unsigned char* /*data*/, std::size_t /*size*/) override { return true; } |
709 | | |
710 | 262 | void ShutdownWrite() override { |
711 | 262 | if (alert_sent_) { |
712 | 0 | return; |
713 | 0 | } |
714 | 262 | static constexpr unsigned char kCloseNotify[] = { |
715 | 262 | 0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x00, |
716 | 262 | }; |
717 | 262 | alert_sent_ = true; |
718 | 262 | (void)MockConnection::WriteAll(kCloseNotify, sizeof(kCloseNotify)); |
719 | 262 | MockConnection::ShutdownWrite(); |
720 | 262 | } |
721 | | |
722 | | private: |
723 | | bool alert_sent_; |
724 | | }; |
725 | | |
726 | | /// Emit one fixed TLS handshake record containing an empty HelloRequest. |
727 | | /// This deliberately predates negotiation and ignores scripted HTTP bytes: |
728 | | /// its only purpose is to drive OpenSSL's message callback through the |
729 | | /// SSL3_MT_HELLO_REQUEST label with harness-owned bytes. |
730 | | class TlsHelloRequestConnection final : public MockConnection { |
731 | | public: |
732 | 215 | TlsHelloRequestConnection() : record_sent_(false) {} |
733 | | |
734 | 155 | bool WriteAll(const unsigned char* /*data*/, std::size_t /*size*/) override { return SendOnce(); } |
735 | | |
736 | 190 | void ShutdownWrite() override { |
737 | 190 | (void)SendOnce(); |
738 | 190 | MockConnection::ShutdownWrite(); |
739 | 190 | } |
740 | | |
741 | | private: |
742 | 345 | bool SendOnce() { |
743 | 345 | if (record_sent_) { |
744 | 137 | return true; |
745 | 137 | } |
746 | 208 | static constexpr unsigned char kHelloRequest[] = { |
747 | 208 | 0x16, 0x03, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, |
748 | 208 | }; |
749 | 208 | record_sent_ = MockConnection::WriteAll(kHelloRequest, sizeof(kHelloRequest)); |
750 | 208 | return record_sent_; |
751 | 345 | } |
752 | | |
753 | | bool record_sent_; |
754 | | }; |
755 | | |
756 | | } // namespace |
757 | | |
758 | | /// Construct one reusable TLS context for a protocol-specific peer. |
759 | | /// @param protocol Fixed ALPN application protocol offered by the server. |
760 | | /// @param certificate_chain Certificate-chain profile presented to curl. |
761 | | /// @param group_policy Immutable server key-exchange group policy. |
762 | | /// @param handshake_profile Closed peer-side handshake terminal. |
763 | | /// @param early_data_policy Fixed server-side TLS 1.3 early-data behavior. |
764 | | /// @param ocsp_staple_profile Fixed server-side stapled OCSP response. |
765 | | TlsMockTransport::TlsMockTransport(TlsApplicationProtocol protocol, |
766 | | curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
767 | | TlsGroupPolicy group_policy, |
768 | | curl::fuzzer::proto::TlsHandshakeProfile handshake_profile, |
769 | | TlsEarlyDataPolicy early_data_policy, |
770 | | curl::fuzzer::proto::TlsOcspStapleProfile ocsp_staple_profile) |
771 | 124k | : group_policy_(group_policy), |
772 | 124k | openssl_close_notify_(handshake_profile == curl::fuzzer::proto::TLS_HANDSHAKE_OPENSSL_CLOSE_NOTIFY && |
773 | 2.76k | CurlClientUsesOpenSsl()), |
774 | 124k | openssl_hello_request_(handshake_profile == curl::fuzzer::proto::TLS_HANDSHAKE_OPENSSL_HELLO_REQUEST && |
775 | 1.84k | CurlClientUsesOpenSsl()), |
776 | 124k | context_(std::make_unique<TlsServerContext>(protocol, certificate_chain, group_policy, early_data_policy, |
777 | 124k | ocsp_staple_profile)) {} |
778 | | |
779 | 124k | TlsMockTransport::~TlsMockTransport() = default; |
780 | | |
781 | | /// Install the stable local trust anchor and strict peer verification. Socket |
782 | | /// callbacks remain owned by the protocol-specific server using this carrier. |
783 | | /// @param easy Easy handle that will connect to this TLS transport. |
784 | 134k | void TlsMockTransport::Install(CURL* easy) const { |
785 | 134k | struct curl_blob trust_anchor = {const_cast<char*>(tls_test_credentials::kCertificatePem), |
786 | 134k | sizeof(tls_test_credentials::kCertificatePem) - 1, CURL_BLOB_NOCOPY}; |
787 | 134k | (void)curl_easy_setopt(easy, CURLOPT_CAINFO_BLOB, &trust_anchor); |
788 | 134k | (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 1L); |
789 | 134k | (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYHOST, 2L); |
790 | 134k | } |
791 | | |
792 | | /// Wrap one socketpair server endpoint in an OpenSSL acceptor. |
793 | | /// @return A failed connection when context setup was unavailable. |
794 | 177k | std::unique_ptr<MockConnection> TlsMockTransport::CreateConnection() { |
795 | 177k | if (openssl_close_notify_) { |
796 | 276 | return std::make_unique<TlsCloseNotifyConnection>(); |
797 | 276 | } |
798 | 177k | if (openssl_hello_request_) { |
799 | 215 | return std::make_unique<TlsHelloRequestConnection>(); |
800 | 215 | } |
801 | 177k | return std::make_unique<TlsMockConnection>(context_.get()); |
802 | 177k | } |
803 | | |
804 | | /// Wrap one accepted loopback descriptor in this transport's OpenSSL server |
805 | | /// context. The special pre-handshake terminal profiles apply only to the |
806 | | /// socketpair fuzz lanes; a listener-backed peer always performs real TLS. |
807 | | /// @param accepted_fd Connected descriptor whose ownership transfers. |
808 | | /// @return TLS connection owning `accepted_fd`. |
809 | 514 | std::unique_ptr<MockConnection> TlsMockTransport::CreateAcceptedConnection(int accepted_fd) { |
810 | 514 | return std::make_unique<TlsMockConnection>(context_.get(), accepted_fd); |
811 | 514 | } |
812 | | |
813 | | /// @return Protocol version selected by the most recent handshake, or zero. |
814 | 15.7k | int TlsMockTransport::negotiated_tls_version() const { |
815 | 15.7k | return context_ == nullptr ? 0 : context_->negotiated_tls_version(); |
816 | 15.7k | } |
817 | | |
818 | | /// @return Number of connections that completed TLS negotiation. |
819 | 966k | std::size_t TlsMockTransport::completed_handshake_count() const { |
820 | 966k | return context_ == nullptr ? 0 : context_->completed_handshake_count(); |
821 | 966k | } |
822 | | |
823 | | /// @return Number of completed connections that resumed a cached session. |
824 | 7 | std::size_t TlsMockTransport::reused_session_count() const { |
825 | 7 | return context_ == nullptr ? 0 : context_->reused_session_count(); |
826 | 7 | } |
827 | | |
828 | | /// @return Number of application writes OpenSSL required an exact retry for. |
829 | 7 | std::size_t TlsMockTransport::write_retry_count() const { |
830 | 7 | return context_ == nullptr ? 0 : context_->write_retry_count(); |
831 | 7 | } |
832 | | |
833 | | /// @return ALPN protocol selected by the most recent handshake. |
834 | 15.7k | std::string TlsMockTransport::negotiated_alpn() const { |
835 | 15.7k | return context_ == nullptr ? std::string() : context_->negotiated_alpn(); |
836 | 15.7k | } |
837 | | |
838 | | /// @return Immutable key-exchange group policy selected at construction. |
839 | 15.5k | TlsGroupPolicy TlsMockTransport::group_policy() const { return group_policy_; } |
840 | | |
841 | | /// @return Key-exchange group from the most recent completed handshake. |
842 | 7 | std::string TlsMockTransport::negotiated_group() const { |
843 | 7 | return context_ == nullptr ? std::string() : context_->negotiated_group(); |
844 | 7 | } |
845 | | |
846 | | /// @return OpenSSL's ECH result, or a negative sentinel when unavailable. |
847 | 7 | int TlsMockTransport::ech_status() const { return context_ == nullptr ? -1 : context_->ech_status(); } |
848 | | |
849 | | /// @return Decrypted inner SNI recovered by the ECH-capable server. |
850 | 7 | std::string TlsMockTransport::ech_inner_name() const { |
851 | 7 | return context_ == nullptr ? std::string() : context_->ech_inner_name(); |
852 | 7 | } |
853 | | |
854 | | /// @return Public outer SNI visible before ECH decryption. |
855 | 7 | std::string TlsMockTransport::ech_outer_name() const { |
856 | 7 | return context_ == nullptr ? std::string() : context_->ech_outer_name(); |
857 | 7 | } |
858 | | |
859 | | /// Build one reusable in-process server context from the complete Scenario. |
860 | | /// @param scenario Bounded scenario configuring both sides of the transfer. |
861 | 64.8k | TlsMockServer::TlsMockServer(const curl::fuzzer::proto::Scenario& scenario) { Init(scenario, PeerRole::kHttp11); } |
862 | | |
863 | | /// Initialize the transport policy for this server's fixed role. Keeping the |
864 | | /// Scenario intact here prevents call sites and delegating constructors from |
865 | | /// growing parallel parameter lists as correlated TLS controls are added. |
866 | | /// @param scenario Bounded scenario configuring both sides of the transfer. |
867 | | /// @param role Fixed application protocol role implemented by this peer. |
868 | 96.5k | void TlsMockServer::Init(const curl::fuzzer::proto::Scenario& scenario, PeerRole role) { |
869 | 96.5k | assert(transport_ == nullptr); |
870 | | |
871 | 96.5k | TlsApplicationProtocol protocol = TlsApplicationProtocol::kHttp11; |
872 | 96.5k | auto certificate_chain = scenario.tls_certificate_chain(); |
873 | 96.5k | TlsGroupPolicy group_policy = TlsGroupPolicy::kProviderDefault; |
874 | 96.5k | auto handshake_profile = curl::fuzzer::proto::TLS_HANDSHAKE_DEFAULT; |
875 | 96.5k | TlsEarlyDataPolicy early_data_policy = TlsEarlyDataPolicy::kDisabled; |
876 | 96.5k | auto ocsp_staple_profile = curl::fuzzer::proto::TLS_OCSP_STAPLE_NONE; |
877 | 96.5k | session_cache_profile_ = curl::fuzzer::proto::TLS_SESSION_CACHE_DEFAULT; |
878 | | |
879 | 96.5k | switch (role) { |
880 | 64.8k | case PeerRole::kHttp11: |
881 | 64.8k | if (scenario.scheme() == curl::fuzzer::proto::SCHEME_HTTPS) { |
882 | 60.3k | handshake_profile = scenario.tls_handshake_profile(); |
883 | 60.3k | early_data_policy = EarlyDataPolicyForScenario(scenario); |
884 | 60.3k | ocsp_staple_profile = scenario.tls_ocsp_staple_profile(); |
885 | 60.3k | session_cache_profile_ = scenario.tls_session_cache_profile(); |
886 | 60.3k | } |
887 | 64.8k | break; |
888 | 15.6k | case PeerRole::kHttp2Origin: |
889 | 15.6k | protocol = TlsApplicationProtocol::kHttp2; |
890 | 15.6k | group_policy = scenario.tls_group_profile() == curl::fuzzer::proto::TLS_GROUP_PROVIDER_DEFAULT |
891 | 15.6k | ? TlsGroupPolicy::kProviderDefault |
892 | 15.6k | : TlsGroupPolicy::kX25519; |
893 | 15.6k | break; |
894 | 16.0k | case PeerRole::kProxy: |
895 | 16.0k | protocol = scenario.connection().proxy_protocol() == curl::fuzzer::proto::PROXY_PROTOCOL_HTTP1 |
896 | 16.0k | ? TlsApplicationProtocol::kHttp11 |
897 | 16.0k | : TlsApplicationProtocol::kHttp2; |
898 | 16.0k | certificate_chain = curl::fuzzer::proto::TLS_CERTIFICATE_CHAIN_DEFAULT_EC; |
899 | 16.0k | break; |
900 | 96.5k | } |
901 | | |
902 | 96.5k | transport_ = std::make_unique<TlsMockTransport>(protocol, certificate_chain, group_policy, handshake_profile, |
903 | 96.5k | early_data_policy, ocsp_staple_profile); |
904 | 96.5k | } |
905 | | |
906 | | /// Release SSL objects before their owning server context. OpenSSL reference |
907 | | /// counting makes the reverse order legal, but making the ownership order |
908 | | /// explicit keeps future transport state from acquiring a hidden dependency. |
909 | 96.5k | TlsMockServer::~TlsMockServer() { ResetConnections(); } |
910 | | |
911 | | /// Install common socket callbacks and a stable local trust anchor. Curl copies |
912 | | /// the blob descriptor during setopt and borrows the inline certificate bytes, |
913 | | /// whose program lifetime safely exceeds every easy handle. Scenario options run |
914 | | /// afterwards and can still disable verification or select failing TLS settings. |
915 | | /// @param easy Easy handle that will connect to this TLS peer. |
916 | 107k | void TlsMockServer::Install(CURL* easy) { |
917 | 107k | MockServer::Install(easy); |
918 | 107k | transport_->Install(easy); |
919 | 107k | } |
920 | | |
921 | | /// @return true once curl exposed a live TLS backend session during drive. |
922 | 7 | bool TlsMockServer::saw_live_tls_session() const { return saw_live_tls_session_; } |
923 | | |
924 | | /// @return number of session representations copied by the export callback |
925 | | /// out of curl's cache. |
926 | 7 | std::size_t TlsMockServer::exported_session_count() const { return exported_session_count_; } |
927 | | |
928 | | /// @return number of copied session representations successfully imported |
929 | | /// into curl's cache again. |
930 | 7 | std::size_t TlsMockServer::imported_session_count() const { return imported_session_count_; } |
931 | | |
932 | | /// Import the retained session into a caller-configured cache. |
933 | | /// @param easy Fresh easy handle whose cache receives the session. |
934 | | /// @return The public import result for the selected profile. |
935 | 84.6k | CURLcode TlsMockServer::ImportArchivedSession(CURL* easy) { |
936 | 84.6k | CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT; |
937 | 84.6k | switch (session_cache_profile_) { |
938 | 9.04k | case curl::fuzzer::proto::TLS_SESSION_CACHE_FRESH_SALTED_HASH: |
939 | 9.04k | result = session_archive_.ImportBySaltedHash(easy); |
940 | 9.04k | break; |
941 | 9.18k | case curl::fuzzer::proto::TLS_SESSION_CACHE_FRESH_SESSION_KEY: |
942 | 9.18k | result = session_archive_.ImportBySessionKey(easy); |
943 | 9.18k | break; |
944 | 8.73k | case curl::fuzzer::proto::TLS_SESSION_CACHE_MALFORMED_SALTED_HASH: |
945 | 8.73k | result = session_archive_.ImportMalformedSaltedHash(easy); |
946 | 8.73k | break; |
947 | 57.6k | case curl::fuzzer::proto::TLS_SESSION_CACHE_DEFAULT: |
948 | 57.6k | default: |
949 | 57.6k | result = session_archive_.ImportBySaltedHash(easy); |
950 | 57.6k | break; |
951 | 84.6k | } |
952 | 84.6k | if (result == CURLE_OK) { |
953 | 70.0k | ++imported_session_count_; |
954 | 70.0k | } |
955 | 84.6k | return result; |
956 | 84.6k | } |
957 | | |
958 | | /// @return the one bounded session retained from curl's export callback. |
959 | 0 | const TlsSessionArchive& TlsMockServer::session_archive() const { return session_archive_; } |
960 | | |
961 | | /// @return protocol version selected by the most recent completed handshake, |
962 | | /// or zero when no connection completed TLS negotiation. |
963 | 7 | int TlsMockServer::negotiated_tls_version() const { return transport_->negotiated_tls_version(); } |
964 | | |
965 | | /// @return number of connections that completed TLS negotiation. |
966 | 7 | std::size_t TlsMockServer::completed_handshake_count() const { return transport_->completed_handshake_count(); } |
967 | | |
968 | | /// @return number of completed connections that resumed an earlier session. |
969 | 7 | std::size_t TlsMockServer::reused_session_count() const { return transport_->reused_session_count(); } |
970 | | |
971 | | /// @return number of application writes OpenSSL required an exact retry for. |
972 | 7 | std::size_t TlsMockServer::write_retry_count() const { return transport_->write_retry_count(); } |
973 | | |
974 | | /// @return ALPN protocol selected by the most recent completed handshake. |
975 | 7 | std::string TlsMockServer::negotiated_alpn() const { return transport_->negotiated_alpn(); } |
976 | | |
977 | | /// @return Immutable key-exchange group policy selected at construction. |
978 | 15.5k | TlsGroupPolicy TlsMockServer::group_policy() const { return transport_->group_policy(); } |
979 | | |
980 | | /// @return Key-exchange group from the most recent completed handshake. |
981 | 7 | std::string TlsMockServer::negotiated_group() const { return transport_->negotiated_group(); } |
982 | | |
983 | | /// @return OpenSSL's ECH status for the most recent completed handshake. |
984 | | /// Builds without ECH return a negative sentinel. |
985 | 7 | int TlsMockServer::ech_status() const { return transport_->ech_status(); } |
986 | | |
987 | | /// @return encrypted inner SNI recovered by the ECH-capable server. |
988 | 7 | std::string TlsMockServer::ech_inner_name() const { return transport_->ech_inner_name(); } |
989 | | |
990 | | /// @return public outer SNI visible before ECH decryption. |
991 | 7 | std::string TlsMockServer::ech_outer_name() const { return transport_->ech_outer_name(); } |
992 | | |
993 | | /// Wrap one socketpair server endpoint in an OpenSSL acceptor consumed by |
994 | | /// MockServer. |
995 | | /// @return a failed connection when context setup was unavailable. |
996 | 151k | std::unique_ptr<MockConnection> TlsMockServer::CreateConnection() { return transport_->CreateConnection(); } |
997 | | |
998 | | /// Query while the connection filters are attached. Result-info probes stop |
999 | | /// after the first live result, and session export has its own fixed attempt |
1000 | | /// bound, so neither recurs throughout every HTTP parser iteration. |
1001 | | /// @param easy Active easy handle whose connection filters remain attached. |
1002 | 939k | void TlsMockServer::ObserveActiveTransfer(CURL* easy) { |
1003 | 939k | if (!saw_live_tls_session_) { |
1004 | 345k | long verify_result = 0; |
1005 | 345k | curl_off_t appconnect_time = 0; |
1006 | 345k | struct curl_certinfo* certificate_info = nullptr; |
1007 | 345k | struct curl_tlssessioninfo* tls_session = nullptr; |
1008 | 345k | (void)curl_easy_getinfo(easy, CURLINFO_SSL_VERIFYRESULT, &verify_result); |
1009 | 345k | (void)curl_easy_getinfo(easy, CURLINFO_APPCONNECT_TIME_T, &appconnect_time); |
1010 | 345k | (void)curl_easy_getinfo(easy, CURLINFO_CERTINFO, &certificate_info); |
1011 | 345k | if (curl_easy_getinfo(easy, CURLINFO_TLS_SSL_PTR, &tls_session) == CURLE_OK && tls_session != nullptr && |
1012 | 345k | tls_session->internals != nullptr) { |
1013 | 66.9k | saw_live_tls_session_ = true; |
1014 | 66.9k | } |
1015 | 345k | } |
1016 | | |
1017 | | // A TLS 1.3 ticket may arrive after the peer first completes its handshake. |
1018 | | // Retry only a small fixed number of outer-loop observations, and stop |
1019 | | // permanently once one copied ticket has made one import attempt. |
1020 | 939k | const bool completed_live_handshake = transport_->completed_handshake_count() != 0; |
1021 | 939k | #if defined(PROTO_FUZZER_OBSERVE_STATE) |
1022 | | // Read the owned peer observations once after a real handshake. Signed |
1023 | | // status values retain their unavailable sentinels; string results are |
1024 | | // consumed immediately while their temporaries and context are still live. |
1025 | 939k | static bool observed = false; |
1026 | 939k | if (completed_live_handshake && !observed) { |
1027 | 7 | observed = true; |
1028 | 7 | const volatile bool live = saw_live_tls_session(); |
1029 | 7 | const volatile int status[] = {negotiated_tls_version(), ech_status()}; |
1030 | 7 | const volatile std::size_t counts[] = { |
1031 | 7 | exported_session_count(), imported_session_count(), completed_handshake_count(), |
1032 | 7 | reused_session_count(), write_retry_count(), negotiated_alpn().size(), |
1033 | 7 | negotiated_group().size(), ech_inner_name().size(), ech_outer_name().size()}; |
1034 | 7 | (void)live; |
1035 | 7 | (void)status; |
1036 | 7 | (void)counts; |
1037 | 7 | } |
1038 | 939k | #endif |
1039 | 939k | if (!completed_live_handshake || exported_session_count_ != 0 || |
1040 | 815k | session_export_attempt_count_ >= kMaxSessionExportAttempts) { |
1041 | 815k | return; |
1042 | 815k | } |
1043 | 123k | ++session_export_attempt_count_; |
1044 | 123k | const CURLcode export_result = session_archive_.CaptureFrom(easy); |
1045 | 123k | if (export_result != CURLE_OK || session_archive_.empty()) { |
1046 | 46.0k | return; |
1047 | 46.0k | } |
1048 | 77.7k | ++exported_session_count_; |
1049 | | |
1050 | | // curl holds the cache lock throughout export. Import only after the public |
1051 | | // export call returns. Nondefault profiles wait until the runner destroys |
1052 | | // this handle and installs a new cache on the replay handle. |
1053 | 77.7k | if (session_cache_profile_ == curl::fuzzer::proto::TLS_SESSION_CACHE_DEFAULT) { |
1054 | 57.6k | (void)ImportArchivedSession(easy); |
1055 | 57.6k | } |
1056 | 77.7k | } |
1057 | | |
1058 | | } // namespace proto_fuzzer |