Coverage Report

Created: 2026-10-31 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/option_apply.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 Implementation of the option-translation helpers declared in
9
///        option_apply.h.
10
11
#include "proto_fuzzer/option_apply.h"
12
13
#include <algorithm>
14
#include <cstddef>
15
#include <cstdint>
16
#include <cstdio>
17
#include <cstdlib>
18
#include <string>
19
20
#include "proto_fuzzer/allocation_fault_injection.h"
21
#include "proto_fuzzer/scenario_limits.h"
22
23
namespace proto_fuzzer {
24
25
namespace {
26
27
constexpr char kEventDrivenProtocolsAllowed[] = "http,https,ws,wss";
28
constexpr char kTelnetProtocolAllowed[] = "telnet";
29
constexpr char kFtpProtocolAllowed[] = "ftp,ftps";
30
constexpr char kTftpProtocolAllowed[] = "tftp";
31
constexpr char kSmtpProtocolAllowed[] = "smtp,smtps";
32
constexpr char kImapProtocolAllowed[] = "imap,imaps";
33
constexpr char kPop3ProtocolAllowed[] = "pop3,pop3s";
34
constexpr char kMqttProtocolAllowed[] = "mqtt,mqtts";
35
constexpr char kDictProtocolAllowed[] = "dict";
36
constexpr char kFileProtocolAllowed[] = "file";
37
constexpr char kLdapProtocolAllowed[] = "ldap,ldaps";
38
constexpr char kRtspProtocolAllowed[] = "rtsp";
39
constexpr char kConnectToOverride[] = "::127.0.1.127:";
40
constexpr char kDevNull[] = "/dev/null";
41
constexpr char kDefaultProvider[] = "default";
42
constexpr char kEngineCertificateType[] = "ENG";
43
constexpr char kPkcs12CertificateType[] = "P12";
44
constexpr char kProviderCertificateType[] = "PROV";
45
constexpr unsigned char kMalformedPkcs12[] = {0x30, 0x00};
46
constexpr char kVerboseEnvVar[] = "FUZZ_VERBOSE";
47
constexpr char kAltSvcHttpEnvVar[] = "CURL_ALTSVC_HTTP";
48
constexpr char kHstsHttpEnvVar[] = "CURL_HSTS_HTTP";
49
constexpr long kConnectTimeoutMs = 200;
50
constexpr long kTimeoutMs = 200;
51
52
/// Baseline write callback for both CURLOPT_WRITEFUNCTION and
53
/// CURLOPT_HEADERFUNCTION. Consumes every byte so transfers don't stall on
54
/// backpressure and emits nothing. Protocol-specific mocks may install their
55
/// own WRITEFUNCTION afterwards if they need to poke protocol APIs while
56
/// inside a curl callback.
57
6.29M
size_t SilentWriteCallback(void* /*contents*/, size_t size, size_t nmemb, void* /*userdata*/) { return size * nmemb; }
58
59
/// Consume libcurl's verbose records without emitting per-input diagnostics.
60
/// TELNET's debug build keeps its negotiation/suboption formatters behind the
61
/// verbose switch, so the protocol lane uses this sink to make that reachable
62
/// code fuzzable without turning millions of iterations into log traffic.
63
15.1M
int SilentDebugCallback(CURL* /*handle*/, curl_infotype /*type*/, char* /*data*/, size_t /*size*/, void* /*userdata*/) {
64
15.1M
  return 0;
65
15.1M
}
66
67
/// Let curl's debug build accept transport-security response headers over the
68
/// plaintext HTTP mock. The HTTPS lane now provides a verified peer, but making
69
/// HSTS and Alt-Svc parser coverage depend on a cryptographic handshake would
70
/// needlessly remove those parsers from the high-throughput HTTP lane.
71
369k
void EnableDebugHttpTransportMetadata() {
72
369k
  static const bool configured = [] {
73
    // CMake builds the fuzzing copy of curl with ENABLE_DEBUG specifically so
74
    // these curl-provided test hooks are available. Do not overwrite values a
75
    // reproducer deliberately supplied in its environment.
76
30
    (void)setenv(kAltSvcHttpEnvVar, "1", 0);
77
30
    (void)setenv(kHstsHttpEnvVar, "1", 0);
78
30
    return true;
79
30
  }();
80
369k
  (void)configured;
81
369k
}
82
83
49.8k
void EnableTraceIds() { (void)curl_global_trace("+LIB-IDS"); }
84
85
}  // namespace
86
87
/// Apply deterministic routing, timeout, output, and persistence defaults.
88
/// Call before applying scenario options. `scheme` identifies the dedicated
89
/// in-process mock that will service the transfer and selects the safe direct-
90
/// protocol allowlist.
91
/// @param easy The curl easy handle to configure.
92
/// @param scheme Protocol whose dedicated in-process mock will service it.
93
/// @param trace_ids Enable verbose LIB-IDS tracing for this scenario.
94
/// @param trace_config Optional curl_global_trace() configuration.
95
/// @return Owner of the CURLOPT_CONNECT_TO list, which must outlive easy cleanup.
96
CurlSlistPtr ApplyBaselineOptions(CURL* easy, curl::fuzzer::proto::Scheme scheme, bool trace_ids,
97
369k
                                  const std::string& trace_config) {
98
369k
  EnableDebugHttpTransportMetadata();
99
100
369k
  curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, &SilentWriteCallback);
101
369k
  curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, &SilentWriteCallback);
102
103
369k
  const bool user_requested_verbose = std::getenv(kVerboseEnvVar) != nullptr;
104
369k
  if (!trace_config.empty()) {
105
    // Apply the fuzzer-selected categories before any explicit trace-ID
106
    // request so a scenario cannot accidentally disable its own ID prefixes.
107
74.3k
    (void)curl_global_trace(trace_config.c_str());
108
74.3k
  }
109
369k
  if (trace_ids) {
110
49.8k
    EnableTraceIds();
111
49.8k
  }
112
369k
  if (trace_ids || !trace_config.empty()) {
113
    // Keep trace coverage enabled during fuzzing without flooding the process
114
    // log. The callback still executes curl_trc.c's formatting path.
115
108k
    curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, &SilentDebugCallback);
116
108k
    curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L);
117
261k
  } else if (scheme == curl::fuzzer::proto::SCHEME_TELNET && !user_requested_verbose) {
118
    // printoption() and printsub() contain a substantial part of curl's TELNET
119
    // parser diagnostics but run only in verbose mode. Keep those paths in the
120
    // ordinary TELNET coverage lane while suppressing their high-volume text.
121
    // An explicit FUZZ_VERBOSE still skips the sink so reproductions remain
122
    // inspectable from the terminal.
123
4.88k
    curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, &SilentDebugCallback);
124
4.88k
    curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L);
125
4.88k
  }
126
127
  // Each non-HTTP protocol must use its dedicated peer invariants. Keep them
128
  // out of the redirect allowlist so an HTTP response cannot switch a stream
129
  // mock into synchronous TELNET, two-channel FTP, or datagram TFTP semantics.
130
  // CURLOPT_PROTOCOLS_STR arrived in 7.85.0.
131
369k
  const char* direct_protocols = kEventDrivenProtocolsAllowed;
132
369k
  switch (scheme) {
133
5.39k
    case curl::fuzzer::proto::SCHEME_TELNET:
134
5.39k
      direct_protocols = kTelnetProtocolAllowed;
135
5.39k
      break;
136
5.41k
    case curl::fuzzer::proto::SCHEME_FTP:
137
7.44k
    case curl::fuzzer::proto::SCHEME_FTPS:
138
7.44k
      direct_protocols = kFtpProtocolAllowed;
139
7.44k
      break;
140
2.36k
    case curl::fuzzer::proto::SCHEME_TFTP:
141
2.36k
      direct_protocols = kTftpProtocolAllowed;
142
2.36k
      break;
143
2.52k
    case curl::fuzzer::proto::SCHEME_SMTP:
144
6.00k
    case curl::fuzzer::proto::SCHEME_SMTPS:
145
6.00k
      direct_protocols = kSmtpProtocolAllowed;
146
6.00k
      break;
147
2.08k
    case curl::fuzzer::proto::SCHEME_IMAP:
148
6.43k
    case curl::fuzzer::proto::SCHEME_IMAPS:
149
6.43k
      direct_protocols = kImapProtocolAllowed;
150
6.43k
      break;
151
954
    case curl::fuzzer::proto::SCHEME_POP3:
152
4.11k
    case curl::fuzzer::proto::SCHEME_POP3S:
153
4.11k
      direct_protocols = kPop3ProtocolAllowed;
154
4.11k
      break;
155
710
    case curl::fuzzer::proto::SCHEME_MQTT:
156
4.17k
    case curl::fuzzer::proto::SCHEME_MQTTS:
157
4.17k
      direct_protocols = kMqttProtocolAllowed;
158
4.17k
      break;
159
3.01k
    case curl::fuzzer::proto::SCHEME_DICT:
160
3.01k
      direct_protocols = kDictProtocolAllowed;
161
3.01k
      break;
162
4.55k
    case curl::fuzzer::proto::SCHEME_GOPHER:
163
4.55k
      direct_protocols = "gopher";
164
4.55k
      break;
165
4.36k
    case curl::fuzzer::proto::SCHEME_GOPHERS:
166
4.36k
      direct_protocols = "gophers";
167
4.36k
      break;
168
4.08k
    case curl::fuzzer::proto::SCHEME_FILE:
169
4.08k
      direct_protocols = kFileProtocolAllowed;
170
4.08k
      break;
171
2.15k
    case curl::fuzzer::proto::SCHEME_LDAP:
172
6.66k
    case curl::fuzzer::proto::SCHEME_LDAPS:
173
6.66k
      direct_protocols = kLdapProtocolAllowed;
174
6.66k
      break;
175
7.82k
    case curl::fuzzer::proto::SCHEME_RTSP:
176
7.82k
      direct_protocols = kRtspProtocolAllowed;
177
7.82k
      break;
178
199k
    case curl::fuzzer::proto::SCHEME_HTTP:
179
263k
    case curl::fuzzer::proto::SCHEME_HTTPS:
180
280k
    case curl::fuzzer::proto::SCHEME_WS:
181
291k
    case curl::fuzzer::proto::SCHEME_WSS:
182
303k
    case curl::fuzzer::proto::SCHEME_IPFS:
183
303k
    case curl::fuzzer::proto::SCHEME_IPNS:
184
303k
    case curl::fuzzer::proto::SCHEME_UNSPECIFIED:
185
303k
    default:
186
303k
      break;
187
369k
  }
188
369k
  curl_easy_setopt(easy, CURLOPT_PROTOCOLS_STR, direct_protocols);
189
369k
  curl_easy_setopt(easy, CURLOPT_REDIR_PROTOCOLS_STR, kEventDrivenProtocolsAllowed);
190
191
  // CONNECT_TO confines direct connections, but an ambient http_proxy or
192
  // ALL_PROXY can select a proxy before curl asks the harness for a socket.
193
  // An explicit empty proxy keeps every transfer inside the socketpair and
194
  // makes replay independent of the machine running the fuzzer.
195
369k
  curl_easy_setopt(easy, CURLOPT_PROXY, "");
196
197
  // Keep raw secure-scheme inputs independent of the host trust store. The
198
  // dedicated TLS mock installs its own in-memory trust anchor after this
199
  // baseline; scenario options still run last and can deliberately select
200
  // verification failures.
201
369k
  curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 0L);
202
203
  // Force every name lookup to the fuzzer's in-process mock peer. The returned
204
  // owner keeps the list alive through curl_easy_cleanup.
205
369k
  CurlSlistPtr connect_to(curl_slist_append(nullptr, kConnectToOverride));
206
369k
  curl_easy_setopt(easy, CURLOPT_CONNECT_TO, connect_to.get());
207
208
  // Short bounds: fuzzing should never sit waiting on real I/O. Response
209
  // volume is already bounded by libFuzzer's input-size limit, so do not rate
210
  // limit receive traffic here: a global bytes-per-second throttle turns every
211
  // otherwise-complete large response into wall-clock sleep.
212
369k
  curl_easy_setopt(easy, CURLOPT_CONNECTTIMEOUT_MS, kConnectTimeoutMs);
213
369k
  curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, kTimeoutMs);
214
215
  // Keep every persistence/read path deterministic and prevent scenarios from
216
  // leaking state onto the filesystem. COOKIEFILE also makes the in-memory
217
  // engine's RELOAD command traverse its loader against a harmless empty
218
  // source. These path options deliberately remain absent from the generated
219
  // mutation manifest, so a proto cannot replace /dev/null.
220
369k
  curl_easy_setopt(easy, CURLOPT_COOKIEJAR, kDevNull);
221
369k
  curl_easy_setopt(easy, CURLOPT_COOKIEFILE, kDevNull);
222
369k
  curl_easy_setopt(easy, CURLOPT_ALTSVC, kDevNull);
223
369k
  curl_easy_setopt(easy, CURLOPT_HSTS, kDevNull);
224
369k
  curl_easy_setopt(easy, CURLOPT_NETRC_FILE, kDevNull);
225
  // Do not set CRLFILE to a placeholder path. An empty CRL is
226
  // not a harmless sink: when a scenario restores certificate verification,
227
  // OpenSSL rejects /dev/null before it can exercise useful handshake and
228
  // verification paths. The option is absent from the mutation manifest, so
229
  // leaving it unset introduces neither filesystem writes nor external input.
230
231
  // FUZZ_VERBOSE in the environment flips curl's own verbose logging on. This
232
  // is useful when reproducing a crashing corpus entry.
233
369k
  if (user_requested_verbose) {
234
0
    curl_easy_setopt(easy, CURLOPT_VERBOSE, 1L);
235
0
  }
236
369k
  return connect_to;
237
369k
}
238
239
/// Apply one closed, harness-owned TLS client-credential configuration.
240
/// No protobuf bytes become a path, provider, or engine identifier.
241
/// @param easy Handle receiving the fixed credential options.
242
/// @param profile Safe credential setup selected by the HTTPS lane.
243
/// @return The first curl_easy_setopt error, or CURLE_OK.
244
40.6k
CURLcode ApplyTlsClientCredentialProfile(CURL* easy, curl::fuzzer::proto::TlsClientCredentialProfile profile) {
245
40.6k
  if (easy == nullptr) {
246
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
247
0
  }
248
249
40.6k
  const auto set_string = [easy](CURLoption option, const char* value) {
250
3.13k
    return curl_easy_setopt(easy, option, value);
251
3.13k
  };
252
40.6k
  switch (profile) {
253
38.3k
    case curl::fuzzer::proto::TLS_CLIENT_CREDENTIAL_NONE:
254
38.3k
      return CURLE_OK;
255
256
851
    case curl::fuzzer::proto::TLS_CLIENT_CREDENTIAL_MALFORMED_PKCS12: {
257
851
      CURLcode result = set_string(CURLOPT_SSLCERTTYPE, kPkcs12CertificateType);
258
851
      if (result != CURLE_OK) {
259
7
        return result;
260
7
      }
261
844
      const curl_blob blob = {const_cast<unsigned char*>(kMalformedPkcs12), sizeof(kMalformedPkcs12), CURL_BLOB_COPY};
262
844
      return curl_easy_setopt(easy, CURLOPT_SSLCERT_BLOB, &blob);
263
851
    }
264
265
247
    case curl::fuzzer::proto::TLS_CLIENT_CREDENTIAL_ENGINE_DEV_NULL: {
266
247
      CURLcode result = set_string(CURLOPT_SSLCERTTYPE, kEngineCertificateType);
267
247
      if (result != CURLE_OK) {
268
3
        return result;
269
3
      }
270
244
      return set_string(CURLOPT_SSLCERT, kDevNull);
271
247
    }
272
273
862
    case curl::fuzzer::proto::TLS_CLIENT_CREDENTIAL_DEFAULT_PROVIDER_DEV_NULL: {
274
862
      CURLcode result = set_string(CURLOPT_SSLENGINE, kDefaultProvider);
275
862
      if (result != CURLE_OK) {
276
630
        return result;
277
630
      }
278
232
      result = set_string(CURLOPT_SSLCERTTYPE, kProviderCertificateType);
279
232
      if (result != CURLE_OK) {
280
34
        return result;
281
34
      }
282
198
      return set_string(CURLOPT_SSLCERT, kDevNull);
283
232
    }
284
285
253
    case curl::fuzzer::proto::TLS_CLIENT_CREDENTIAL_UNLOADED_PROVIDER_DEV_NULL: {
286
253
      CURLcode result = set_string(CURLOPT_SSLCERTTYPE, kProviderCertificateType);
287
253
      if (result != CURLE_OK) {
288
7
        return result;
289
7
      }
290
246
      return set_string(CURLOPT_SSLCERT, kDevNull);
291
253
    }
292
293
0
    default:
294
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
295
40.6k
  }
296
40.6k
}
297
298
/// Translate and apply one generated scalar/string SetOption to the easy handle.
299
/// Pointer-valued options borrow the SetOption's protobuf-owned string storage,
300
/// so its containing Scenario must remain alive and unmodified until the
301
/// transfer has stopped and the easy handle has been cleaned up. Borrowing
302
/// avoids a duplicate backing allocation on every iteration; the lifetime is
303
/// especially important for CURLOPT_POSTFIELDS, which curl does not copy.
304
/// @param easy The curl easy handle to configure.
305
/// @param option The SetOption proto describing which option and value to set.
306
/// @return curl's setopt result, or CURLE_UNKNOWN_OPTION for an unknown id.
307
1.15M
CURLcode ApplySetOption(CURL* easy, const curl::fuzzer::proto::SetOption& option) {
308
1.15M
  const OptionDescriptor* desc = LookupOptionDescriptor(option.option_id());
309
1.15M
  if (desc == nullptr) {
310
51.3k
    return CURLE_UNKNOWN_OPTION;
311
51.3k
  }
312
1.09M
  const CURLoption curlopt = static_cast<CURLoption>(desc->curlopt);
313
314
1.09M
  switch (desc->kind) {
315
471k
    case OptionValueKind::kString: {
316
471k
      const std::string& value = option.string_value();
317
318
      // COPYPOSTFIELDS allocates after reading the separately configured
319
      // POSTFIELDSIZE. First install the same protobuf-owned bytes as a
320
      // no-allocation borrowed fallback. A genuine OOM then still leaves a
321
      // coherent pointer and length for later consumers such as AWS SigV4.
322
471k
      if (desc->curlopt == CURLOPT_COPYPOSTFIELDS) {
323
10.3k
        CURLcode result = curl_easy_setopt(easy, CURLOPT_POSTFIELDS, value.c_str());
324
10.3k
        if (result != CURLE_OK) {
325
0
          return result;
326
0
        }
327
10.3k
      }
328
329
      // POSTFIELDS borrows its pointer and COPYPOSTFIELDS copies exactly the
330
      // previously configured size. Apply the correlated byte length first so
331
      // either option accepts embedded NULs without strlen semantics and the
332
      // copying variant can never read beyond the protobuf-owned buffer.
333
471k
      if (desc->curlopt == CURLOPT_POSTFIELDS || desc->curlopt == CURLOPT_COPYPOSTFIELDS) {
334
17.7k
        CURLcode result = curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(value.size()));
335
17.7k
        if (result != CURLE_OK) {
336
0
          return result;
337
0
        }
338
17.7k
      }
339
340
471k
      if (desc->curlopt == CURLOPT_COPYPOSTFIELDS) {
341
        // Copy ownership is a harness invariant rather than an allocation-
342
        // failure target. Preserve pending ordinals for later injectable work.
343
10.3k
        allocation_fault_injection::ScopedFailureSuppression suppress_failures;
344
10.3k
        return curl_easy_setopt(easy, CURLOPT_COPYPOSTFIELDS, value.c_str());
345
10.3k
      }
346
347
      // Curl otherwise treats this option as a filename during the TLS
348
      // handshake. Fixed-policy inputs normally arrive pre-constrained by the
349
      // postprocessor; this runtime check also protects compatibility inputs,
350
      // which intentionally bypass it. Curl copies this option in setopt, so
351
      // the temporary remains valid for the call's full ownership contract.
352
461k
      if (desc->curlopt == CURLOPT_PINNEDPUBLICKEY && !UsesInMemoryPublicKeyPin(value)) {
353
372
        std::string constrained = value;
354
372
        ConstrainPinnedPublicKeyValue(&constrained);
355
372
        return curl_easy_setopt(easy, curlopt, constrained.c_str());
356
372
      }
357
358
460k
      return curl_easy_setopt(easy, curlopt, value.c_str());
359
461k
    }
360
361
    // Decode the uint_value and pass it as either a long or a curl_off_t depending on the option.
362
344k
    case OptionValueKind::kUint: {
363
344k
      const std::uint64_t raw = DecodeIntegralOptionValue(*desc, option);
364
      // CURLOPTTYPE_OFF_T options start at 30000. Everything below takes a
365
      // long; everything at/above takes a curl_off_t.
366
344k
      if (static_cast<int>(desc->curlopt) >= 30000) {
367
49.5k
        return curl_easy_setopt(easy, curlopt, static_cast<curl_off_t>(raw));
368
49.5k
      }
369
294k
      return curl_easy_setopt(easy, curlopt, static_cast<long>(raw));
370
344k
    }
371
372
    // Decode the bool_value and pass it as a long flag (0 or 1).
373
283k
    case OptionValueKind::kBool: {
374
283k
      const long flag = static_cast<long>(DecodeIntegralOptionValue(*desc, option));
375
283k
      return curl_easy_setopt(easy, curlopt, flag);
376
344k
    }
377
1.09M
  }
378
0
  return CURLE_UNKNOWN_OPTION;
379
1.09M
}
380
381
/// Return the runtime-visible option prefix length. Fixed targets normally
382
/// trim the protobuf in their postprocessor, but the compatibility target must
383
/// preserve its historical message unchanged; applying the same bound here
384
/// prevents that lane from doing mutation-sized setopt work while exposing the
385
/// same option prefix as postprocessed fixed lanes.
386
/// @param scenario Structured input whose option prefix will be consumed.
387
/// @return Number of options visible to the runtime.
388
716k
std::size_t RuntimeOptionCount(const curl::fuzzer::proto::Scenario& scenario) {
389
716k
  return std::min<std::size_t>(static_cast<std::size_t>(scenario.options_size()), scenario_limits::kMaxOptions);
390
716k
}
391
392
/// Apply the bounded runtime-visible prefix of Scenario.options. Individual
393
/// CURLcode values remain intentionally ignored, matching the fuzzer runner's
394
/// historical behavior. Bounding here also covers standalone compatibility
395
/// seeds that reach RunScenario without normalization.
396
/// @param easy Easy handle receiving each supported option.
397
/// @param scenario Structured input that owns all borrowed option strings.
398
/// @return Number of option entries attempted.
399
369k
std::size_t ApplyScenarioOptions(CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
400
369k
  const std::size_t option_count = RuntimeOptionCount(scenario);
401
1.52M
  for (std::size_t index = 0; index < option_count; ++index) {
402
1.15M
    (void)ApplySetOption(easy, scenario.options(static_cast<int>(index)));
403
1.15M
  }
404
369k
  return option_count;
405
369k
}
406
407
}  // namespace proto_fuzzer