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.

Add optional bounded Candiru pattern detection

interplainse97874f8cdbc
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index e766f0c..1d472b2 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -45,6 +45,23 @@ jobs:
working-directory: scan
run: python -X utf8 adint-scan.py --quick --json scan.json
+ optional-patterns:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ python-version: ["3.9", "3.12"]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install the pinned official optional engine wheels
+ run: python -m pip install -r requirements-patterns.txt
+ - name: Test optional patterns and default checks using harmless fixtures
+ run: python -B -m unittest discover -s scan/tests -v
+
reproducible-build:
# The build must be deterministic and the committed artifacts up to date, so
# anyone can rebuild zero-breach.py from source and get the published file.
diff --git a/DETECTION-UPGRADE.md b/DETECTION-UPGRADE.md
new file mode 100644
index 0000000..fec353c
--- /dev/null
+++ b/DETECTION-UPGRADE.md
@@ -0,0 +1,134 @@
+# Candiru pattern upgrade: unreleased research candidate
+
+This branch adds an optional check to Zero Breach itself. It is not a separate
+product and has not replaced the signed v0.1.2 release or the website download.
+The development version is 0.1.3.dev0. It is not approved for publication.
+
+## Scope
+
+`--patterns` scans local file bytes with two unchanged published Candiru rules:
+Microsoft's 2021 DevilsTongue hijack-DLL rule and Malpedia's automatically
+generated DevilsTongue rule. The latter was derived from unpacked files or
+memory dumps. A new date on a rule does not establish coverage of a new campaign.
+Neither rule proves infection, execution, or coverage of every Candiru build.
+This mode does not acquire or scan running memory, decrypt payloads, inspect
+phone backups, or add Pegasus detection.
+
+The default scanner still requires only Python's standard library. Pattern
+scanning additionally requires Python 3.9+ and the pinned official YARA-X 1.21.0
+wheel. `requirements-patterns.txt` pins all published wheel SHA-256 values and
+rejects source builds. Install into a dedicated environment during setup:
+
+```text
+python -m venv .venv
+<venv-python> -m pip install -r requirements-patterns.txt
+<venv-python> scan/adint-scan.py --patterns
+```
+
+The scanner never installs packages, downloads rules, or contacts sample/IOC
+servers. Without the requested engine it reports UNKNOWN with an explicit gap.
+Python 3.8 remains supported for the default checks.
+
+`--pattern-path ABSOLUTE_PATH` can be repeated to choose files or folders for
+the pattern check. Without it, the check uses the existing file-hash roots.
+It limits only the pattern check: browser, hash and host checks keep their
+usual scope. `--quick` skips hashes but still runs explicitly requested patterns.
+Relative, redirected and cloud-recall paths are refused. Windows UNC paths and
+remote drives are refused. On POSIX systems, a network-mounted directory can
+look like an ordinary absolute path and may be read; use operating-system
+network isolation when strict offline operation is required. Files are eligible
+regardless of extension. Per-file size and time limits, traversal and
+total-byte limits, directory exclusions, unreadable files and other coverage
+gaps are described in the module output. A limit is never treated as a completed
+clean check.
+
+The JSON evidence grade is `file-pattern`, separate from exact hash evidence
+(`on-disk`). The human report asks for review and preserves rule authorship,
+source and licence. Rule provenance and original texts are under
+`third_party/candiru/`; these rules are not covered by the IOC feed's CC0 grant.
+
+## Validation gate
+
+**User-required release gate:** Before publishing this upgrade, remind the user
+to switch to Astra and complete a final review of the changes, validation
+evidence, remaining limitations and release artifacts. Do not publish before
+that review. This gate was requested after the sample tests on 2026-10-19.
+
+Before considering a release:
+
+- Run default and optional-engine suites, source and standalone entry points,
+ missing-engine/error/timeout cases, path and resource-limit cases.
+- Verify deterministic builds and that ordinary files/fixtures stay unchanged.
+- Check authentic, hash-verified Candiru files strictly inside the disposable
+ VM. Download only inside that VM; disconnect acquisition networking before
+ extracting/scanning. Never execute the samples or export them to the host,
+ repository, backups or Docker image layers. Export only small structured
+ results containing approved hashes, rule names and aggregate metrics.
+- Measure false positives on a documented clean corpus. Harmless pattern
+ fixtures prove integration and rule mechanics, not real malware sensitivity.
+- Independently review the implementation and record all remaining gaps.
+
+## Validation recorded on 2026-10-19
+
+The authentic sample receipts certify candidate SHA-256
+`d2aaaec5554d04e69db9700832e35d8e7f77aca6e962b31903683a1048e889a6`.
+An Astra review then found that a pruned cache folder could be marked clean.
+The candidate now records that omission as a coverage gap, with a regression
+test. The change affects directory traversal, not the explicit-file rule scan
+used for the sample receipts. Rebuild and record the final artifact hash before
+publication. The Windows suite originally ran 267 tests with
+no failures and one platform-permission skip; without the optional engine it
+ran 267 tests with seven expected skips. The disposable Linux VM ran all 52
+pattern/integration tests without failures or skips. A small clean corpus of
+200 Debian files and 26 official Python Windows PE files produced no matches.
+
+The revised development candidate is SHA-256
+`57a1d4293e9f3a32c4dfc36393ecf007efef7cc4e5609bd42ba088f173f5cfd5`.
+After the prune correction and documentation changes, the Windows suite ran
+268 tests with no failures and one permission skip; without the optional engine
+it ran 268 tests with seven expected skips. These are development receipts;
+version and packaging changes require a new final hash and checks.
+
+Two hash-verified MalwareBazaar downloads were scanned as static bytes inside
+the disconnected VM, without execution:
+
+| SHA-256 | Published rule matched | Existing exact-hash coverage |
+| --- | --- | --- |
+| `255869de85e2a171993fc5eb8a556d873a1b8966e040f6f55926f2fa2d595cc8` | `win_devilstongue_auto` | Yes |
+| `a550c64443d50c7863cf4b4e3c1d13714824938eac33691a580b6453374fd5be` | `MAL_DevilsTongue_HijackDll` | No |
+
+The first hash has primary-source Candiru attribution. The second is tagged
+DevilsTongue by MalwareBazaar and matches Microsoft's published rule; its
+family attribution has not been independently corroborated by a primary source.
+Both scans checked one file, skipped none, left the input unchanged and recorded
+zero Python network attempts. The VM had no external network, host mounts or
+shared folders. It has been removed; only sanitized results were exported.
+
+These two positives and the small clean corpus demonstrate useful additional
+coverage, not a measured detection rate or proof of broad Candiru coverage.
+New native macOS execution, actual cloud placeholders and an adversarial
+wall-clock engine-timeout case remain untested. The live v0.1.2 release remains
+unchanged. Detailed local receipts are under `findings/vm-lab/`.
+
+## MVT integration assessment
+
+MVT could power an optional phone-evidence mode in this same tool, but has not
+been integrated in this candidate. It requires a supplied phone acquisition or
+backup; it adds no desktop detection by itself. Current upstream requires
+Python 3.10+ and does not officially support native Windows.
+
+A safe adapter needs a pinned isolated worker, read-only inputs, controlled
+config/output paths, operating-system network denial, disabled URL expansion
+and update checks, no unreviewed plugins, and explicit coverage accounting.
+The existing Python socket guard does not constrain a separate MVT process.
+MVT writes configuration at import time and catches some module failures, so
+an ordinary import/subprocess plus exit-code check would break our assumptions.
+Its own licence and informed data-owner consent requirements must be retained.
+
+Sources:
+- https://github.com/mvt-project/mvt
+- https://github.com/mvt-project/mvt/blob/main/pyproject.toml
+- https://github.com/mvt-project/mvt/blob/main/docs/install.md
+- https://docs.mvt.re/en/latest/iocs/
+- https://license.mvt.re/1.1/
+- https://github.com/VirusTotal/yara-x
diff --git a/NOTICE b/NOTICE
index 9f9b63e..c612811 100644
--- a/NOTICE
+++ b/NOTICE
@@ -41,6 +41,15 @@ released into the public domain under CC0 1.0 so that it can be copied into
blocklists, STIX bundles, MISP instances and other tools without friction.
See iocs/LICENSE.md.
+The optional Candiru YARA rules are NOT part of that CC0 indicator grant.
+Microsoft Threat Intelligence Center's MAL_DevilsTongue_HijackDll rule is
+redistributed from Signature-Base under Detection Rule License 1.1.
+Felix Bilstein's win_devilstongue_auto rule is redistributed from Malpedia
+under CC BY-SA 4.0. Both rules are unchanged. Author, source and license
+attribution are retained in the embedded rules, match details, and
+third_party/candiru/. YARA-X itself is a separate optional BSD-3-Clause
+dependency, not embedded executable code in this script.
+
Primary sources for the indicator set:
The Citizen Lab, "Exposing AdFection: How Discover-Tech Turned Targeted Ads
diff --git a/README.md b/README.md
index 9d98582..f215886 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,10 @@
# Zero Breach
+> Development branch: optional Candiru pattern scanning is under validation.
+> It is not part of the signed v0.1.2 release. See
+> [the upgrade scope and test gate](DETECTION-UPGRADE.md). The optional mode
+> needs a pinned YARA-X dependency; default checks remain standard-library-only.
+
[![tests](https://github.com/interplains/zero-breach/actions/workflows/tests.yml/badge.svg)](https://github.com/interplains/zero-breach/actions/workflows/tests.yml)
A local, read-only scanner that checks a computer for traces of the **AdFection /
@@ -94,8 +99,10 @@ python -X utf8 scan/adint-scan.py
```
The scan changes no system settings and needs no administrator. It makes no
-intentional network requests or indicator lookups. Remote and redirected paths
-are skipped, and online certificate verification is disabled. Locked database
+intentional network requests or indicator lookups. Redirected paths and Windows
+remote drives are skipped, and online certificate verification is disabled.
+On POSIX, network mounts can still be read through ordinary filesystem calls.
+Locked database
snapshots are temporary; cleanup is attempted after use, and any cleanup failure
is reported with the retained location. `--json` writes the requested report.
@@ -281,7 +288,8 @@ file shipped with v0.1.2, not later development-branch updates; see [SIGNING.md]
## Design principles
- **Never contact an indicator.** A Python socket guard blocks direct DNS and
- network calls. Local-path checks reject remote and redirected paths, and
+ network calls. Local-path checks reject redirected paths and Windows remote
+ drives, while POSIX network mounts may appear as local filesystem paths;
Authenticode checks that could retrieve certificates are disabled. The socket
guard is not an operating-system network sandbox; use OS isolation when a
strict offline execution boundary is required.
diff --git a/build/bundle.py b/build/bundle.py
index 90ecf7d..6092e2b 100644
--- a/build/bundle.py
+++ b/build/bundle.py
@@ -135,6 +135,8 @@ A(' The Citizen Lab https://citizenlab.ca/')
A('')
A('LICENCE')
A(' Software: Apache License 2.0. Indicator data: CC0 1.0 (public domain).')
+A(' Optional Candiru rules retain their separate DRL 1.1 / CC BY-SA 4.0')
+A(' licences and author credits, embedded below with their provenance.')
A(' Copyright 2026 archivegenocide.com. Provided AS IS, without warranty.')
A(' Full text, and the sources every indicator came from:')
A(' https://github.com/interplains/zero-breach')
@@ -147,6 +149,8 @@ A(' python -X utf8 zero-breach.py --json report.json')
A('')
A('Requires Python 3.8 or newer. Needs no administrator. All supported platforms')
A('get browser and file checks; Windows also gets host checks.')
+A('Experimental --patterns also requires Python 3.9+ and yara-x==1.21.0.')
+A('This development build is not an approved release.')
A('"""')
A('from __future__ import annotations')
A('')
@@ -155,7 +159,7 @@ A('import datetime')
A('import sys')
A('import time')
A('')
-A('__version__ = "0.1.2 (single-file build)"')
+A('__version__ = "0.1.3.dev0 (single-file build)"')
A('')
A('# --- embedded indicator data ------------------------------------------------')
A('# The real file is iocs/adfection_iocs.txt in the project. Its provenance')
@@ -172,6 +176,7 @@ for label, fname in (("result", "result.py"),
("netguard", "netguard.py"),
("localpaths", "localpaths.py"),
("context", "context.py"),
+ ("candiru_rules", "candiru_rules.py"),
("report", "report.py")):
A('# --- {} {}'.format(label, '-' * max(0, 72 - len(label))))
A(strip_imports(read(os.path.join(PKG, fname))))
@@ -179,8 +184,11 @@ for label, fname in (("result", "result.py"),
for label, fname, suffix in (("modules/browser", "browser.py", "browser"),
("modules/hashscan", "hashscan.py", "hash"),
- ("modules/host", "host.py", "host")):
+ ("modules/host", "host.py", "host"),
+ ("modules/patternscan", "patternscan.py", "patterns")):
A('# --- {} {}'.format(label, '-' * max(0, 72 - len(label))))
+ if suffix == "patterns":
+ A('_pattern_roots = _roots # hash module default local roots')
A(namespace(strip_imports(read(os.path.join(PKG, "modules", fname))), suffix))
A('')
@@ -256,7 +264,15 @@ def main(argv=None):
"as clean.")
p.add_argument("--no-pause", action="store_true",
help="do not wait for a keypress before exiting")
+ p.add_argument("--patterns", action="store_true",
+ help="experimental local Candiru file-pattern check; needs "
+ "Python 3.9+ and yara-x==1.21.0; no memory scan")
+ p.add_argument("--pattern-path", action="append", default=[], metavar="PATH",
+ help="file or folder for --patterns (repeatable). Limits only "
+ "the pattern check, not the other checks")
args = p.parse_args(sys.argv[1:] if argv is None else argv)
+ if args.pattern_path and not args.patterns:
+ p.error("--pattern-path requires --patterns")
if sys.version_info < (3, 8):
print("This needs Python 3.8 or newer; this is {}.{}.".format(
@@ -271,13 +287,16 @@ def main(argv=None):
_hold(args)
return 1
- ctx = ScanContext(iocs=ioc_set, quick=args.quick)
+ ctx = ScanContext(iocs=ioc_set, quick=args.quick, patterns=args.patterns,
+ pattern_paths=tuple(args.pattern_path))
started = datetime.datetime.now()
results = []
# The whole scan runs inside the no-network guard (see the header).
with no_network():
- for name, fn in (("browser", run_browser), ("hash", run_hash),
- ("host", run_host)):
+ modules = [("browser", run_browser), ("hash", run_hash), ("host", run_host)]
+ if args.patterns:
+ modules.append(("patterns", run_patterns))
+ for name, fn in modules:
if name == "hash" and args.quick:
r = ModuleResult("hash")
r.could_not_run(
diff --git a/requirements-patterns.txt b/requirements-patterns.txt
new file mode 100644
index 0000000..bbea268
--- /dev/null
+++ b/requirements-patterns.txt
@@ -0,0 +1,15 @@
+# Optional experimental engine; default Zero Breach needs no packages.
+# Python 3.9+; official PyPI wheels only. No source builds or dependencies.
+--only-binary=:all:
+--require-hashes
+yara-x==1.21.0 \
+ --hash=sha256:24a739f492782335bb3b886cb2b6eaf008991f67b9e63e15b940af02aba233c0 \
+ --hash=sha256:1c6e15cf61500bc27960099872586d41f3cfdd8597e4bb8d2f0361b921b118d9 \
+ --hash=sha256:9bd9961b44b47dd747d526e61c703a2a8170426d003e789e7724bc7862de6d56 \
+ --hash=sha256:33bc3665170e640752fed275a7ad6551079696f00d698c9433607dfc6bdd7493 \
+ --hash=sha256:04be37c92bbbcba4065a4cf0f0029c0b0bf3e7c68f3c35b4cf523300e534cf58 \
+ --hash=sha256:cc1ed7760521aa80ba5a4ae4703441e7146d88ad09733d751a3b6e277bf0ef69 \
+ --hash=sha256:db8565ba7ec71746349ec92d2662a70d90cbc580a6623d633ae2468af432144c \
+ --hash=sha256:b863e93b7a01cbb7c192ce9582d2da562706d603ec7a58416a84940cde7540ac \
+ --hash=sha256:54222707bc9e0ee9fca7b6553e330b7885ba43d068d1ae560809724951f7c728 \
+ --hash=sha256:c5a8bcce08ece1e57d116cac63e671fe88d28f0dff58ee1d1055ca611d0eb0a8
diff --git a/scan/CONTRACT.md b/scan/CONTRACT.md
index 15d9eee..e1d2a9f 100644
--- a/scan/CONTRACT.md
+++ b/scan/CONTRACT.md
@@ -1,5 +1,11 @@
# Module contract — build against this
+Development extension: `ctx.patterns` explicitly enables the optional `patterns`
+module; `ctx.pattern_paths` supplies absolute local paths for that module only.
+The default checks remain standard-library-only. The optional module uses the
+pinned YARA-X engine without downloads, writes or sample execution. Its hits use
+`file-pattern` evidence and `candiru-pattern` tier, never exact-hash claims.
+
Each scan module is a file in `adint_scan/modules/` that defines exactly:
```python
diff --git a/scan/README.md b/scan/README.md
index 16cd7e2..7e19761 100644
--- a/scan/README.md
+++ b/scan/README.md
@@ -1,5 +1,9 @@
# adint-scan
+> This development branch includes experimental `--patterns` support. See
+> [DETECTION-UPGRADE.md](../DETECTION-UPGRADE.md) for dependencies, limits and
+> validation requirements. It has not replaced the signed public release.
+
A local, read-only check for the published AdFection / Candiru indicators,
with explicit reporting of missing evidence and checks that could not run.
@@ -97,7 +101,8 @@ record to search instead of an empty attic.
- **Never contact an indicator.** No DNS resolution, ping, HTTP or WHOIS of any
indicator, ever — resolving a C&C domain announces a possible victim to the
people running it. A runtime guard blocks Python network calls. Local-path
- guards reject remote/redirected paths; certificate verification that could
+ guards reject redirected paths and Windows remote drives; POSIX network mounts
+ can appear local and may be read. Certificate verification that could
retrieve data is disabled. The guard is not an OS network sandbox. Tests use
synthetic fixtures and reject network-capable imports; `urllib.parse` is
permitted solely for lexical URL parsing.
diff --git a/scan/adint_scan/__init__.py b/scan/adint_scan/__init__.py
index 2370256..c74e99f 100644
--- a/scan/adint_scan/__init__.py
+++ b/scan/adint_scan/__init__.py
@@ -4,4 +4,4 @@ A clean result from this tool means "no known indicators were found in the place
that can be checked." It does NOT mean the device is clean. See SPEC-scanner.md.
"""
-__version__ = "0.1.2"
+__version__ = "0.1.3.dev0"
diff --git a/scan/adint_scan/candiru_rules.py b/scan/adint_scan/candiru_rules.py
new file mode 100644
index 0000000..e1d8add
--- /dev/null
+++ b/scan/adint_scan/candiru_rules.py
@@ -0,0 +1,12 @@
+"""Pinned public Candiru research rules, embedded for offline standalone builds.
+
+The two rule strings retain their own third-party licenses and authorship.
+See third_party/candiru/PROVENANCE.json and the corresponding license texts.
+Do not replace these with downloaded rules at scan time.
+"""
+
+CANDIRU_ENGINE_VERSION = "1.21.0"
+
+CANDIRU_RULE_SOURCES = ('import "pe"\n\nrule MAL_DevilsTongue_HijackDll {\n meta:\n description = "Detects SOURGUM\'s DevilsTongue hijack DLL"\n author = "Microsoft Threat Intelligence Center (MSTIC)"\n date = "2021-07-15"\n reference = "https://www.microsoft.com/security/blog/2021/07/15/protecting-customers-from-a-private-sector-offensive-actor-using-0-day-exploits-and-devilstongue-malware/"\n score = 80\n id = "390b8b73-6740-513d-8c70-c9002be0ce69"\n strings:\n $str1 = "windows.old\\\\windows" wide\n $str2 = "NtQueryInformationThread"\n $str3 = "dbgHelp.dll" wide\n $str4 = "StackWalk64"\n $str5 = "ConvertSidToStringSidW"\n $str6 = "S-1-5-18" wide\n $str7 = "SMNew.dll" // DLL original name\n // Call check in stack manipulation\n // B8 FF 15 00 00 mov eax, 15FFh\n // 66 39 41 FA cmp [rcx-6], ax\n // 74 06 jz short loc_1800042B9\n // 80 79 FB E8 cmp byte ptr [rcx-5], 0E8h ;\n $code1 = { B8 FF 15 00 00 66 39 41 FA 74 06 80 79 FB E8 }\n // PRNG to generate number of times to sleep 1s before exiting\n // 44 8B C0 mov r8d, eax\n // B8 B5 81 4E 1B mov eax, 1B4E81B5h\n // 41 F7 E8 imul r8d\n // C1 FA 05 sar edx, 5\n // 8B CA mov ecx, edx\n // C1 E9 1F shr ecx, 1Fh\n // 03 D1 add edx, ecx\n // 69 CA 2C 01 00 00 imul ecx, edx, 12Ch\n // 44 2B C1 sub r8d, ecx\n // 45 85 C0 test r8d, r8d\n // 7E 19 jle short loc_1800014D0\n $code2 = { 44 8B C0 B8 B5 81 4E 1B 41 F7 E8 C1 FA 05 8B CA C1 E9 1F 03 D1 69 CA 2C 01 00 00 44 2B C1 45 85 C0 7E 19 }\n condition:\n filesize < 800KB and\n uint16(0) == 0x5A4D and\n ( pe.characteristics & pe.DLL ) and\n (\n 4 of them or\n ( $code1 and $code2 ) or\n pe.imphash() == "9a964e810949704ff7b4a393d9adda60"\n )\n}\n', 'rule win_devilstongue_auto {\n\n meta:\n author = "Felix Bilstein - yara-signator at cocacoding dot com"\n date = "2026-09-17"\n version = "1"\n description = "Detects win.devilstongue."\n info = "autogenerated rule brought to you by yara-signator"\n tool = "yara-signator v0.6.0"\n signator_config = "callsandjumps;datarefs;binvalue"\n malpedia_reference = "https://malpedia.caad.fkie.fraunhofer.de/details/win.devilstongue"\n malpedia_rule_date = "20260916"\n malpedia_hash = "53a643781c18e08f4a50949af60172d837a0b6f6"\n malpedia_version = "20260917"\n malpedia_license = "CC BY-SA 4.0"\n malpedia_sharing = "TLP:WHITE"\n\n /* DISCLAIMER\n * The strings used in this rule have been automatically selected from the\n * disassembly of memory dumps and unpacked files, using YARA-Signator.\n * The code and documentation is published here:\n * https://github.com/fxb-cocacoding/yara-signator\n * As Malpedia is used as data source, please note that for a given\n * number of families, only single samples are documented.\n * This likely impacts the degree of generalization these rules will offer.\n * Take the described generation method also into consideration when you\n * apply the rules in your use cases and assign them confidence levels.\n */\n\n\n strings:\n $sequence_0 = { 4d85c0 0f94442402 bba2984e80 ebc5 81fb97ab74c9 0f8f97000000 81fba2984e80 }\n // n = 7, score = 100\n // 4d85c0 | dec esp\n // 0f94442402 | mov esi, ecx\n // bba2984e80 | dec ecx\n // ebc5 | mov edi, edx\n // 81fb97ab74c9 | dec eax\n // 0f8f97000000 | cmp dword ptr [ecx], 0\n // 81fba2984e80 | je 0xb24\n\n $sequence_1 = { 4883ec28 4889d1 e8???????? b801000000 4883c428 c3 56 }\n // n = 7, score = 100\n // 4883ec28 | push ebx\n // 4889d1 | dec eax\n // e8???????? | \n // b801000000 | sub esp, 0x28\n // 4883c428 | dec eax\n // c3 | lea ebp, [edx + 0x60]\n // 56 | dec eax\n\n $sequence_2 = { 4829d7 48bdffffffffffffff7f 4889e9 4829f9 4839cb 0f879b010000 4d89fe }\n // n = 7, score = 100\n // 4829d7 | inc esp\n // 48bdffffffffffffff7f | jne 0xfffffff6\n // 4889e9 | jmp 0xd\n // 4829f9 | mov eax, 0x445c91b1\n // 4839cb | jmp 0xfffffff6\n // 0f879b010000 | dec eax\n // 4d89fe | mov dword ptr [esp + 8], ecx\n\n $sequence_3 = { 4c89e1 e8???????? 4829d8 4839e8 0f82dc010000 4801dd 4c8b6f18 }\n // n = 7, score = 100\n // 4c89e1 | dec eax\n // e8???????? | \n // 4829d8 | lea ecx, [esi + 0x10]\n // 4839e8 | inc ebp\n // 0f82dc010000 | mov eax, dword ptr [eax]\n // 4801dd | dec eax\n // 4c8b6f18 | mov eax, esi\n\n $sequence_4 = { 85c0 0f8492010000 e9???????? 488b442448 49894608 8b442450 41894618 }\n // n = 7, score = 100\n // 85c0 | mov ecx, dword ptr [esp]\n // 0f8492010000 | mov ecx, 0x50ecbd49\n // e9???????? | \n // 488b442448 | dec ecx\n // 49894608 | mov ecx, edx\n // 8b442450 | jmp 0x688\n // 41894618 | dec esp\n\n $sequence_5 = { 48895818 48897020 488b05???????? 4833c4 488985f0010000 418bf0 4c8bf2 }\n // n = 7, score = 100\n // 48895818 | mov ecx, dword ptr [esp + 0x20]\n // 48897020 | dec eax\n // 488b05???????? | \n // 4833c4 | mov edx, edi\n // 488985f0010000 | dec ecx\n // 418bf0 | mov eax, ebx\n // 4c8bf2 | dec eax\n\n $sequence_6 = { 57 4883ec30 488d6c2430 48c745f8feffffff 4889d6 4889cf 4c89c2 }\n // n = 7, score = 100\n // 57 | dec ecx\n // 4883ec30 | sub ebp, esi\n // 488d6c2430 | mov eax, 0xcde3b609\n // 48c745f8feffffff | dec esp\n // 4889d6 | lea esp, [ebp - 0x38]\n // 4889cf | cmp eax, 0xaaa31545\n // 4c89c2 | je 0xeee\n\n $sequence_7 = { 488d4d08 41b80c000000 e8???????? 488d4d08 e8???????? 488d4dc8 4889c2 }\n // n = 7, score = 100\n // 488d4d08 | jmp 0x1435\n // 41b80c000000 | dec eax\n // e8???????? | \n // 488d4d08 | mov dword ptr [esp + 0x20], edi\n // e8???????? | \n // 488d4dc8 | dec eax\n // 4889c2 | mov ecx, dword ptr [esp + 0x20]\n\n $sequence_8 = { 488b442428 488b442420 488b442438 b800554687 e9???????? 488b4c2470 4831e1 }\n // n = 7, score = 100\n // 488b442428 | inc ecx\n // 488b442420 | mov ecx, ebp\n // 488b442438 | dec eax\n // b800554687 | mov dword ptr [esp + 0x38], eax\n // e9???????? | \n // 488b4c2470 | mov eax, 0x886bf338\n // 4831e1 | jmp 0x9b7\n\n $sequence_9 = { 81fa15b7785c 75f0 488b542410 48c7411000000000 ba251f32f5 ebdc }\n // n = 6, score = 100\n // 81fa15b7785c | jne 0x1a7\n // 75f0 | dec esp\n // 488b542410 | mov ecx, edi\n // 48c7411000000000 | jg 0x136\n // ba251f32f5 | cmp eax, 0x45b54eab\n // ebdc | je 0x19e\n\n condition:\n 7 of them and filesize < 990208\n}')
+
+CANDIRU_RULE_METADATA = {'MAL_DevilsTongue_HijackDll': {'identifier': 'MAL_DevilsTongue_HijackDll', 'author': 'Microsoft Threat Intelligence Center (MSTIC)', 'license': 'DRL 1.1', 'license_url': 'https://raw.githubusercontent.com/Neo23x0/signature-base/master/LICENSE', 'source': 'https://raw.githubusercontent.com/Neo23x0/signature-base/master/yara/apt_candiru.yar', 'filename': 'apt_candiru.yar'}, 'win_devilstongue_auto': {'identifier': 'win_devilstongue_auto', 'author': 'Felix Bilstein - yara-signator at cocacoding dot com', 'license': 'CC BY-SA 4.0', 'license_url': 'https://creativecommons.org/licenses/by-sa/4.0/', 'source': 'https://malpedia.caad.fkie.fraunhofer.de/details/win.devilstongue', 'filename': 'win_devilstongue_auto.yar'}}
diff --git a/scan/adint_scan/cli.py b/scan/adint_scan/cli.py
index 079cb41..1445427 100644
--- a/scan/adint_scan/cli.py
+++ b/scan/adint_scan/cli.py
@@ -71,13 +71,24 @@ def _parse(argv: List[str]) -> argparse.Namespace:
p.add_argument("--deep", action="store_true",
help="tier 2: full persistence sweep (noisy; most hits are "
"legitimate). Opens with a warning.")
+ p.add_argument("--patterns", action="store_true",
+ help="experimental local Candiru file-pattern check; needs "
+ "the separately installed, pinned YARA-X dependency. "
+ "Does not inspect running memory.")
+ p.add_argument("--pattern-path", action="append", default=[], metavar="PATH",
+ help="file or folder for --patterns (repeatable). Limits only "
+ "the pattern check; browser, hash and host checks keep "
+ "their usual scope.")
p.add_argument("--json", metavar="PATH",
help="also write the machine-readable report to PATH.")
p.add_argument("--iocs", metavar="PATH", default=_default_ioc_path(),
help="indicator file (default: bundled adfection_iocs.txt).")
p.add_argument("--version", action="version",
version="Zero Breach {}".format(__version__))
- return p.parse_args(argv)
+ args = p.parse_args(argv)
+ if args.pattern_path and not args.patterns:
+ p.error("--pattern-path requires --patterns")
+ return args
def _run_modules(ctx: ScanContext) -> List[ModuleResult]:
@@ -88,7 +99,11 @@ def _run_modules(ctx: ScanContext) -> List[ModuleResult]:
results: List[ModuleResult] = []
# The entire scan runs inside the no-network guard (D2).
with no_network():
- for mod in (browser, hashscan, host):
+ modules = [browser, hashscan, host]
+ if ctx.patterns:
+ from .modules import patternscan
+ modules.append(patternscan)
+ for mod in modules:
# --quick drops the file-fingerprint check. It costs ~45% of the
# whole scan (345s of 774s measured) to look for ONE published file
# hash, and Candiru compiles a fresh build per target, so another
@@ -171,7 +186,8 @@ def main(argv: List[str] = None) -> int:
"panic at an unsigned binary in a user-writable path.\n",
file=sys.stderr)
- ctx = ScanContext(iocs=iocs, deep=args.deep, quick=args.quick)
+ ctx = ScanContext(iocs=iocs, deep=args.deep, quick=args.quick,
+ patterns=args.patterns, pattern_paths=tuple(args.pattern_path))
started = datetime.datetime.now()
results = _run_modules(ctx)
diff --git a/scan/adint_scan/context.py b/scan/adint_scan/context.py
index b741647..2ec6c33 100644
--- a/scan/adint_scan/context.py
+++ b/scan/adint_scan/context.py
@@ -27,3 +27,6 @@ class ScanContext:
# could only build a fresh empty result and the hits were thrown away.
# Modules set it; nothing else should read it except the CLI's recovery path.
partial: object = None
+ # Optional research feature. Never installs a dependency or fetches rules.
+ patterns: bool = False
+ pattern_paths: tuple = ()
diff --git a/scan/adint_scan/localpaths.py b/scan/adint_scan/localpaths.py
index 76d3f4d..99f1090 100644
--- a/scan/adint_scan/localpaths.py
+++ b/scan/adint_scan/localpaths.py
@@ -1,7 +1,8 @@
-"""Refuse remote paths and filesystem redirections before scanner reads.
+"""Refuse Windows remote drives and filesystem redirections before reads.
Checks are conservative and use lstat so a reparse point is inspected rather
-than followed. This is not a sandbox against concurrent filesystem changes.
+than followed. POSIX network mounts cannot always be distinguished from local
+paths here. This is not a sandbox against concurrent filesystem changes.
"""
import os
diff --git a/scan/adint_scan/modules/patternscan.py b/scan/adint_scan/modules/patternscan.py
new file mode 100644
index 0000000..9ff242f
--- /dev/null
+++ b/scan/adint_scan/modules/patternscan.py
@@ -0,0 +1,352 @@
+"""Optional, bounded matching of pinned public Candiru research rules.
+
+Matches require investigation; they are neither exact sample identifications nor
+confirmation of infection. No rule or sample is fetched by this module.
+"""
+
+from __future__ import annotations
+
+import importlib as _pattern_importlib
+import io as _pattern_io
+import os as _pattern_os
+import stat as _pattern_stat
+import sys as _pattern_sys
+
+from ..result import Hit, ModuleResult
+from ..localpaths import path_problem
+from ..candiru_rules import (CANDIRU_ENGINE_VERSION, CANDIRU_RULE_SOURCES,
+ CANDIRU_RULE_METADATA)
+from .hashscan import _roots as _pattern_roots
+
+NAME = "patterns"
+_PATTERN_MAX_BYTES = 1024 * 1024
+_PATTERN_MAX_FILES = 50000
+_PATTERN_MAX_DIRS = 20000
+_PATTERN_MAX_ENTRIES = 100000
+_PATTERN_MAX_DEPTH = 64
+_PATTERN_MAX_TOTAL_BYTES = 256 * 1024 * 1024
+_PATTERN_TIMEOUT = 5
+_PATTERN_PRUNE = ("cache", "cache_data", "gpucache", "code cache", "node_modules",
+ ".git", "servicepackfiles", "winsxs")
+_PATTERN_CLOUD_ATTRIBUTES = 0x1000 | 0x40000 | 0x400000
+
+
+class _PatternLimit(RuntimeError):
+ """A resource bound left part of the requested scope unobserved."""
+
+
+class _PatternNoRead(OSError):
+ """A known preflight rejection before any file data read was attempted."""
+
+
+def _pattern_budget(counts):
+ if counts["files"] >= _PATTERN_MAX_FILES:
+ raise _PatternLimit("file cap reached")
+ if counts["bytes"] + _PATTERN_MAX_BYTES + 1 > _PATTERN_MAX_TOTAL_BYTES:
+ raise _PatternLimit("byte cap reached")
+
+
+def _pattern_walk(root, counts, r, onerror, depth=0):
+ """Yield files from streaming scandir; never materialize directory entries.
+
+ Entry budget includes refused and pruned entries, before any classification
+ or locality/cloud checks. At most MAX_DEPTH iterators are open; early close
+ unwinds every with-block. There is no growing pending-directory list.
+ """
+ _pattern_budget(counts)
+ if counts["entries"] >= _PATTERN_MAX_ENTRIES:
+ raise _PatternLimit("directory entry cap reached")
+ if depth >= _PATTERN_MAX_DEPTH:
+ raise _PatternLimit("directory depth cap reached")
+ if counts["dirs"] >= _PATTERN_MAX_DIRS:
+ raise _PatternLimit("directory cap reached")
+ counts["dirs"] += 1
+ r.submetrics["directories_pattern_visited"] = counts["dirs"]
+ try:
+ problem = _pattern_problem(root)
+ if problem:
+ raise OSError(problem)
+ with _pattern_os.scandir(root) as entries:
+ while True:
+ # Check before requesting/classifying another entry. Reaching
+ # the exact cap is conservatively a gap, even if it was last.
+ _pattern_budget(counts)
+ if counts["entries"] >= _PATTERN_MAX_ENTRIES:
+ raise _PatternLimit("directory entry cap reached")
+ try:
+ entry = next(entries)
+ except StopIteration:
+ return
+ counts["entries"] += 1
+ r.submetrics["filesystem_entries_considered"] = counts["entries"]
+ try:
+ info = entry.stat(follow_symlinks=False)
+ if (_pattern_stat.S_ISLNK(info.st_mode)
+ or getattr(info, "st_file_attributes", 0) & 0x400):
+ raise OSError("symlink or reparse point was not followed")
+ if getattr(info, "st_file_attributes", 0) & _PATTERN_CLOUD_ATTRIBUTES:
+ raise OSError("offline or cloud-recall path was not opened")
+ if _pattern_stat.S_ISDIR(info.st_mode):
+ if entry.name.lower() in _PATTERN_PRUNE:
+ r.submetrics["directories_pruned"] = r.submetrics.get("directories_pruned", 0) + 1
+ onerror("directory skipped by pattern scan's size limits", entry.path)
+ else:
+ yield from _pattern_walk(entry.path, counts, r, onerror, depth + 1)
+ elif _pattern_stat.S_ISREG(info.st_mode):
+ yield entry.path
+ else:
+ raise OSError("special filesystem entry was not opened")
+ except OSError as exc:
+ onerror(str(exc), entry.path)
+ except OSError as exc:
+ onerror(str(exc), root)
+
+
+def _pattern_problem(path):
+ problem = path_problem(path)
+ if problem:
+ return problem
+ # OFFLINE and recall attributes can occur independently of reparse points.
+ # Inspect every ancestor without opening the file's data stream.
+ current = path
+ while current:
+ try:
+ info = _pattern_os.lstat(current)
+ except FileNotFoundError:
+ return ""
+ if getattr(info, "st_file_attributes", 0) & _PATTERN_CLOUD_ATTRIBUTES:
+ return "offline or cloud-recall path was not opened"
+ parent = _pattern_os.path.dirname(current)
+ if parent == current:
+ break
+ current = parent
+ return ""
+
+
+def _pattern_identity(info):
+ return (info.st_dev, info.st_ino, info.st_size,
+ getattr(info, "st_mtime_ns", info.st_mtime),
+ getattr(info, "st_ctime_ns", info.st_ctime))
+
+
+def _pattern_read(path):
+ """Bound the read, reject special files, and detect observable replacements.
+
+ Like the shared locality guard, this is conservative filesystem validation,
+ not a sandbox against a concurrent privileged filesystem adversary.
+ """
+ read_started = False
+ try:
+ problem = _pattern_problem(path)
+ if problem:
+ raise OSError(problem)
+ before = _pattern_os.lstat(path)
+ if not _pattern_stat.S_ISREG(before.st_mode):
+ raise OSError("not a regular local file")
+ if before.st_size > _PATTERN_MAX_BYTES:
+ raise OSError("file exceeds 1 MiB pattern read cap")
+ flags = (_pattern_os.O_RDONLY | getattr(_pattern_os, "O_BINARY", 0)
+ | getattr(_pattern_os, "O_NOFOLLOW", 0)
+ | getattr(_pattern_os, "O_NONBLOCK", 0))
+ fd = _pattern_os.open(path, flags)
+ try:
+ stream = _pattern_io.open(fd, "rb", closefd=True)
+ except Exception:
+ _pattern_os.close(fd)
+ raise
+ with stream:
+ opened = _pattern_os.fstat(stream.fileno())
+ if (not _pattern_stat.S_ISREG(opened.st_mode)
+ or _pattern_identity(before) != _pattern_identity(opened)):
+ raise OSError("file changed before bounded read")
+ problem = _pattern_problem(path)
+ if problem:
+ raise OSError(problem)
+ # From this point an incomplete/failed read may have consumed data;
+ # preserve the caller's maximum reservation for every such failure.
+ read_started = True
+ data = stream.read(_PATTERN_MAX_BYTES + 1)
+ after = _pattern_os.fstat(stream.fileno())
+ final = _pattern_os.lstat(path)
+ problem = _pattern_problem(path)
+ if problem:
+ raise OSError(problem)
+ if (len(data) > _PATTERN_MAX_BYTES or len(data) != before.st_size
+ or _pattern_identity(before) != _pattern_identity(after)
+ or _pattern_identity(before) != _pattern_identity(final)):
+ raise OSError("file grew or changed during bounded read")
+ return data
+ except OSError as exc:
+ if not read_started:
+ raise _PatternNoRead(str(exc)) from exc
+ raise
+
+
+def _pattern_engine():
+ if _pattern_sys.version_info < (3, 9):
+ raise RuntimeError("optional Candiru patterns require Python 3.9 or newer")
+ engine = _pattern_importlib.import_module("yara_x")
+ metadata = _pattern_importlib.import_module("importlib.metadata")
+ version = metadata.version("yara-x")
+ if version != CANDIRU_ENGINE_VERSION:
+ raise RuntimeError("unsupported yara-x version {}; supported pinned version is {}"
+ .format(version, CANDIRU_ENGINE_VERSION))
+ compiler = engine.Compiler()
+ compiler.enable_includes(False)
+ for source in CANDIRU_RULE_SOURCES:
+ compiler.add_source(source)
+ scanner = engine.Scanner(compiler.build())
+ scanner.set_timeout(_PATTERN_TIMEOUT)
+ return scanner
+
+
+def _pattern_selected_roots(ctx):
+ requested = getattr(ctx, "pattern_paths", ())
+ roots = requested if requested else _pattern_roots()
+ # Lexical normalization only: resolving first could follow a refused link.
+ unique = []
+ for root in roots:
+ raw = _pattern_os.fspath(root)
+ # Check traversal and UNC/device spellings before normalization.
+ problem = path_problem(raw)
+ normalized = raw if problem else _pattern_os.path.normpath(raw)
+ key = _pattern_os.path.normcase(normalized)
+ if not any(key == old[0] for old in unique):
+ unique.append((key, normalized, bool(problem)))
+ # An explicitly selected child remains meaningful even beneath a selected
+ # parent: the parent traversal might prune its directory. File-level dedup
+ # below avoids duplicate scans while retaining each requested root.
+ return [path for _, path, _ in unique]
+
+
+def run(ctx) -> ModuleResult:
+ r = ModuleResult(NAME)
+ ctx.partial = r
+ r.note("Optional public Candiru file patterns; matches require investigation, "
+ "not an exact sample identification or confirmed infection. "
+ "No match does not exclude encrypted, packed, memory-only, or other builds.")
+ r.note("All regular file names are eligible, including extensionless files. "
+ "Read cap: 1 MiB/file; scan caps: {} files, {} directories, {} entries, "
+ "{} directory levels, {} MiB read budget; "
+ "{} seconds per engine scan. Pruned directory names: {}."
+ .format(_PATTERN_MAX_FILES, _PATTERN_MAX_DIRS, _PATTERN_MAX_ENTRIES,
+ _PATTERN_MAX_DEPTH, _PATTERN_MAX_TOTAL_BYTES // (1024 * 1024), _PATTERN_TIMEOUT,
+ ", ".join(_PATTERN_PRUNE)))
+ try:
+ scanner = _pattern_engine()
+ except Exception as exc:
+ r.could_not_run("pattern-engine", "optional pinned yara-x {} unavailable "
+ "or could not compile trusted rules: {}: {}"
+ .format(CANDIRU_ENGINE_VERSION, type(exc).__name__, exc))
+ return r
+ try:
+ roots = _pattern_selected_roots(ctx)
+ except (OSError, ValueError, TypeError) as exc:
+ r.could_not_run("pattern-roots", str(exc))
+ return r
+ if not roots:
+ r.could_not_run("pattern-roots", "no local pattern paths were selected")
+ return r
+
+ counts = {"files": 0, "dirs": 0, "entries": 0, "bytes": 0}
+ seen_files = {} # bounded by MAX_FILES; value says whether scan succeeded
+ for root in roots:
+ name = "root:" + root
+ tally = {"checked": 0, "covered": 0, "gaps": 0, "candidates": 0}
+
+ def _pattern_gap(reason, location=root):
+ tally["gaps"] += 1
+ r.skipped += 1
+ # Keep output and memory bounded even with a tree of refused files.
+ if tally["gaps"] <= 10:
+ r.note("Pattern file skipped at {}: {}".format(location, reason))
+
+ try:
+ problem = _pattern_problem(root)
+ if problem:
+ raise OSError(problem)
+ info = _pattern_os.lstat(root)
+ if _pattern_stat.S_ISREG(info.st_mode):
+ entries = iter((root,))
+ elif _pattern_stat.S_ISDIR(info.st_mode):
+ entries = _pattern_walk(root, counts, r, _pattern_gap)
+ else:
+ raise OSError("not a regular file or directory")
+ except OSError as exc:
+ r.skipped += 1
+ r.could_not_run(name, str(exc))
+ continue
+ ctx.emit("[patterns] scanning {} ...".format(root))
+ try:
+ for full in entries:
+ key = _pattern_os.path.normcase(_pattern_os.path.normpath(full))
+ if key in seen_files:
+ if seen_files[key]:
+ tally["covered"] += 1
+ else:
+ tally["gaps"] += 1
+ continue
+ _pattern_budget(counts)
+ counts["files"] += 1
+ seen_files[key] = False
+ tally["candidates"] += 1
+ # Charge the maximum bounded read before touching data. Failed
+ # reads retain the reservation, so changed/failed files cannot
+ # bypass the aggregate budget. Proven preflight rejections
+ # refund it all; successful reads refund only unused bytes.
+ counts["bytes"] += _PATTERN_MAX_BYTES + 1
+ try:
+ data = _pattern_read(full)
+ counts["bytes"] -= _PATTERN_MAX_BYTES + 1 - len(data)
+ matches = scanner.scan(data).matching_rules
+ known = []
+ for rule in matches:
+ identifier = rule.identifier
+ if identifier not in CANDIRU_RULE_METADATA:
+ raise RuntimeError("engine returned unknown rule identifier: {}".format(identifier))
+ known.append(identifier)
+ except _PatternNoRead as exc:
+ counts["bytes"] -= _PATTERN_MAX_BYTES + 1
+ _pattern_gap("{}: {}".format(type(exc).__name__, exc), full)
+ continue
+ except Exception as exc:
+ _pattern_gap("{}: {}".format(type(exc).__name__, exc), full)
+ continue
+ r.checked += 1
+ seen_files[key] = True
+ tally["checked"] += 1
+ r.submetrics["files_pattern_scanned"] = r.checked
+ r.submetrics["bytes_pattern_scanned"] = r.submetrics.get("bytes_pattern_scanned", 0) + len(data)
+ for identifier in known:
+ attribution = CANDIRU_RULE_METADATA[identifier]
+ detail = ("Public research rule {} matched; author: {}; license: {} ({}). "
+ "Pattern match requires investigation; not an exact sample "
+ "identification or confirmed infection. Source: {}"
+ .format(identifier, attribution["author"], attribution["license"],
+ attribution["license_url"], attribution["source"]))
+ r.add_hit(Hit(indicator="yara:" + identifier, location=full,
+ detail=detail, tier="candiru-pattern",
+ confidence="research-rule", source=attribution["source"],
+ evidence="file-pattern"))
+ # Match messages also preserve the DRL-required authorship.
+ ctx.emit("[patterns] !! MATCH {}: {}".format(full, detail))
+ except _PatternLimit as exc:
+ if tally["checked"] or tally["covered"]:
+ r.ran(name + " (scanned subset)")
+ r.could_not_run("pattern-limits", str(exc) +
+ "; this and remaining roots were not fully scanned")
+ return r
+ finally:
+ close = getattr(entries, "close", None)
+ if close:
+ close()
+ if tally["checked"] or tally["covered"]:
+ r.ran(name)
+ elif not tally["gaps"]:
+ r.could_not_run(name, "no regular files were available for pattern scanning")
+ if tally["gaps"]:
+ r.could_not_run(name + " (coverage gaps)",
+ "{} file/subtree item(s) unreadable, unsafe, oversized, changed, "
+ "or not scanned successfully; {} file(s) scanned".format(
+ tally["gaps"], tally["checked"] + tally["covered"]))
+ return r
diff --git a/scan/adint_scan/report.py b/scan/adint_scan/report.py
index 5f4702c..32e00c3 100644
--- a/scan/adint_scan/report.py
+++ b/scan/adint_scan/report.py
@@ -20,7 +20,7 @@ from typing import Any, Dict, List
from . import __version__
from .iocs import IocSet
from .result import (CLEAN, HITS, PARTIAL, UNKNOWN, ModuleResult, is_serious,
- EV_ON_DISK, EV_PERSISTENCE, EV_CONTACTED, EV_ATTEMPTED,
+ EV_ON_DISK, EV_FILE_PATTERN, EV_PERSISTENCE, EV_CONTACTED, EV_ATTEMPTED,
EV_CONFIGURED, EV_REFERENCED, EV_DNS)
# The exact text required by D1. Do not reword.
@@ -144,6 +144,8 @@ _METRIC_LABELS = {
"hsts_entries": "HSTS security records checked (proof of past connections)",
"connection_records": "saved connection records checked",
"files_hashed": "files fingerprinted",
+ "files_pattern_scanned": "files checked against Candiru patterns",
+ "bytes_pattern_scanned": "bytes checked against Candiru patterns",
"com_registrations": "auto-start COM registrations reviewed",
"com_user_writable": " of those, in a folder you can write to",
"dns_cache_entries": "names in the DNS cache since last reboot",
@@ -226,7 +228,7 @@ def render_human(document: Dict[str, Any]) -> str:
# Strongest evidence first: someone reading this should see a sample
# on disk or a proven contact before a string that merely appeared in
# cached page text.
- order = {EV_ON_DISK: 0, EV_PERSISTENCE: 1, EV_CONTACTED: 2,
+ order = {EV_ON_DISK: 0, EV_FILE_PATTERN: 0.5, EV_PERSISTENCE: 1, EV_CONTACTED: 2,
EV_DNS: 3, EV_ATTEMPTED: 4, EV_CONFIGURED: 5,
EV_REFERENCED: 6, "": 0}
for h in sorted(m["hits"], key=lambda x: order.get(x.get("evidence", ""), 0)):
@@ -478,6 +480,10 @@ TIER_MEANING = {
"current ownership and activity are not established."),
"sample": ("The file fingerprint of a published Candiru sample. A match "
"here is conclusive, not circumstantial."),
+ "candiru-pattern": ("A published Candiru detection rule matched patterns "
+ "inside a file. This needs expert verification; it is "
+ "not an exact sample identification or proof that "
+ "spyware ran."),
"vuln-driver": ("A LEGITIMATE, signed third-party driver that this actor "
"abuses to disable protections (bring-your-own-vulnerable-"
"driver). The file itself is not spyware and is present on "
@@ -493,6 +499,9 @@ TIER_MEANING = {
NOT_MALWARE_TIERS = {"vuln-driver"}
EVIDENCE_MEANING = {
+ EV_FILE_PATTERN: ("patterns inside a file matched a published detection "
+ "rule. This is a lead for investigation, not a confirmed "
+ "infection or an exact known-file match"),
EV_ON_DISK: ("a file on this machine has the fingerprint of a published "
"spyware sample - this is conclusive, not circumstantial"),
# Same grade, different claim: see _on_disk_gloss(). A legitimate-but-abused
@@ -515,6 +524,7 @@ EVIDENCE_MEANING = {
# not EV_REFERENCED are serious and each gets its own, so a sample on disk and a
# persistence entry can never be rendered as "probably nothing".
EVIDENCE_HEADLINE = {
+ EV_FILE_PATTERN: "A FILE MATCHED A CANDIRU DETECTION RULE - NEEDS REVIEW",
EV_ON_DISK: "A KNOWN SPYWARE FILE IS ON THIS MACHINE",
EV_PERSISTENCE: "SOMETHING IS SET TO RUN AUTOMATICALLY FROM THIS INFRASTRUCTURE",
EV_CONTACTED: "THIS DEVICE CONTACTED THIS INFRASTRUCTURE",
@@ -673,6 +683,15 @@ def _advice_paragraph(w, text):
def _next_steps(w, hits):
action = max(_recommended_action(h) for h in hits)
w(" WHAT TO DO")
+ if any(h.get("evidence") == EV_FILE_PATTERN for h in hits):
+ _advice_paragraph(w, "A file matched a Candiru pattern rule. Ask a "
+ "qualified incident responder to verify the named file "
+ "and rule. Preserve the file and this report; do not "
+ "open, run or delete the file. A pattern match alone "
+ "does not prove infection or that the file executed.")
+ w("")
+ if all(h.get("evidence") in (EV_FILE_PATTERN, EV_REFERENCED) for h in hits):
+ return
if action == 3:
_advice_paragraph(w, "Seek expert help promptly. Preserve this report and "
"the named files or registrations. Do NOT delete, move, "
diff --git a/scan/adint_scan/result.py b/scan/adint_scan/result.py
index eef4ab7..ecbf256 100644
--- a/scan/adint_scan/result.py
+++ b/scan/adint_scan/result.py
@@ -26,6 +26,7 @@ PARTIAL = "PARTIAL"
# Evidence grades, strongest first. See Hit.evidence for what each one means.
EV_ON_DISK = "on-disk" # a known sample's fingerprint matched a file
+EV_FILE_PATTERN = "file-pattern" # a research rule matched; needs verification
EV_PERSISTENCE = "persistence" # named in an auto-start registration
EV_CONTACTED = "contacted" # the device demonstrably talked to the host
EV_DNS = "dns-record" # a resolver record; endpoint contact unverified
@@ -33,7 +34,7 @@ EV_ATTEMPTED = "attempted" # a lookup happened but a filter blocked it
EV_CONFIGURED = "configured" # named in local config, NOT as a block
EV_REFERENCED = "referenced" # the string appeared in saved content
-EVIDENCE_ORDER = [EV_ON_DISK, EV_PERSISTENCE, EV_CONTACTED, EV_DNS, EV_ATTEMPTED,
+EVIDENCE_ORDER = [EV_ON_DISK, EV_FILE_PATTERN, EV_PERSISTENCE, EV_CONTACTED, EV_DNS, EV_ATTEMPTED,
EV_CONFIGURED, EV_REFERENCED]
# Everything except `referenced` is a finding that needs a person to look at it.
diff --git a/scan/tests/test_pattern_integration.py b/scan/tests/test_pattern_integration.py
new file mode 100644
index 0000000..b54ac46
--- /dev/null
+++ b/scan/tests/test_pattern_integration.py
@@ -0,0 +1,175 @@
+"""Optional pattern feature stays opt-in and keeps reports honest in both CLIs.
+
+All scan modules are redirected to fixtures; no personal data or live malware.
+"""
+import contextlib
+import datetime
+import importlib.util
+import io
+import hashlib
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from adint_scan import cli, report
+from adint_scan.context import ScanContext
+from adint_scan.iocs import load
+from adint_scan.modules import browser, hashscan, host, patternscan
+from adint_scan.result import Hit, ModuleResult, EV_FILE_PATTERN
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+class PatternIntegration(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.build_dir = tempfile.TemporaryDirectory(prefix="zb_pattern_bundle_")
+ output = Path(cls.build_dir.name) / "candidate.py"
+ subprocess.run([sys.executable, "-B", str(ROOT / "build/bundle.py"),
+ str(ROOT), str(output)], check=True, capture_output=True)
+ spec = importlib.util.spec_from_file_location("_pattern_bundle", output)
+ cls.bundle = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = cls.bundle
+ spec.loader.exec_module(cls.bundle)
+
+ @classmethod
+ def tearDownClass(cls):
+ sys.modules.pop("_pattern_bundle", None)
+ cls.build_dir.cleanup()
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="zb_pattern_integration_")
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.feed = self.root / "iocs.txt"
+ self.feed.write_text("# as-of: 2026-10-19\nunused.invalid\tdelivery\tprimary\tfixture\n",
+ encoding="utf-8")
+
+ def run_cli(self, bundled, extra, patterns):
+ documents = []
+ target = self.bundle if bundled else cli
+
+ def empty(name):
+ def run(ctx):
+ result = target.ModuleResult(name)
+ result.ran("fixture")
+ return result
+ return run
+
+ with contextlib.ExitStack() as stack:
+ if bundled:
+ for name in ("browser", "hash", "host"):
+ stack.enter_context(patch.object(target, "run_" + name, empty(name)))
+ stack.enter_context(patch.object(target, "run_patterns", patterns))
+ else:
+ for mod in (browser, hashscan, host):
+ stack.enter_context(patch.object(mod, "run", empty(mod.NAME)))
+ stack.enter_context(patch.object(patternscan, "run", patterns))
+ stack.enter_context(patch.object(target, "_force_utf8_io", lambda: None))
+ stack.enter_context(patch.object(target, "render_human",
+ lambda d: documents.append(d) or ""))
+ stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
+ stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
+ args = ["--iocs", str(self.feed)] + extra
+ if bundled:
+ args.append("--no-pause")
+ code = target.main(args)
+ return code, documents[0]
+
+ def test_default_does_not_run_pattern_engine(self):
+ def forbidden(ctx):
+ self.fail("optional pattern check ran without --patterns")
+ for bundled in (False, True):
+ with self.subTest(bundled=bundled):
+ code, doc = self.run_cli(bundled, [], forbidden)
+ self.assertEqual(code, 0)
+ self.assertNotIn("patterns", doc["modules"])
+
+ def test_explicit_patterns_runs_with_quick_and_paths(self):
+ for bundled in (False, True):
+ target = self.bundle if bundled else cli
+ def selected(ctx):
+ self.assertTrue(ctx.patterns)
+ self.assertEqual(ctx.pattern_paths, (str(self.root),))
+ r = target.ModuleResult("patterns")
+ r.could_not_run("engine", "fixture engine unavailable")
+ return r
+ with self.subTest(bundled=bundled):
+ code, doc = self.run_cli(bundled,
+ ["--quick", "--patterns", "--pattern-path", str(self.root)], selected)
+ self.assertEqual(code, 0)
+ self.assertEqual(doc["modules"]["patterns"]["status"], "UNKNOWN")
+ self.assertEqual(doc["verdict"]["status"], "NO_KNOWN_INDICATORS_WITH_GAPS")
+ self.assertTrue(any("engine unavailable" in g for g in doc["verdict"]["gaps"]))
+
+ def test_failure_preserves_pattern_hit_and_gap(self):
+ for bundled in (False, True):
+ target = self.bundle if bundled else cli
+ hit_type = self.bundle.Hit if bundled else Hit
+ def interrupted(ctx):
+ r = target.ModuleResult("patterns")
+ ctx.partial = r
+ r.add_hit(hit_type("yara:fixture", str(self.root / "data"), "fixture",
+ tier="candiru-pattern", evidence=EV_FILE_PATTERN))
+ raise ValueError("fixture late failure")
+ with self.subTest(bundled=bundled):
+ code, doc = self.run_cli(bundled, ["--patterns"], interrupted)
+ self.assertEqual(code, 2)
+ self.assertEqual(doc["verdict"]["hits_total"], 1)
+ self.assertTrue(any("late failure" in g for g in doc["verdict"]["gaps"]))
+
+ def test_pattern_report_does_not_claim_exact_sample_or_infection(self):
+ r = ModuleResult("patterns")
+ r.ran("fixture")
+ r.add_hit(Hit("yara:MAL_DevilsTongue_HijackDll", str(self.root / "data"),
+ "Author: Microsoft Threat Intelligence Center (MSTIC)",
+ tier="candiru-pattern", evidence=EV_FILE_PATTERN,
+ source="https://example.org/research"))
+ doc = report.build_document(load(str(self.feed)), [r], datetime.datetime.now())
+ text = " ".join(report.render_human(doc).split())
+ self.assertIn("A FILE MATCHED A CANDIRU DETECTION RULE", text)
+ self.assertIn("pattern match alone does not prove infection", text)
+ self.assertIn("Microsoft Threat Intelligence Center", text)
+ self.assertNotIn("A KNOWN SPYWARE FILE IS ON THIS MACHINE", text)
+ self.assertEqual(doc["verdict"]["status"], "INDICATORS_FOUND")
+
+ def test_pattern_path_requires_opt_in(self):
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as err:
+ cli._parse(["--pattern-path", str(self.root)])
+ self.assertEqual(err.exception.code, 2)
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as err:
+ self.bundle.main(["--pattern-path", str(self.root), "--no-pause"])
+ self.assertEqual(err.exception.code, 2)
+
+ @unittest.skipUnless(importlib.util.find_spec("yara_x"), "optional YARA-X not installed")
+ def test_actual_rules_through_both_entrypoints_preserve_fixture_bytes(self):
+ from test_patterns import synthetic_mstic_fixture, synthetic_malpedia_fixture
+ fixtures = (("mstic", synthetic_mstic_fixture(), "MAL_DevilsTongue_HijackDll"),
+ ("malpedia", synthetic_malpedia_fixture(), "win_devilstongue_auto"),
+ ("ordinary", b"ordinary harmless local document", None))
+ for bundled in (False, True):
+ target = self.bundle.run_patterns if bundled else patternscan.run
+ for name, data, rule in fixtures:
+ with self.subTest(bundled=bundled, fixture=name):
+ path = self.root / name
+ path.write_bytes(data)
+ before = hashlib.sha256(path.read_bytes()).hexdigest()
+ code, doc = self.run_cli(bundled,
+ ["--quick", "--patterns", "--pattern-path", str(path)], target)
+ matches = doc["modules"]["patterns"]["hits"]
+ self.assertEqual(code, 2 if rule else 0)
+ self.assertEqual({h["indicator"] for h in matches},
+ {"yara:" + rule} if rule else set())
+ self.assertEqual(doc["modules"]["patterns"]["checked"], 1)
+ self.assertEqual(before, hashlib.sha256(path.read_bytes()).hexdigest())
+ for hit in matches:
+ self.assertEqual(hit["evidence"], "file-pattern")
+ self.assertIn("author:", hit["detail"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scan/tests/test_patterns.py b/scan/tests/test_patterns.py
new file mode 100644
index 0000000..4ff98c9
--- /dev/null
+++ b/scan/tests/test_patterns.py
@@ -0,0 +1,630 @@
+"""Hermetic patterns tests: harmless bytes, temporary trees, no live artifacts.
+
+Real-engine positives exercise rule mechanics on assembled test byte fragments.
+They do not validate detection against authentic spyware or its variants.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import struct
+import sys
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from adint_scan.modules import patternscan as patterns
+from adint_scan.candiru_rules import (CANDIRU_RULE_METADATA, CANDIRU_RULE_SOURCES,
+ CANDIRU_ENGINE_VERSION)
+from adint_scan.result import CLEAN, HITS, PARTIAL, UNKNOWN
+
+
+def synthetic_malpedia_fixture():
+ """Artificial public-pattern fragments, not an authentic malware sample."""
+ sequences = re.findall(r"\$sequence_\d+ = \{ ([^}]+) \}", CANDIRU_RULE_SOURCES[1])
+ data = b"Harmless synthetic rule-mechanics fixture; never execute.\n"
+ for sequence in sequences[:7]:
+ data += bytes.fromhex(sequence.replace("?", "0")) + b"\x90" * 32
+ return data
+
+
+def synthetic_mstic_fixture():
+ """Data-only DLL header and strings, zero entry point, no code sections."""
+ data = bytearray(512)
+ data[:2] = b"MZ"
+ struct.pack_into("<I", data, 0x3c, 0x80)
+ data[0x80:0x84] = b"PE\x00\x00"
+ struct.pack_into("<HHIIIHH", data, 0x84, 0x8664, 0, 0, 0, 0, 240, 0x2022)
+ struct.pack_into("<H", data, 0x98, 0x20b)
+ data += (b"Harmless synthetic headers, no executable sections.\x00"
+ b"NtQueryInformationThread\x00StackWalk64\x00ConvertSidToStringSidW\x00SMNew.dll\x00")
+ return bytes(data)
+
+
+class PatternTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(prefix="candiru_patterns_test_")
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.messages = []
+ self.ctx = SimpleNamespace(pattern_paths=(str(self.root),),
+ emit=self.messages.append, partial=None)
+ self.scanner = Mock()
+ self.scanner.scan.return_value = SimpleNamespace(matching_rules=[])
+
+ def file(self, name="extensionless", data=b"harmless test bytes"):
+ target = self.root / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(data)
+ return target
+
+ def run_mock(self):
+ with patch.object(patterns, "_pattern_engine", return_value=self.scanner):
+ return patterns.run(self.ctx)
+
+ def counted_scandir(self, mode, total=1000, name="extensionless"):
+ """A wide lazy iterator that records requests and classification work."""
+ class Entries:
+ requested = 0
+ closed = False
+ classified = []
+
+ def __enter__(entries):
+ return entries
+
+ def __exit__(entries, *_args):
+ entries.closed = True
+
+ def __iter__(entries):
+ return entries
+
+ def __next__(entries):
+ entries.requested += 1
+ if entries.requested > total:
+ raise StopIteration
+ entry = SimpleNamespace(name=name, path=str(self.root / name),
+ stat=Mock(return_value=SimpleNamespace(st_mode=mode,
+ st_file_attributes=0)))
+ entries.classified.append(entry.stat)
+ return entry
+
+ return Entries()
+
+ def test_extensionless_miss_and_partial_recovery(self):
+ self.file()
+ result = self.run_mock()
+ self.assertEqual(result.status, CLEAN)
+ self.assertEqual(result.checked, 1)
+ self.assertIs(self.ctx.partial, result)
+ self.scanner.scan.assert_called_once_with(b"harmless test bytes")
+
+ def test_file_path_and_attribution(self):
+ target = self.file(data=b"harmless mock match")
+ self.ctx.pattern_paths = (str(target),)
+ self.scanner.scan.return_value.matching_rules = [
+ SimpleNamespace(identifier=name) for name in CANDIRU_RULE_METADATA]
+ result = self.run_mock()
+ self.assertEqual(result.status, HITS)
+ self.assertEqual(len(result.hits), 2)
+ for hit, metadata in zip(result.hits, CANDIRU_RULE_METADATA.values()):
+ self.assertEqual(hit.evidence, "file-pattern")
+ self.assertEqual(hit.tier, "candiru-pattern")
+ self.assertEqual(hit.confidence, "research-rule")
+ self.assertEqual(hit.source, metadata["source"])
+ self.assertIn(metadata["author"], hit.detail)
+ self.assertIn(metadata["license"], hit.detail)
+ self.assertIn("not an exact sample", hit.detail)
+ self.assertIn("confirmed infection", hit.detail)
+ self.assertTrue(any(metadata["author"] in msg for msg in self.messages))
+
+ def test_missing_dependency_is_unknown(self):
+ with patch.object(patterns._pattern_importlib, "import_module",
+ side_effect=ModuleNotFoundError("no yara_x")):
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("optional pinned yara-x", " ".join(result.notes))
+
+ def test_old_python_is_unknown_without_import(self):
+ with patch.object(patterns._pattern_sys, "version_info", (3, 8)), \
+ patch.object(patterns._pattern_importlib, "import_module") as imported:
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("Python 3.9", " ".join(result.notes))
+ imported.assert_not_called()
+
+ def test_engine_uses_trusted_sources_disabled_includes_timeout(self):
+ engine = Mock()
+ metadata = SimpleNamespace(version=lambda name: CANDIRU_ENGINE_VERSION)
+ with patch.object(patterns._pattern_importlib, "import_module",
+ side_effect=[engine, metadata]):
+ scanner = patterns._pattern_engine()
+ engine.Compiler.return_value.enable_includes.assert_called_once_with(False)
+ self.assertEqual(engine.Compiler.return_value.add_source.call_count, 2)
+ self.assertEqual([c.args[0] for c in engine.Compiler.return_value.add_source.call_args_list],
+ list(CANDIRU_RULE_SOURCES))
+ scanner.set_timeout.assert_called_once_with(5)
+
+ def test_wrong_engine_version_is_unknown(self):
+ with patch.object(patterns._pattern_importlib, "import_module", side_effect=[
+ Mock(), SimpleNamespace(version=lambda name: "0.0.0")]):
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("unsupported yara-x version", " ".join(result.notes))
+
+ def test_compile_failure_is_unknown(self):
+ engine = Mock()
+ engine.Compiler.return_value.add_source.side_effect = ValueError("compile failed")
+ with patch.object(patterns._pattern_importlib, "import_module", side_effect=[
+ engine, SimpleNamespace(version=lambda name: CANDIRU_ENGINE_VERSION)]):
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("compile failed", " ".join(result.notes))
+
+ def test_scan_error_or_timeout_is_gap(self):
+ self.file()
+ for error in (RuntimeError("scan failed"), TimeoutError("5 seconds")):
+ with self.subTest(error=error):
+ self.scanner.scan.side_effect = error
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(result.checked, 0)
+ self.assertEqual(result.skipped, 1)
+ self.assertIn(type(error).__name__, " ".join(result.notes))
+
+ def test_unknown_rule_cannot_be_reported_as_clean_or_trusted(self):
+ self.file()
+ self.scanner.scan.return_value.matching_rules = [SimpleNamespace(identifier="untrusted")]
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertFalse(result.hits)
+ self.assertIn("unknown rule identifier", " ".join(result.notes))
+
+ def test_read_error_after_success_is_partial(self):
+ self.file("good")
+ self.file("bad")
+ original = patterns._pattern_read
+ with patch.object(patterns, "_pattern_read", side_effect=lambda path:
+ original(path) if Path(path).name == "good" else
+ (_ for _ in ()).throw(PermissionError("locked"))):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.skipped, 1)
+
+ def test_oversized_is_not_opened(self):
+ self.file(data=b"X" * (patterns._PATTERN_MAX_BYTES + 1))
+ with patch.object(patterns._pattern_os, "open") as opened:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("1 MiB", " ".join(result.notes))
+ opened.assert_not_called()
+
+ def test_preflight_rejection_is_distinct_from_unknown_read_failure(self):
+ target = self.file(data=b"X" * (patterns._PATTERN_MAX_BYTES + 1))
+ with self.assertRaises(patterns._PatternNoRead):
+ patterns._pattern_read(str(target))
+
+ def test_stream_read_error_cannot_be_marked_as_no_read(self):
+ target = self.file()
+ real_open = patterns._pattern_io.open
+ class FailingRead:
+ def __init__(stream, *args, **kwargs):
+ stream.inner = real_open(*args, **kwargs)
+
+ def __enter__(stream):
+ return stream
+
+ def __exit__(stream, *_args):
+ stream.inner.close()
+
+ def fileno(stream):
+ return stream.inner.fileno()
+
+ def read(stream, amount):
+ raise OSError("read failed after it began")
+
+ with patch.object(patterns._pattern_io, "open", side_effect=FailingRead):
+ with self.assertRaises(OSError) as caught:
+ patterns._pattern_read(str(target))
+ self.assertNotIsInstance(caught.exception, patterns._PatternNoRead)
+
+ def test_exact_cap_read_is_bounded(self):
+ target = self.file(data=b"X" * patterns._PATTERN_MAX_BYTES)
+ self.assertEqual(len(patterns._pattern_read(str(target))), patterns._PATTERN_MAX_BYTES)
+
+ def test_missing_and_empty_requested_roots_are_unknown(self):
+ for path in (self.root / "absent", self.root):
+ with self.subTest(path=path):
+ self.ctx.pattern_paths = (str(path),)
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(result.checked, 0)
+
+ def test_no_roots_is_unknown(self):
+ self.ctx.pattern_paths = ()
+ with patch.object(patterns, "_pattern_roots", return_value=[]):
+ self.assertEqual(self.run_mock().status, UNKNOWN)
+
+ def test_default_roots_use_hash_roots(self):
+ self.ctx.pattern_paths = ()
+ self.file()
+ with patch.object(patterns, "_pattern_roots", return_value=[str(self.root)]) as roots:
+ result = self.run_mock()
+ roots.assert_called_once_with()
+ self.assertEqual(result.checked, 1)
+
+ def test_overlapping_roots_do_not_duplicate_files(self):
+ target = self.file("nested/extensionless")
+ self.ctx.pattern_paths = (str(target), str(target.parent), str(self.root), str(self.root))
+ result = self.run_mock()
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(self.scanner.scan.call_count, 1)
+ self.assertEqual(result.status, CLEAN)
+
+ def test_explicit_child_under_pruned_parent_is_still_scanned(self):
+ ordinary = self.file("ordinary")
+ wanted = self.file("cache/wanted", synthetic_malpedia_fixture())
+ self.ctx.pattern_paths = (str(self.root), str(wanted))
+ self.scanner.scan.side_effect = lambda data: SimpleNamespace(matching_rules=(
+ [SimpleNamespace(identifier="win_devilstongue_auto")]
+ if data == wanted.read_bytes() else []))
+ result = self.run_mock()
+ self.assertEqual(result.checked, 2)
+ self.assertEqual([hit.location for hit in result.hits], [str(wanted)])
+ self.assertEqual(result.status, HITS)
+
+ def test_relative_and_traversal_roots_refused(self):
+ for root in ("relative", str(self.root) + os.sep + ".." + os.sep + self.root.name):
+ with self.subTest(root=root):
+ self.ctx.pattern_paths = (root,)
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.scanner.scan.assert_not_called()
+
+ def test_remote_roots_refused_without_read(self):
+ self.ctx.pattern_paths = (r"\\server.invalid\share\file",)
+ with patch.object(patterns, "_pattern_read") as reader:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ reader.assert_not_called()
+
+ def test_symlink_and_reparse_are_refused(self):
+ target = self.file()
+ actual = os.lstat(target)
+ fake = SimpleNamespace(**{name: getattr(actual, name) for name in
+ ("st_dev", "st_ino", "st_size", "st_mtime", "st_ctime")},
+ st_mode=actual.st_mode, st_file_attributes=0x400)
+ original = patterns._pattern_os.lstat
+ with patch.object(patterns._pattern_os, "lstat", side_effect=lambda path:
+ fake if os.fspath(path) == str(target) else original(path)):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(result.skipped, 1)
+ self.scanner.scan.assert_not_called()
+
+ def test_real_symlink_if_platform_allows(self):
+ target = self.file()
+ link = self.root / "link"
+ try:
+ link.symlink_to(target)
+ except OSError:
+ self.skipTest("creating symlinks requires privileges on this Windows host")
+ self.ctx.pattern_paths = (str(link),)
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.scanner.scan.assert_not_called()
+
+ def test_cloud_recall_file_refused_before_open(self):
+ target = self.file()
+ actual = os.lstat(target)
+ for attribute in (0x1000, 0x40000, 0x400000):
+ fake = SimpleNamespace(st_mode=actual.st_mode, st_file_attributes=attribute)
+ original = patterns._pattern_os.lstat
+ self.ctx.pattern_paths = (str(target),)
+ with self.subTest(attribute=attribute), \
+ patch.object(patterns._pattern_os, "lstat", side_effect=lambda path:
+ fake if os.fspath(path) == str(target) else original(path)), \
+ patch.object(patterns._pattern_os, "open") as opened:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ opened.assert_not_called()
+
+ def test_special_file_refused(self):
+ target = self.file()
+ with patch.object(patterns._pattern_stat, "S_ISREG", return_value=False), \
+ patch.object(patterns._pattern_stat, "S_ISDIR", return_value=False), \
+ patch.object(patterns._pattern_os, "open") as opened:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ opened.assert_not_called()
+
+ def test_changed_file_before_read_is_gap(self):
+ self.file()
+ original = patterns._pattern_os.fstat
+ def changed(fd):
+ info = original(fd)
+ return SimpleNamespace(st_mode=info.st_mode, st_dev=info.st_dev,
+ st_ino=info.st_ino, st_size=info.st_size + 1,
+ st_mtime=info.st_mtime, st_ctime=info.st_ctime,
+ st_mtime_ns=info.st_mtime_ns, st_ctime_ns=info.st_ctime_ns)
+ with patch.object(patterns._pattern_os, "fstat", side_effect=changed):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("changed before", " ".join(result.notes))
+
+ def test_changed_file_after_read_is_gap(self):
+ self.file()
+ original = patterns._pattern_os.fstat
+ calls = []
+ def changed(fd):
+ info = original(fd)
+ calls.append(fd)
+ if len(calls) == 1:
+ return info
+ return SimpleNamespace(st_mode=info.st_mode, st_dev=info.st_dev,
+ st_ino=info.st_ino, st_size=info.st_size,
+ st_mtime=info.st_mtime, st_ctime=info.st_ctime,
+ st_mtime_ns=info.st_mtime_ns + 1,
+ st_ctime_ns=info.st_ctime_ns)
+ with patch.object(patterns._pattern_os, "fstat", side_effect=changed):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("grew or changed", " ".join(result.notes))
+ self.scanner.scan.assert_not_called()
+
+ def test_unreadable_subtree_is_gap(self):
+ self.file()
+ denied = self.root / "denied"
+ denied.mkdir()
+ original = patterns._pattern_os.scandir
+ def unreadable_scandir(root):
+ if os.fspath(root) == str(denied):
+ raise PermissionError(13, "subtree denied", str(denied))
+ return original(root)
+ with patch.object(patterns._pattern_os, "scandir", side_effect=unreadable_scandir):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.skipped, 1)
+
+ def test_grown_file_read_is_bounded_and_discarded(self):
+ target = self.file()
+ stream = Mock()
+ stream.__enter__ = Mock(return_value=stream)
+ stream.__exit__ = Mock(return_value=False)
+ stream.read.return_value = b"X" * (patterns._PATTERN_MAX_BYTES + 1)
+ with open(target, "rb") as real:
+ stream.fileno.return_value = real.fileno()
+ original_open = patterns._pattern_os.open
+ descriptors = []
+ def tracked_open(*args):
+ fd = original_open(*args)
+ descriptors.append(fd)
+ return fd
+ try:
+ with patch.object(patterns._pattern_io, "open", return_value=stream), \
+ patch.object(patterns._pattern_os, "open", side_effect=tracked_open):
+ result = self.run_mock()
+ finally:
+ for fd in descriptors:
+ os.close(fd)
+ stream.read.assert_called_once_with(patterns._PATTERN_MAX_BYTES + 1)
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertIn("grew or changed", " ".join(result.notes))
+
+ def test_pruned_directories_are_disclosed(self):
+ self.file("safe")
+ self.file("node_modules/ignored")
+ result = self.run_mock()
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.submetrics["directories_pruned"], 1)
+ self.assertIn("node_modules", " ".join(result.notes))
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.skipped, 1)
+
+ def test_unscanned_hit_under_pruned_directory_cannot_report_clean(self):
+ self.file("safe")
+ self.file("cache/unscanned-hit", synthetic_malpedia_fixture())
+ result = self.run_mock()
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.hits, [])
+ self.assertEqual(result.status, PARTIAL)
+ self.assertIn("cache", " ".join(result.notes))
+
+ def test_file_cap_partial_and_stops(self):
+ self.file("a")
+ self.file("b")
+ with patch.object(patterns, "_PATTERN_MAX_FILES", 1):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+ self.assertIn("cap reached", " ".join(result.notes))
+
+ def test_wide_folder_file_cap_stops_before_next_entry_or_stat(self):
+ self.file()
+ entries = self.counted_scandir(patterns._pattern_stat.S_IFREG)
+ with patch.object(patterns._pattern_os, "scandir", return_value=entries), \
+ patch.object(patterns, "_PATTERN_MAX_FILES", 1):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(entries.requested, 1)
+ self.assertEqual(sum(stat.call_count for stat in entries.classified), 1)
+ self.assertTrue(entries.closed)
+
+ def test_wide_refused_folder_entry_cap_bounds_metadata_and_gap_count(self):
+ entries = self.counted_scandir(patterns._pattern_stat.S_IFLNK)
+ with patch.object(patterns._pattern_os, "scandir", return_value=entries), \
+ patch.object(patterns, "_PATTERN_MAX_ENTRIES", 3), \
+ patch.object(patterns, "_pattern_problem", wraps=patterns._pattern_problem) as cloud:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(result.skipped, 3)
+ self.assertEqual(entries.requested, 3)
+ self.assertEqual(sum(stat.call_count for stat in entries.classified), 3)
+ self.assertEqual(result.submetrics["filesystem_entries_considered"], 3)
+ self.assertEqual(cloud.call_count, 2) # requested root and traversal root only
+ self.assertTrue(entries.closed)
+ self.scanner.scan.assert_not_called()
+
+ def test_wide_pruned_folder_entries_are_charged_before_pruning(self):
+ entries = self.counted_scandir(patterns._pattern_stat.S_IFDIR, name="cache")
+ with patch.object(patterns._pattern_os, "scandir", return_value=entries) as opened, \
+ patch.object(patterns, "_PATTERN_MAX_ENTRIES", 4):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(entries.requested, 4)
+ self.assertEqual(result.submetrics["directories_pruned"], 4)
+ opened.assert_called_once_with(str(self.root))
+ self.assertTrue(entries.closed)
+
+ def test_wide_directories_do_not_accumulate_pending_paths(self):
+ entries = self.counted_scandir(patterns._pattern_stat.S_IFDIR, name="child")
+ with patch.object(patterns._pattern_os, "scandir", return_value=entries) as opened, \
+ patch.object(patterns, "_PATTERN_MAX_DIRS", 1), \
+ patch.object(patterns, "_pattern_problem", wraps=patterns._pattern_problem) as cloud:
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(entries.requested, 1)
+ self.assertEqual(sum(stat.call_count for stat in entries.classified), 1)
+ self.assertEqual(cloud.call_count, 2)
+ opened.assert_called_once_with(str(self.root))
+ self.assertTrue(entries.closed)
+
+ def test_depth_cap_closes_all_streaming_iterators(self):
+ self.file("a/b/c/target")
+ real = patterns._pattern_os.scandir
+ opened = []
+ class Tracked:
+ def __init__(tracked, path):
+ tracked.inner = real(path)
+ tracked.closed = False
+ opened.append(tracked)
+
+ def __enter__(tracked):
+ return tracked.inner
+
+ def __exit__(tracked, *_args):
+ tracked.inner.close()
+ tracked.closed = True
+
+ with patch.object(patterns._pattern_os, "scandir", side_effect=Tracked), \
+ patch.object(patterns, "_PATTERN_MAX_DEPTH", 3):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(len(opened), 3)
+ self.assertTrue(all(entries.closed for entries in opened))
+ self.assertIn("depth cap reached", " ".join(result.notes))
+
+ def test_failed_reads_still_consume_total_byte_budget(self):
+ self.file("a")
+ self.file("b")
+ with patch.object(patterns, "_pattern_read", side_effect=OSError("file changed")) as reader, \
+ patch.object(patterns, "_PATTERN_MAX_TOTAL_BYTES", patterns._PATTERN_MAX_BYTES + 1):
+ result = self.run_mock()
+ self.assertEqual(result.status, UNKNOWN)
+ self.assertEqual(result.skipped, 1)
+ self.assertEqual(reader.call_count, 1)
+ self.assertIn("byte cap reached", " ".join(result.notes))
+
+ def test_directory_cap_partial_and_stops(self):
+ first = self.file("a")
+ self.file("nested/b")
+ # Complete one explicit file root before walking the directory. Native
+ # scandir order is unspecified; encountering nested first must not turn
+ # this test into an assumption that root files are enumerated first.
+ self.ctx.pattern_paths = (str(first), str(self.root))
+ with patch.object(patterns, "_PATTERN_MAX_DIRS", 1):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.submetrics["directories_pattern_visited"], 1)
+ self.assertTrue(any(check.name == "pattern-limits" and
+ "directory cap reached" in check.reason
+ for check in result.checks))
+
+ def test_total_byte_cap_partial(self):
+ self.file("a", b"A" * patterns._PATTERN_MAX_BYTES)
+ self.file("b", b"B")
+ with patch.object(patterns, "_PATTERN_MAX_TOTAL_BYTES", patterns._PATTERN_MAX_BYTES + 1):
+ result = self.run_mock()
+ self.assertEqual(result.status, PARTIAL)
+ self.assertEqual(result.checked, 1)
+
+ def test_error_notes_are_bounded(self):
+ for number in range(30):
+ self.file(str(number))
+ with patch.object(patterns, "_pattern_read", side_effect=PermissionError("locked")):
+ result = self.run_mock()
+ self.assertEqual(result.skipped, 30)
+ self.assertEqual(sum("Pattern file skipped" in note for note in result.notes), 10)
+
+ def test_embedded_sources_are_verbatim_and_hashed(self):
+ base = Path(__file__).resolve().parents[2] / "third_party" / "candiru"
+ provenance = json.loads((base / "PROVENANCE.json").read_text(encoding="utf-8"))
+ for source, metadata in zip(CANDIRU_RULE_SOURCES, CANDIRU_RULE_METADATA.values()):
+ raw = (base / metadata["filename"]).read_bytes()
+ self.assertEqual(source.encode("utf-8"), raw)
+ self.assertEqual(hashlib.sha256(raw).hexdigest(),
+ provenance["files_sha256"][metadata["filename"]])
+ self.assertIn(metadata["author"], source)
+ self.assertIn("malpedia_license = \"CC BY-SA 4.0\"", CANDIRU_RULE_SOURCES[1])
+
+
[email protected](importlib.util.find_spec("yara_x"), "optional yara-x is absent")
+class RealEnginePatternTests(unittest.TestCase):
+ setUp = PatternTests.setUp
+ file = PatternTests.file
+
+ def test_real_engine_misses_harmless_file(self):
+ self.file(data=b"Synthetic harmless text. No malware or executable content.")
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.status, CLEAN, result.notes)
+ self.assertEqual(result.checked, 1)
+
+ def test_real_malpedia_pattern_fragments_extensionless(self):
+ # Deliberately artificial concatenation of seven public hex patterns.
+ self.file(data=synthetic_malpedia_fixture())
+ result = patterns.run(self.ctx)
+ self.assertEqual([hit.indicator for hit in result.hits], ["yara:win_devilstongue_auto"])
+
+ def test_real_mstic_strings_in_synthetic_pe_header(self):
+ # Minimal artificial DLL headers + four strings; no executable section.
+ self.file("synthetic.dll", synthetic_mstic_fixture())
+ result = patterns.run(self.ctx)
+ self.assertEqual([hit.indicator for hit in result.hits], ["yara:MAL_DevilsTongue_HijackDll"], result.notes)
+
+ def test_real_explicit_pattern_blob_survives_parent_pruning(self):
+ self.file("ordinary", b"harmless text")
+ wanted = self.file("cache/wanted", synthetic_malpedia_fixture())
+ self.ctx.pattern_paths = (str(self.root), str(wanted))
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.checked, 2)
+ self.assertEqual([hit.location for hit in result.hits], [str(wanted)])
+ self.assertEqual([hit.indicator for hit in result.hits], ["yara:win_devilstongue_auto"])
+
+ def test_300_oversized_files_do_not_exhaust_data_read_budget(self):
+ # Sparse temporary test files: metadata says >1 MiB, no contents read.
+ for number in range(300):
+ with (self.root / ("oversized_{:03d}".format(number))).open("wb") as stream:
+ stream.truncate(patterns._PATTERN_MAX_BYTES + 1)
+ wanted = self.file("wanted", synthetic_malpedia_fixture())
+ result = patterns.run(self.ctx)
+ self.assertEqual(result.checked, 1)
+ self.assertEqual(result.skipped, 300)
+ self.assertEqual(result.submetrics["filesystem_entries_considered"], 301)
+ self.assertEqual([hit.location for hit in result.hits], [str(wanted)])
+ self.assertEqual([hit.indicator for hit in result.hits], ["yara:win_devilstongue_auto"])
+ self.assertFalse(any(check.name == "pattern-limits" for check in result.checks))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/third_party/candiru/.gitattributes b/third_party/candiru/.gitattributes
new file mode 100644
index 0000000..7f88ae1
--- /dev/null
+++ b/third_party/candiru/.gitattributes
@@ -0,0 +1,3 @@
+# Preserve the exact retrieved textual bytes recorded in PROVENANCE.json.
+*.yar -text
+LICENSE-*.txt -text
diff --git a/third_party/candiru/LICENSE-CC-BY-SA-4.0.txt b/third_party/candiru/LICENSE-CC-BY-SA-4.0.txt
new file mode 100644
index 0000000..624cc2b
--- /dev/null
+++ b/third_party/candiru/LICENSE-CC-BY-SA-4.0.txt
@@ -0,0 +1,7 @@
+win_devilstongue_auto is licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0).
+Author: Felix Bilstein - yara-signator at cocacoding dot com
+Original: https://malpedia.caad.fkie.fraunhofer.de/details/win.devilstongue
+License text: https://creativecommons.org/licenses/by-sa/4.0/legalcode
+License overview: https://creativecommons.org/licenses/by-sa/4.0/
+Rule retained unchanged, including its disclaimer and attribution. No endorsement is implied.
+The rule's separate third-party license applies to its verbatim embedded copy as well.
diff --git a/third_party/candiru/LICENSE-DRL-1.1.txt b/third_party/candiru/LICENSE-DRL-1.1.txt
new file mode 100644
index 0000000..a2486e6
--- /dev/null
+++ b/third_party/candiru/LICENSE-DRL-1.1.txt
@@ -0,0 +1,38 @@
+# Detection Rule License (DRL) 1.1
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this rule set and associated documentation files (the "Rules"), to deal
+in the Rules without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Rules, and to permit persons to whom the Rules are furnished to do so,
+subject to the following conditions:
+
+If you share the Rules (including in modified form), you must retain the
+following if it is supplied within the Rules:
+
+1. identification of the authors(s) ("author" field) of the Rule and any
+ others designated to receive attribution, in any reasonable manner
+ requested by the Rule author (including by pseudonym if designated).
+
+2. a URI or hyperlink to the Rule set or explicit Rule to the extent
+ reasonably practicable
+
+3. indicate the Rules are licensed under this Detection Rule License, and
+ include the text of, or the URI or hyperlink to, this Detection Rule
+ License to the extent reasonably practicable
+
+If you use the Rules (including in modified form) on data, messages based on
+matches with the Rules must retain the following if it is supplied within the
+Rules:
+
+1. identification of the authors(s) ("author" field) of the Rule and any
+ others designated to receive attribution, in any reasonable manner
+ requested by the Rule author (including by pseudonym if designated).
+
+THE RULES ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE RULES OR THE USE OR OTHER DEALINGS IN THE
+RULES.
diff --git a/third_party/candiru/PROVENANCE.json b/third_party/candiru/PROVENANCE.json
new file mode 100644
index 0000000..c931274
--- /dev/null
+++ b/third_party/candiru/PROVENANCE.json
@@ -0,0 +1,31 @@
+{
+ "retrieved_utc": "2026-10-19T10:05:38.569504+00:00",
+ "scope": "Only public textual rules and license text retrieved. No samples, binaries, download-all endpoints or sample links fetched.",
+ "modifications": "Rules unchanged; Malpedia HTML entities decoded to displayed rule text. Original line endings retained in vendored bytes. Embedded strings are identical when UTF-8 encoded.",
+ "license_delivery": "DRL text reproduced; CC BY-SA 4.0 legalcode and overview hyperlinks supplied with author and original source in license notice.",
+ "malpedia_page_sha256": "a6edd8cebc4c4cbbeacf5f2566195c96a831a4d8f3497369f6ece3818db1c9a1",
+ "rules": [
+ {
+ "identifier": "MAL_DevilsTongue_HijackDll",
+ "author": "Microsoft Threat Intelligence Center (MSTIC)",
+ "license": "DRL 1.1",
+ "license_url": "https://raw.githubusercontent.com/Neo23x0/signature-base/master/LICENSE",
+ "source": "https://raw.githubusercontent.com/Neo23x0/signature-base/master/yara/apt_candiru.yar",
+ "filename": "apt_candiru.yar"
+ },
+ {
+ "identifier": "win_devilstongue_auto",
+ "author": "Felix Bilstein - yara-signator at cocacoding dot com",
+ "license": "CC BY-SA 4.0",
+ "license_url": "https://creativecommons.org/licenses/by-sa/4.0/",
+ "source": "https://malpedia.caad.fkie.fraunhofer.de/details/win.devilstongue",
+ "filename": "win_devilstongue_auto.yar"
+ }
+ ],
+ "files_sha256": {
+ "apt_candiru.yar": "1a298e8d5cd766334da384ab4b06bccec2c8020c3d8dbb68eba159cab755307d",
+ "win_devilstongue_auto.yar": "1daaf0ceaa7d21b12869bc60492a9e089c6504be2ac26ddc508d25107e45fcb5",
+ "LICENSE-DRL-1.1.txt": "8a959b2413d0c83ca1b3ce9153076c649abf2e4bbfebbb493fb24c2074a1eb8a",
+ "LICENSE-CC-BY-SA-4.0.txt": "b013f21a44956c6d717f211990b450aeaa4d7266da4614ab8c386b479565296e"
+ }
+}
diff --git a/third_party/candiru/README.md b/third_party/candiru/README.md
new file mode 100644
index 0000000..7cd22d1
--- /dev/null
+++ b/third_party/candiru/README.md
@@ -0,0 +1,25 @@
+These are pinned public textual research rules, not malware samples.
+
+`apt_candiru.yar` is the unchanged signature-base rule by Microsoft Threat
+Intelligence Center (MSTIC), under Detection Rule License 1.1. Its license text
+is in `LICENSE-DRL-1.1.txt`. Match messages retain its author attribution.
+
+`win_devilstongue_auto.yar` is the unchanged displayed Malpedia rule by Felix
+Bilstein, licensed CC BY-SA 4.0. `LICENSE-CC-BY-SA-4.0.txt` provides attribution,
+the original source, and links to the license and legal text. HTML entities
+were decoded to reproduce the displayed rule. Its disclaimer is retained.
+
+`PROVENANCE.json` records retrieval time, source URLs, rule metadata, the source
+page hash, and SHA-256 hashes of vendored rule/license bytes. The embedded strings
+in `scan/adint_scan/candiru_rules.py` reproduce the rule bytes exactly when
+encoded as UTF-8, preserving their separate third-party licensing. These files
+are a collection of separately licensed rules; project licensing does not
+replace their licenses. No author endorsement is implied.
+
+No malware, samples, binary links, or download-all endpoints were retrieved.
+The scanner compiles only the embedded copies, with YARA includes disabled.
+It never updates rules or downloads anything at scan time. A future update
+requires deliberate source review, attribution, new hashes, and regression
+checks. Pattern matches require investigation; they do not establish exact
+sample identity or confirmed infection. Synthetic byte fixtures test matching
+mechanics only, not real-world detection sensitivity.
diff --git a/third_party/candiru/apt_candiru.yar b/third_party/candiru/apt_candiru.yar
new file mode 100644
index 0000000..1060cf1
--- /dev/null
+++ b/third_party/candiru/apt_candiru.yar
@@ -0,0 +1,47 @@
+import "pe"
+
+rule MAL_DevilsTongue_HijackDll {
+ meta:
+ description = "Detects SOURGUM's DevilsTongue hijack DLL"
+ author = "Microsoft Threat Intelligence Center (MSTIC)"
+ date = "2021-07-15"
+ reference = "https://www.microsoft.com/security/blog/2021/07/15/protecting-customers-from-a-private-sector-offensive-actor-using-0-day-exploits-and-devilstongue-malware/"
+ score = 80
+ id = "390b8b73-6740-513d-8c70-c9002be0ce69"
+ strings:
+ $str1 = "windows.old\\windows" wide
+ $str2 = "NtQueryInformationThread"
+ $str3 = "dbgHelp.dll" wide
+ $str4 = "StackWalk64"
+ $str5 = "ConvertSidToStringSidW"
+ $str6 = "S-1-5-18" wide
+ $str7 = "SMNew.dll" // DLL original name
+ // Call check in stack manipulation
+ // B8 FF 15 00 00 mov eax, 15FFh
+ // 66 39 41 FA cmp [rcx-6], ax
+ // 74 06 jz short loc_1800042B9
+ // 80 79 FB E8 cmp byte ptr [rcx-5], 0E8h ;
+ $code1 = { B8 FF 15 00 00 66 39 41 FA 74 06 80 79 FB E8 }
+ // PRNG to generate number of times to sleep 1s before exiting
+ // 44 8B C0 mov r8d, eax
+ // B8 B5 81 4E 1B mov eax, 1B4E81B5h
+ // 41 F7 E8 imul r8d
+ // C1 FA 05 sar edx, 5
+ // 8B CA mov ecx, edx
+ // C1 E9 1F shr ecx, 1Fh
+ // 03 D1 add edx, ecx
+ // 69 CA 2C 01 00 00 imul ecx, edx, 12Ch
+ // 44 2B C1 sub r8d, ecx
+ // 45 85 C0 test r8d, r8d
+ // 7E 19 jle short loc_1800014D0
+ $code2 = { 44 8B C0 B8 B5 81 4E 1B 41 F7 E8 C1 FA 05 8B CA C1 E9 1F 03 D1 69 CA 2C 01 00 00 44 2B C1 45 85 C0 7E 19 }
+ condition:
+ filesize < 800KB and
+ uint16(0) == 0x5A4D and
+ ( pe.characteristics & pe.DLL ) and
+ (
+ 4 of them or
+ ( $code1 and $code2 ) or
+ pe.imphash() == "9a964e810949704ff7b4a393d9adda60"
+ )
+}
diff --git a/third_party/candiru/win_devilstongue_auto.yar b/third_party/candiru/win_devilstongue_auto.yar
new file mode 100644
index 0000000..d7528e5
--- /dev/null
+++ b/third_party/candiru/win_devilstongue_auto.yar
@@ -0,0 +1,133 @@
+rule win_devilstongue_auto {
+
+ meta:
+ author = "Felix Bilstein - yara-signator at cocacoding dot com"
+ date = "2026-09-17"
+ version = "1"
+ description = "Detects win.devilstongue."
+ info = "autogenerated rule brought to you by yara-signator"
+ tool = "yara-signator v0.6.0"
+ signator_config = "callsandjumps;datarefs;binvalue"
+ malpedia_reference = "https://malpedia.caad.fkie.fraunhofer.de/details/win.devilstongue"
+ malpedia_rule_date = "20260916"
+ malpedia_hash = "53a643781c18e08f4a50949af60172d837a0b6f6"
+ malpedia_version = "20260917"
+ malpedia_license = "CC BY-SA 4.0"
+ malpedia_sharing = "TLP:WHITE"
+
+ /* DISCLAIMER
+ * The strings used in this rule have been automatically selected from the
+ * disassembly of memory dumps and unpacked files, using YARA-Signator.
+ * The code and documentation is published here:
+ * https://github.com/fxb-cocacoding/yara-signator
+ * As Malpedia is used as data source, please note that for a given
+ * number of families, only single samples are documented.
+ * This likely impacts the degree of generalization these rules will offer.
+ * Take the described generation method also into consideration when you
+ * apply the rules in your use cases and assign them confidence levels.
+ */
+
+
+ strings:
+ $sequence_0 = { 4d85c0 0f94442402 bba2984e80 ebc5 81fb97ab74c9 0f8f97000000 81fba2984e80 }
+ // n = 7, score = 100
+ // 4d85c0 | dec esp
+ // 0f94442402 | mov esi, ecx
+ // bba2984e80 | dec ecx
+ // ebc5 | mov edi, edx
+ // 81fb97ab74c9 | dec eax
+ // 0f8f97000000 | cmp dword ptr [ecx], 0
+ // 81fba2984e80 | je 0xb24
+
+ $sequence_1 = { 4883ec28 4889d1 e8???????? b801000000 4883c428 c3 56 }
+ // n = 7, score = 100
+ // 4883ec28 | push ebx
+ // 4889d1 | dec eax
+ // e8???????? |
+ // b801000000 | sub esp, 0x28
+ // 4883c428 | dec eax
+ // c3 | lea ebp, [edx + 0x60]
+ // 56 | dec eax
+
+ $sequence_2 = { 4829d7 48bdffffffffffffff7f 4889e9 4829f9 4839cb 0f879b010000 4d89fe }
+ // n = 7, score = 100
+ // 4829d7 | inc esp
+ // 48bdffffffffffffff7f | jne 0xfffffff6
+ // 4889e9 | jmp 0xd
+ // 4829f9 | mov eax, 0x445c91b1
+ // 4839cb | jmp 0xfffffff6
+ // 0f879b010000 | dec eax
+ // 4d89fe | mov dword ptr [esp + 8], ecx
+
+ $sequence_3 = { 4c89e1 e8???????? 4829d8 4839e8 0f82dc010000 4801dd 4c8b6f18 }
+ // n = 7, score = 100
+ // 4c89e1 | dec eax
+ // e8???????? |
+ // 4829d8 | lea ecx, [esi + 0x10]
+ // 4839e8 | inc ebp
+ // 0f82dc010000 | mov eax, dword ptr [eax]
+ // 4801dd | dec eax
+ // 4c8b6f18 | mov eax, esi
+
+ $sequence_4 = { 85c0 0f8492010000 e9???????? 488b442448 49894608 8b442450 41894618 }
+ // n = 7, score = 100
+ // 85c0 | mov ecx, dword ptr [esp]
+ // 0f8492010000 | mov ecx, 0x50ecbd49
+ // e9???????? |
+ // 488b442448 | dec ecx
+ // 49894608 | mov ecx, edx
+ // 8b442450 | jmp 0x688
+ // 41894618 | dec esp
+
+ $sequence_5 = { 48895818 48897020 488b05???????? 4833c4 488985f0010000 418bf0 4c8bf2 }
+ // n = 7, score = 100
+ // 48895818 | mov ecx, dword ptr [esp + 0x20]
+ // 48897020 | dec eax
+ // 488b05???????? |
+ // 4833c4 | mov edx, edi
+ // 488985f0010000 | dec ecx
+ // 418bf0 | mov eax, ebx
+ // 4c8bf2 | dec eax
+
+ $sequence_6 = { 57 4883ec30 488d6c2430 48c745f8feffffff 4889d6 4889cf 4c89c2 }
+ // n = 7, score = 100
+ // 57 | dec ecx
+ // 4883ec30 | sub ebp, esi
+ // 488d6c2430 | mov eax, 0xcde3b609
+ // 48c745f8feffffff | dec esp
+ // 4889d6 | lea esp, [ebp - 0x38]
+ // 4889cf | cmp eax, 0xaaa31545
+ // 4c89c2 | je 0xeee
+
+ $sequence_7 = { 488d4d08 41b80c000000 e8???????? 488d4d08 e8???????? 488d4dc8 4889c2 }
+ // n = 7, score = 100
+ // 488d4d08 | jmp 0x1435
+ // 41b80c000000 | dec eax
+ // e8???????? |
+ // 488d4d08 | mov dword ptr [esp + 0x20], edi
+ // e8???????? |
+ // 488d4dc8 | dec eax
+ // 4889c2 | mov ecx, dword ptr [esp + 0x20]
+
+ $sequence_8 = { 488b442428 488b442420 488b442438 b800554687 e9???????? 488b4c2470 4831e1 }
+ // n = 7, score = 100
+ // 488b442428 | inc ecx
+ // 488b442420 | mov ecx, ebp
+ // 488b442438 | dec eax
+ // b800554687 | mov dword ptr [esp + 0x38], eax
+ // e9???????? |
+ // 488b4c2470 | mov eax, 0x886bf338
+ // 4831e1 | jmp 0x9b7
+
+ $sequence_9 = { 81fa15b7785c 75f0 488b542410 48c7411000000000 ba251f32f5 ebdc }
+ // n = 6, score = 100
+ // 81fa15b7785c | jne 0x1a7
+ // 75f0 | dec esp
+ // 488b542410 | mov ecx, edi
+ // 48c7411000000000 | jg 0x136
+ // ba251f32f5 | cmp eax, 0x45b54eab
+ // ebdc | je 0x19e
+
+ condition:
+ 7 of them and filesize < 990208
+}
\ No newline at end of file