Skip to content

Zero Breach — local, read-only scanner that checks a computer for indicators of the AdFection / Candiru ad-delivered spyware campaign. No network, no admin, no dependencies.

Fix Linux portability and test hermeticity (from real-hardware testing)

interplains6e2624f13eaf
diff --git a/scan/adint_scan/modules/browser.py b/scan/adint_scan/modules/browser.py
index 50ca1f6..9d20039 100644
--- a/scan/adint_scan/modules/browser.py
+++ b/scan/adint_scan/modules/browser.py
@@ -51,10 +51,10 @@ def _chromium_roots():
The label names the browser in each per-artifact sub-check, so an
installed-but-clean browser is recorded distinctly from an absent one, and a
- locked artifact names the browser it belongs to. Windows roots are derived
- from the module globals LOCAL/ROAMING, which the test-suite overrides; the
- macOS and Linux branches never run on a Windows machine, so the real profile
- is never read under test.
+ locked artifact names the browser it belongs to. Tests override the roots by
+ patching CHROMIUM_ROOTS / FIREFOX_ROOTS directly (not by patching LOCAL /
+ ROAMING), so the suite is hermetic on every platform, never the tester's own
+ browser.
"""
home = os.path.expanduser("~")
if sys.platform == "win32":
@@ -75,10 +75,22 @@ def _chromium_roots():
]
if sys.platform.startswith("linux"):
cfg = os.path.join(home, ".config")
+ var = os.path.join(home, ".var", "app")
+ snap = os.path.join(home, "snap")
return [
("chrome", os.path.join(cfg, "google-chrome")),
("chromium", os.path.join(cfg, "chromium")),
("brave", os.path.join(cfg, "BraveSoftware", "Brave-Browser")),
+ ("edge", os.path.join(cfg, "microsoft-edge")),
+ # snap packaging
+ ("chromium-snap", os.path.join(snap, "chromium", "common", "chromium")),
+ # flatpak packaging
+ ("chrome-flatpak", os.path.join(var, "com.google.Chrome", "config",
+ "google-chrome")),
+ ("brave-flatpak", os.path.join(var, "com.brave.Browser", "config",
+ "BraveSoftware", "Brave-Browser")),
+ ("chromium-flatpak", os.path.join(var, "org.chromium.Chromium",
+ "config", "chromium")),
]
return []
@@ -86,6 +98,13 @@ def _chromium_roots():
# Computed at import so the test-suite can monkeypatch this attribute directly.
CHROMIUM_ROOTS = _chromium_roots()
+# Firefox (profiles_dir, cache_dir) pairs. None means "derive from the platform
+# at run() time"; tests set an explicit list so the suite never reads the real
+# profile on any OS (the Windows branch of _firefox_roots used to be the only one
+# the tests could neutralise, which let the suite read the tester's real Firefox
+# on macOS/Linux).
+FIREFOX_ROOTS = None
+
def _firefox_roots():
"""Firefox (profiles_dir, cache_dir) pairs by platform.
@@ -174,31 +193,61 @@ def _chromium_profile_names(user_data):
return out
-def _firefox_profile_names(profiles_dir):
- """Same idea for Firefox, whose names live in profiles.ini one level up."""
- out = {}
- ini = os.path.join(os.path.dirname(profiles_dir), "profiles.ini")
- section = {}
+# Files that mark a directory as a real Firefox profile (as opposed to a sibling
+# folder like Crash Reports / Pending Pings / Profile Groups that lives in the
+# same root on Linux). Any one is enough.
+_FF_PROFILE_MARKERS = ("prefs.js", "places.sqlite", "cookies.sqlite",
+ "favicons.sqlite", "SiteSecurityServiceState.txt",
+ "cert9.db", "key4.db", "logins.json")
+
+
+def _firefox_ini(profiles_dir):
+ """Parse Firefox's profiles.ini. Returns ({folder_basename: display_name},
+ {folder basenames that profiles.ini lists as profiles}).
+
+ profiles.ini sits INSIDE profiles_dir on Linux (~/.mozilla/firefox) but one
+ level ABOVE it on Windows/macOS (...\\Firefox\\Profiles). Try both, so names
+ resolve on every platform; the first readable one wins.
+ """
+ names, known = {}, set()
def flush(sec):
- path, name = sec.get("Path"), sec.get("Name")
- if path and name:
- out[os.path.basename(path.replace("/", os.sep).rstrip(os.sep))] = name
+ path = sec.get("Path")
+ if path:
+ base = os.path.basename(path.replace("/", os.sep).rstrip(os.sep))
+ known.add(base)
+ if sec.get("Name"):
+ names[base] = sec["Name"]
+
+ for ini in (os.path.join(profiles_dir, "profiles.ini"),
+ os.path.join(os.path.dirname(profiles_dir), "profiles.ini")):
+ section = {}
+ try:
+ with io.open(ini, encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ line = raw.strip()
+ if line.startswith("["):
+ flush(section)
+ section = {}
+ elif "=" in line:
+ key, value = line.split("=", 1)
+ section[key.strip()] = value.strip()
+ flush(section)
+ break
+ except OSError:
+ continue
+ return names, known
+
+def _is_ff_profile_dir(path):
+ """True if `path` looks like a real Firefox profile (holds a marker file)."""
try:
- with io.open(ini, encoding="utf-8", errors="replace") as fh:
- for raw in fh:
- line = raw.strip()
- if line.startswith("["):
- flush(section)
- section = {}
- elif "=" in line:
- key, value = line.split("=", 1)
- section[key.strip()] = value.strip()
- flush(section)
+ for marker in _FF_PROFILE_MARKERS:
+ if os.path.exists(os.path.join(path, marker)):
+ return True
except OSError:
pass
- return out
+ return False
def _fmt_time(conv, raw):
@@ -880,7 +929,7 @@ def run(ctx) -> ModuleResult:
# No browser profile location is known for this platform at all: say so as a
# gap rather than returning an empty, falsely-clean result.
- ff_roots = _firefox_roots()
+ ff_roots = FIREFOX_ROOTS if FIREFOX_ROOTS is not None else _firefox_roots()
if not CHROMIUM_ROOTS and not ff_roots:
r.could_not_run("browser", "no browser profile locations are known for "
"{}".format(sys.platform))
@@ -932,7 +981,7 @@ def run(ctx) -> ModuleResult:
cache_is_dir = os.path.isdir(cache_dir)
if not prof_is_dir and not cache_is_dir:
continue
- ff_names = _firefox_profile_names(profiles_dir) if prof_is_dir else {}
+ ff_names, ff_known = _firefox_ini(profiles_dir) if prof_is_dir else ({}, set())
ctx.emit("[*] {}".format(profiles_dir if prof_is_dir else cache_dir))
folders = set()
@@ -953,6 +1002,12 @@ def run(ctx) -> ModuleResult:
cprof = os.path.join(cache_dir, name)
if not os.path.isdir(prof) and not os.path.isdir(cprof):
continue
+ # On Linux the profiles root also holds non-profile folders (Crash
+ # Reports, Pending Pings, Profile Groups). Only treat a folder as a
+ # profile if profiles.ini lists it or it holds a profile marker file,
+ # so those are not scanned and mislabelled as profiles.
+ if name not in ff_known and not _is_ff_profile_dir(prof):
+ continue
display = ff_names.get(name, "")
current["name"] = ("{} ({})".format(display, name) if display
else name)
diff --git a/scan/adint_scan/modules/host.py b/scan/adint_scan/modules/host.py
index e27b577..2ba366e 100644
--- a/scan/adint_scan/modules/host.py
+++ b/scan/adint_scan/modules/host.py
@@ -665,8 +665,11 @@ def _check_hosts(r: ModuleResult, ctx) -> None:
# path and the exact hash. The path is a generic name, so presence alone is only a
# pointer - the check hashes the file and says whether it is the KNOWN-BAD build
# (hash in the IOC set) or merely a same-named file to look at.
+# Path parts, not a backslash string: os.path.join builds the right separator on
+# every OS. A literal "System32\\drivers\\HW.sys" would be one filename with
+# embedded backslashes on POSIX, so the check (and its test) only worked on Windows.
_KNOWN_DROPS = [
- (r"System32\drivers\HW.sys",
+ (("System32", "drivers", "HW.sys"),
"the signed-but-vulnerable driver Candiru uses to disable protections "
"(bring-your-own-vulnerable-driver); documented by Avast, CVE-2022-2294"),
]
@@ -677,8 +680,8 @@ def _check_known_paths(r: ModuleResult, ctx) -> None:
root = os.environ.get("SystemRoot", r"C:\Windows")
known_hashes = {h.value for h in ctx.iocs.hashes}
found = 0
- for rel, why in _KNOWN_DROPS:
- path = os.path.join(root, rel)
+ for parts, why in _KNOWN_DROPS:
+ path = os.path.join(root, *parts)
try:
present = os.path.isfile(path)
except OSError:
diff --git a/scan/adint_scan/report.py b/scan/adint_scan/report.py
index f625f0d..a598ef0 100644
--- a/scan/adint_scan/report.py
+++ b/scan/adint_scan/report.py
@@ -445,10 +445,17 @@ def _render_reach(w, document: Dict[str, Any]) -> None:
w(" {}: {:,} cache file(s)".format(y, merged.get(y, 0)))
w("")
- # The actionable part: if any check reported how to extend its window, print it.
+ # The actionable part, rendered as its own ruled-off section so the one thing
+ # a reader can act on does not get lost at the tail of the reach block.
+ howto = []
for _mod_name, _label, info in entries:
- for line in info.get("how_to_enable") or []:
- w(" " + line)
+ howto.extend(info.get("how_to_enable") or [])
+ if howto:
+ w("")
+ w(_RULE)
+ for line in howto:
+ w(line)
+ w(_RULE)
w("")
diff --git a/scan/tests/test_browser_launch.py b/scan/tests/test_browser_launch.py
index 8bc8fd3..46bc309 100644
--- a/scan/tests/test_browser_launch.py
+++ b/scan/tests/test_browser_launch.py
@@ -78,11 +78,16 @@ class BrowserLaunchBase(unittest.TestCase):
fh.write("{}\tdelivery\tprimary\ttest-source\n".format(TEST_DOMAIN))
self.ctx = ScanContext(iocs=iocmod.load(ioc_path), emit=lambda _m: None)
self._saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
- browser.copy_locked)
+ browser.copy_locked, browser.FIREFOX_ROOTS)
+ # No Firefox in these Chromium tests. Pin it to [] so the suite never
+ # reads the tester's real Firefox profile (it would on macOS/Linux, where
+ # _firefox_roots ignores ROAMING/LOCAL) and so an all-locked Chromium run
+ # rolls up to UNKNOWN, not PARTIAL.
+ browser.FIREFOX_ROOTS = []
def tearDown(self):
(browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
- browser.copy_locked) = self._saved
+ browser.copy_locked, browser.FIREFOX_ROOTS) = self._saved
shutil.rmtree(self.tmp, ignore_errors=True)
def run_chromium(self, root):
@@ -237,14 +242,19 @@ class FirefoxArtifactBase(unittest.TestCase):
with open(ioc_path, "w", encoding="utf-8", newline="\n") as fh:
fh.write("{}\tdelivery\tprimary\ttest-source\n".format(TEST_DOMAIN))
self.ctx = ScanContext(iocs=iocmod.load(ioc_path), emit=lambda _m: None)
- self._saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL)
+ self._saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS)
browser.CHROMIUM_ROOTS = [] # no Chromium browsers at all
- browser.ROAMING = self.roaming
browser.LOCAL = os.path.join(self.tmp, "Local") # no Firefox cache there
os.makedirs(browser.LOCAL)
+ # Point Firefox straight at the planted profile tree, on every OS - the
+ # explicit override is what makes this test hermetic on macOS/Linux too.
+ browser.FIREFOX_ROOTS = [(os.path.join(self.roaming, "Mozilla", "Firefox",
+ "Profiles"), browser.LOCAL)]
def tearDown(self):
- (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL) = self._saved
+ (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS) = self._saved
shutil.rmtree(self.tmp, ignore_errors=True)
diff --git a/scan/tests/test_evidence.py b/scan/tests/test_evidence.py
index 595a92c..18f6d8a 100644
--- a/scan/tests/test_evidence.py
+++ b/scan/tests/test_evidence.py
@@ -45,14 +45,17 @@ def run_browser_on(tmp, root):
ctx = make_ctx(tmp)
empty = os.path.join(tmp, "empty")
os.makedirs(empty, exist_ok=True)
- saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL)
+ saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS)
try:
browser.CHROMIUM_ROOTS = [("test", root)]
browser.ROAMING = empty
browser.LOCAL = empty
+ browser.FIREFOX_ROOTS = [] # hermetic: never read the real Firefox
return browser.run(ctx)
finally:
- browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL = saved
+ (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS) = saved
class TestHstsIsContactedGrade(unittest.TestCase):
diff --git a/scan/tests/test_known_paths.py b/scan/tests/test_known_paths.py
index 9f70aad..2d25cfb 100644
--- a/scan/tests/test_known_paths.py
+++ b/scan/tests/test_known_paths.py
@@ -32,8 +32,6 @@ def _ioc_set_with_hash(tmp, digest):
class TestKnownPaths(unittest.TestCase):
- @unittest.skipUnless(sys.platform == "win32" or True,
- "the check reads SystemRoot; the logic is platform-neutral")
def _run_with_fake_sysroot(self, sysroot, ioc_set):
r = host.ModuleResult("host")
ctx = ScanContext(iocs=ioc_set, emit=lambda _m: None)
diff --git a/scan/tests/test_not_infostealer.py b/scan/tests/test_not_infostealer.py
index 7aa7843..4cdb578 100644
--- a/scan/tests/test_not_infostealer.py
+++ b/scan/tests/test_not_infostealer.py
@@ -147,14 +147,17 @@ class TestNeverDecryptsSecrets(unittest.TestCase):
empty = os.path.join(tmp, "empty")
os.makedirs(empty)
- saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL)
+ saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS)
try:
browser.CHROMIUM_ROOTS = [("test", os.path.join(tmp, "User Data"))]
browser.ROAMING = empty
browser.LOCAL = empty
+ browser.FIREFOX_ROOTS = []
result = browser.run(ctx)
finally:
- browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL = saved
+ (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS) = saved
# The indicator must still be found - we are not testing that it reads
# nothing, only that it never reads the secret.
@@ -211,14 +214,17 @@ class TestLocalStateMasterKey(unittest.TestCase):
empty = os.path.join(tmp, "empty")
os.makedirs(empty)
- saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL)
+ saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS)
try:
browser.CHROMIUM_ROOTS = [("test", ud)]
browser.ROAMING = empty
browser.LOCAL = empty
+ browser.FIREFOX_ROOTS = []
result = browser.run(ctx)
finally:
- browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL = saved
+ (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS) = saved
blob = repr(result.to_dict())
self.assertNotIn(key_sentinel, blob,
diff --git a/scan/tests/test_synthetic.py b/scan/tests/test_synthetic.py
index d937ed9..9f8d1a8 100644
--- a/scan/tests/test_synthetic.py
+++ b/scan/tests/test_synthetic.py
@@ -158,14 +158,16 @@ class TestBrowserModuleSyntheticPositive(SyntheticBase):
# read from the environment AT IMPORT TIME, so os.environ is useless.
self.empty = os.path.join(self.tmp, "empty")
os.makedirs(self.empty)
- self._saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL)
+ self._saved = (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS)
browser.CHROMIUM_ROOTS = [("test", self.root)]
browser.ROAMING = self.empty
browser.LOCAL = self.empty
+ browser.FIREFOX_ROOTS = [] # hermetic: never read the real Firefox
def tearDown(self):
- (browser.CHROMIUM_ROOTS, browser.ROAMING,
- browser.LOCAL) = self._saved
+ (browser.CHROMIUM_ROOTS, browser.ROAMING, browser.LOCAL,
+ browser.FIREFOX_ROOTS) = self._saved
super().tearDown()
def test_detects_the_domain_in_both_sqlite_and_blob_artifacts(self):