Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fuzz_http1_auth.cpp
Line
Count
Source
1
// Copyright 2026 Google LLC
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
////////////////////////////////////////////////////////////////////////////////
16
//
17
// End-to-end HTTP/1.x fuzzer focused on HTTP authentication
18
// (src/mhd2/auth_digest.c, auth_basic.c, request_auth_get.c) and the
19
// connection/event-processing layer (daemon_add_conn.c, events_process.c,
20
// conn_data_recv.c, conn_data_send.c, stream_process_reply.c).
21
//
22
// Threat model: a remote, unauthenticated client sends arbitrary bytes over a
23
// TCP connection.  The "Authorization" header (RFC 7616 Digest / RFC 7617
24
// Basic) is parsed by MHD before any credential is known to be valid, so its
25
// parser, the username/userhash/extended-notation decoders and the nonce /
26
// nonce-count bookkeeping are pre-authentication attack surface.
27
//
28
// The raw fuzz input is written into a real MHD daemon connection (see the
29
// driver below).  To let the fuzzer get past the server-nonce check and reach
30
// the URI/argument matching and response-hash code, the harness first
31
// obtains a genuine nonce: if the input contains the token "@NONCE@", an
32
// unauthenticated request for /auth is sent first, the nonce is extracted
33
// from the 401 WWW-Authenticate challenge (exactly as a real client does),
34
// and every "@NONCE@" in the input is replaced with it.
35
36
#include <errno.h>
37
#include <fcntl.h>
38
#include <poll.h>
39
#include <signal.h>
40
#include <stdarg.h>
41
#include <stddef.h>
42
#include <stdint.h>
43
#include <string.h>
44
#include <sys/socket.h>
45
#include <sys/types.h>
46
#include <netinet/in.h>
47
#include <netinet/tcp.h>
48
#include <arpa/inet.h>
49
#include <unistd.h>
50
51
#include <map>
52
#include <string>
53
#include <vector>
54
55
#include "microhttpd2.h"
56
57
// Realm/credentials known to the fuzz application (also in the dictionary).
58
34
#define FUZZ_REALM "fuzzrealm"
59
0
#define FUZZ_USER "fuzzuser"
60
0
#define FUZZ_PASS "fuzzpass"
61
62
namespace {
63
64
// A TCP client connection to the fuzz daemon.
65
class FuzzClient {
66
 public:
67
  explicit FuzzClient(struct MHD_Daemon *d);
68
  ~FuzzClient();
69
66
  bool ok() const { return fd_ >= 0; }
70
71
  // Write @a data to the server (as much as fits), driving the daemon so it
72
  // keeps draining its receive side; all server output is appended to
73
  // response().
74
  void Send(const uint8_t *data, size_t size);
75
  // Run the daemon event loop a few rounds, collecting output.
76
  void Pump(unsigned rounds);
77
  // Close client side and run the daemon until the connection is gone.
78
  void Close();
79
80
17
  const std::string &response() const { return resp_; }
81
17
  void ClearResponse() { resp_.clear(); }
82
83
 private:
84
  void Drain();
85
  struct MHD_Daemon *d_;
86
  int fd_;
87
  std::string resp_;
88
};
89
90
// ---- End-to-end driver
91
//
92
// A single MHD daemon is started in MHD_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL mode,
93
// listening on 127.0.0.1 (kernel-assigned port).  Each fuzz iteration
94
// connects a new TCP client, lets MHD accept() it and writes the attacker
95
// bytes into the client end; the client is closed with an RST.  The daemon is
96
// driven by a tiny zero-timeout poll() loop feeding MHD_daemon_event_update()
97
// and MHD_daemon_process_reg_events(), so everything runs single-threaded and
98
// deterministically: socket recv -> HTTP/1.x or HTTP/2 layer -> request
99
// parsing -> application callback -> reply -> socket send.
100
//
101
// NOTE: the same driver is duplicated in fuzz_h2_conn.cpp and
102
// fuzz_http1_auth.cpp; keep the two copies in sync.
103
104
struct MHD_Daemon *g_daemon = nullptr;
105
bool g_daemon_tried = false;
106
struct sockaddr_in g_listen_addr;
107
108
volatile uint8_t g_sink;  // Prevents the compiler from dropping reads.
109
110
272
void TouchBytes(const char *p, size_t len) {
111
272
  uint8_t acc = 0;
112
272
  if (p == nullptr)
113
48
    return;
114
30.4k
  for (size_t i = 0; i < len; ++i)
115
30.1k
    acc ^= static_cast<uint8_t>(p[i]);
116
224
  g_sink = acc;
117
224
}
118
119
52
void SilentLog(void *, enum MHD_StatusCode, const char *, va_list) {}
120
121
// ---- Minimal level-triggered external event loop
122
// (MHD_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL), driven with zero-timeout poll().
123
124
struct WatchedFd {
125
  enum MHD_FdState watch_for;
126
  struct MHD_EventUpdateContext *ecb;
127
};
128
std::map<MHD_Socket, WatchedFd> g_watched;
129
int g_app_cntx_marker;  // Address used as the non-NULL application context.
130
131
void *SocketRegCb(void *, MHD_Socket fd, enum MHD_FdState watch_for,
132
139
                  void *, struct MHD_EventUpdateContext *ecb) {
133
139
  if (MHD_FD_STATE_NONE == watch_for) {
134
66
    g_watched.erase(fd);
135
66
    return nullptr;
136
66
  }
137
73
  g_watched[fd] = WatchedFd{watch_for, ecb};
138
73
  return &g_app_cntx_marker;
139
139
}
140
141
679
void RunEventLoopOnce(struct MHD_Daemon *d) {
142
679
  std::vector<struct pollfd> pfds;
143
679
  std::vector<WatchedFd> regs;
144
679
  pfds.reserve(g_watched.size());
145
679
  regs.reserve(g_watched.size());
146
1.63k
  for (const auto &it : g_watched) {
147
1.63k
    struct pollfd p;
148
1.63k
    p.fd = it.first;
149
1.63k
    p.events = 0;
150
1.63k
    if (MHD_FD_STATE_IS_SET_RECV(it.second.watch_for))
151
1.62k
      p.events |= POLLIN;
152
1.63k
    if (MHD_FD_STATE_IS_SET_SEND(it.second.watch_for))
153
7
      p.events |= POLLOUT;
154
1.63k
    p.revents = 0;
155
1.63k
    pfds.push_back(p);
156
1.63k
    regs.push_back(it.second);
157
1.63k
  }
158
679
  if (!pfds.empty())
159
679
    (void)poll(pfds.data(), pfds.size(), 0);
160
2.31k
  for (size_t i = 0; i < pfds.size(); ++i) {
161
1.63k
    unsigned int st = MHD_FD_STATE_NONE;
162
    // A peer hang-up is reported as "readable" so that recv() returns 0.
163
1.63k
    if (pfds[i].revents & (POLLIN | POLLHUP))
164
172
      st |= MHD_FD_STATE_RECV;
165
1.63k
    if (pfds[i].revents & POLLOUT)
166
7
      st |= MHD_FD_STATE_SEND;
167
1.63k
    if (pfds[i].revents & (POLLERR | POLLNVAL))
168
17
      st |= MHD_FD_STATE_EXCEPT;
169
1.63k
    MHD_daemon_event_update(d, regs[i].ecb, static_cast<enum MHD_FdState>(st));
170
1.63k
  }
171
679
  (void)MHD_daemon_process_reg_events(d, nullptr);
172
679
}
173
174
35
bool PathStartsWith(const struct MHD_String *path, const char *prefix) {
175
35
  const size_t plen = strlen(prefix);
176
35
  return path->len >= plen && 0 == memcmp(path->cstr, prefix, plen);
177
35
}
178
179
// ---- Request inspection: what a typical application reads from a request.
180
181
enum MHD_Bool ValueIter(void *, enum MHD_ValueKind,
182
123
                        const struct MHD_NameAndValue *nv) {
183
123
  TouchBytes(nv->name.cstr, nv->name.len);
184
123
  TouchBytes(nv->value.cstr, nv->value.len);
185
123
  return MHD_YES;
186
123
}
187
188
32
void InspectRequest(struct MHD_Request *request) {
189
32
  struct MHD_StringNullable v;
190
32
  (void)MHD_request_get_values_cb(
191
32
      request,
192
32
      static_cast<enum MHD_ValueKind>(MHD_VK_HEADER | MHD_VK_COOKIE |
193
32
                                      MHD_VK_URI_QUERY_PARAM),
194
32
      &ValueIter, nullptr);
195
32
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_HEADER,
196
32
                                       MHD_HTTP_HEADER_HOST, &v))
197
17
    TouchBytes(v.cstr, v.len);
198
32
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_HEADER,
199
32
                                       MHD_HTTP_HEADER_CONTENT_TYPE, &v))
200
6
    TouchBytes(v.cstr, v.len);
201
32
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_COOKIE, "session", &v))
202
0
    TouchBytes(v.cstr, v.len);
203
32
  if (MHD_YES ==
204
32
      MHD_request_get_value(request, MHD_VK_URI_QUERY_PARAM, "q", &v))
205
0
    TouchBytes(v.cstr, v.len);
206
207
32
  union MHD_RequestInfoDynamicData dyn;
208
32
  static const enum MHD_RequestInfoDynamicType kDyn[] = {
209
32
      MHD_REQUEST_INFO_DYNAMIC_HTTP_METHOD_STRING,
210
32
      MHD_REQUEST_INFO_DYNAMIC_URI,
211
32
      MHD_REQUEST_INFO_DYNAMIC_NUMBER_URI_PARAMS,
212
32
      MHD_REQUEST_INFO_DYNAMIC_NUMBER_COOKIES,
213
32
      MHD_REQUEST_INFO_DYNAMIC_HEADER_SIZE,
214
32
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_PRESENT,
215
32
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_CHUNKED,
216
32
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_SIZE_TOTAL,
217
32
  };
218
32
  for (enum MHD_RequestInfoDynamicType t : kDyn)
219
256
    (void)MHD_request_get_info_dynamic(request, t, &dyn);
220
221
32
  union MHD_RequestInfoFixedData fix;
222
32
  (void)MHD_request_get_info_fixed(request, MHD_REQUEST_INFO_FIXED_HTTP_VER,
223
32
                                   &fix);
224
32
}
225
226
// ---- Responses
227
228
const struct MHD_Action *RespondText(struct MHD_Request *request,
229
                                     enum MHD_HTTP_StatusCode sc,
230
7
                                     const char *text) {
231
7
  struct MHD_Response *r =
232
7
      MHD_response_from_buffer_static(sc, strlen(text), text);
233
7
  if (r == nullptr)
234
0
    return MHD_action_abort_request(request);
235
7
  (void)MHD_response_add_header(r, MHD_HTTP_HEADER_CONTENT_TYPE,
236
7
                                "text/plain");
237
7
  (void)MHD_response_add_header(r, "X-Fuzz", "1");
238
7
  return MHD_action_from_response(request, r);
239
7
}
240
241
6
const struct MHD_UploadAction *UploadRespond(struct MHD_Request *request) {
242
6
  static const char kOk[] = "upload ok";
243
6
  struct MHD_Response *r = MHD_response_from_buffer_static(
244
6
      MHD_HTTP_STATUS_OK, sizeof(kOk) - 1, kOk);
245
6
  if (r == nullptr)
246
0
    return MHD_upload_action_abort_request(request);
247
6
  return MHD_upload_action_from_response(request, r);
248
6
}
249
250
const struct MHD_UploadAction *UploadFull(void *, struct MHD_Request *request,
251
1
                                          size_t size, void *data) {
252
1
  TouchBytes(static_cast<const char *>(data), size);
253
1
  return UploadRespond(request);
254
1
}
255
256
const struct MHD_UploadAction *UploadInc(void *, struct MHD_Request *request,
257
2
                                         size_t size, void *data) {
258
2
  if (size != 0) {
259
2
    TouchBytes(static_cast<const char *>(data), size);
260
2
    return MHD_upload_action_continue(request);
261
2
  }
262
0
  return UploadRespond(request);
263
2
}
264
265
const struct MHD_UploadAction *PostReader(
266
    struct MHD_Request *request, void *, const struct MHD_String *name,
267
    const struct MHD_StringNullable *filename,
268
    const struct MHD_StringNullable *content_type,
269
    const struct MHD_StringNullable *encoding, size_t size, const void *data,
270
0
    uint_fast64_t, enum MHD_Bool) {
271
0
  TouchBytes(name->cstr, name->len);
272
0
  TouchBytes(filename->cstr, filename->len);
273
0
  TouchBytes(content_type->cstr, content_type->len);
274
0
  TouchBytes(encoding->cstr, encoding->len);
275
0
  TouchBytes(static_cast<const char *>(data), size);
276
0
  return MHD_upload_action_continue(request);
277
0
}
278
279
const struct MHD_UploadAction *PostDone(struct MHD_Request *request, void *,
280
5
                                        enum MHD_PostParseResult) {
281
5
  return UploadRespond(request);
282
5
}
283
284
// Digest / Basic authentication, as done by a typical protected resource.
285
17
const struct MHD_Action *HandleAuth(struct MHD_Request *request) {
286
17
  union MHD_RequestInfoDynamicData dyn;
287
288
17
  if (MHD_SC_OK ==
289
17
      MHD_request_get_info_dynamic(
290
17
          request, MHD_REQUEST_INFO_DYNAMIC_AUTH_BASIC_CREDS, &dyn)) {
291
0
    const struct MHD_AuthBasicCreds *bc = dyn.v_auth_basic_creds;
292
0
    TouchBytes(bc->username.cstr, bc->username.len);
293
0
    TouchBytes(bc->password.cstr, bc->password.len);
294
0
    if (bc->username.len == strlen(FUZZ_USER) &&
295
0
        0 == memcmp(bc->username.cstr, FUZZ_USER, bc->username.len) &&
296
0
        bc->password.cstr != nullptr &&
297
0
        bc->password.len == strlen(FUZZ_PASS) &&
298
0
        0 == memcmp(bc->password.cstr, FUZZ_PASS, bc->password.len))
299
0
      return RespondText(request, MHD_HTTP_STATUS_OK, "basic ok");
300
0
  }
301
302
17
  bool stale = false;
303
17
  if (MHD_SC_OK ==
304
17
      MHD_request_get_info_dynamic(
305
17
          request, MHD_REQUEST_INFO_DYNAMIC_AUTH_DIGEST_INFO, &dyn)) {
306
0
    const struct MHD_AuthDigestInfo *di = dyn.v_auth_digest_info;
307
0
    TouchBytes(di->username.cstr, di->username.len);
308
0
    TouchBytes(di->realm.cstr, di->realm.len);
309
0
    TouchBytes(di->opaque.cstr, di->opaque.len);
310
0
    TouchBytes(di->userhash_hex.cstr, di->userhash_hex.len);
311
0
    TouchBytes(reinterpret_cast<const char *>(di->userhash_bin),
312
0
               di->userhash_bin_size);
313
314
0
    enum MHD_DigestAuthResult res = MHD_digest_auth_check(
315
0
        request, FUZZ_REALM, FUZZ_USER, FUZZ_PASS, 0,
316
0
        MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO_ANY);
317
0
    if (MHD_DAUTH_OK == res)
318
0
      return RespondText(request, MHD_HTTP_STATUS_OK, "digest ok");
319
0
    stale = (MHD_DAUTH_NONCE_STALE == res);
320
321
    // Same check through the pre-computed "userdigest" API (SHA-256).
322
0
    uint8_t ud[MHD_SHA256_DIGEST_SIZE];
323
0
    if (MHD_SC_OK == MHD_digest_auth_calc_userdigest(
324
0
                         MHD_DIGEST_AUTH_ALGO_SHA256, FUZZ_USER, FUZZ_REALM,
325
0
                         FUZZ_PASS, sizeof(ud), ud)) {
326
0
      if (MHD_DAUTH_OK ==
327
0
          MHD_digest_auth_check_digest(
328
0
              request, FUZZ_REALM, FUZZ_USER, sizeof(ud), ud, 0,
329
0
              MHD_DIGEST_AUTH_MULT_QOP_AUTH_ANY,
330
0
              MHD_DIGEST_AUTH_MULT_ALGO_SHA256_ANY))
331
0
        return RespondText(request, MHD_HTTP_STATUS_OK, "digest ok");
332
0
    }
333
0
  }
334
335
17
  static const char kDenied[] = "denied";
336
17
  struct MHD_Response *r = MHD_response_from_buffer_static(
337
17
      MHD_HTTP_STATUS_UNAUTHORIZED, sizeof(kDenied) - 1, kDenied);
338
17
  if (r == nullptr)
339
0
    return MHD_action_abort_request(request);
340
17
  (void)MHD_response_add_auth_basic_challenge(r, FUZZ_REALM, MHD_YES);
341
17
  return MHD_action_digest_auth_challenge(
342
17
      request, FUZZ_REALM, "fuzzopaque", "/", stale ? MHD_YES : MHD_NO,
343
17
      MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO_ANY_NON_SESSION,
344
17
      MHD_YES, MHD_YES, r, MHD_NO);
345
17
}
346
347
// The application.  Behaviour is selected by the (attacker supplied) path,
348
// as real applications route on the path.
349
const struct MHD_Action *RequestCb(void *, struct MHD_Request *request,
350
                                   const struct MHD_String *path,
351
                                   enum MHD_HTTP_Method method,
352
32
                                   uint_fast64_t) {
353
32
  InspectRequest(request);
354
355
32
  if (method == MHD_HTTP_METHOD_POST || method == MHD_HTTP_METHOD_PUT) {
356
8
    if (PathStartsWith(path, "/form"))
357
5
      return MHD_action_parse_post(request, 512, 256,
358
5
                                   MHD_HTTP_POST_ENCODING_OTHER, &PostReader,
359
5
                                   nullptr, &PostDone, nullptr);
360
3
    if (PathStartsWith(path, "/inc"))
361
0
      return MHD_action_process_upload(request, 0, nullptr, nullptr,
362
0
                                       &UploadInc, nullptr);
363
3
    return MHD_action_process_upload(request, 1024, &UploadFull, nullptr,
364
3
                                     &UploadInc, nullptr);
365
3
  }
366
24
  if (PathStartsWith(path, "/auth"))
367
17
    return HandleAuth(request);
368
7
  return RespondText(request, MHD_HTTP_STATUS_OK, "hello");
369
24
}
370
371
66
struct MHD_Daemon *fuzz_get_daemon() {
372
66
  if (g_daemon_tried)
373
65
    return g_daemon;
374
1
  g_daemon_tried = true;
375
376
1
  signal(SIGPIPE, SIG_IGN);
377
378
  // Listen on 127.0.0.1 with a kernel-assigned port (unique per fuzzing
379
  // process, so parallel jobs do not collide).  The socket is created here
380
  // and handed to MHD; MHD accept()s the client connections itself.
381
  // (MHD_daemon_add_connection() cannot be used: externally added sockets
382
  // are rejected with MHD_SC_FEATURE_DISABLED by the current library.)
383
1
  int lfd = socket(AF_INET, SOCK_STREAM, 0);
384
1
  if (lfd < 0)
385
0
    return nullptr;
386
1
  memset(&g_listen_addr, 0, sizeof(g_listen_addr));
387
1
  g_listen_addr.sin_family = AF_INET;
388
1
  g_listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
389
1
  g_listen_addr.sin_port = 0;
390
1
  socklen_t alen = sizeof(g_listen_addr);
391
1
  if (0 != bind(lfd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
392
1
                sizeof(g_listen_addr)) ||
393
1
      0 != listen(lfd, 64) ||
394
1
      0 != getsockname(lfd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
395
1
                       &alen)) {
396
0
    close(lfd);
397
0
    return nullptr;
398
0
  }
399
400
1
  struct MHD_Daemon *d = MHD_daemon_create(&RequestCb, nullptr);
401
1
  if (d == nullptr) {
402
0
    close(lfd);
403
0
    return nullptr;
404
0
  }
405
406
  // Fixed entropy: nonces are derived deterministically from it.
407
1
  static uint8_t entropy[32];
408
33
  for (size_t i = 0; i < sizeof(entropy); ++i)
409
32
    entropy[i] = static_cast<uint8_t>(0x5A ^ (i * 31));
410
411
1
  if (MHD_SC_OK !=
412
1
          MHD_DAEMON_SET_OPTIONS(
413
1
              d,
414
1
              MHD_D_OPTION_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL(&SocketRegCb,
415
1
                                                           nullptr),
416
1
              MHD_D_OPTION_LISTEN_SOCKET(lfd),
417
1
              MHD_D_OPTION_LOG_CALLBACK(&SilentLog, nullptr),
418
1
              MHD_D_OPTION_RANDOM_ENTROPY(sizeof(entropy), entropy),
419
1
              MHD_D_OPTION_SUPPRESS_DATE_HEADER(MHD_YES),
420
1
              MHD_D_OPTION_AUTH_DIGEST_NONCE_TIMEOUT(3600),
421
1
              MHD_D_OPTION_CONN_MEMORY_LIMIT(32 * 1024)) ||
422
1
      MHD_SC_OK != MHD_daemon_start(d)) {
423
0
    MHD_daemon_destroy(d);
424
0
    return nullptr;
425
0
  }
426
1
  g_daemon = d;
427
1
  return g_daemon;
428
1
}
429
430
66
FuzzClient::FuzzClient(struct MHD_Daemon *d) : d_(d), fd_(-1) {
431
66
  int fd = socket(AF_INET, SOCK_STREAM, 0);
432
66
  if (fd < 0)
433
0
    return;
434
  // Loopback connect() completes immediately (the kernel finishes the
435
  // handshake; MHD accept()s from the backlog below).
436
66
  if (0 != connect(fd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
437
66
                   sizeof(g_listen_addr))) {
438
0
    close(fd);
439
0
    return;
440
0
  }
441
66
  int one = 1;
442
66
  (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
443
66
  int fl = fcntl(fd, F_GETFL);
444
66
  fcntl(fd, F_SETFL, fl | O_NONBLOCK);
445
66
  fd_ = fd;
446
  // Let MHD accept() the new connection.
447
66
  for (unsigned i = 0; i < 16; ++i) {
448
66
    RunEventLoopOnce(d_);
449
66
    union MHD_DaemonInfoDynamicData info;
450
66
    if (MHD_SC_OK == MHD_daemon_get_info_dynamic(
451
66
                         d_, MHD_DAEMON_INFO_DYNAMIC_HAS_CONNECTIONS, &info) &&
452
66
        MHD_YES == info.v_has_connections_bool)
453
66
      break;
454
66
  }
455
66
}
456
457
66
FuzzClient::~FuzzClient() { Close(); }
458
459
547
void FuzzClient::Drain() {
460
547
  if (fd_ < 0)
461
0
    return;
462
547
  char buf[4096];
463
588
  for (;;) {
464
588
    ssize_t n = recv(fd_, buf, sizeof(buf), 0);
465
588
    if (n <= 0)
466
547
      break;
467
    // Bound memory use: only the beginning of the output is of interest.
468
41
    if (resp_.size() < 65536)
469
41
      resp_.append(buf, static_cast<size_t>(n));
470
41
  }
471
547
}
472
473
232
void FuzzClient::Pump(unsigned rounds) {
474
779
  for (unsigned i = 0; i < rounds; ++i) {
475
547
    RunEventLoopOnce(d_);
476
547
    Drain();
477
547
  }
478
232
}
479
480
83
void FuzzClient::Send(const uint8_t *data, size_t size) {
481
83
  if (fd_ < 0)
482
0
    return;
483
83
  size_t off = 0;
484
83
  unsigned stalls = 0;
485
166
  while (off < size && stalls < 64) {
486
83
    ssize_t n = send(fd_, data + off, size - off, MSG_NOSIGNAL);
487
83
    if (n > 0) {
488
83
      off += static_cast<size_t>(n);
489
83
      stalls = 0;
490
83
    } else if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK &&
491
0
               errno != EINTR) {
492
0
      break;  // Server closed the connection.
493
0
    } else {
494
0
      ++stalls;
495
0
    }
496
83
    Pump(1);
497
83
  }
498
83
  Pump(4);
499
83
}
500
501
132
void FuzzClient::Close() {
502
132
  if (fd_ < 0)
503
66
    return;
504
66
  Pump(2);
505
  // Abortive close (RST) to avoid TIME_WAIT port exhaustion.
506
66
  struct linger lg;
507
66
  lg.l_onoff = 1;
508
66
  lg.l_linger = 0;
509
66
  (void)setsockopt(fd_, SOL_SOCKET, SO_LINGER, &lg, sizeof(lg));
510
66
  close(fd_);
511
66
  fd_ = -1;
512
  // Let MHD notice the EOF and clean the connection up, so that no state is
513
  // carried over to the next fuzz iteration.
514
66
  for (unsigned i = 0; i < 64; ++i) {
515
66
    RunEventLoopOnce(d_);
516
66
    union MHD_DaemonInfoDynamicData info;
517
66
    if (MHD_SC_OK == MHD_daemon_get_info_dynamic(
518
66
                         d_, MHD_DAEMON_INFO_DYNAMIC_HAS_CONNECTIONS, &info) &&
519
66
        MHD_NO == info.v_has_connections_bool)
520
66
      break;
521
66
  }
522
66
}
523
524
}  // namespace
525
526
static const char kToken[] = "@NONCE@";
527
528
17
static std::string ExtractNonce(const std::string &resp) {
529
17
  static const char kKey[] = "nonce=\"";
530
17
  size_t p = resp.find(kKey);
531
17
  if (p == std::string::npos)
532
0
    return std::string();
533
17
  p += sizeof(kKey) - 1;
534
17
  size_t e = resp.find('"', p);
535
17
  if (e == std::string::npos)
536
0
    return std::string();
537
17
  return resp.substr(p, e - p);
538
17
}
539
540
66
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
541
66
  struct MHD_Daemon *d = fuzz_get_daemon();
542
66
  if (d == nullptr)
543
0
    return 0;
544
545
66
  std::string input(reinterpret_cast<const char *>(data), size);
546
547
66
  FuzzClient client(d);
548
66
  if (!client.ok())
549
0
    return 0;
550
551
66
  if (input.find(kToken) != std::string::npos) {
552
17
    static const char kPrime[] =
553
17
        "GET /auth HTTP/1.1\r\nHost: fuzz\r\n\r\n";
554
17
    client.Send(reinterpret_cast<const uint8_t *>(kPrime), sizeof(kPrime) - 1);
555
17
    const std::string nonce = ExtractNonce(client.response());
556
17
    client.ClearResponse();
557
17
    size_t pos = 0;
558
3.42k
    while ((pos = input.find(kToken, pos)) != std::string::npos) {
559
3.41k
      input.replace(pos, sizeof(kToken) - 1, nonce);
560
3.41k
      pos += nonce.size();
561
3.41k
    }
562
17
  }
563
564
66
  if (!input.empty())
565
66
    client.Send(reinterpret_cast<const uint8_t *>(input.data()), input.size());
566
66
  client.Close();
567
66
  return 0;
568
66
}