/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/ech.h> |
14 | | #include <openssl/err.h> |
15 | | #include <openssl/ssl.h> |
16 | | #include <sys/socket.h> |
17 | | |
18 | | #include <cstddef> |
19 | | #include <cstring> |
20 | | #include <string> |
21 | | #include <vector> |
22 | | |
23 | | #include "proto_fuzzer/tls_test_credential_cache.h" |
24 | | #include "proto_fuzzer/tls_test_credentials.h" |
25 | | |
26 | | namespace proto_fuzzer { |
27 | | |
28 | | namespace { |
29 | | |
30 | | constexpr std::size_t kMaxSessionExportAttempts = 8; |
31 | | constexpr std::size_t kMaxSessionHashSize = 128; |
32 | | constexpr std::size_t kMaxSessionDataSize = 16 * 1024; |
33 | | |
34 | | /// The TLS carrier always uses OpenSSL on its server side, but the HTTPS seed |
35 | | /// corpus is also replayed by curl clients built with GnuTLS and mbedTLS. |
36 | | /// Backend-specific handshake terminals must not replace their ordinary peer. |
37 | 1.96k | bool CurlClientUsesOpenSsl() { |
38 | 1.96k | const curl_version_info_data* version = curl_version_info(CURLVERSION_NOW); |
39 | 1.96k | constexpr char kOpenSslPrefix[] = "OpenSSL/"; |
40 | 1.96k | return version != nullptr && version->ssl_version != nullptr && |
41 | 1.96k | std::strncmp(version->ssl_version, kOpenSslPrefix, sizeof(kOpenSslPrefix) - 1) == 0; |
42 | 1.96k | } |
43 | | |
44 | | /// Own the only export retained by one probe. curl owns every pointer passed |
45 | | /// to the callback, so both binary fields must be copied before it returns. |
46 | | struct ExportedSession { |
47 | | std::vector<unsigned char> salted_hash; |
48 | | std::vector<unsigned char> session_data; |
49 | | }; |
50 | | |
51 | | /// Retain at most one bounded ticket while allowing curl to finish its cache |
52 | | /// walk. Importing here would recurse into the already-locked session cache. |
53 | | CURLcode CaptureExportedSession(CURL* /*easy*/, void* user_data, const char* /*session_key*/, |
54 | | const unsigned char* salted_hash, std::size_t salted_hash_size, |
55 | | const unsigned char* session_data, std::size_t session_data_size, |
56 | | curl_off_t /*valid_until*/, int /*ietf_tls_id*/, const char* /*alpn*/, |
57 | 102k | std::size_t /*early_data_max*/) { |
58 | 102k | auto* exported = static_cast<ExportedSession*>(user_data); |
59 | 102k | if (!exported->session_data.empty() || salted_hash == nullptr || salted_hash_size == 0 || |
60 | 61.4k | salted_hash_size > kMaxSessionHashSize || session_data == nullptr || session_data_size == 0 || |
61 | 61.4k | session_data_size > kMaxSessionDataSize) { |
62 | 40.6k | return CURLE_OK; |
63 | 40.6k | } |
64 | 61.4k | exported->salted_hash.assign(salted_hash, salted_hash + salted_hash_size); |
65 | 61.4k | exported->session_data.assign(session_data, session_data + session_data_size); |
66 | 61.4k | return CURLE_OK; |
67 | 102k | } |
68 | | |
69 | | /// Isolate the server and curl client even though both OpenSSL instances run |
70 | | /// on one thread. SSL_get_error requires an empty queue before its I/O call; |
71 | | /// clearing at both boundaries also prevents a server failure from changing |
72 | | /// curl's subsequent error classification. |
73 | | class OpenSslErrorQueueGuard { |
74 | | public: |
75 | 1.74M | OpenSslErrorQueueGuard() { ERR_clear_error(); } |
76 | | |
77 | 1.74M | ~OpenSslErrorQueueGuard() { ERR_clear_error(); } |
78 | | |
79 | | OpenSslErrorQueueGuard(const OpenSslErrorQueueGuard&) = delete; |
80 | | OpenSslErrorQueueGuard& operator=(const OpenSslErrorQueueGuard&) = delete; |
81 | | }; |
82 | | |
83 | | /// Select the one protocol owned by this peer. A fixed server preference keeps |
84 | | /// ordinary HTTPS scripts on HTTP/1.1 while allowing the proxy lane to prove |
85 | | /// curl installed its HTTP/2 connection filter after TLS. |
86 | | int SelectAlpn(SSL* /*ssl*/, const unsigned char** selected, unsigned char* selected_length, |
87 | 71.8k | const unsigned char* client_protocols, unsigned int client_protocols_length, void* userdata) { |
88 | 71.8k | const auto protocol = *static_cast<const TlsApplicationProtocol*>(userdata); |
89 | | // OpenSSL may return a pointer into the server preference list. Function- |
90 | | // local static storage keeps that result valid for the rest of the |
91 | | // handshake without reintroducing mutable transport policy as a global. |
92 | 71.8k | static constexpr unsigned char http11_alpn[] = {8, 'h', 't', 't', 'p', '/', '1', '.', '1'}; |
93 | 71.8k | static constexpr unsigned char http2_alpn[] = {2, 'h', '2'}; |
94 | 71.8k | const unsigned char* server_protocols = protocol == TlsApplicationProtocol::kHttp2 ? http2_alpn : http11_alpn; |
95 | 71.8k | const unsigned int server_protocols_length = |
96 | 71.8k | protocol == TlsApplicationProtocol::kHttp2 ? sizeof(http2_alpn) : sizeof(http11_alpn); |
97 | 71.8k | unsigned char* match = nullptr; |
98 | 71.8k | unsigned char match_length = 0; |
99 | 71.8k | const int result = SSL_select_next_proto(&match, &match_length, server_protocols, server_protocols_length, |
100 | 71.8k | client_protocols, client_protocols_length); |
101 | 71.8k | if (result != OPENSSL_NPN_NEGOTIATED) { |
102 | 5.70k | return SSL_TLSEXT_ERR_NOACK; |
103 | 5.70k | } |
104 | 66.1k | *selected = match; |
105 | 66.1k | *selected_length = match_length; |
106 | 66.1k | return SSL_TLSEXT_ERR_OK; |
107 | 71.8k | } |
108 | | |
109 | | } // namespace |
110 | | |
111 | | /// Own the certificate, key, session cache, ALPN policy, and observations |
112 | | /// shared by every bounded connection in one Scenario. Keeping both session |
113 | | /// state and its measurements here makes redirects related while preventing |
114 | | /// one fuzz input from affecting the next. |
115 | | class TlsServerContext { |
116 | | public: |
117 | | // Doxygen's no-preprocessing pass would see both conditional body openings. |
118 | | // Skip this implementation-only constructor to preserve the enclosing scope. |
119 | | /// @cond |
120 | | TlsServerContext(TlsApplicationProtocol protocol, curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
121 | | TlsGroupPolicy group_policy) |
122 | 104k | : context_(nullptr), |
123 | 104k | protocol_(protocol), |
124 | 104k | group_policy_(group_policy), |
125 | 104k | negotiated_tls_version_(0), |
126 | 104k | completed_handshake_count_(0), |
127 | 104k | reused_session_count_(0), |
128 | 104k | write_retry_count_(0), |
129 | | #ifndef OPENSSL_NO_ECH |
130 | 104k | ech_status_(SSL_ECH_STATUS_NOT_TRIED) { |
131 | | #else |
132 | | ech_status_(-1) { |
133 | | #endif |
134 | 104k | OpenSslErrorQueueGuard error_guard; |
135 | 104k | context_ = SSL_CTX_new(TLS_server_method()); |
136 | 104k | if (context_ == nullptr || !ApplyGroupPolicy() || !InstallCachedTlsTestCredentials(context_, certificate_chain) || |
137 | 104k | !LoadEchConfig()) { |
138 | 0 | SSL_CTX_free(context_); |
139 | 0 | context_ = nullptr; |
140 | 0 | return; |
141 | 0 | } |
142 | | |
143 | 104k | (void)SSL_CTX_set_min_proto_version(context_, TLS1_2_VERSION); |
144 | 104k | (void)SSL_CTX_set_options(context_, SSL_OP_NO_COMPRESSION); |
145 | 104k | (void)SSL_CTX_set_session_cache_mode(context_, SSL_SESS_CACHE_SERVER); |
146 | 104k | constexpr unsigned char session_id_context[] = "curl-fuzzer"; |
147 | 104k | (void)SSL_CTX_set_session_id_context(context_, session_id_context, sizeof(session_id_context) - 1); |
148 | 104k | SSL_CTX_set_alpn_select_cb(context_, &SelectAlpn, &protocol_); |
149 | 104k | } |
150 | | /// @endcond |
151 | | |
152 | 104k | ~TlsServerContext() { |
153 | 104k | OpenSslErrorQueueGuard error_guard; |
154 | 104k | SSL_CTX_free(context_); |
155 | 104k | } |
156 | | |
157 | | TlsServerContext(const TlsServerContext&) = delete; |
158 | | TlsServerContext& operator=(const TlsServerContext&) = delete; |
159 | | |
160 | | /// @return the configured context, or nullptr when credential setup failed. |
161 | 108k | SSL_CTX* get() const { return context_; } |
162 | | |
163 | | /// Retain only scalar handshake results; SSL itself remains connection-owned. |
164 | | /// @param ssl connection that has just completed SSL_accept. |
165 | 100k | void RecordHandshake(SSL* ssl) { |
166 | 100k | if (ssl == nullptr) { |
167 | 0 | return; |
168 | 0 | } |
169 | 100k | negotiated_tls_version_ = SSL_version(ssl); |
170 | 100k | const unsigned char* alpn = nullptr; |
171 | 100k | unsigned int alpn_length = 0; |
172 | 100k | SSL_get0_alpn_selected(ssl, &alpn, &alpn_length); |
173 | 100k | if (alpn != nullptr && alpn_length != 0) { |
174 | 63.7k | negotiated_alpn_.assign(reinterpret_cast<const char*>(alpn), alpn_length); |
175 | 63.7k | } else { |
176 | 37.1k | negotiated_alpn_.clear(); |
177 | 37.1k | } |
178 | 100k | ++completed_handshake_count_; |
179 | 100k | if (SSL_session_reused(ssl) == 1) { |
180 | 7.96k | ++reused_session_count_; |
181 | 7.96k | } |
182 | 100k | const int negotiated_group = SSL_get_negotiated_group(ssl); |
183 | 100k | const char* group_name = negotiated_group == 0 ? nullptr : SSL_group_to_name(ssl, negotiated_group); |
184 | 100k | negotiated_group_ = group_name == nullptr ? std::string() : group_name; |
185 | 100k | #ifndef OPENSSL_NO_ECH |
186 | 100k | char* inner_name = nullptr; |
187 | 100k | char* outer_name = nullptr; |
188 | 100k | ech_status_ = SSL_ech_get1_status(ssl, &inner_name, &outer_name); |
189 | 100k | ech_inner_name_ = inner_name == nullptr ? std::string() : inner_name; |
190 | 100k | ech_outer_name_ = outer_name == nullptr ? std::string() : outer_name; |
191 | 100k | OPENSSL_free(inner_name); |
192 | 100k | OPENSSL_free(outer_name); |
193 | 100k | #endif |
194 | 100k | } |
195 | | |
196 | | /// Record that OpenSSL requires an identical application-write retry. |
197 | 1.12k | void RecordWriteRetry() { ++write_retry_count_; } |
198 | | |
199 | | /// @return protocol version from the most recent completed handshake. |
200 | 21.0k | int negotiated_tls_version() const { return negotiated_tls_version_; } |
201 | | /// @return number of connections that completed their handshake. |
202 | 598k | std::size_t completed_handshake_count() const { return completed_handshake_count_; } |
203 | | /// @return number of completed handshakes that reused a session. |
204 | 7 | std::size_t reused_session_count() const { return reused_session_count_; } |
205 | | /// @return number of application writes that OpenSSL asked to retry. |
206 | 7 | std::size_t write_retry_count() const { return write_retry_count_; } |
207 | | /// @return ALPN protocol from the most recent completed handshake. |
208 | 21.0k | const std::string& negotiated_alpn() const { return negotiated_alpn_; } |
209 | | /// @return key-exchange group from the most recent completed handshake. |
210 | 7 | const std::string& negotiated_group() const { return negotiated_group_; } |
211 | | /// @return fixed application protocol this context offers. |
212 | 98.0k | TlsApplicationProtocol protocol() const { return protocol_; } |
213 | | /// @return OpenSSL ECH result from the latest completed handshake. |
214 | 7 | int ech_status() const { return ech_status_; } |
215 | | /// @return latest decrypted inner SNI, if ECH was attempted. |
216 | 7 | const std::string& ech_inner_name() const { return ech_inner_name_; } |
217 | | /// @return latest public outer SNI, if ECH was attempted. |
218 | 7 | const std::string& ech_outer_name() const { return ech_outer_name_; } |
219 | | |
220 | | private: |
221 | | /// Apply the constructor-selected group policy before any SSL is created. |
222 | | /// @return true when the provider accepted the requested policy. |
223 | 104k | bool ApplyGroupPolicy() { |
224 | 104k | switch (group_policy_) { |
225 | 90.7k | case TlsGroupPolicy::kProviderDefault: |
226 | 90.7k | return true; |
227 | 13.5k | case TlsGroupPolicy::kX25519: |
228 | 13.5k | return SSL_CTX_set1_groups_list(context_, "X25519") == 1; |
229 | 104k | } |
230 | 0 | return false; |
231 | 104k | } |
232 | | |
233 | | /// Load a fixed test-only ECH private key and matching public config. This |
234 | | /// makes a successful encrypted ClientHello deterministic without DNS or |
235 | | /// filesystem state; builds configured without ECH retain the TLS mock. |
236 | 104k | bool LoadEchConfig() { |
237 | 104k | #ifndef OPENSSL_NO_ECH |
238 | 104k | BIO* ech_bio = BIO_new_mem_buf(tls_test_credentials::kEchConfigPem, -1); |
239 | 104k | OSSL_ECHSTORE* store = OSSL_ECHSTORE_new(nullptr, nullptr); |
240 | 104k | if (ech_bio == nullptr || store == nullptr) { |
241 | 0 | BIO_free(ech_bio); |
242 | 0 | OSSL_ECHSTORE_free(store); |
243 | 0 | return false; |
244 | 0 | } |
245 | 104k | const bool loaded = |
246 | 104k | OSSL_ECHSTORE_read_pem(store, ech_bio, OSSL_ECH_NO_RETRY) == 1 && SSL_CTX_set1_echstore(context_, store) == 1; |
247 | 104k | BIO_free(ech_bio); |
248 | 104k | OSSL_ECHSTORE_free(store); |
249 | 104k | return loaded; |
250 | | #else |
251 | | return true; |
252 | | #endif |
253 | 104k | } |
254 | | |
255 | | SSL_CTX* context_; |
256 | | TlsApplicationProtocol protocol_; |
257 | | const TlsGroupPolicy group_policy_; |
258 | | std::string negotiated_alpn_; |
259 | | std::string negotiated_group_; |
260 | | int negotiated_tls_version_; |
261 | | std::size_t completed_handshake_count_; |
262 | | std::size_t reused_session_count_; |
263 | | std::size_t write_retry_count_; |
264 | | int ech_status_; |
265 | | std::string ech_inner_name_; |
266 | | std::string ech_outer_name_; |
267 | | }; |
268 | | |
269 | | namespace { |
270 | | |
271 | | /// TLS-aware MockConnection. Application writes are queued before the client |
272 | | /// starts, then encrypted only after SSL_accept has completed. This preserves |
273 | | /// MockServer's useful initial_response semantics without ever putting those |
274 | | /// plaintext bytes onto the TLS wire. |
275 | | class TlsMockConnection final : public MockConnection { |
276 | | public: |
277 | | explicit TlsMockConnection(TlsServerContext* context) |
278 | 108k | : ssl_(nullptr), |
279 | 108k | context_(context), |
280 | 108k | pending_offset_(0), |
281 | 108k | pending_write_end_(0), |
282 | 108k | handshake_complete_(false), |
283 | 108k | shutdown_requested_(false), |
284 | 108k | write_shutdown_(false), |
285 | 108k | failed_(false) { |
286 | 108k | OpenSslErrorQueueGuard error_guard; |
287 | 108k | SSL_CTX* ssl_context = context_ == nullptr ? nullptr : context_->get(); |
288 | 108k | ssl_ = ssl_context == nullptr ? nullptr : SSL_new(ssl_context); |
289 | 108k | if (ssl_ != nullptr) { |
290 | 108k | SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); |
291 | 108k | if (SSL_set_fd(ssl_, server_fd()) != 1) { |
292 | 0 | SSL_free(ssl_); |
293 | 0 | ssl_ = nullptr; |
294 | 108k | } else { |
295 | 108k | SSL_set_accept_state(ssl_); |
296 | 108k | } |
297 | 108k | } |
298 | 108k | } |
299 | | |
300 | 108k | ~TlsMockConnection() override { |
301 | 108k | OpenSslErrorQueueGuard error_guard; |
302 | 108k | if (ssl_ != nullptr) { |
303 | 108k | SSL_free(ssl_); |
304 | 108k | } |
305 | 108k | } |
306 | | |
307 | | /// Require both the socketpair and its OpenSSL wrapper to be usable. |
308 | 1.43M | bool ok() const override { return MockConnection::ok() && ssl_ != nullptr; } |
309 | | |
310 | | /// Queue bounded application bytes until the handshake can encrypt them. |
311 | 268k | bool WriteAll(const unsigned char* data, std::size_t size) override { |
312 | 268k | if (failed_ || (data == nullptr && size != 0) || size > pending_plaintext_.max_size() - pending_plaintext_.size()) { |
313 | 2.57k | return false; |
314 | 2.57k | } |
315 | 266k | if (size != 0) { |
316 | 266k | pending_plaintext_.append(reinterpret_cast<const char*>(data), size); |
317 | 266k | } |
318 | 266k | return true; |
319 | 268k | } |
320 | | |
321 | | /// Advance the handshake, consume encrypted request records, flush queued |
322 | | /// response records, and finish a requested close without ever waiting. |
323 | | /// @return decrypted/application bytes plus state transitions made this turn. |
324 | 1.32M | std::size_t DrainIncoming() override { |
325 | 1.32M | if (!ok() || failed_) { |
326 | 11.5k | return 0; |
327 | 11.5k | } |
328 | | |
329 | 1.31M | OpenSslErrorQueueGuard error_guard; |
330 | 1.31M | std::size_t progress = 0; |
331 | 1.31M | if (!handshake_complete_) { |
332 | 279k | const int state_before = static_cast<int>(SSL_get_state(ssl_)); |
333 | 279k | const int result = SSL_accept(ssl_); |
334 | | // SSL_get_error must be the next OpenSSL call after failed I/O. Even a |
335 | | // state query in between would make its use formally unreliable. |
336 | 279k | const int error = result == 1 ? SSL_ERROR_NONE : SSL_get_error(ssl_, result); |
337 | 279k | const int state_after = static_cast<int>(SSL_get_state(ssl_)); |
338 | 279k | if (state_after != state_before) { |
339 | 205k | ++progress; |
340 | 205k | } |
341 | 279k | if (result == 1) { |
342 | 100k | handshake_complete_ = true; |
343 | 100k | if (context_ != nullptr) { |
344 | 100k | context_->RecordHandshake(ssl_); |
345 | 100k | } |
346 | 100k | ++progress; |
347 | 178k | } else { |
348 | 178k | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) { |
349 | 177k | return progress; |
350 | 177k | } |
351 | 1.44k | failed_ = true; |
352 | 1.44k | return progress; |
353 | 178k | } |
354 | 279k | } |
355 | | |
356 | | // A WANT result leaves SSL_write_ex in flight. OpenSSL requires the next |
357 | | // I/O operation to retry that exact write, so do not interpose SSL_read_ex |
358 | | // merely because the outer driver has yielded back to us. |
359 | 1.13M | if (pending_write_end_ != 0) { |
360 | 1.08k | progress += FlushPendingWrites(); |
361 | 1.08k | if (failed_ || pending_write_end_ != 0) { |
362 | 980 | return progress; |
363 | 980 | } |
364 | 1.08k | } |
365 | | |
366 | 1.13M | unsigned char request[4096]; |
367 | 1.61M | while (true) { |
368 | 1.61M | std::size_t received = 0; |
369 | 1.61M | const int result = SSL_read_ex(ssl_, request, sizeof(request), &received); |
370 | 1.61M | if (result == 1 && received != 0) { |
371 | 481k | NotifyIncomingData(request, received); |
372 | 481k | progress += received; |
373 | 481k | continue; |
374 | 481k | } |
375 | 1.13M | if (result != 1) { |
376 | 1.13M | const int error = SSL_get_error(ssl_, result); |
377 | 1.13M | if (error == SSL_ERROR_ZERO_RETURN) { |
378 | | // The client sent close_notify. TLS requires a reciprocal close_notify |
379 | | // before the orderly shutdown completes; protocols such as FTP upload |
380 | | // wait for that completion even though the application data is done. |
381 | 90.6k | shutdown_requested_ = true; |
382 | 1.04M | } else if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { |
383 | 12.0k | failed_ = true; |
384 | 12.0k | } |
385 | 1.13M | } |
386 | 1.13M | break; |
387 | 1.61M | } |
388 | | |
389 | 1.13M | progress += FlushPendingWrites(); |
390 | | |
391 | 1.13M | if (!failed_ && shutdown_requested_ && pending_plaintext_.empty() && !write_shutdown_) { |
392 | 64.2k | const int result = SSL_shutdown(ssl_); |
393 | 64.2k | if (result >= 0) { |
394 | | // The first successful call sends close_notify. The fuzzer does not |
395 | | // need to wait for the client's reciprocal alert before exposing EOF. |
396 | 64.0k | (void)::shutdown(server_fd(), SHUT_WR); |
397 | 64.0k | write_shutdown_ = true; |
398 | 64.0k | ++progress; |
399 | 64.0k | } else { |
400 | 241 | const int error = SSL_get_error(ssl_, result); |
401 | 241 | if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) { |
402 | 43 | failed_ = true; |
403 | 43 | } |
404 | 241 | } |
405 | 64.2k | } |
406 | 1.13M | return progress; |
407 | 1.13M | } |
408 | | |
409 | | /// Defer close_notify until every queued plaintext byte has become a record. |
410 | 98.0k | void ShutdownWrite() override { |
411 | | // An HTTP/2 proxy connection outlives the scripted origin response inside |
412 | | // its CONNECT stream. Half-closing TLS when the last script chunk is |
413 | | // queued would make curl observe a dead proxy rather than exercise its |
414 | | // own stream/session shutdown and GOAWAY handling. |
415 | 98.0k | if (context_ != nullptr && context_->protocol() == TlsApplicationProtocol::kHttp2) { |
416 | 26.2k | return; |
417 | 26.2k | } |
418 | 71.7k | shutdown_requested_ = true; |
419 | 71.7k | (void)DrainIncoming(); |
420 | 71.7k | } |
421 | | |
422 | | private: |
423 | | /// Flush queued response bytes while preserving any OpenSSL retry boundary. |
424 | | /// @return plaintext bytes OpenSSL accepted during this call. |
425 | 1.13M | std::size_t FlushPendingWrites() { |
426 | 1.13M | std::size_t progress = 0; |
427 | 1.37M | while (!failed_ && pending_offset_ < pending_plaintext_.size()) { |
428 | 239k | if (pending_write_end_ == 0) { |
429 | | // Freeze one write boundary until OpenSSL accepts it. WriteAll may |
430 | | // append the next scripted chunk after WANT_READ/WANT_WRITE, but the |
431 | | // retry contract permits only pointer relocation—not changed bytes or |
432 | | // length—for the outstanding SSL_write_ex call. |
433 | 234k | pending_write_end_ = pending_plaintext_.size(); |
434 | 234k | } |
435 | 239k | std::size_t written = 0; |
436 | 239k | const int result = SSL_write_ex(ssl_, pending_plaintext_.data() + pending_offset_, |
437 | 239k | pending_write_end_ - pending_offset_, &written); |
438 | 239k | if (result == 1) { |
439 | 237k | if (written == 0) { |
440 | 0 | failed_ = true; |
441 | 0 | break; |
442 | 0 | } |
443 | 237k | pending_offset_ += written; |
444 | 237k | progress += written; |
445 | 237k | if (pending_offset_ == pending_write_end_) { |
446 | 233k | pending_write_end_ = 0; |
447 | 233k | } |
448 | 237k | continue; |
449 | 237k | } |
450 | 2.13k | const int error = SSL_get_error(ssl_, result); |
451 | 2.13k | if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) { |
452 | 1.12k | if (context_ != nullptr) { |
453 | 1.12k | context_->RecordWriteRetry(); |
454 | 1.12k | } |
455 | 1.12k | } else { |
456 | 1.01k | failed_ = true; |
457 | 1.01k | } |
458 | 2.13k | break; |
459 | 239k | } |
460 | 1.13M | if (pending_offset_ == pending_plaintext_.size()) { |
461 | 1.13M | pending_plaintext_.clear(); |
462 | 1.13M | pending_offset_ = 0; |
463 | 1.13M | pending_write_end_ = 0; |
464 | 1.13M | } |
465 | 1.13M | return progress; |
466 | 1.13M | } |
467 | | |
468 | | SSL* ssl_; |
469 | | TlsServerContext* context_; |
470 | | std::string pending_plaintext_; |
471 | | std::size_t pending_offset_; |
472 | | /// Exclusive end of a write that OpenSSL may require us to retry exactly. |
473 | | std::size_t pending_write_end_; |
474 | | bool handshake_complete_; |
475 | | bool shutdown_requested_; |
476 | | bool write_shutdown_; |
477 | | bool failed_; |
478 | | }; |
479 | | |
480 | | /// Emit one fixed clean-shutdown alert without completing a server handshake. |
481 | | /// OpenSSL classifies this as SSL_ERROR_ZERO_RETURN with an empty error queue; |
482 | | /// ignoring scripted response bytes keeps protobuf data out of the TLS record. |
483 | | class TlsCloseNotifyConnection final : public MockConnection { |
484 | | public: |
485 | 382 | TlsCloseNotifyConnection() : alert_sent_(false) {} |
486 | | |
487 | 220 | bool WriteAll(const unsigned char* /*data*/, std::size_t /*size*/) override { return true; } |
488 | | |
489 | 350 | void ShutdownWrite() override { |
490 | 350 | if (alert_sent_) { |
491 | 0 | return; |
492 | 0 | } |
493 | 350 | static constexpr unsigned char kCloseNotify[] = { |
494 | 350 | 0x15, 0x03, 0x03, 0x00, 0x02, 0x01, 0x00, |
495 | 350 | }; |
496 | 350 | alert_sent_ = true; |
497 | 350 | (void)MockConnection::WriteAll(kCloseNotify, sizeof(kCloseNotify)); |
498 | 350 | MockConnection::ShutdownWrite(); |
499 | 350 | } |
500 | | |
501 | | private: |
502 | | bool alert_sent_; |
503 | | }; |
504 | | |
505 | | /// Emit one fixed TLS handshake record containing an empty HelloRequest. |
506 | | /// This deliberately predates negotiation and ignores scripted HTTP bytes: |
507 | | /// its only purpose is to drive OpenSSL's message callback through the |
508 | | /// SSL3_MT_HELLO_REQUEST label with harness-owned bytes. |
509 | | class TlsHelloRequestConnection final : public MockConnection { |
510 | | public: |
511 | 58 | TlsHelloRequestConnection() : record_sent_(false) {} |
512 | | |
513 | 81 | bool WriteAll(const unsigned char* /*data*/, std::size_t /*size*/) override { return SendOnce(); } |
514 | | |
515 | 49 | void ShutdownWrite() override { |
516 | 49 | (void)SendOnce(); |
517 | 49 | MockConnection::ShutdownWrite(); |
518 | 49 | } |
519 | | |
520 | | private: |
521 | 130 | bool SendOnce() { |
522 | 130 | if (record_sent_) { |
523 | 74 | return true; |
524 | 74 | } |
525 | 56 | static constexpr unsigned char kHelloRequest[] = { |
526 | 56 | 0x16, 0x03, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, |
527 | 56 | }; |
528 | 56 | record_sent_ = MockConnection::WriteAll(kHelloRequest, sizeof(kHelloRequest)); |
529 | 56 | return record_sent_; |
530 | 130 | } |
531 | | |
532 | | bool record_sent_; |
533 | | }; |
534 | | |
535 | | } // namespace |
536 | | |
537 | | /// Construct one reusable TLS context for a protocol-specific peer. |
538 | | /// @param protocol Fixed ALPN application protocol offered by the server. |
539 | | /// @param certificate_chain Certificate-chain profile presented to curl. |
540 | | /// @param group_policy Immutable server key-exchange group policy. |
541 | | /// @param handshake_profile Closed peer-side handshake terminal. |
542 | | TlsMockTransport::TlsMockTransport(TlsApplicationProtocol protocol, |
543 | | curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
544 | | TlsGroupPolicy group_policy, |
545 | | curl::fuzzer::proto::TlsHandshakeProfile handshake_profile) |
546 | 104k | : group_policy_(group_policy), |
547 | 104k | openssl_close_notify_(handshake_profile == curl::fuzzer::proto::TLS_HANDSHAKE_OPENSSL_CLOSE_NOTIFY && |
548 | 1.81k | CurlClientUsesOpenSsl()), |
549 | 104k | openssl_hello_request_(handshake_profile == curl::fuzzer::proto::TLS_HANDSHAKE_OPENSSL_HELLO_REQUEST && |
550 | 156 | CurlClientUsesOpenSsl()), |
551 | 104k | context_(std::make_unique<TlsServerContext>(protocol, certificate_chain, group_policy)) {} |
552 | | |
553 | 104k | TlsMockTransport::~TlsMockTransport() = default; |
554 | | |
555 | | /// Install the stable local trust anchor and strict peer verification. Socket |
556 | | /// callbacks remain owned by the protocol-specific server using this carrier. |
557 | | /// @param easy Easy handle that will connect to this TLS transport. |
558 | 90.5k | void TlsMockTransport::Install(CURL* easy) const { |
559 | 90.5k | struct curl_blob trust_anchor = {const_cast<char*>(tls_test_credentials::kCertificatePem), |
560 | 90.5k | sizeof(tls_test_credentials::kCertificatePem) - 1, CURL_BLOB_NOCOPY}; |
561 | 90.5k | (void)curl_easy_setopt(easy, CURLOPT_CAINFO_BLOB, &trust_anchor); |
562 | 90.5k | (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 1L); |
563 | 90.5k | (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYHOST, 2L); |
564 | 90.5k | } |
565 | | |
566 | | /// Wrap one socketpair server endpoint in an OpenSSL acceptor. |
567 | | /// @return A failed connection when context setup was unavailable. |
568 | 109k | std::unique_ptr<MockConnection> TlsMockTransport::CreateConnection() { |
569 | 109k | if (openssl_close_notify_) { |
570 | 382 | return std::make_unique<TlsCloseNotifyConnection>(); |
571 | 382 | } |
572 | 108k | if (openssl_hello_request_) { |
573 | 58 | return std::make_unique<TlsHelloRequestConnection>(); |
574 | 58 | } |
575 | 108k | return std::make_unique<TlsMockConnection>(context_.get()); |
576 | 108k | } |
577 | | |
578 | | /// @return Protocol version selected by the most recent handshake, or zero. |
579 | 21.0k | int TlsMockTransport::negotiated_tls_version() const { |
580 | 21.0k | return context_ == nullptr ? 0 : context_->negotiated_tls_version(); |
581 | 21.0k | } |
582 | | |
583 | | /// @return Number of connections that completed TLS negotiation. |
584 | 598k | std::size_t TlsMockTransport::completed_handshake_count() const { |
585 | 598k | return context_ == nullptr ? 0 : context_->completed_handshake_count(); |
586 | 598k | } |
587 | | |
588 | | /// @return Number of completed connections that resumed a cached session. |
589 | 7 | std::size_t TlsMockTransport::reused_session_count() const { |
590 | 7 | return context_ == nullptr ? 0 : context_->reused_session_count(); |
591 | 7 | } |
592 | | |
593 | | /// @return Number of application writes OpenSSL required an exact retry for. |
594 | 7 | std::size_t TlsMockTransport::write_retry_count() const { |
595 | 7 | return context_ == nullptr ? 0 : context_->write_retry_count(); |
596 | 7 | } |
597 | | |
598 | | /// @return ALPN protocol selected by the most recent handshake. |
599 | 21.0k | std::string TlsMockTransport::negotiated_alpn() const { |
600 | 21.0k | return context_ == nullptr ? std::string() : context_->negotiated_alpn(); |
601 | 21.0k | } |
602 | | |
603 | | /// @return Immutable key-exchange group policy selected at construction. |
604 | 14.7k | TlsGroupPolicy TlsMockTransport::group_policy() const { return group_policy_; } |
605 | | |
606 | | /// @return Key-exchange group from the most recent completed handshake. |
607 | 7 | std::string TlsMockTransport::negotiated_group() const { |
608 | 7 | return context_ == nullptr ? std::string() : context_->negotiated_group(); |
609 | 7 | } |
610 | | |
611 | | /// @return OpenSSL's ECH result, or a negative sentinel when unavailable. |
612 | 7 | int TlsMockTransport::ech_status() const { return context_ == nullptr ? -1 : context_->ech_status(); } |
613 | | |
614 | | /// @return Decrypted inner SNI recovered by the ECH-capable server. |
615 | 7 | std::string TlsMockTransport::ech_inner_name() const { |
616 | 7 | return context_ == nullptr ? std::string() : context_->ech_inner_name(); |
617 | 7 | } |
618 | | |
619 | | /// @return Public outer SNI visible before ECH decryption. |
620 | 7 | std::string TlsMockTransport::ech_outer_name() const { |
621 | 7 | return context_ == nullptr ? std::string() : context_->ech_outer_name(); |
622 | 7 | } |
623 | | |
624 | | /// Build one reusable in-process server context per fuzz iteration. |
625 | 0 | TlsMockServer::TlsMockServer() : TlsMockServer(curl::fuzzer::proto::TLS_CERTIFICATE_CHAIN_DEFAULT_EC) {} |
626 | | |
627 | | /// Select one bounded certificate-chain profile for an HTTP/1.1 TLS peer. |
628 | | /// @param certificate_chain Peer certificate chain presented to curl. |
629 | | /// @param handshake_profile Closed peer-side handshake terminal. |
630 | | TlsMockServer::TlsMockServer(curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
631 | | curl::fuzzer::proto::TlsHandshakeProfile handshake_profile) |
632 | 45.0k | : TlsMockServer(TlsApplicationProtocol::kHttp11, certificate_chain, TlsGroupPolicy::kProviderDefault, |
633 | 45.0k | handshake_profile) {} |
634 | | |
635 | | /// Construct the shared TLS transport for a protocol-specific derived peer |
636 | | /// with one fixed ALPN outcome. |
637 | | /// @param protocol Fixed application protocol the server must negotiate. |
638 | | /// @param certificate_chain Peer certificate chain presented to curl. |
639 | | /// @param group_policy Immutable server key-exchange group policy. |
640 | | /// @param handshake_profile Closed peer-side handshake terminal. |
641 | | TlsMockServer::TlsMockServer(TlsApplicationProtocol protocol, |
642 | | curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain, |
643 | | TlsGroupPolicy group_policy, curl::fuzzer::proto::TlsHandshakeProfile handshake_profile) |
644 | 73.3k | : transport_(protocol, certificate_chain, group_policy, handshake_profile), |
645 | 73.3k | saw_live_tls_session_(false), |
646 | 73.3k | session_export_attempt_count_(0), |
647 | 73.3k | exported_session_count_(0), |
648 | 73.3k | imported_session_count_(0) {} |
649 | | |
650 | | /// Release SSL objects before their owning server context. OpenSSL reference |
651 | | /// counting makes the reverse order legal, but making the ownership order |
652 | | /// explicit keeps future transport state from acquiring a hidden dependency. |
653 | 73.3k | TlsMockServer::~TlsMockServer() { ResetConnections(); } |
654 | | |
655 | | /// Install common socket callbacks and a stable local trust anchor. Curl copies |
656 | | /// the blob descriptor during setopt and borrows the inline certificate bytes, |
657 | | /// whose program lifetime safely exceeds every easy handle. Scenario options run |
658 | | /// afterwards and can still disable verification or select failing TLS settings. |
659 | | /// @param easy Easy handle that will connect to this TLS peer. |
660 | 59.7k | void TlsMockServer::Install(CURL* easy) { |
661 | 59.7k | MockServer::Install(easy); |
662 | 59.7k | transport_.Install(easy); |
663 | 59.7k | } |
664 | | |
665 | | /// @return true once curl exposed a live TLS backend session during drive. |
666 | 7 | bool TlsMockServer::saw_live_tls_session() const { return saw_live_tls_session_; } |
667 | | |
668 | | /// @return number of session representations copied by the export callback |
669 | | /// out of curl's cache. |
670 | 7 | std::size_t TlsMockServer::exported_session_count() const { return exported_session_count_; } |
671 | | |
672 | | /// @return number of copied session representations successfully imported |
673 | | /// into curl's cache again. |
674 | 7 | std::size_t TlsMockServer::imported_session_count() const { return imported_session_count_; } |
675 | | |
676 | | /// @return protocol version selected by the most recent completed handshake, |
677 | | /// or zero when no connection completed TLS negotiation. |
678 | 7 | int TlsMockServer::negotiated_tls_version() const { return transport_.negotiated_tls_version(); } |
679 | | |
680 | | /// @return number of connections that completed TLS negotiation. |
681 | 7 | std::size_t TlsMockServer::completed_handshake_count() const { return transport_.completed_handshake_count(); } |
682 | | |
683 | | /// @return number of completed connections that resumed an earlier session. |
684 | 7 | std::size_t TlsMockServer::reused_session_count() const { return transport_.reused_session_count(); } |
685 | | |
686 | | /// @return number of application writes OpenSSL required an exact retry for. |
687 | 7 | std::size_t TlsMockServer::write_retry_count() const { return transport_.write_retry_count(); } |
688 | | |
689 | | /// @return ALPN protocol selected by the most recent completed handshake. |
690 | 7 | std::string TlsMockServer::negotiated_alpn() const { return transport_.negotiated_alpn(); } |
691 | | |
692 | | /// @return Immutable key-exchange group policy selected at construction. |
693 | 14.7k | TlsGroupPolicy TlsMockServer::group_policy() const { return transport_.group_policy(); } |
694 | | |
695 | | /// @return Key-exchange group from the most recent completed handshake. |
696 | 7 | std::string TlsMockServer::negotiated_group() const { return transport_.negotiated_group(); } |
697 | | |
698 | | /// @return OpenSSL's ECH status for the most recent completed handshake. |
699 | | /// Builds without ECH return a negative sentinel. |
700 | 7 | int TlsMockServer::ech_status() const { return transport_.ech_status(); } |
701 | | |
702 | | /// @return encrypted inner SNI recovered by the ECH-capable server. |
703 | 7 | std::string TlsMockServer::ech_inner_name() const { return transport_.ech_inner_name(); } |
704 | | |
705 | | /// @return public outer SNI visible before ECH decryption. |
706 | 7 | std::string TlsMockServer::ech_outer_name() const { return transport_.ech_outer_name(); } |
707 | | |
708 | | /// Wrap one socketpair server endpoint in an OpenSSL acceptor consumed by |
709 | | /// MockServer. |
710 | | /// @return a failed connection when context setup was unavailable. |
711 | 79.6k | std::unique_ptr<MockConnection> TlsMockServer::CreateConnection() { return transport_.CreateConnection(); } |
712 | | |
713 | | /// Query while the connection filters are attached. Result-info probes stop |
714 | | /// after the first live result, and session export has its own fixed attempt |
715 | | /// bound, so neither recurs throughout every HTTP parser iteration. |
716 | | /// @param easy Active easy handle whose connection filters remain attached. |
717 | 567k | void TlsMockServer::ObserveActiveTransfer(CURL* easy) { |
718 | 567k | if (!saw_live_tls_session_) { |
719 | 255k | long verify_result = 0; |
720 | 255k | curl_off_t appconnect_time = 0; |
721 | 255k | struct curl_certinfo* certificate_info = nullptr; |
722 | 255k | struct curl_tlssessioninfo* tls_session = nullptr; |
723 | 255k | (void)curl_easy_getinfo(easy, CURLINFO_SSL_VERIFYRESULT, &verify_result); |
724 | 255k | (void)curl_easy_getinfo(easy, CURLINFO_APPCONNECT_TIME_T, &appconnect_time); |
725 | 255k | (void)curl_easy_getinfo(easy, CURLINFO_CERTINFO, &certificate_info); |
726 | 255k | if (curl_easy_getinfo(easy, CURLINFO_TLS_SSL_PTR, &tls_session) == CURLE_OK && tls_session != nullptr && |
727 | 255k | tls_session->internals != nullptr) { |
728 | 50.3k | saw_live_tls_session_ = true; |
729 | 50.3k | } |
730 | 255k | } |
731 | | |
732 | | // A TLS 1.3 ticket may arrive after the peer first completes its handshake. |
733 | | // Retry only a small fixed number of outer-loop observations, and stop |
734 | | // permanently once one copied ticket has made one import attempt. |
735 | 567k | const bool completed_live_handshake = transport_.completed_handshake_count() != 0; |
736 | 567k | #if defined(PROTO_FUZZER_OBSERVE_STATE) |
737 | | // Read the owned peer observations once after a real handshake. Signed |
738 | | // status values retain their unavailable sentinels; string results are |
739 | | // consumed immediately while their temporaries and context are still live. |
740 | 567k | static bool observed = false; |
741 | 567k | if (completed_live_handshake && !observed) { |
742 | 7 | observed = true; |
743 | 7 | const volatile bool live = saw_live_tls_session(); |
744 | 7 | const volatile int status[] = {negotiated_tls_version(), ech_status()}; |
745 | 7 | const volatile std::size_t counts[] = { |
746 | 7 | exported_session_count(), imported_session_count(), completed_handshake_count(), |
747 | 7 | reused_session_count(), write_retry_count(), negotiated_alpn().size(), |
748 | 7 | negotiated_group().size(), ech_inner_name().size(), ech_outer_name().size()}; |
749 | 7 | (void)live; |
750 | 7 | (void)status; |
751 | 7 | (void)counts; |
752 | 7 | } |
753 | 567k | #endif |
754 | 567k | if (!completed_live_handshake || exported_session_count_ != 0 || |
755 | 490k | session_export_attempt_count_ >= kMaxSessionExportAttempts) { |
756 | 490k | return; |
757 | 490k | } |
758 | 77.7k | ++session_export_attempt_count_; |
759 | 77.7k | ExportedSession exported; |
760 | 77.7k | const CURLcode export_result = curl_easy_ssls_export(easy, &CaptureExportedSession, &exported); |
761 | 77.7k | if (export_result != CURLE_OK || exported.session_data.empty()) { |
762 | 16.2k | return; |
763 | 16.2k | } |
764 | 61.4k | ++exported_session_count_; |
765 | | |
766 | | // curl holds the SSL session-cache lock throughout CaptureExportedSession. |
767 | | // This deliberately separate call therefore exercises import without |
768 | | // recursive API use or retaining any callback-owned pointer. |
769 | 61.4k | if (curl_easy_ssls_import(easy, nullptr, exported.salted_hash.data(), exported.salted_hash.size(), |
770 | 61.4k | exported.session_data.data(), exported.session_data.size()) == CURLE_OK) { |
771 | 61.3k | ++imported_session_count_; |
772 | 61.3k | } |
773 | 61.4k | } |
774 | | |
775 | | } // namespace proto_fuzzer |