Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ jobs:
ghcr.io/hbgit/map2check-dev:latest bash -c '
bash tests/integration/test_verdict_classifier.sh
bash tests/integration/test_juliet_sampling.sh
bash tests/integration/test_juliet_stubs.sh
bash tests/integration/test_castle_regression.sh
bash tests/integration/test_main_argv.sh
bash tests/integration/test_modes.sh
Expand Down
84 changes: 84 additions & 0 deletions tests/integration/test_juliet_stubs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/bin/bash
# test_juliet_stubs.sh — the Juliet print sinks of tests/juliet/juliet_stubs.c
# must read what they print.
#
# They were no-ops, so a flaw whose only use is the print never happened: 36
# of 70 CWE-416 bad programs (use after free through printLine or
# printStructLine) came out TRUE. Each case below is built the way
# run_juliet_evaluation.sh builds a testcase (clang -O0 -g, linked with the
# stubs) and checked with --memtrack.
#
# Needs the Juliet submodule (testcasesupport) and MAP2CHECK_PATH.
set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MAP2CHECK="${MAP2CHECK_PATH:-/workspace/install_castle_ci}/map2check"
CLANG="${CLANG:-/usr/bin/clang-16}"
LLVM_LINK="${LLVM_LINK:-/usr/bin/llvm-link-16}"
JULIET_DIR="${JULIET_DIR:-$SCRIPT_DIR/../juliet/juliet-test-suite-c}"
SUPPORT="$JULIET_DIR/testcasesupport"
STUBS="$SCRIPT_DIR/../juliet/juliet_stubs.c"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
PASSED=0
FAILED=0

[ -f "$SUPPORT/std_testcase.h" ] || { echo "FATAL: no Juliet testcasesupport at $SUPPORT"; exit 1; }
"$CLANG" -c -emit-llvm -g -O0 -I "$SUPPORT" "$STUBS" -o "$TMP/stubs.bc" ||
{ echo "FATAL: juliet_stubs.c does not compile"; exit 1; }

# case_ <name> <TRUE|FALSE-DEREF> < source
case_() {
local name=$1 expect=$2 out got
cat > "$TMP/$name.c"
"$CLANG" -c -emit-llvm -g -O0 -I "$SUPPORT" "$TMP/$name.c" -o "$TMP/$name.bc" &&
"$LLVM_LINK" "$TMP/$name.bc" "$TMP/stubs.bc" -o "$TMP/$name.linked.bc" ||
{ echo " FAIL $name: does not build"; FAILED=$((FAILED+1)); return; }
out=$(cd "$TMP" && timeout -k 10 120 "$MAP2CHECK" --memtrack --timeout 60 \
"$TMP/$name.linked.bc" 2>&1 | sed 's/\x1b\[[0-9;]*m//g')
if echo "$out" | grep -q 'FALSE-DEREF'; then got=FALSE-DEREF
elif echo "$out" | grep -q 'VERIFICATION SUCCEEDED'; then got=TRUE
else got=$(echo "$out" | grep -oE 'FALSE-[A-Z]+|VERIFICATION [A-Z]+' | tail -1); fi
if [ "$got" = "$expect" ]; then
echo " PASS $name: $got"; PASSED=$((PASSED+1))
else
echo " FAIL $name: expected $expect, got ${got:-no verdict}"; FAILED=$((FAILED+1))
fi
}

echo "============================================================"
echo "Juliet stubs: the print sinks read their data"
echo "============================================================"

case_ printLine_freed FALSE-DEREF <<'EOF'
#include "std_testcase.h"
int main(void) { char *d = (char *)malloc(8); if (!d) return 1;
strcpy(d, "abc"); free(d); printLine(d); return 0; }
EOF
case_ printWLine_freed FALSE-DEREF <<'EOF'
#include "std_testcase.h"
int main(void) { wchar_t *d = (wchar_t *)malloc(8 * sizeof(wchar_t)); if (!d) return 1;
d[0] = L'a'; d[1] = L'\0'; free(d); printWLine(d); return 0; }
EOF
case_ printStructLine_freed FALSE-DEREF <<'EOF'
#include "std_testcase.h"
int main(void) { twoIntsStruct *d = (twoIntsStruct *)malloc(sizeof(twoIntsStruct));
if (!d) return 1; d->intOne = 1; d->intTwo = 2; free(d); printStructLine(d); return 0; }
EOF
case_ printBytesLine_past_end FALSE-DEREF <<'EOF'
#include "std_testcase.h"
int main(void) { unsigned char *d = (unsigned char *)malloc(4); if (!d) return 1;
memset(d, 1, 4); printBytesLine(d, 5); free(d); return 0; }
EOF
case_ print_live_ok TRUE <<'EOF'
#include "std_testcase.h"
int main(void) { char *d = (char *)malloc(8); twoIntsStruct s = {1, 2};
if (!d) return 1; strcpy(d, "abc"); printLine(d); printLine(NULL);
printStructLine(&s); printBytesLine((unsigned char *)d, 4); free(d); return 0; }
EOF

echo ""
echo "============================================================"
echo "Results: $PASSED passed, $FAILED failed"
echo "============================================================"
[ $FAILED -eq 0 ]
29 changes: 29 additions & 0 deletions tests/integration/test_verdict_classifier.sh
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,35 @@ check "VERIFICATION SUCCEEDED" TRUE "VERIFICATION SUCCEEDED" 0 1 60
check "verdict wins over budget exhaustion" \
TRUE "VERIFICATION SUCCEEDED" 0 60 60

# --- Scoring against the CWE (classify_for_cwe) -------------------------------
# Juliet's programs for the memory CWEs leak on purpose, the fixed ones too.
# Counting the leak as the flaw scored all 70 fixed CWE-416 programs FP.
score() {
local name="$1" expect="$2" cwe="$3" vuln="$4" verdict="$5" got
got=$(classify_for_cwe "$cwe" "$vuln" "$verdict")
if [ "$got" = "$expect" ]; then
echo " PASS $name"
PASSED=$((PASSED+1))
else
echo " FAIL $name: expected $expect, got $got"
FAILED=$((FAILED+1))
fi
}
score "leak in a fixed CWE-416 program is TN" TN 416 False FALSE-MEMTRACK
score "leak in a flawed CWE-416 program is FN" FN 416 True FALSE-MEMTRACK
score "leak is the flaw of CWE-401" TP 401 True FALSE-MEMTRACK
score "leak report on a fixed CWE-401 is FP" FP 401 False FALSE-MEMTRACK
score "deref in a flawed CWE-416 program is TP" TP 416 True FALSE-DEREF
score "deref in a fixed CWE-122 program is FP" FP 122 False FALSE-DEREF
score "free error in CWE-415 is TP" TP 415 True FALSE-FREE
score "overflow in CWE-190 is TP" TP 190 True FALSE-OVERFLOW
score "memcleanup in CWE-401 is TP" TP 401 True FALSE-MEMCLEANUP
score "generic FALSE is a finding" FP 476 False FALSE
score "TRUE on a flawed program is FN" FN 121 True TRUE
score "TIMEOUT stays TIMEOUT" TIMEOUT 121 True TIMEOUT
score "ERROR stays ERROR" ERROR 121 False ERROR
score "UNKNOWN stays UNKNOWN" UNKNOWN 121 True UNKNOWN

echo "============================================================"
echo "Results: $PASSED passed, $FAILED failed"
echo "============================================================"
Expand Down
31 changes: 20 additions & 11 deletions tests/juliet/juliet_stubs.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* Map2Check report UNKNOWN instead of TRUE.
*
* These stubs neutralise that I/O so KLEE can exhaust safe programs:
* - print*Line are no-ops (the bug, when present, happens *before* the sink);
* - print*Line make no external call; the pointer ones read their data;
* - globalReturnsTrueOrFalse() becomes nondeterministic via __VERIFIER_nondet_int
* (replaced by Map2Check's NonDetPass and made symbolic by the KLEE backend),
* so both branches are explored;
Expand All @@ -22,11 +22,11 @@
* bug into a trivially safe program. Those variants must be EXCLUDED from
* the scope rather than counted as easy true negatives.
* - printLine() in the stock io.c does `if (line != NULL) printf("%s\n", ...)`,
* i.e. it READS the buffer. As a no-op it stops reading, which can mask an
* out-of-bounds READ whose only sink is the print. 1924 CWE121 testcases
* call printLine(data); zero do in CWE190/191/369, so this does not affect
* the overflow scope — but it must be revisited before buffer-overflow CWEs
* enter the baseline.
* i.e. it READS the buffer. The print sinks that take a pointer
* (printLine, printWLine, printStructLine, printBytesLine) still read
* what they would print, without the external call. As no-ops they hid
* every flaw whose only use is the print: 36 of 70 CWE-416 bad programs
* (use after free through printLine/printStructLine) came out TRUE.
*
* Link this (instead of io.c) into the Juliet bitcode passed to map2check.
*/
Expand All @@ -36,8 +36,16 @@

#define NODISCARD(x) (void)(x)

void printLine(const char *line) { NODISCARD(line); }
void printWLine(const wchar_t *line) { NODISCARD(line); }
static volatile unsigned char m2c_sink;
/* As in io.c, the print sinks read what they print. */
void printLine(const char *line) {
if (line != NULL)
while (*line) m2c_sink = (unsigned char)*line++;
}
void printWLine(const wchar_t *line) {
if (line != NULL)
while (*line) m2c_sink = (unsigned char)*line++;
}
void printIntLine(int intNumber) { NODISCARD(intNumber); }
void printShortLine(short shortNumber) { NODISCARD(shortNumber); }
void printFloatLine(float floatNumber) { NODISCARD(floatNumber); }
Expand All @@ -49,10 +57,11 @@ void printWcharLine(wchar_t wideChar) { NODISCARD(wideChar); }
void printUnsignedLine(unsigned unsignedNumber) { NODISCARD(unsignedNumber); }
void printHexUnsignedCharLine(unsigned char c) { NODISCARD(c); }
void printDoubleLine(double doubleNumber) { NODISCARD(doubleNumber); }
void printStructLine(const twoIntsStruct *s) { NODISCARD(s); }
void printStructLine(const twoIntsStruct *s) {
m2c_sink = (unsigned char)(s->intOne + s->intTwo);
}
void printBytesLine(const unsigned char *bytes, size_t numBytes) {
NODISCARD(bytes);
NODISCARD(numBytes);
for (size_t i = 0; i < numBytes; i++) m2c_sink = bytes[i];
}

size_t decodeHexChars(unsigned char *bytes, size_t numBytes, const char *hex) {
Expand Down
53 changes: 53 additions & 0 deletions tests/juliet/rescore_juliet.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/bin/bash
# rescore_juliet.sh — rescore a finished Juliet run with classify_for_cwe.
#
# rescore_juliet.sh <results_dir> [out_csv]
#
# Runs before the CWE-aware scoring wrote a bare FALSE for every FALSE-*
# verdict and counted a leak as the flaw of any CWE. The raw output of every
# run is kept in <results_dir>/raw, and a definitive verdict depends on that
# output alone, so the property of each FALSE is read back from it and the row
# rescored. No run is repeated. The other verdicts are kept as recorded.
#
# Writes out_csv (default <results_dir>/juliet_scope_c_results.rescored.csv)
# and prints, per CWE, TP FP TN FN, the inconclusive runs, precision and recall.
set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=../lib/verdict_classifier.sh
. "$SCRIPT_DIR/../lib/verdict_classifier.sh"

DIR="${1:?usage: rescore_juliet.sh <results_dir> [out_csv]}"
CSV="$DIR/juliet_scope_c_results.csv"
OUT="${2:-$DIR/juliet_scope_c_results.rescored.csv}"
[ -f "$CSV" ] || { echo "no $CSV" >&2; exit 1; }

echo "cwe,name,variant,vulnerable,mode,verdict,elapsed_s,classification" > "$OUT"
tail -n +2 "$CSV" | while IFS=, read -r cwe name variant vuln mode verdict elapsed _cls; do
if [ "$verdict" = "FALSE" ]; then
raw="$DIR/raw/${name//\//__}.$variant.txt"
[ -f "$raw" ] || { echo "missing raw log: $raw" >&2; exit 1; }
verdict=$(classify_map2check_verdict "$(cat "$raw")" 0 0 0)
fi
case "$verdict" in
COMPILE-FAIL | LINK-FAIL) cls="$verdict" ;;
*) cls=$(classify_for_cwe "$cwe" "$vuln" "$verdict") ;;
esac
echo "$cwe,$name,$variant,$vuln,$mode,$verdict,$elapsed,$cls"
done >> "$OUT" || exit 1

python3 - "$OUT" <<'PY'
import collections, csv, sys
per = collections.defaultdict(collections.Counter)
for r in csv.DictReader(open(sys.argv[1])):
per[r['cwe']][r['classification']] += 1
print('cwe runs TP FP TN FN inconcl precision recall')
for cwe in sorted(per, key=int):
c = per[cwe]
tp, fp, tn, fn = c['TP'], c['FP'], c['TN'], c['FN']
inc = sum(c.values()) - tp - fp - tn - fn
p = f'{100 * tp / (tp + fp):.1f}%' if tp + fp else '-'
r = f'{100 * tp / (tp + fn):.1f}%' if tp + fn else '-'
print(f'{cwe:<5}{sum(c.values()):>5}{tp:>6}{fp:>6}{tn:>6}{fn:>6}{inc:>9}{p:>11}{r:>8}')
PY
echo "written: $OUT"
28 changes: 5 additions & 23 deletions tests/juliet/run_juliet_evaluation.sh
Original file line number Diff line number Diff line change
Expand Up @@ -149,22 +149,14 @@ log() { echo "[$(date -u +%H:%M:%S)] $*" | tee -a "$LOG"; }

# Verdict classification is shared with the CASTLE runner and covered by
# tests/integration/test_verdict_classifier.sh — see that file for why
# "Forcing timeout" is not a timeout signal. Juliet only needs the coarse
# FALSE/TRUE distinction, so the fine-grained FALSE-* verdicts collapse here.
# "Forcing timeout" is not a timeout signal. The CSV keeps the fine-grained
# FALSE-* verdict: classify_for_cwe scores it against the CWE, and a leak
# (FALSE-MEMTRACK) is the flaw of CWE-401 only.
# shellcheck source=../lib/verdict_classifier.sh
. "$SCRIPT_DIR/../lib/verdict_classifier.sh"
# shellcheck source=../lib/isolated_run.sh
. "$SCRIPT_DIR/../lib/isolated_run.sh"

classify_verdict() {
local verdict
verdict=$(classify_map2check_verdict "$1" "${2:-0}" "${3:-0}" "${4:-0}")
case "$verdict" in
FALSE-*) echo "FALSE" ;;
*) echo "$verdict" ;;
esac
}

PROCESSED=0
SKIP=0
CF=0
Expand Down Expand Up @@ -246,18 +238,8 @@ for cwe in "${SCOPE_CWES[@]}"; do
end=$(date +%s%N)
elapsed=$(python3 -c "print(round(($end - $start) / 1000000000, 1))")
output=$(cat "$raw")
verdict=$(classify_verdict "$output" "$rc" "$elapsed" "$INNER_TIMEOUT")
if [ "$verdict" = "FALSE" ]; then
[ "$vuln" = "True" ] && cls="TP" || cls="FP"
elif [ "$verdict" = "TRUE" ]; then
[ "$vuln" = "True" ] && cls="FN" || cls="TN"
elif [ "$verdict" = "TIMEOUT" ]; then
cls="TIMEOUT"
elif [ "$verdict" = "ERROR" ]; then
cls="ERROR"
else
cls="UNKNOWN"
fi
verdict=$(classify_map2check_verdict "$output" "$rc" "$elapsed" "$INNER_TIMEOUT")
cls=$(classify_for_cwe "$cwe" "$vuln" "$verdict")
echo "$cwe,$rel,$vtag,$vuln,$mode,$verdict,$elapsed,$cls" >> "$CSV"
log "CWE-$cwe $rel/$vtag => $verdict [$cls] ${elapsed}s"
)
Expand Down
26 changes: 26 additions & 0 deletions tests/lib/verdict_classifier.sh
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,29 @@ classify_map2check_verdict() {

echo "UNKNOWN"
}

# classify_for_cwe <cwe> <vulnerable True|False> <verdict>
#
# Scores a verdict of classify_map2check_verdict against the CWE the program
# was written for. Prints TP FP TN FN TIMEOUT ERROR or UNKNOWN.
#
# A FALSE-MEMTRACK is a memory leak, which is the flaw of CWE-401 only.
# Juliet's programs for the other memory CWEs leak on purpose (the source marks
# it "POTENTIAL INCIDENTAL - Possible memory leak"), the fixed ones included.
# Counting every FALSE-* as the flaw scored all 70 fixed CWE-416 programs as
# false positives, and 37 flawed programs as true positives for a leak rather
# than their flaw. A leak report ends the analysis, so for those CWEs it counts
# as no finding.
classify_for_cwe() {
local cwe="$1" vuln="$2" verdict="$3"
case "$verdict" in
FALSE-MEMTRACK) [ "$cwe" = "401" ] && verdict=FALSE || verdict=TRUE ;;
FALSE*) verdict=FALSE ;;
esac
case "$verdict" in
FALSE) [ "$vuln" = "True" ] && echo "TP" || echo "FP" ;;
TRUE) [ "$vuln" = "True" ] && echo "FN" || echo "TN" ;;
TIMEOUT | ERROR) echo "$verdict" ;;
*) echo "UNKNOWN" ;;
esac
}
Loading