// Fuzz target for the remotes, CA files and credentials parsers: whatever parses must
// write back out and parse again to the same entries, and a failed parse
// leaves nothing behind.
#include "platform.h"
#include "remote.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static Remotes r1;
static Remotes r2;
static Creds c1;
static Creds c2;
static CaFiles f1;
static CaFiles f2;
static char fpath[4096 + 32];
static char rpath[4096 + 32];
static char cpath[4096 + 32];
static char spath[4096 + 32];
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
if (rpath[0] == '\0') {
const char *tmp = getenv("TMPDIR");
char dir[4096];
snprintf(dir, sizeof dir, "%s/suit-fuzz-remote.XXXXXX", tmp != nullptr ? tmp : "/tmp");
if (mkdtemp(dir) == nullptr) abort();
snprintf(rpath, sizeof rpath, "%s/remotes", dir);
snprintf(cpath, sizeof cpath, "%s/credentials", dir);
snprintf(spath, sizeof spath, "%s/wd.syncfail", dir);
snprintf(fpath, sizeof fpath, "%s/cafiles", dir);
}
RemoteError e;
if (!remotes_parse(&r1, (const char *)data, size, &e)) {
ensure(e.msg[0] != '\0' && r1.n == 0);
} else {
[[maybe_unused]] int written = remotes_write(&r1, rpath);
ensure(written == 0);
[[maybe_unused]] bool again = remotes_load(&r2, rpath, &e);
ensure(again && r2.n == r1.n);
}
if (!creds_parse(&c1, (const char *)data, size, &e)) {
ensure(e.msg[0] != '\0' && c1.n == 0);
} else {
[[maybe_unused]] int written = creds_write(&c1, cpath);
ensure(written == 0);
[[maybe_unused]] bool again = creds_load(&c2, cpath, &e);
ensure(again && c2.n == c1.n);
}
if (!cafiles_parse(&f1, (const char *)data, size, &e)) {
ensure(e.msg[0] != '\0' && f1.n == 0);
} else {
[[maybe_unused]] int written = cafiles_write(&f1, fpath);
ensure(written == 0);
[[maybe_unused]] bool again = cafiles_load(&f2, fpath, &e);
ensure(again && f2.n == f1.n);
}
unsigned n1;
unsigned n2;
if (!syncfail_parse((const char *)data, size, &n1)) {
ensure(n1 == 0);
} else {
[[maybe_unused]] int written = syncfail_write(spath, n1);
ensure(written == 0);
[[maybe_unused]] bool again = syncfail_load(spath, &n2, &e);
ensure(again && n2 == n1 && n1 >= 1 && n1 <= SYNC_FAILS_MAX);
}
secret_wipe(&c1, sizeof c1);
secret_wipe(&c2, sizeof c2);
return 0;
}