#include "strawberry/daemon_app.hpp" #include "strawberry/database.hpp" #include "strawberry/hash_utils.hpp" #include "strawberry/control_server.hpp" #include "strawberry/policy.hpp" #include "strawberry/behavior_engine.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__APPLE__) #include #endif #if defined(_WIN32) #include #endif #ifndef STRAWBERRY_HAVE_YARA #define STRAWBERRY_HAVE_YARA 0 #endif namespace fs = std::filesystem; namespace { #if STRAWBERRY_HAVE_YARA fs::path make_test_root() { const auto root = fs::temp_directory_path() / "strawberry_daemon_runtime_tests"; std::error_code ec; fs::remove_all(root, ec); fs::create_directories(root, ec); assert(!ec); return root; } void write_binary_file(const fs::path& path, const std::string& content) { if (path.has_parent_path()) { std::error_code ec; fs::create_directories(path.parent_path(), ec); assert(!ec); } std::ofstream output(path, std::ios::binary); assert(output.good()); output.write(content.data(), static_cast(content.size())); output.close(); assert(output.good()); } void write_cmdline_file(const fs::path& path, const std::vector& args) { if (path.has_parent_path()) { std::error_code ec; fs::create_directories(path.parent_path(), ec); assert(!ec); } std::ofstream output(path, std::ios::binary); assert(output.good()); for (const auto& arg : args) { output.write(arg.data(), static_cast(arg.size())); output.put('\0'); } output.close(); assert(output.good()); } void write_status_file(const fs::path& path, int parent_pid) { if (path.has_parent_path()) { std::error_code ec; fs::create_directories(path.parent_path(), ec); assert(!ec); } std::ofstream output(path); assert(output.good()); output << "Name:\tsynthetic-daemon\n"; output << "State:\tR (running)\n"; output << "PPid:\t" << parent_pid << "\n"; output.close(); assert(output.good()); } void write_rule_file(const fs::path& path) { if (path.has_parent_path()) { std::error_code ec; fs::create_directories(path.parent_path(), ec); assert(!ec); } std::ofstream output(path); assert(output.good()); output << "rule SyntheticDaemonRule {\n" " strings:\n" " $marker = \"synthetic-daemon-marker\"\n" " condition:\n" " $marker\n" "}\n"; output.close(); assert(output.good()); } void write_config_file(const fs::path& path, const std::string& db_path, const std::string& rules_dir) { if (path.has_parent_path()) { std::error_code ec; fs::create_directories(path.parent_path(), ec); assert(!ec); } std::ofstream output(path); assert(output.good()); output << "db_path=" << db_path << "\n"; output << "yara_rules_path=" << rules_dir << "\n"; output << "daemonize=false\n"; output << "enable_bpf_monitoring=true\n"; output.close(); assert(output.good()); } void set_env_var(const std::string& key, const std::string& value) { #if defined(_WIN32) _putenv_s(key.c_str(), value.c_str()); #else ::setenv(key.c_str(), value.c_str(), 1); #endif } void unset_env_var(const std::string& key) { #if defined(_WIN32) _putenv_s(key.c_str(), ""); #else ::unsetenv(key.c_str()); #endif } bool wait_for_running(strawberry::StrawberryDaemon& daemon, std::chrono::milliseconds timeout) { const auto deadline = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < deadline) { if (daemon.is_running()) { return true; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); } return daemon.is_running(); } void test_daemon_procfs_event_persists_match() { const auto root = make_test_root(); const auto proc_root = root / "proc"; const auto rules_dir = root / "rules"; const auto executable = root / "bin" / "synthetic_daemon_exec"; const auto database_path = (root / "daemon_runtime.db").string(); const auto config_path = root / "strawberry.conf"; std::error_code ec; fs::create_directories(proc_root, ec); assert(!ec); fs::create_directories(rules_dir, ec); assert(!ec); write_binary_file(executable, std::string("\x7f\x45\x4c\x46") + "synthetic-daemon-marker"); write_rule_file(rules_dir / "synthetic_daemon.yar"); write_config_file(config_path, database_path, rules_dir.string()); const auto expected_hash = strawberry::HashUtils::sha256_file(executable.string()); assert(!expected_hash.empty()); set_env_var("STRAWBERRY_PROCFS_ROOT", proc_root.string()); set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25"); strawberry::StrawberryDaemon daemon; std::cout << "Test daemon_procfs_event_persists_match:" << std::endl; assert(daemon.initialize(config_path.string())); assert(daemon.is_initialized()); std::thread daemon_thread([&]() { daemon.run(); }); assert(wait_for_running(daemon, std::chrono::seconds(2))); const auto staged_proc_dir = proc_root / "pending-654"; fs::create_directories(staged_proc_dir, ec); assert(!ec); fs::create_symlink(executable, staged_proc_dir / "exe", ec); assert(!ec); write_cmdline_file(staged_proc_dir / "cmdline", {"synthetic_daemon_exec", "--daemon-test"}); write_status_file(staged_proc_dir / "status", 42); const auto live_proc_dir = proc_root / "654"; fs::rename(staged_proc_dir, live_proc_dir, ec); assert(!ec); std::this_thread::sleep_for(std::chrono::seconds(1)); daemon.request_stop(); daemon_thread.join(); assert(!daemon.is_running()); strawberry::Database database; assert(database.open(database_path)); auto hits = database.find_indicators_by_hash(expected_hash); assert(hits.size() == 1); assert(hits[0].rule_name == "SyntheticDaemonRule"); assert(hits[0].metadata.at("source") == "yara"); assert(hits[0].metadata.at("scan_kind") == "process_executable"); assert(hits[0].metadata.at("pid") == "654"); assert(hits[0].metadata.at("parent_pid") == "42"); assert(hits[0].metadata.at("process_path") == executable.string()); assert(hits[0].metadata.at("cmdline") == "synthetic_daemon_exec --daemon-test"); assert(!hits[0].metadata.at("event_timestamp_ns").empty()); const std::string process_node_id = "process_654"; const std::string file_node_id = "file_" + expected_hash; auto related = database.find_related_nodes(process_node_id, 1); assert(related.size() == 2); bool saw_indicator = false; bool saw_file = false; for (const auto& node : related) { if (node.type == "indicator") { saw_indicator = true; assert(node.properties.at("rule_name") == "SyntheticDaemonRule"); assert(node.properties.at("cmdline") == "synthetic_daemon_exec --daemon-test"); assert(node.properties.at("parent_pid") == "42"); } else if (node.id == file_node_id) { saw_file = true; assert(node.type == "file"); assert(node.properties.at("path") == executable.string()); assert(node.properties.at("hash") == expected_hash); assert(node.properties.at("kind") == "executable_image"); } } assert(saw_indicator); assert(saw_file); auto edges = database.get_node_edges(process_node_id); assert(edges.size() == 3); bool saw_spawned = false; bool saw_executed = false; bool saw_matched = false; for (const auto& edge : edges) { if (edge.relationship_type == "spawned") { saw_spawned = true; } else if (edge.relationship_type == "executed") { saw_executed = true; assert(edge.to_id == file_node_id); } else if (edge.relationship_type == "matched") { saw_matched = true; } } assert(saw_spawned); assert(saw_executed); assert(saw_matched); auto parent_related = database.find_related_nodes("process_42", 1); assert(parent_related.size() == 1); assert(parent_related[0].id == process_node_id); auto file_edges = database.get_node_edges(file_node_id); assert(file_edges.size() == 2); bool saw_content_matched = false; for (const auto& edge : file_edges) { if (edge.relationship_type == "content_matched") { saw_content_matched = true; } } assert(saw_content_matched); database.close(); std::cout << " PASSED" << std::endl; unset_env_var("STRAWBERRY_PROCFS_ROOT"); unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS"); fs::remove_all(root, ec); } bool contains_text(const std::string& haystack, const std::string& needle) { return haystack.find(needle) != std::string::npos; } void test_daemon_opensnitch_containment() { const auto root = make_test_root(); const auto proc_root = root / "proc"; const auto rules_dir = root / "rules"; const auto os_rules = root / "opensnitch" / "rules"; const auto executable = root / "bin" / "contain_me"; const auto socket_path = (fs::temp_directory_path() / ("sbd-" + std::to_string(::getpid()) + ".sock")).string(); const auto config_path = root / "strawberry.conf"; std::error_code ec; fs::create_directories(proc_root, ec); fs::create_directories(os_rules, ec); fs::create_directories(rules_dir, ec); write_binary_file(executable, std::string("\x7f\x45\x4c\x46") + "contain-marker"); { std::ofstream rule(rules_dir / "high.yar"); rule << "rule High_Severity_Test { meta: severity = \"high\" strings: $m = \"contain-marker\" condition: $m }\n"; } // OpenSnitch config with checksums on, so rules are hash-pinned. std::ofstream(root / "opensnitch" / "default-config.json") << R"({"Rules":{"EnableChecksums":true}})"; { std::ofstream config(config_path); config << "db_path=" << (root / "daemon.db").string() << "\n" << "yara_rules_path=" << rules_dir.string() << "\n" << "enable_bpf_monitoring=true\n" << "control_socket_path=" << socket_path << "\n" << "control_group=\n" << "opensnitch_rules_dir=" << os_rules.string() << "\n" << "opensnitch_config=" << (root / "opensnitch" / "default-config.json").string() << "\n"; } const auto hash = strawberry::HashUtils::sha256_file(executable.string()); const auto rule_file = os_rules / ("strawberry-contain-" + hash.substr(0, 12) + ".json"); set_env_var("STRAWBERRY_PROCFS_ROOT", proc_root.string()); set_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS", "25"); std::cout << "Test daemon_opensnitch_containment:" << std::endl; strawberry::StrawberryDaemon daemon; assert(daemon.initialize(config_path.string())); std::thread runner([&]() { daemon.run(); }); assert(wait_for_running(daemon, std::chrono::seconds(2))); const auto staged = proc_root / "pending-777"; fs::create_directories(staged, ec); fs::create_symlink(executable, staged / "exe", ec); write_cmdline_file(staged / "cmdline", {"contain_me"}); write_status_file(staged / "status", 1); fs::rename(staged, proc_root / "777", ec); // Auto-containment: high severity, not a system path. for (int i = 0; i < 80 && !fs::exists(rule_file); ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } assert(fs::exists(rule_file)); { std::ifstream input(rule_file); const std::string text((std::istreambuf_iterator(input)), std::istreambuf_iterator()); assert(contains_text(text, "process.hash.md5") && contains_text(text, executable.string())); } auto status = strawberry::control_request(socket_path, "status", std::chrono::seconds(2)); assert(status && contains_text(*status, "\"containments\":1")); // Resource governor + timing surfaces. assert(contains_text(*status, "\"resources\":{\"cgroup\"") || contains_text(*status, "\"resources\":{")); assert(contains_text(*status, "\"profile\":\"balanced\"")); assert(contains_text(*status, "\"level\":\"")); assert(contains_text(*status, "\"timings\":{")); assert(contains_text(*status, "\"exec_decision\":{\"count\"")); auto policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2)); assert(policy && contains_text(*policy, "\"automatic\":true")); // Allowlisting the binary releases its containment. auto reply = strawberry::control_request_with_payload(socket_path, "allowlist-add", R"({"kind":"sha256","value":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"ok\":true")); assert(!fs::exists(rule_file)); // Manual containment works only for binaries in stored evidence, and takes // path/md5 from that evidence. reply = strawberry::control_request_with_payload(socket_path, "contain-add", R"({"sha256":")" + std::string(64, 'e') + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "no stored evidence")); reply = strawberry::control_request_with_payload(socket_path, "contain-add", R"({"sha256":")" + hash + R"(","path":"/etc/passwd"})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "payload must be")); reply = strawberry::control_request_with_payload(socket_path, "contain-add", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"hash_pinned\":true")); assert(fs::exists(rule_file)); // Undo by id. const auto id_at = reply->find("\"id\":\"") + 6; const auto id = reply->substr(id_at, reply->find('"', id_at) - id_at); assert(id.starts_with("contain-")); reply = strawberry::control_request_with_payload(socket_path, "contain-remove", R"({"id":")" + id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"removed\"")); assert(!fs::exists(rule_file)); // Protection settings are validated. reply = strawberry::control_request_with_payload(socket_path, "protection-set", R"({"prevention_mode":"yolo"})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "prevention_mode must be")); reply = strawberry::control_request_with_payload(socket_path, "protection-set", R"({"contain_auto":false,"contain_min_severity":"critical"})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"contain_auto\":false")); // Quarantine: only binaries from stored evidence; undo releases containment. reply = strawberry::control_request_with_payload(socket_path, "quarantine", R"({"sha256":")" + std::string(64, 'e') + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "no stored evidence")); reply = strawberry::control_request_with_payload(socket_path, "quarantine", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"quarantined\"")); assert(fs::exists(rule_file)); policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2)); assert(policy && contains_text(*policy, hash)); reply = strawberry::control_request_with_payload(socket_path, "quarantine", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "already quarantined")); reply = strawberry::control_request_with_payload(socket_path, "quarantine-remove", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"released\"")); assert(!fs::exists(rule_file)); // A containment that existed before the quarantine survives its release. reply = strawberry::control_request_with_payload(socket_path, "contain-add", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && fs::exists(rule_file)); reply = strawberry::control_request_with_payload(socket_path, "quarantine", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"quarantined\"")); reply = strawberry::control_request_with_payload(socket_path, "quarantine-remove", R"({"sha256":")" + hash + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"released\"") && fs::exists(rule_file)); // Process actions: stable ids only, re-verified against the live process. const auto self_id = strawberry::resolve_process_ref(::getpid()); assert(self_id); reply = strawberry::control_request_with_payload(socket_path, "process-kill", R"({"node_id":"process_)" + std::to_string(::getpid()) + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "stable process id")); reply = strawberry::control_request_with_payload(socket_path, "process-kill", R"({"node_id":")" + self_id->node_id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "protected")); // the daemon itself if (const auto init = strawberry::resolve_process_ref(1)) { reply = strawberry::control_request_with_payload(socket_path, "process-kill", R"({"node_id":")" + init->node_id + R"("})", std::chrono::seconds(2)); assert(reply && (contains_text(*reply, "protected") || contains_text(*reply, "no longer running"))); } const pid_t child = ::fork(); if (child == 0) { ::execl("/bin/sleep", "sleep", "30", static_cast(nullptr)); ::_exit(127); } std::optional child_ref; for (int i = 0; i < 80; ++i) { child_ref = strawberry::resolve_process_ref(child); if (child_ref && child_ref->exe.find("sleep") != std::string::npos) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); } assert(child_ref); // Wrong start time (as after PID reuse) is refused. auto stale = child_ref->node_id; stale.back() = stale.back() == '1' ? '2' : '1'; reply = strawberry::control_request_with_payload(socket_path, "process-suspend", R"({"node_id":")" + stale + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "no longer running")); const auto state_of = [&]() { #if defined(__APPLE__) int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, child}; kinfo_proc info{}; std::size_t size = sizeof(info); if (::sysctl(mib, 4, &info, &size, nullptr, 0) != 0 || size != sizeof(info)) { return '?'; } return info.kp_proc.p_stat == SSTOP ? 'T' : 'R'; #else std::ifstream stat("/proc/" + std::to_string(child) + "/stat"); std::string text((std::istreambuf_iterator(stat)), std::istreambuf_iterator()); const auto close = text.rfind(')'); return close == std::string::npos || close + 2 >= text.size() ? '?' : text[close + 2]; #endif }; reply = strawberry::control_request_with_payload(socket_path, "process-suspend", R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"done\"")); for (int i = 0; i < 40 && state_of() != 'T'; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } assert(state_of() == 'T'); reply = strawberry::control_request_with_payload(socket_path, "process-resume", R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"done\"")); reply = strawberry::control_request_with_payload(socket_path, "scan-memory", R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"queued\":true")); reply = strawberry::control_request_with_payload(socket_path, "process-kill", R"({"node_id":")" + child_ref->node_id + R"("})", std::chrono::seconds(2)); assert(reply && contains_text(*reply, "\"done\"")); int wstatus = 0; assert(::waitpid(child, &wstatus, 0) == child && WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGKILL); policy = strawberry::control_request(socket_path, "policy", std::chrono::seconds(2)); assert(policy && contains_text(*policy, "process-kill")); daemon.request_stop(); runner.join(); unset_env_var("STRAWBERRY_PROCFS_ROOT"); unset_env_var("STRAWBERRY_PROCESS_MONITOR_POLL_MS"); fs::remove_all(root, ec); std::cout << " PASSED" << std::endl; } #endif } // namespace int main() { std::cout << "Running StrawberryDaemon tests..." << std::endl << std::endl; #if !STRAWBERRY_HAVE_YARA std::cout << "SKIP: daemon runtime test requires libyara" << std::endl; return 0; #else test_daemon_procfs_event_persists_match(); test_daemon_opensnitch_containment(); std::cout << std::endl << "All tests passed!" << std::endl; return 0; #endif }