strawberry/tests/test_exec_guard.cpp
trvon 383c22cbd3
exec guard: answer a cache hit without holding the cache lock
Both hit paths (fanotify and Endpoint Security) called finish() while holding
cache_mutex_. finish() is the answer: it writes the kernel response, runs the
observation callback, bumps stats under stats_mutex_ and pushes to
report_mutex_. Holding the cache lock across that serialised every cache-hit
exec behind one mutex even though the daemon runs two workers, so on Linux a
slow answer was a slow exec - in the path whose whole job is to keep launches
fast.

detail::answer_cached_assessment copies the entry under the lock, releases it,
and only then answers. cache_mutex_ is now a leaf lock (also at the work-loop
insert), so the old edge cache_mutex_ -> {pending, stats, report} is gone and no
inversion can be introduced. Answer-exactly-once is unchanged: respond() still
checks pending->responded under the pending mutex, and the hit path still
answers once and returns.

The seam is declared in exec_guard.hpp so the tests no longer redeclare an
internal function in their own translation unit.
2026-11-19 17:29:38 -07:00

277 lines
10 KiB
C++

#include "strawberry/exec_guard.hpp"
// Private helper header: the guard and the pipeline must derive one cache key.
#include "../src/image_file.hpp"
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
using namespace strawberry;
namespace {
ExecAssessment hit(const std::string& severity, bool ioc = false) {
ExecAssessment a;
a.scanned = true;
a.top_rule = "Rule";
a.top_severity = severity;
a.ioc_match = ioc;
return a;
}
void test_decisions() {
std::cout << "Test verdict logic:" << std::endl;
// Mode off / unscanned / clean -> allow.
assert(decide_exec("off", "critical", hit("critical"), false) == ExecVerdict::allow);
ExecAssessment unscanned = hit("critical");
unscanned.scanned = false;
assert(decide_exec("enforce", "critical", unscanned, false) == ExecVerdict::allow);
ExecAssessment clean;
clean.scanned = true;
assert(decide_exec("enforce", "medium", clean, false) == ExecVerdict::allow);
// Threshold.
assert(decide_exec("enforce", "critical", hit("high"), false) == ExecVerdict::allow);
assert(decide_exec("enforce", "high", hit("high"), false) == ExecVerdict::block);
assert(decide_exec("audit", "high", hit("critical"), false) == ExecVerdict::would_block);
// IOC hash matches always count, whatever the YARA threshold.
assert(decide_exec("enforce", "critical", hit("", true), false) == ExecVerdict::block);
// System paths are never blocked automatically.
assert(decide_exec("enforce", "high", hit("critical", true), true) == ExecVerdict::would_block);
// Allowlist wins; operator quarantine beats allowlist, mode and path.
ExecAssessment allowed = hit("critical", true);
allowed.allowlisted = true;
assert(decide_exec("enforce", "high", allowed, false) == ExecVerdict::allow);
ExecAssessment quarantined = clean;
quarantined.quarantined = true;
assert(decide_exec("audit", "critical", quarantined, true) == ExecVerdict::block);
assert(decide_exec("off", "critical", quarantined, false) == ExecVerdict::block);
std::cout << " PASSED" << std::endl;
}
void test_mountinfo() {
std::cout << "Test mount point selection:" << std::endl;
const std::string mountinfo =
"22 1 259:2 / / rw,relatime shared:1 - btrfs /dev/nvme0n1p2 rw\n"
"23 22 259:2 /@home /home rw,relatime shared:2 - btrfs /dev/nvme0n1p2 rw\n" // same superblock
"24 22 0:5 / /proc rw - proc proc rw\n"
"25 22 0:30 / /tmp rw - tmpfs tmpfs rw\n"
"26 22 0:31 / /dev/shm rw - tmpfs tmpfs rw\n"
"27 22 0:40 / /run/user/1000/doc rw - fuse.portal portal rw\n"
"28 22 0:41 / /media/My\\040Disk rw - exfat /dev/sdb1 rw\n";
const auto points = ExecGuard::local_mount_points(mountinfo);
assert((points == std::vector<std::string>{"/", "/tmp", "/dev/shm", "/media/My Disk"}));
std::cout << " PASSED" << std::endl;
}
} // namespace
// F2: the guard cache is keyed by file identity + rules generation only, so only a complete,
// undegraded scan may be stored. A degraded/partial result must be re-assessed next time.
void test_assessment_cache_policy() {
std::cout << "Test which assessments may be cached:" << std::endl;
ExecAssessment clean = hit("high");
assert(guard_assessment_cacheable(clean));
ExecAssessment degraded = hit("");
degraded.degraded = true; // hash/IOC/quarantine only (e.g. a transient buffer-lease miss)
assert(!guard_assessment_cacheable(degraded));
ExecAssessment partial = hit("high");
partial.partial = true; // only the loaded ELF segments were scanned
assert(!guard_assessment_cacheable(partial));
ExecAssessment unscanned;
unscanned.scanned = false;
assert(!guard_assessment_cacheable(unscanned));
std::cout << " PASSED" << std::endl;
}
// The verdict cache is keyed by dev:ino:size:mtime:ctime. mtime is settable
// (`utimensat`), so a rewrite that restores size and mtime (`cp -p`,
// `install -p`, a package restore, or an attacker) still changes ctime and is
// re-assessed instead of inheriting the previous verdict.
struct timespec& key_test_mtime(struct stat& st) {
#if defined(__APPLE__)
return st.st_mtimespec;
#else
return st.st_mtim;
#endif
}
struct timespec& key_test_ctime(struct stat& st) {
#if defined(__APPLE__)
return st.st_ctimespec;
#else
return st.st_ctim;
#endif
}
void test_cache_key_covers_ctime() {
std::cout << "Test image cache key covers ctime:" << std::endl;
struct stat original{};
original.st_dev = 1;
original.st_ino = 2;
original.st_size = 3;
key_test_mtime(original).tv_sec = 10;
key_test_mtime(original).tv_nsec = 20;
key_test_ctime(original).tv_sec = 30;
key_test_ctime(original).tv_nsec = 40;
const std::string key = detail::image_cache_key(original);
assert(detail::image_cache_key(original) == key); // stable
// Same identity, size and mtime: only ctime differs.
struct stat rewritten = original;
key_test_ctime(rewritten).tv_nsec += 1;
assert(detail::image_cache_key(rewritten) != key);
// The other fields still take part in the key.
struct stat resized = original;
resized.st_size += 1;
assert(detail::image_cache_key(resized) != key);
struct stat retimed = original;
key_test_mtime(retimed).tv_nsec += 1;
assert(detail::image_cache_key(retimed) != key);
std::cout << " PASSED" << std::endl;
}
// A timed-out scan is incomplete, NOT unscanned: quarantine must still block. An executor that
// reported scanned=false here would let an operator-quarantined binary run (decide_exec returns
// allow on !scanned before it ever looks at quarantine).
void test_incomplete_scan_still_enforces_quarantine() {
std::cout << "Test an incomplete scan still enforces quarantine:" << std::endl;
ExecAssessment q;
q.scanned = true;
q.incomplete = true; // YARA hit its deadline
q.quarantined = true; // operator block
assert(decide_exec("enforce", "high", q, false) == ExecVerdict::block);
assert(decide_exec("audit", "high", q, false) == ExecVerdict::block);
// ...and an incomplete clean result is allowed (fail open) but never cached.
ExecAssessment a;
a.scanned = true;
a.incomplete = true;
assert(decide_exec("enforce", "high", a, false) == ExecVerdict::allow);
assert(!guard_assessment_cacheable(a));
std::cout << " PASSED" << std::endl;
}
// finish() is the answer: it writes the kernel response, runs the observation
// callback and takes the stats and report mutexes. It must not run while the
// verdict cache is locked, or every cache-hit exec answer serialises through
// cache_mutex_ (the daemon runs 2 workers, so on Linux a slow answer is a slow
// exec). The seam is declared in exec_guard.hpp (detail::answer_cached_assessment)
// and defined in src/exec_guard.cpp; both hit paths and these tests use it.
void test_cache_hit_answers_outside_the_lock() {
std::cout << "Test a cache hit answers outside the verdict-cache lock:" << std::endl;
std::mutex mutex;
std::unordered_map<std::string, ExecAssessment> cache;
cache["key"] = hit("critical");
bool answered = false;
const bool found = detail::answer_cached_assessment(mutex, cache, "key", [&](const ExecAssessment& a) {
answered = true;
// The cache lock is already free when the answer runs.
assert(mutex.try_lock());
mutex.unlock();
// ...so a later verdict write needs no lock ordering, and the answer
// holds a copy taken under the lock, not a live reference into it.
cache["key"] = hit("high");
assert(a.top_severity == "critical");
});
assert(found);
assert(answered);
// A miss answers nothing and still leaves the lock released.
bool miss_answered = false;
const bool miss = detail::answer_cached_assessment(mutex, cache, "absent", [&](const ExecAssessment&) {
miss_answered = true;
});
assert(!miss);
assert(!miss_answered);
assert(mutex.try_lock());
mutex.unlock();
std::cout << " PASSED" << std::endl;
}
// Two execs hitting the cache must be able to answer at the same time: the
// answer is the blocking part (fanotify write, on_observation, report queue), so
// holding cache_mutex_ across it turns every cache hit into a serialised answer.
void test_cache_hits_answer_concurrently() {
std::cout << "Test two cache hits answer at the same time:" << std::endl;
std::mutex mutex;
std::unordered_map<std::string, ExecAssessment> cache;
cache["a"] = hit("critical");
cache["b"] = hit("critical");
std::mutex gate_mutex;
std::condition_variable gate;
int inside = 0;
int overlapped = 0;
auto answer = [&](const char* key) {
return detail::answer_cached_assessment(mutex, cache, key, [&](const ExecAssessment&) {
std::unique_lock lock(gate_mutex);
++inside;
gate.notify_all();
// Both answers must be in flight at once: with the cache lock held
// across the answer the second one could never get here.
if (gate.wait_for(lock, std::chrono::seconds(5), [&]() { return inside == 2; })) {
++overlapped;
}
});
};
std::thread first([&]() { assert(answer("a")); });
std::thread second([&]() { assert(answer("b")); });
first.join();
second.join();
assert(overlapped == 2);
// The premise of the probe above: a lock held for the answer's lifetime does
// block the second answer, so the probe fails against the shape this test
// guards against.
std::mutex control;
std::unique_lock hold(control);
bool acquired = true;
std::thread blocked([&]() {
acquired = control.try_lock();
if (acquired) {
control.unlock();
}
});
blocked.join();
assert(!acquired);
std::cout << " PASSED" << std::endl;
}
int main() {
std::cout << "Running exec guard tests..." << std::endl << std::endl;
test_decisions();
test_mountinfo();
test_assessment_cache_policy();
test_incomplete_scan_still_enforces_quarantine();
test_cache_key_covers_ctime();
test_cache_hit_answers_outside_the_lock();
test_cache_hits_answer_concurrently();
std::cout << std::endl << "All tests passed!" << std::endl;
return 0;
}