From 3a8e7aad8c4d329ce0a11bd84d680fc82dd9a1e7 Mon Sep 17 00:00:00 2001 From: Guilherme Bernardo Date: Mon, 30 Nov 2026 21:54:43 -0400 Subject: [PATCH] feat(native): --model-input makes the program's libc input nondeterministic Without it, fgets on stdin reads nothing, getenv finds nothing, connect is refused and accept waits forever: a flaw that needs input is never reached and the verdict is TRUE (Juliet CWE-761: 80 of 100 flawed programs FN). NonDetPass, given -m2c-model-input, retargets the program's declarations of fgets, fgetc/getc, getchar, fread, fgetws, fgetwc/getwc, getwchar, fscanf/scanf, read, recv, recvfrom, getenv, fopen, connect, bind, listen and accept to map2check_input_* in LibcInputModel.c. Their content and length come from map2check_non_det_*: symbolic under KLEE, the fuzzer's bytes under AFL++, read back on replay -- the model --wasm uses for WASI's fd_read. The bytes over all calls are bounded by --input-bound (default 4); a TRUE holds for inputs of at most that size. Every byte is a branch, so a larger bound keeps KLEE from exhausting the paths; on a Juliet calibration (CWE-761 and CWE-190, 64 programs) bounds 4 and 8 found the same flaws. Opt-in: in SV-COMP and Test-Comp the input comes only from __VERIFIER_nondet_*, and modelled libc input would misalign the test vectors. --- .github/workflows/ci.yml | 1 + modules/backend/library/lib/CMakeLists.txt | 1 + modules/backend/library/lib/LibcInputModel.c | 351 +++++++++++++++++++ modules/backend/pass/NonDetPass.cpp | 75 ++++ modules/frontend/caller.cpp | 7 + modules/frontend/caller.hpp | 11 + modules/frontend/map2check.cpp | 19 + tests/integration/test_model_input.sh | 141 ++++++++ 8 files changed, 606 insertions(+) create mode 100644 modules/backend/library/lib/LibcInputModel.c create mode 100755 tests/integration/test_model_input.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ea2a9078..2e08a8450 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -371,6 +371,7 @@ jobs: bash tests/integration/test_fuzzer_pruned_corpus.sh bash tests/integration/test_exit_codes.sh bash tests/integration/test_cwe_mode_mapping.sh + bash tests/integration/test_model_input.sh ' # =========================================================== diff --git a/modules/backend/library/lib/CMakeLists.txt b/modules/backend/library/lib/CMakeLists.txt index 9b532e8d0..4379760d7 100755 --- a/modules/backend/library/lib/CMakeLists.txt +++ b/modules/backend/library/lib/CMakeLists.txt @@ -12,6 +12,7 @@ list(APPEND MAP2CHECK_C_LIB "BTree") list(APPEND MAP2CHECK_C_LIB "ContainerBTree") list(APPEND MAP2CHECK_C_LIB "ContainerRealloc") list(APPEND MAP2CHECK_C_LIB "HeapLog") +list(APPEND MAP2CHECK_C_LIB "LibcInputModel") list(APPEND MAP2CHECK_C_LIB "ListLog") list(APPEND MAP2CHECK_C_LIB "Map2CheckFunctions") list(APPEND MAP2CHECK_C_LIB "NonDetGeneratorNone") diff --git a/modules/backend/library/lib/LibcInputModel.c b/modules/backend/library/lib/LibcInputModel.c new file mode 100644 index 000000000..e80923849 --- /dev/null +++ b/modules/backend/library/lib/LibcInputModel.c @@ -0,0 +1,351 @@ +/** + * Copyright (C) 2014 - 2020 Map2Check tool + * This file is part of the Map2Check tool, and is made available under + * the terms of the GNU General Public License version 2. + * + * SPDX-License-Identifier: (GPL-2.0) + **/ + +/* LibcInputModel.c -- the program's input from the outside world, as + * nondeterministic values (--model-input). + * + * Without it, a call such as fgets(buf, n, stdin) is a real call: KLEE runs + * it concretely (stdin is empty, getenv finds nothing, connect is refused), + * AFL++ only varies the __VERIFIER_nondet_* values, and the program takes one + * path, the one with no input. A flaw that needs input is then never reached + * and the verdict is TRUE (Juliet CWE-761: 80 of 100 flawed programs). + * + * NonDetPass retargets the program's calls to these functions (input: + * map2check_input_fgets, ...). Each one delivers what the real function could + * deliver, with its content and length taken from map2check_non_det_*: KLEE + * makes them symbolic, AFL++ reads them from its input, the replay of a test + * reads them back. This is how --wasm models WASI's fd_read + * (WasmRuntimeStubs.c). + * + * The input a run can receive is bounded: map2check_input_max bytes over all + * calls (--input-bound; NonDetPass defines the global in the program). A TRUE + * with --model-input holds for inputs of at most that size. Every byte is a + * branch for the program that reads it, so the bound decides whether KLEE can + * exhaust the paths and prove a program safe; and a flaw that needs a longer + * input ("2147483647" for atoi) is out of reach below it. Numbers read by + * fscanf take no bytes: they get their whole range. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../header/NonDetGenerator.h" + +/* Strings with no bound of their own (%s, getenv) take at most this much. */ +#define M2C_INPUT_MAX 16u + +extern const unsigned map2check_input_max; +static unsigned input_left = 0; +static int input_started = 0; + +static void input_start(void) { + if (input_started) return; + input_started = 1; + input_left = map2check_input_max; +} + +/* A length in [0, max], max capped by what is left of the budget. */ +static size_t input_length(size_t max) { + input_start(); + if (max > input_left) max = input_left; + size_t length = map2check_non_det_unsigned() % (max + 1); + input_left -= (unsigned)length; + return length; +} + +/* --- Character streams ---------------------------------------------------- */ + +char *map2check_input_fgets(char *s, int n, FILE *stream) { + (void)stream; + if (s == NULL || n <= 0) return NULL; + size_t length = input_length((size_t)n - 1); + if (length == 0) return NULL; /* end of file before any character */ + for (size_t i = 0; i < length; i++) { + s[i] = (char)map2check_non_det_uchar(); + if (s[i] == '\n') { /* fgets stops after a newline */ + input_left += (unsigned)(length - i - 1); + length = i + 1; + break; + } + } + s[length] = '\0'; + return s; +} + +int map2check_input_fgetc(FILE *stream) { + (void)stream; + if (input_length(1) == 0) return EOF; + return (int)map2check_non_det_uchar(); +} + +int map2check_input_getchar(void) { return map2check_input_fgetc(stdin); } + +size_t map2check_input_fread(void *ptr, size_t size, size_t nmemb, + FILE *stream) { + (void)stream; + if (ptr == NULL || size == 0 || nmemb == 0) return 0; + input_start(); + size_t max_items = input_left / size; + if (max_items > nmemb) max_items = nmemb; + size_t items = map2check_non_det_unsigned() % (max_items + 1); + input_left -= (unsigned)(items * size); + unsigned char *bytes = (unsigned char *)ptr; + for (size_t i = 0; i < items * size; i++) bytes[i] = map2check_non_det_uchar(); + return items; +} + +/* --- Wide character streams ----------------------------------------------- */ + +wchar_t *map2check_input_fgetws(wchar_t *ws, int n, FILE *stream) { + (void)stream; + if (ws == NULL || n <= 0) return NULL; + size_t length = input_length((size_t)n - 1); + if (length == 0) return NULL; + for (size_t i = 0; i < length; i++) { + ws[i] = (wchar_t)map2check_non_det_uint(); + if (ws[i] == L'\n') { + input_left += (unsigned)(length - i - 1); + length = i + 1; + break; + } + } + ws[length] = L'\0'; + return ws; +} + +wint_t map2check_input_fgetwc(FILE *stream) { + (void)stream; + if (input_length(1) == 0) return WEOF; + return (wint_t)map2check_non_det_uint(); +} + +wint_t map2check_input_getwchar(void) { return map2check_input_fgetwc(stdin); } + +/* --- Formatted input ------------------------------------------------------ */ + +/* Assigns every conversion of the format a nondeterministic value, or + * returns EOF having assigned none. A partial match is not modelled. Strings + * (%s, %[, %c) take their length from the input budget. */ +static int input_vscanf(const char *format, va_list ap) { + if ((int)map2check_non_det_int() < 0) return EOF; + int assigned = 0; + for (const char *f = format; f != NULL && *f != '\0'; f++) { + if (*f != '%') continue; + f++; + if (*f == '%') continue; + int suppress = 0; + if (*f == '*') { + suppress = 1; + f++; + } + size_t width = 0; + while (*f >= '0' && *f <= '9') width = width * 10 + (size_t)(*f++ - '0'); + int length = 0; /* -2 hh, -1 h, 0, 1 l, 2 ll/j/q, 3 z/t, 4 L */ + for (;; f++) { + if (*f == 'h') length = length == -1 ? -2 : -1; + else if (*f == 'l') length = length == 1 ? 2 : 1; + else if (*f == 'j' || *f == 'q') length = 2; + else if (*f == 'z' || *f == 't') length = 3; + else if (*f == 'L') length = 4; + else break; + } + char conversion = *f; + if (conversion == '\0') break; + if (conversion == '[') { /* skip the set: a leading ] belongs to it */ + f++; + if (*f == '^') f++; + if (*f == ']') f++; + while (*f != '\0' && *f != ']') f++; + if (*f == '\0') break; + } + if (suppress) continue; + switch (conversion) { + case 'd': + case 'i': + case 'u': + case 'o': + case 'x': + case 'X': + if (length == -2) *va_arg(ap, char *) = (char)map2check_non_det_char(); + else if (length == -1) *va_arg(ap, short *) = map2check_non_det_short(); + else if (length == 1) *va_arg(ap, long *) = map2check_non_det_long(); + else if (length == 2) + *va_arg(ap, long long *) = map2check_non_det_longlong(); + else if (length == 3) + *va_arg(ap, size_t *) = map2check_non_det_size_t(); + else *va_arg(ap, int *) = map2check_non_det_int(); + break; + case 'f': + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + case 'a': + case 'A': + if (length == 1) *va_arg(ap, double *) = map2check_non_det_double(); + else if (length == 4) + *va_arg(ap, long double *) = map2check_non_det_double(); + else *va_arg(ap, float *) = map2check_non_det_float(); + break; + case 'c': { + size_t count = width == 0 ? 1 : width; + if (length == 1) { + wchar_t *ws = va_arg(ap, wchar_t *); + for (size_t i = 0; i < count; i++) + ws[i] = (wchar_t)map2check_non_det_uint(); + } else { + char *s = va_arg(ap, char *); + for (size_t i = 0; i < count; i++) + s[i] = (char)map2check_non_det_uchar(); + } + break; + } + case 's': + case '[': { + /* Without a width a real %s has no bound: the budget gives one. */ + size_t count = input_length(width == 0 ? M2C_INPUT_MAX : width); + if (length == 1) { + wchar_t *ws = va_arg(ap, wchar_t *); + for (size_t i = 0; i < count; i++) + ws[i] = (wchar_t)map2check_non_det_uint(); + ws[count] = L'\0'; + } else { + char *s = va_arg(ap, char *); + for (size_t i = 0; i < count; i++) + s[i] = (char)map2check_non_det_uchar(); + s[count] = '\0'; + } + break; + } + case 'p': + *va_arg(ap, void **) = NULL; + break; + case 'n': + *va_arg(ap, int *) = 0; + continue; /* %n is not counted as an assignment */ + default: + continue; + } + assigned++; + } + return assigned; +} + +int map2check_input_fscanf(FILE *stream, const char *format, ...) { + (void)stream; + va_list ap; + va_start(ap, format); + int result = input_vscanf(format, ap); + va_end(ap); + return result; +} + +int map2check_input_scanf(const char *format, ...) { + va_list ap; + va_start(ap, format); + int result = input_vscanf(format, ap); + va_end(ap); + return result; +} + +/* --- File descriptors and sockets ----------------------------------------- */ + +ssize_t map2check_input_read(int fd, void *buf, size_t count) { + (void)fd; + if (buf == NULL) return 0; + size_t length = input_length(count); + unsigned char *bytes = (unsigned char *)buf; + for (size_t i = 0; i < length; i++) bytes[i] = map2check_non_det_uchar(); + return (ssize_t)length; /* 0 is end of file, or the peer closing */ +} + +ssize_t map2check_input_recv(int fd, void *buf, size_t len, int flags) { + (void)flags; + return map2check_input_read(fd, buf, len); +} + +ssize_t map2check_input_recvfrom(int fd, void *buf, size_t len, int flags, + struct sockaddr *from, socklen_t *fromlen) { + (void)flags; + (void)from; + (void)fromlen; + return map2check_input_read(fd, buf, len); +} + +/* A peer is always there: the connection succeeds, and accept returns a new + * descriptor at once. Without this, connect is refused and the input never + * read, and accept waits for a client that never comes until the time + * limit. */ +int map2check_input_connect(int fd, const struct sockaddr *addr, + socklen_t len) { + (void)fd; + (void)addr; + (void)len; + return 0; +} + +int map2check_input_bind(int fd, const struct sockaddr *addr, socklen_t len) { + (void)fd; + (void)addr; + (void)len; + return 0; +} + +int map2check_input_listen(int fd, int backlog) { + (void)fd; + (void)backlog; + return 0; +} + +int map2check_input_accept(int fd, struct sockaddr *addr, socklen_t *len) { + (void)addr; + (void)len; + int peer = dup(fd); + return peer >= 0 ? peer : fd; +} + +/* A file opened for reading exists. When the real one does not, the stream + * is /dev/null: the reads are modelled above, whatever the stream, and the + * program gets a FILE it can close. */ +FILE *map2check_input_fopen(const char *path, const char *mode) { + FILE *file = fopen(path, mode); + if (file == NULL && mode[0] == 'r' && strchr(mode, '+') == NULL) + file = fopen("/dev/null", mode); + return file; +} + +/* --- Environment ---------------------------------------------------------- */ + +/* Unset, or a nondeterministic string. Four buffers in turn, so that a + * program may hold a few values at once; each ends in enough zero bytes for + * a wchar_t reading (Juliet's wide variants call getenv on Linux). */ +#define M2C_ENV_SLOTS 4 +static char env_values[M2C_ENV_SLOTS][M2C_INPUT_MAX + sizeof(wchar_t)]; +static unsigned env_next = 0; + +char *map2check_input_getenv(const char *name) { + (void)name; + if (map2check_non_det_bool()) return NULL; + char *value = env_values[env_next++ % M2C_ENV_SLOTS]; + size_t length = input_length(M2C_INPUT_MAX); + memset(value, 0, M2C_INPUT_MAX + sizeof(wchar_t)); + for (size_t i = 0; i < length; i++) { + value[i] = (char)map2check_non_det_uchar(); + if (value[i] == '\0') break; /* the string ends there */ + } + return value; +} diff --git a/modules/backend/pass/NonDetPass.cpp b/modules/backend/pass/NonDetPass.cpp index 5025ea3b7..bb9cab4a8 100644 --- a/modules/backend/pass/NonDetPass.cpp +++ b/modules/backend/pass/NonDetPass.cpp @@ -14,6 +14,7 @@ #include #include +#include using llvm::CastInst; using llvm::dyn_cast; @@ -28,8 +29,74 @@ inline Instruction *BBIteratorToInst(BasicBlock::iterator i) { } } // namespace +// --model-input: the program's libc input becomes nondeterministic. +static llvm::cl::opt ModelInput( + "m2c-model-input", + llvm::cl::desc("send the program's libc input calls to LibcInputModel.c"), + llvm::cl::init(false)); + +// --input-bound: the bytes of input a run can receive in all, read by +// LibcInputModel.c from the global map2check_input_max. +static llvm::cl::opt ModelInputMax( + "m2c-model-input-max", + llvm::cl::desc("bytes of libc input a run can receive (--model-input)"), + llvm::cl::init(4)); + namespace { +/** The libc functions --model-input replaces, and the model of each + * (map2check_input_, LibcInputModel.c). glibc's headers give some + * calls another symbol: fscanf is __isoc99_fscanf, getc may be _IO_getc. */ +struct InputModel { + const char *libc; + const char *model; +}; +const InputModel kInputModels[] = { + {"fgets", "fgets"}, {"fgetc", "fgetc"}, + {"getc", "fgetc"}, {"_IO_getc", "fgetc"}, + {"getc_unlocked", "fgetc"}, {"getchar", "getchar"}, + {"fread", "fread"}, {"fgetws", "fgetws"}, + {"fgetwc", "fgetwc"}, {"getwc", "fgetwc"}, + {"getwchar", "getwchar"}, {"fscanf", "fscanf"}, + {"__isoc99_fscanf", "fscanf"}, {"scanf", "scanf"}, + {"__isoc99_scanf", "scanf"}, {"read", "read"}, + {"recv", "recv"}, {"recvfrom", "recvfrom"}, + {"connect", "connect"}, {"bind", "bind"}, + {"listen", "listen"}, {"accept", "accept"}, + {"fopen", "fopen"}, {"fopen64", "fopen"}, + {"getenv", "getenv"}, {"secure_getenv", "getenv"}, +}; + +/** Sends every call of a modelled libc function to its model. The + * declaration is what is replaced, so one change reaches every call site; a + * function the program defines itself is its own, and stays. */ +void retargetInputCall(Function *callee) { + if (!callee->isDeclaration()) return; + for (const InputModel &m : kInputModels) { + if (callee->getName() != m.libc) continue; + const std::string name = std::string("map2check_input_") + m.model; + llvm::Module *module = callee->getParent(); + Function *model = module->getFunction(name); + if (model == nullptr) { + callee->setName(name); + } else if (model->getFunctionType() == callee->getFunctionType()) { + // A second libc name for the same model (getc after fgetc). + callee->replaceAllUsesWith(model); + } + return; + } +} + +/** Defines map2check_input_max, the input bound LibcInputModel.c reads. */ +void defineInputBound(llvm::Module *module) { + if (module->getNamedGlobal("map2check_input_max") != nullptr) return; + llvm::Type *int32 = llvm::Type::getInt32Ty(module->getContext()); + new llvm::GlobalVariable(*module, int32, /*isConstant=*/true, + llvm::GlobalValue::ExternalLinkage, + llvm::ConstantInt::get(int32, ModelInputMax), + "map2check_input_max"); +} + /** Names the benchmarks use for "prune this path", implemented as an abort. * * `__VERIFIER_assume` is usually only declared, and the call-site rewriting @@ -164,6 +231,10 @@ PreservedAnalyses NonDetPass::run(Function &F, rewriteAbortCallsToPrune(F); + if (ModelInput) { + defineInputBound(F.getParent()); + } + this->nonDetFunctions = make_unique(&F, &F.getContext()); bool initializedFunctionName = false; for (Function::iterator bb = F.begin(), e = F.end(); bb != e; ++bb) { @@ -203,6 +274,10 @@ void NonDetPass::runOnCallInstruction(CallInst *callInst, LLVMContext *Ctx) { } } + if (ModelInput) { + retargetInputCall(calleeFunction); + } + // TODO(rafa.sa.xp@gmail.com): Should not rename __VERIFIER functions // clang-format if (true) { diff --git a/modules/frontend/caller.cpp b/modules/frontend/caller.cpp index 1f250b216..cd40e9cbe 100644 --- a/modules/frontend/caller.cpp +++ b/modules/frontend/caller.cpp @@ -1169,6 +1169,10 @@ int Caller::callPass(std::string target_function, bool sv_comp) { Map2Check::Log::Info("Adding nondet pass"); transformCommand << " -tailcallopt"; transformCommand << " -load-pass-plugin=" << nonDetPlugin << getLibSuffix(); + if (this->modelInput) { + transformCommand << " -m2c-model-input" + << " -m2c-model-input-max=" << this->inputBound; + } // Build the passes pipeline std::ostringstream passesArg; @@ -1339,6 +1343,9 @@ void Caller::linkLLVM() { if (this->wasmMode) { linkCommand << " ${MAP2CHECK_PATH}/lib/WasmRuntimeStubs.bc"; } + if (this->modelInput) { + linkCommand << " ${MAP2CHECK_PATH}/lib/LibcInputModel.bc"; + } witnessCommand.str(""); witnessCommand << linkCommand.str(); diff --git a/modules/frontend/caller.hpp b/modules/frontend/caller.hpp index dafeb1830..68bf71ecb 100644 --- a/modules/frontend/caller.hpp +++ b/modules/frontend/caller.hpp @@ -140,6 +140,17 @@ class Caller { * decision the caller makes rather than a default. */ bool sliceProgram = false; + /** The program's libc input is nondeterministic (--model-input). + * + * NonDetPass sends the program's calls to fgets, fscanf, read, recv, + * getenv, fopen, connect, accept, ... to LibcInputModel.c, which answers + * them with map2check_non_det_* values. Off by default: the SV-COMP and + * Test-Comp programs take their input only from __VERIFIER_nondet_*, and a + * test vector holding values for other calls would not replay there. */ + bool modelInput = false; + /** The bytes of input a run can receive in all (--input-bound). */ + unsigned inputBound = 4; + /** Runs sbt-slicer over the compiled (not yet instrumented) bitcode. * * `criteria` are the primary slicing criteria (the target function, or the diff --git a/modules/frontend/map2check.cpp b/modules/frontend/map2check.cpp index a81d1ee9c..e1984ad04 100644 --- a/modules/frontend/map2check.cpp +++ b/modules/frontend/map2check.cpp @@ -465,6 +465,8 @@ struct map2check_args { // phase that follows; -1: the fixed hybrid's rule (the first phase only). int feedsKlee = -1; bool sliceProgram = false; + bool modelInput = false; + unsigned inputBound = 4; std::string testSuiteDir = "test-suite"; std::string propertyFile; std::string architecture = "64bit"; @@ -649,6 +651,8 @@ int map2check_execution(map2check_args args) { caller->engineWindow = args.engineWindow; caller->stagnationLimit = args.stagnationLimit; caller->sliceProgram = args.sliceProgram; + caller->modelInput = args.modelInput && !args.wasmMode; + caller->inputBound = args.inputBound; caller->setTimeout(args.timeout); caller->entryFunction = args.entryFunction; caller->wasmMode = args.wasmMode; @@ -963,6 +967,15 @@ z3 (Z3 is default), btor (Boolector), and yices2 (Yices))") "the assertions (--check-asserts) or the runtime checks (--memtrack, " "--memcleanup-property, --check-overflow) before analysing it; needs " "sbt-slicer") + ("model-input", + "\tthe program's input from libc (fgets, fscanf, fread, read, recv, " + "getenv, ...) is nondeterministic, as are the files and peers it " + "comes from: without it, stdin is empty and the environment unset. " + "Not for SV-COMP or Test-Comp, whose programs read only " + "__VERIFIER_nondet_*") + ("input-bound", po::value(), + "\twith --model-input: the bytes of input a run can receive in all " + "(default 4). A TRUE holds for inputs up to this size") ("alternate-engines", "\tthe default hybrid (needs --timeout): the fuzzer and KLEE take " "turns, each stopped once it stops finding coverage, with windows " @@ -1086,6 +1099,12 @@ z3 (Z3 is default), btor (Boolector), and yices2 (Yices))") if (vm.count("slice")) { args.sliceProgram = true; } + if (vm.count("model-input")) { + args.modelInput = true; + } + if (vm.count("input-bound")) { + args.inputBound = vm["input-bound"].as(); + } if (vm.count("seed-exchange")) { args.seedExchange = true; } diff --git a/tests/integration/test_model_input.sh b/tests/integration/test_model_input.sh new file mode 100755 index 000000000..2bb88cc73 --- /dev/null +++ b/tests/integration/test_model_input.sh @@ -0,0 +1,141 @@ +#!/bin/bash +# test_model_input.sh — --model-input: the program's libc input is +# nondeterministic. +# +# Without it, fgets on stdin reads nothing, getenv finds nothing, connect is +# refused and accept waits forever: a flaw that needs input is never reached, +# and the verdict is TRUE (Juliet CWE-761: 80 of 100 flawed programs). Each +# case below has a flaw only some input reaches, or none at all. +# +# Needs MAP2CHECK_PATH (KLEE and AFL++ available, as in map2check-dev). +set -u + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +# shellcheck source=../lib/verdict_classifier.sh +. "$SCRIPT_DIR/../lib/verdict_classifier.sh" +MAP2CHECK="${MAP2CHECK_PATH:-/workspace/install_castle_ci}/map2check" +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +PASSED=0 +FAILED=0 + +# case_ < source +case_() { + local name=$1 expect=$2 out got rc=0 + shift 2 + mkdir -p "$TMP/$name" + cat > "$TMP/$name/$name.c" + out=$(cd "$TMP/$name" && timeout -k 10 200 "$MAP2CHECK" --timeout 60 "$@" \ + "$name.c" 2>&1) || rc=$? + got=$(classify_map2check_verdict "$out" "$rc" 0 0) + if [ "$got" = "$expect" ]; then + echo " PASS $name: $got"; PASSED=$((PASSED+1)) + else + echo " FAIL $name: expected $expect, got $got"; FAILED=$((FAILED+1)) + fi +} + +echo "============================================================" +echo "--model-input: libc input is nondeterministic" +echo "============================================================" + +# The Juliet CWE-761 shape: the pointer walks the input, then is freed. +WALK='for (; *data != 0; data++) if (*data == 83) break; + free(data); return 0; }' + +case_ stdin_off TRUE --memtrack < +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + if (fgets(data, 100, stdin) == NULL) data[0] = 0; + $WALK +EOF +case_ stdin_fgets FALSE-FREE --memtrack --model-input < +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + if (fgets(data, 100, stdin) == NULL) data[0] = 0; + $WALK +EOF +case_ stdin_fgets_safe TRUE --memtrack --model-input <<'EOF' +#include +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + if (fgets(data, 100, stdin) == NULL) data[0] = 0; + size_t i; for (i = 0; data[i] != 0; i++) if (data[i] == 'S') break; + free(data); return 0; } +EOF +case_ stdin_fgetws FALSE-FREE --memtrack --model-input < +#include +#include +int main(void) { wchar_t *data = malloc(100 * sizeof(wchar_t)); if (!data) return 1; + data[0] = 0; if (fgetws(data, 100, stdin) == NULL) data[0] = 0; + $WALK +EOF +case_ getenv FALSE-FREE --memtrack --model-input < +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + char *e = getenv("ADD"); if (e != NULL) strncat(data, e, 99); + $WALK +EOF +case_ fopen_missing_file FALSE-FREE --memtrack --model-input < +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + FILE *f = fopen("/nonexistent/m2c-input", "r"); + if (f != NULL) { if (fgets(data, 100, f) == NULL) data[0] = 0; fclose(f); } + $WALK +EOF +case_ connect_recv FALSE-FREE --memtrack --model-input < +#include +#include +#include +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (s != -1) { struct sockaddr_in a; memset(&a, 0, sizeof a); + a.sin_family = AF_INET; a.sin_addr.s_addr = inet_addr("127.0.0.1"); + a.sin_port = htons(27015); + if (connect(s, (struct sockaddr *)&a, sizeof a) != -1) { + ssize_t r = recv(s, data, 99, 0); if (r > 0) data[r] = 0; } + close(s); } + $WALK +EOF +case_ listen_accept_recv FALSE-FREE --memtrack --model-input < +#include +#include +#include +#include +int main(void) { char *data = malloc(100); if (!data) return 1; data[0] = 0; + int l = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP), c = -1; + if (l != -1) { struct sockaddr_in a; memset(&a, 0, sizeof a); + a.sin_family = AF_INET; a.sin_addr.s_addr = INADDR_ANY; a.sin_port = htons(27015); + if (bind(l, (struct sockaddr *)&a, sizeof a) != -1 && listen(l, 5) != -1 && + (c = accept(l, NULL, NULL)) != -1) { + ssize_t r = recv(c, data, 99, 0); if (r > 0) data[r] = 0; } + if (c != -1) close(c); close(l); } + $WALK +EOF +case_ fscanf_int FALSE --check-overflow --model-input <<'EOF' +#include +int main(void) { int data = 0; fscanf(stdin, "%d", &data); + int r = data + 1; printf("%d\n", r); return 0; } +EOF +case_ fread_bytes FALSE-DEREF --memtrack --model-input <<'EOF' +#include +#include +int main(void) { unsigned char b[2] = {0, 0}; int *p = malloc(4 * sizeof(int)); + if (!p) return 1; fread(b, 1, 2, stdin); + if (b[0] == 'k' && b[1] == 9) p[4] = 1; + free(p); return 0; } +EOF + +echo "" +echo "============================================================" +echo "Results: $PASSED passed, $FAILED failed" +echo "============================================================" +[ $FAILED -eq 0 ]