Mailstrix — YARA malware scanning for mail, ICAP and clamd
Mailstrix is the owl that finds malware hiding in your mail. It takes hostile
attachments apart — unwrapping OLE2/OOXML, VBA, RTF objects, PDFs, archives and
nested carriers — until YARA detection rules can finally see the dangerous bits.
It runs out-of-process behind Rspamd (async HTTP), SpamAssassin, an ICAP server,
Dovecot Sieve, or standalone.

strixd is a small HTTP service that scans email for malware with
YARA. You hand it a message (or one
attachment) on POST /scan; it runs compiled YARA rules over it
and tells you which ones matched. It ships as a ready-to-run Docker image with
an initial rules bundle — see Quick start below or pull it
straight from Docker Hub.
Why YARA, in one paragraph. YARA is the rule engine malware analysts use to
recognise families of malicious files — booby-trapped Office docs, packed
executables, phishing kits, script droppers. A plain string signature dies the
moment the author edits one byte; a YARA rule matches the shape of a file (PE
imports, section entropy, embedded magic) and survives the next variant. strixd
compiles those rules — libyara modules and all — and runs them over your mail.
Six ways to plug it into a mail server, all shipped in this repo:
- rspamd — an async
mailstrix.lua plugin (contrib/rspamd/) POSTs each
message/part to strixd at SMTP time and turns the hits into a spam-score symbol.
- SpamAssassin — the
Mailstrix.pm plugin scans each message
through the same central service and turns a YARA match into a spam-score hit
(contrib/spamassassin/).
- Dovecot / Sieve — the lean
strix-scan
client scans at delivery and a Sieve rule quarantines a match
(contrib/sieve/).
- Postfix / Sendmail (milter) — the lean
strix-milter runs on the MTA host,
POSTs each message to strixd and stamps the verdict as a header. It always
accepts; your milter_header_checks decides what to do about it
(contrib/postfix/).
- ICAP — set
MAILSTRIX_ICAP_ADDR and strixd also speaks ICAP (RFC 3507) so an
ICAP-aware proxy or content-filter (Squid, c-icap) scans REQMOD/RESPMOD bodies
through the same engine (ICAP mode).
- clamd streams — opt-in Unix/TCP listeners in
strixd accept INSTREAM
from supported clamd clients (subset, limits and examples).
These integrations use the same strixd scan engine and rules:
| Interface |
Clients |
HTTP POST /scan |
Rspamd, SpamAssassin, Sieve, Postfix/Sendmail Milter |
| ICAP REQMOD/RESPMOD |
ICAP-aware proxies |
clamd INSTREAM |
Supported stream clients |
Where should YARA scanning live — opinion. YARA scanning is genuinely
CPU-intensive, and the MTA hot path is the most latency-sensitive place to spend
that CPU: every connection waits on it, and at SMTP time you scan a lot of mail
you will reject anyway. A defensible view is that it doesn’t belong in the MTA at
all — scanning at delivery (Dovecot LDA / Sieve), after rspamd has already
dropped the obvious spam, scans far less and off the connection’s critical path.
Which is right depends on your mailflow and goals: scan early at SMTP to reject
with rspamd’s score, or scan late at delivery to quarantine a smaller, cleaner
stream. strixd supports both; see the thin client
and contrib/sieve/ for the delivery-time path.
It runs out of process, never inside the MTA worker, because libyara is a C
library (CGO): in an rspamd worker it would block the event loop and drag a heavy
C dependency into the mail image. Separate, the caller stays async and strixd can
be scaled, restarted, or reload its rules on its own. Same shape as the
gozer DCC/Razor/Pyzor backend.
📋 Jump to Status & roadmap for what’s done vs planned.
Exactly what it does
- Scans mail with YARA —
POST /scan raw message bytes (or one MIME part),
get back the matched rules as JSON; the rspamd mailstrix.lua plugin
(contrib/rspamd/) wires the hits into the spam score, or the strix-scan
client scans at delivery from Dovecot/Sieve (contrib/sieve/).
- Loads a compiled rules bundle — the image includes a seed; the rolling
rules-current publication can refresh the active bundle without changing
the binary. The source set includes YARA-Forge, signature-base, ANY.RUN,
Didier Stevens, bartblaze, InQuest, CAPEv2 and YARAify.
- Decompresses Office macros before matching — MS-OVBA VBA out of
.docm/.xlsm/.doc/.xls, scans the cleartext (sets the VBA rule var).
- Cracks open containers — pulls the hidden payload out of: OLE2/OOXML,
RTF
\objdata, OLE Package (Ole10Native), MSI, Outlook .msg, TNEF
(winmail.dat), OneNote .one, PDF (FlateDecode streams), .lnk shortcuts,
VBE/JSE encoded scripts, and nested archives (zip/7z/rar/gz/tar.gz/cab, recursive)
— then scans each. A part that is itself a message is walked as MIME, so
attachments inside a forwarded or message/rfc822 carrier are unpacked too.
- Deobfuscates before matching — decodes long base64/hex runs, undoes
StrReverse, and folds the olevba string set (Chr/ChrW concat,
Replace(), Array() Xor k, Environ, Dridex DridexUrlDecode) to
cleartext; a bounded recursive pass unwinds multi-stage (2±layer)
payloads, not just the first layer.
- Resolves Excel 4.0 (XLM) macros — detects hidden/very-hidden macrosheets
(OOXML + legacy
.xls BIFF), reassembles ptg-token formula strings
(BIFF8/.xlsb/SLK), and runs a bounded XLM emulator (cell eval, GOTO,
SET.VALUE) to resolve obfuscated cell references. BIFF8 macrosheets also
resolve SHRFMLA shared formulas referenced by ptgExp, within parser limits.
- Triages PDFs — surfaces
/OpenAction, /JS, /Launch, /EmbeddedFile,
/JBIG2Decode and hex-name obfuscation as scoreable markers.
- Catches macro-less & exploit attacks — Equation Editor (CVE-2017-11882),
remote-template injection (CVE-2017-0199 / T1221), DDE/DDEAUTO fields,
MHTML/
x-usc (CVE-2021-40444), Shell.Explorer CLSID, and OLE structural
indicators (ObjectPool, embedded Flash, digital-signature, doc-security).
- Decrypts default-password documents — VelvetSweatshop XOR, BIFF8 RC4, and
OOXML agile/standard AES, so an “encrypted” but default-keyed payload is
unlocked and re-scanned (other encryption is flagged, not cracked).
- Analyses carved executables — PE/ELF structural checks on embedded/decoded
binaries (section entropy / packing, overlay, .NET, anomalies), plus base64-PE
carving that re-aligns a padded
MZ header so the pe rules fire.
- Ships 100+ of its own rules —
docker/local-rules/
scores the structural evidence extraction surfaces, so a sample with no public
signature still has something to hit: weight-of-evidence maldoc scoring,
oleid/oletimes/pdfid parity indicators, XLM dropper shapes,
macro-less execution carriers, HTML/SVG smuggling, PowerShell/VBS/JScript
dropper families, polyglot and renamed-container evasion, and carved-PE
structure — full inventory under
What Mailstrix detects on its own.
Among them: an mraptor-style autoexec∧write∧execute rule, olevba suspicious-keyword / VBA-shellcode-API heuristics, LOLBin / WMI /
PowerShell / anti-analysis intent rules, HTML-smuggling (data: URI, embedded
SVG, javascript:/vbscript: and entity-hidden script URIs) detection, and a
position-independent-shellcode GetEIP prologue rule.
- Scales effort under load — a single 1–10 effort dial (
MAILSTRIX_EFFORT)
scales decode depth, XLM/PDF clamps, feeds and scan timeout; auto sheds a
level at a time as the admission gate fills and climbs back as it drains.
- Speaks ICAP too (optional) —
MAILSTRIX_ICAP_ADDR adds an RFC 3507
REQMOD/RESPMOD listener for ICAP-aware proxies, sharing the same scan engine,
cache and concurrency gate as /scan.
- Uses the attachment name —
filename/extension YARA vars from the
plugin’s X-MAILSTRIX-Filename, so name-keyed (THOR/Loki) rules fire.
- Checks abuse.ch feeds (optional) — URLhaus malware-URL/host lookup (with
URL defanging), MalwareBazaar attachment-SHA256 lookup, and ThreatFox
URL/domain IOCs; all cached, fail-open.
- Drops/demotes noisy rules —
MAILSTRIX_RULE_DENYLIST (suppress) and
MAILSTRIX_RULE_ALLOWLIST (keep but score log-only) without patching upstream.
- Canary mode —
MAILSTRIX_CANARY=1 returns hits as log-only metadata so
integrations can observe rule/feed behaviour without scoring or blocking mail.
- Caches verdicts —
SHA256(body) → matches (LRU+TTL), plus request
coalescing and an optional shared Redis/Valkey L2 for a high-volume firehose.
The L2 can be integrity-protected with MAILSTRIX_REDIS_MAC_KEY: an
HMAC-SHA256 bound to the Redis key, so a tampered or un-MACed value, or a valid
value lifted to a different key, is treated as a cache miss instead of a trusted
verdict. The MAC carries no nonce or counter, so it does not make an entry fresh
— a stale value restored under its own key still verifies.
- Fails open, always — a scan error, timeout, or libyara panic is reported
as “no match”; a broken scanner never blocks mail. Bounded concurrency,
per-scan timeout, body cap, graceful drain on SIGTERM.
- Updatable rules without a rebuild, origin-checked —
strixd fetch-rules
pulls a version-matched compiled bundle into a cache; SIGHUP reloads it. The
remote manifest must carry a valid ed25519 signature from a trusted public
key — one pinned into the binary (internal/rulespin), plus any the operator
adds through MAILSTRIX_RULES_EXTRA_SIGNING_KEYS, which is additive and cannot
remove a pinned key. Otherwise the update is refused, so a tampered, truncated or
untrusted-key manifest never reaches the compiler. There is no switch to turn
verification off (details).
- CLI tools —
strixd scan (local triage), strixd extract (dump what a
container carves), strixd check-rules, strixd info; and strix-scan, a tiny
CGO-free client for a Dovecot/Sieve box (contrib/sieve/).
- Optional CAPE detonation adapter (report-only) — a separate, disabled-by-default
HTTPS listener (
MAILSTRIX_CAPE_CONFIG_FILE) can submit an attachment to a
CAPEv2 sandbox and poll its report. It
is deliberately not in the delivery path: MAILSTRIX_CAPE_POLICY accepts
only static-only, so mail always follows the static verdict and a pending
detonation never holds, quarantines or tempfails a message. No automatic
submission, no enforcement, no callback bridge
(configuration,
operator guide).
- Observable —
/health, /ready, /version, Prometheus /metrics
(scans, matches, cache, per-extractor counters, rule staleness).
Install
Three ways, pick one:
Debian/Ubuntu package (.deb, amd64 + arm64) — attached to every
release:
# Resolve the latest version + your arch (release assets are version-pinned,
# e.g. strixd_1.1.0_amd64.deb — the bare latest/download/ path is not).
VER=$(curl -fsSL https://api.github.com/repos/myguard-labs/mailstrix/releases/latest \
| grep -oP '"tag_name":\s*"v\K[^"]+')
ARCH=$(dpkg --print-architecture) # amd64 or arm64
BASE=https://github.com/myguard-labs/mailstrix/releases/download/v${VER}
# strixd — the daemon (systemd unit + /etc/mailstrix/strixd.env config)
curl -fsSLO "${BASE}/strixd_${VER}_${ARCH}.deb"
sudo apt install "./strixd_${VER}_${ARCH}.deb"
# fetch the rolling compiled rule bundle into the cache dir, then start it
sudo -u strixd strixd fetch-rules -cache-dir /var/cache/mailstrix # or drop your own .yar in /var/lib/mailstrix/rules
sudoedit /etc/mailstrix/strixd.env # set MAILSTRIX_TOKEN, feeds, …
sudo systemctl enable --now strixd
# strix-scan — the lean CGO-free Sieve/LDA client (no daemon)
curl -fsSLO "${BASE}/strix-scan_${VER}_${ARCH}.deb"
sudo apt install "./strix-scan_${VER}_${ARCH}.deb"
# strix-milter — the lean CGO-free Postfix/Sendmail milter (systemd unit)
curl -fsSLO "${BASE}/strix-milter_${VER}_${ARCH}.deb"
sudo apt install "./strix-milter_${VER}_${ARCH}.deb"
The daemon package installs a hardened systemd unit (unprivileged strixd user,
ProtectSystem=strict, NoNewPrivileges) and a documented
/etc/mailstrix/strixd.env. State (rules) lives in /var/lib/mailstrix.
Static binaries — strixd-linux-{amd64,arm64},
strix-scan-linux-{amd64,arm64} and strix-milter-linux-{amd64,arm64} plus
SHA256SUMS are on the same release page.
Docker — see Quick start below (rules baked in).
Quick start
The image includes a compiled seed bundle. Generate a unique token into a local
file first; the private directory protects the read-only bind-mounted token on
the host, and the separate curl header file keeps the token out of process
arguments and command output:
install -d -m 700 .mailstrix-secrets
openssl rand -hex 32 > .mailstrix-secrets/token
chmod 0444 .mailstrix-secrets/token
(umask 077; printf 'X-MAILSTRIX-Token: ' > .mailstrix-secrets/curl-header
cat .mailstrix-secrets/token >> .mailstrix-secrets/curl-header)
docker run -d --name strixd \
-v "$PWD/.mailstrix-secrets/token:/run/secrets/token:ro" \
-e MAILSTRIX_TOKEN_FILE=/run/secrets/token \
-p 127.0.0.1:8079:8079 \
eilandert/mailstrix
# ask it something:
printf 'hello' | curl -s --header @.mailstrix-secrets/curl-header \
--data-binary @- http://127.0.0.1:8079/scan
# -> {"matches":[]}
To use your own rules instead of the baked bundle:
docker run -d --name strixd \
-v "$PWD/.mailstrix-secrets/token:/run/secrets/token:ro" \
-e MAILSTRIX_TOKEN_FILE=/run/secrets/token \
-e MAILSTRIX_RULES= \
-e MAILSTRIX_RULES_DIR=/rules \
-v "$PWD/myrules:/rules:ro" \
-p 127.0.0.1:8079:8079 \
eilandert/mailstrix
Send an attachment name so name-keyed rules fire (base64 — the name is
attacker-controlled, encoding it stops header injection). To check that
detection works end to end, send the harmless
EICAR test string:
printf '%s' 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*' |
curl -s --header @.mailstrix-secrets/curl-header \
-H "X-MAILSTRIX-Filename: $(printf 'eicar.com' | base64)" \
--data-binary @- http://127.0.0.1:8079/scan
# -> {"matches":[{"rule":"SUSP_Just_EICAR",…},{"rule":"TRELLIX_ARC_Malw_Eicar",…}]}
A few placeholder bytes such as MZ... are not malware and correctly return
{"matches":[]}; test with a real sample. Set MAILSTRIX_VERBOSE=1 to log one
line per request.
Token is optional but recommended. Set MAILSTRIX_TOKEN (or
MAILSTRIX_TOKEN_FILE) and the caller must present the same secret as a Bearer
header or X-MAILSTRIX-Token. A *_FILE secret that is set but cannot be read
stops strixd serve with exit code 2 instead of falling back to the plain variable.
Leave it unset (or none/0/off) to run an
open scanner for a trusted private network — strixd logs a loud warning,
since anyone who can reach the port can submit CPU-costly scans.
The /scan reply names the rule and its source ruleset file:
{"matches":[{"rule":"Suspicious_Macro","namespace":"sigbase-gen_maldoc.yar","tags":["office"],"meta":{"author":"…"}}]}
The list is [] (never null) when nothing matched. namespace is the file the
rule was compiled from, so a generic rule like http is traceable to the set
that shipped it.
When strixd could not compute a complete verdict, the reply still answers 200
(fail-open) but adds "degraded" and an X-MAILSTRIX-Degraded header with the
reason: incomplete (scan budget ran out, an extraction cap such as the
stream or archive-member limit stopped the walk, a RAR archive or member was
refused undecoded because it is solid or its main header cannot prove otherwise
(cap kind rar-solid), an extracted stream failed to scan, or an extractor
crashed), error (the scan failed) or busy (no scan slot
freed up in time). A log-only MAILSTRIX_SCAN_INCOMPLETE or
MAILSTRIX_SCAN_DEGRADED match names it too. Treat a degraded reply with no
actionable match as unknown, not clean; any actionable match in it is still
a real detection. Degraded results are never cached. ICAP answers 500 instead
of 204 for them. For the hardened container setup (read-only rootfs, dropped
caps, Docker secret, static IPv4) see
docker/docker-compose.yml.
Scanning without a server
The same binary scans locally — no HTTP, no token — by compiling the rules
in-process. For one-off triage and pipelines:
strixd scan suspicious.doc # one file
strixd scan /var/mail/cur # a maildir, recursed
cat msg.eml | strixd scan # stdin
strixd scan -json /tmp/quarantine # machine-readable
Exit codes: 0 clean, 1 ≥1 match, 2 usage/load/read error. Other
helpers share the binary (strixd help):
strixd check-rules # compile rules, print the count, non-zero on failure (CI gate)
strixd extract suspicious.doc # show what the extractor carves (no scan)
strixd fetch-rules # update the cached rule bundle from the release
strixd info # build / libyara / loaded-bundle identity
Updating rules without rebuilding (fetch-rules)
Rules move faster than image rebuilds — and outside Docker you’d otherwise need
yarac + a matching libyara to compile them. strixd fetch-rules downloads a
prebuilt, version-matched bundle into the cache instead:
strixd fetch-rules -cache-dir /var/cache/mailstrix
The tagged binary release and the rolling rules-current bundle have separate
dates. The local nightly publisher replaces the rolling bundle’s assets; it
does not rebuild a tagged binary. A binary’s release date therefore cannot tell
you when its loaded rules were generated. Check the /version fields
rules_manifest.generated and rules_update.loaded_version for the active
bundle when present. The published and cached versions may differ from the
successfully loaded one.
It reads a small manifest first and updates only when the published version
is newer; it refuses a bundle built against a different libyara,
verifies the sha256, and swaps atomically (keeping one .bak). On any error
the current bundle is retained; rollback errors explicitly require cache recovery.
Then SIGHUP (or restart) strixd to load it, or enable daemon polling below. The
bundle is published by docker/generate-rules.sh (run from cron).
Point -url /
MAILSTRIX_RULES_URL at a mirror if not fetching from GitHub. The URL must be
https; a plain-http mirror needs an explicit opt-in (-allow-http,
serve -rules-allow-http, or MAILSTRIX_RULES_ALLOW_HTTP=1). Other schemes and
URLs without a host are always refused, and a redirect from https to http is
refused even with the opt-in. The base URL must not contain userinfo
(credentials), query parameters, or fragments; these are refused to prevent
credential leaks and broken asset URL construction.
Marker tree (speed gain after a refresh)
A refreshed compiled.yac would otherwise lose the faster marker scan path.
The publisher can ship a signed marker tree beside it, named by the manifest’s
optional marker field. fetch-rules installs the tree only when the running
binary links the same libyara and yarac that built it, which is the latest
release toolchain. Other binaries, and source builds without that identity,
report skipped and keep the full main ruleset. Detection is the same either
way; only the speed differs. In one measurement against 15425 rules, marker-bearing
attachments had a median scan of 3.13 ms against 5.04 ms on the fallback, with
identical matches.
The tree is extracted into the cache directory next to compiled.yac; the
download is a temporary file removed after verification. The code caps the
signed archive at 1 GiB and the extracted tree at 2 GiB and 131072 entries, so
the real size is whatever the release publishes. The bound costs about 184 MiB
of peak RSS, about 3 s of extra startup and about 1.85 s per reload for artifact
verification. A crash in the middle of an update can leave .marker-stage-* directories,
.compiled-dl-*.tmp download files or .rules-rollback-* directories in the
cache. Startup removes .marker-stage-* and .compiled-dl-*.tmp entries older
than 6 hours (a younger one may belong to a fetch running right now; symlinks
with those names are removed as links, never followed). .rules-rollback-*
follows the rule below. Failures to remove are logged and do not stop startup.
strixd fetch-rules -timeout defaults to 60s with MAILSTRIX_RULES_MARKERS=off
and to 5m otherwise, matching MAILSTRIX_RULES_FETCH_TIMEOUT, so a large marker
tree is not cut short and silently replaced by the full ruleset. An explicit
-timeout always wins.
MAILSTRIX_RULES_MARKERS takes auto (the default) or off. With off,
fetch-rules downloads no tree. The next newer bundle it installs contains
compiled.yac only and removes any tree already in the cache; until that
install happens, a matching tree already in the cache is still loaded, because
the scanner load path does not read this setting. Any other value is refused.
The tree download runs under a shorter deadline than the whole fetch. The
update keeps max(15 s, 25% of the remaining time) for installing compiled.yac;
when less than that is left the tree is skipped, and a slow or failed tree
never blocks the compiled.yac update.
strixd fetch-rules -verify-only -require-marker fetches and loads the
published bundle into a temporary cache that is deleted afterwards, never
touching the configured cache. It exits 2 unless the marker tree reports
installed. -require-marker needs -verify-only; the publisher uses it as a
release gate.
Rules-manifest signature
A remote manifest must carry a valid ed25519 signature or the update is
refused and the running rules stay loaded. The publisher writes a detached
compiled.yac.manifest.json.sig beside the manifest: base64 of the raw 64-byte
signature over the exact manifest bytes. strixd verifies it against the
public key(s) compiled into the binary before reading a single manifest field,
so an unsigned, truncated, tampered or untrusted-key manifest never reaches the
update logic. Verification uses the Go standard library only.
Two embedded key slots (current, then a pre-published successor) allow rotation
without an unsigned window: ship the build that trusts the successor first, then
switch publication to it. -require-trusted only proves the key matches the pin
in the publisher’s checkout; it cannot speak for binaries already deployed, so
the trusting build must reach clients before publication switches keys. MAILSTRIX_RULES_EXTRA_SIGNING_KEYS can add further
trust anchors for an operator who signs their own mirror; it can never remove an
embedded key, and there is deliberately no switch to skip verification.
A manifest already installed in the cache is not signature-checked — it is
trusted on its recorded checksum against the cached bytes, as before. An
existing deployment that was seeded before signing existed therefore keeps
serving its bundle; it simply cannot be updated until the publisher signs.
Publishing requires MAILSTRIX_RULES_SIGNING_KEY (an ed25519 PKCS#8 PEM key)
in the environment of docker/generate-rules.sh, which signs through
cmd/rulessign. The key is never passed on a command line, and it must never be
exposed to a pull_request-triggered CI job. The nightly cron run has no such
environment, so when MAILSTRIX_RULES_SIGNING_KEY is unset the publisher falls
back to /etc/myguard-build-env, where the operator installs the same key as a
single base64 line MAILSTRIX_RULES_SIGNING_KEY_B64=$(base64 -w0 key.pem) in
that root-owned mode-600 file (the PEM is multi-line; the build-env reader is
not). An exported MAILSTRIX_RULES_SIGNING_KEY always wins. The publisher
resolves and validates the key before building, so a missing or malformed one
fails in seconds instead of after the rules build. The publisher signs with
-require-trusted, so a key whose public half is not pinned in the binary
aborts the run before any asset is uploaded rather than publishing a bundle
every client would refuse. rulessign -print-public prints the base64 public
key to compare against the pin, which lives in internal/rulespin — a
stdlib-only package, so the signer builds on a host without libyara.
A bundle is refused when the rules actually loaded from the verified download
number zero, or fall below 50% of the installed bundle’s rule count (exactly 50%
is accepted; a first install is refused only at zero). The manifest rules
field is never trusted for this. On a refusal, a daemon poll keeps the current
rules, logs the error and counts it in count_drop_refusals of the rules-update
state, while strixd fetch-rules keeps the current rules, prints the error and
exits 2. To deliberately ship a much smaller ruleset, set
MAILSTRIX_RULES_ALLOW_COUNT_DROP=1 (default off) or
pass strixd fetch-rules -allow-count-drop.
Docker images, the reference Compose service, and Debian packages enable daemon
polling daily (MAILSTRIX_RULES_POLL_INTERVAL=86400 seconds). Set it explicitly
to 0 to disable polling for offline installations or custom local .yar
directories. Bare binaries and library configuration keep the code default 0;
opt in with MAILSTRIX_RULES_POLL_INTERVAL=900 or
serve -rules-poll-interval=15m. Polling requires the compiled cache actually
loaded by the scanner; a cache fallback cannot silently change to remote rules.
If writable cache setup fails, strixd serves the baked/local
fallback and logs that automatic polling was disabled. Network and cache-lock
waits share a configurable five-minute default deadline. Native libyara
validation and reload finish synchronously once entered. There is one check at
startup, then one per interval plus 0–20% jitter,
including after failure (no retry burst).
Concurrent polls coalesce and shutdown cancels and joins the worker.
The manifest checksum detects corruption but is not an origin signature because
the manifest and bundle share one channel. Use an HTTPS URL whose publisher you
trust; reserve plaintext HTTP overrides for loopback or an equivalently trusted
private transport. Detached manifest signing remains tracked separately.
The lifecycle is check manifest -> validate/download -> install -> reload.
Version, libyara, positive bounded size, generation timestamp and SHA-256 must
validate; the native library must load the staged bytes before publication.
Cache readers/writers and SIGHUP share a process-independent cache lock, acquired
after downloading, with the version rechecked under that lock. The daemon uses
the existing atomic rules swap and flushes verdicts only after successful reload.
Standalone fetch-rules installs are picked up on the next successful poll.
The cache directory is a writable runtime directory, not a read-only rules mount;
the daemon and any cron updater must both be able to create .rules.lock and
replace its files. Size MAILSTRIX_RULES_FETCH_TIMEOUT for the complete download,
native validation, and subsequent lock acquisition on the slowest expected link.
| Outcome |
Cache and active rules |
| Current release, valid cache |
No download; reconcile cached rules |
| Invalid metadata, bytes or interrupted download |
Preserve both |
| Install or reload fails |
Restore both cache files; retain active rules |
| Rollback itself fails |
Keep active rules and remaining recovery files |
| Successful update |
Record version; new scans use new rules |
Each file replacement is atomic and participating readers see coherent pairs.
The two files are not crash/power-loss atomic. Startup still load-validates
and reseeds the cache; a version record whose checksum does not describe the
cache cannot suppress a repair download. Do not modify the cache concurrently
with tools that ignore its .rules.lock advisory lock. An update can briefly
use roughly four bundle sizes of disk for the live file, .bak, staged download,
and rollback copy. Startup removes interrupted .rules-rollback-* directories
only after proving the public cache pair coherent or installing the baked seed;
otherwise they remain as operator recovery data.
Age checking now defaults to 48 hours, using a verified manifest’s generated
time or the local rules’ modification time. Remote manifests with future
timestamps are rejected without clock-skew tolerance; a cached future timestamp
falls back to filesystem mtime. Keep publisher and scanner clocks synchronized.
Set MAILSTRIX_RULES_MAX_AGE=0
(or -rules-max-age=0) explicitly for static/offline rules. /health and scans
remain available; /ready stays HTTP 200 for stale rules and reports the stale
state in its body. A strict deployment must explicitly have its readiness probe
reject that state; it trades outage availability for freshness. Unknown age is
reported separately through a zero rules_mtime_unix/mtime metric. These legacy
field names report the age origin (publication time or filesystem fallback),
not necessarily filesystem mtime. /version
and metrics expose whether age checking is enabled, so disabled does not mean
fresh.
/version.rules_update and corresponding mailstrix_rules_* metrics distinguish
the last observed published version, the cached publication record, and the
successfully loaded version, plus last check/success/failure times and failure
counters. Zero version means unknown and zero timestamp means never. Cached
telemetry reads the record; byte integrity is checked during fetch/reload, not
on every scrape. While a cache transaction is busy, telemetry keeps its last
observed identity pair without delaying HTTP probes. Custom local rules do not
inherit an unrelated release manifest from a feed cache directory.
The bundled Prometheus alerts allow 30 hours after an earlier successful check,
covering the daily polling default plus up to 20% jitter (28.8 hours). Adjust the
108000-second threshold when selecting a longer polling interval. The initial
check and published-but-not-loaded deadlines remain 30 minutes.
These are monitoring thresholds, not a guarantee that new rule updates will be
available or loaded within a fixed time. A failed publisher, network check or
reload keeps the last good rules and must be investigated through the receipt,
/version identity and alert metrics.
The publisher uploads the bundle first and manifest last, then runs an isolated
native verifier against the released URLs. During replacement, a mismatched
manifest/asset pair is rejected and retried at the next poll. Verification uses
a fresh temporary cache and alerts on failure; it never mounts a production
cache. Reproduce the verification with:
strixd fetch-rules -verify-only -expected-version 42
The receipt includes version, libyara, size, checksum and native load success.
Each nightly whose serializer can write emits exactly one JSON receipt line with
schema mailstrix-rules-nightly-v1. A successful receipt reports stage
verify and records that same fresh verifier evidence; a failed receipt contains only
schema: "mailstrix-rules-nightly-v1", stage (build, publish, verify,
or receipt), and status: "failed". A broken
serializer fails closed and may leave no JSON line; cron monitoring must treat a
missing or failed receipt as a failure. For the publish/native-verification
outcome, a completed success receipt takes precedence over the process exit
code: a later signal can still produce a nonzero exit (for example, 143 during
success notification). Monitor that exit as a subsequent process interruption,
not as a reversal of the recorded publish/verification success.
Failure notifications carry the same stage in
their title. Discord delivery is the sole best-effort publisher exception: its
failure does not change an otherwise successful publish or receipt.
Thin client for Dovecot / Sieve (strix-scan)
strixd scan (above) compiles the rules in-process, so it needs libyara and
the rule set on the host that runs it — fine on the scanner box, too heavy for a
mail-delivery box that should stay thin. strix-scan is the answer: a
separate, tiny client that links no CGO / libyara and embeds no rules — pure
Go, a ~6 MB static binary you can drop on any mail host. It just reads the
message (stdin or a file), POSTs it to a central strixd serve, and exits on the
verdict — so all the CPU-heavy scanning stays on the central service.
# stdin or a file; exit code carries the verdict:
strix-scan -url http://strixd.internal:8079 -token-file /etc/strixd.token - < message
cat message | strix-scan -url http://strixd.internal:8079
|
|
| Exit 0 |
clean — no actionable rule matched (also for canary/allowlisted log-only hits and on a fail-open scanner outage) |
| Exit 1 |
at least one actionable rule matched |
| Exit 2 |
usage / read / (fail-closed) transport error |
- Fails open by default — any transport error, timeout, or non-200 is treated
as clean (exit 0), so a scanner outage never blocks or bounces delivery. Pass
-fail-open=false for interactive triage where a silent miss is worse.
- Token via
-token-file or MAILSTRIX_TOKEN — never -token on a shared host
(it shows in ps). Redirects are never followed, so the token can’t leak to a
3xx target.
- Same wire format as the rspamd plugin:
X-MAILSTRIX-Token for auth, base64
X-MAILSTRIX-Filename for the attachment name.
- Structured verdict —
-json prints
{"malicious":bool,"family":"<name|>","confidence":"family|rule|","rules":[...]}
and -label prints a single LABEL <family> line (nothing when no family is
known). The family comes from the matched rules’ metadata
(family / malware_family / actor, in that order); generic/technique rules
that carry no family meta still count as malicious but contribute no family. One
family per file = the highest-confidence family-bearing hit. Useful for labelling
a malware-store sample’s family without burning external lookup quota.
-json and -label are mutually exclusive (passing both is a usage error).
This is the delivery-time path from the opinion in the intro: let rspamd drop
the obvious spam at SMTP, then scan the smaller, cleaner stream with YARA at
delivery and quarantine a hit — off the connection’s critical path.
A ready-to-use Dovecot Sieve example (the execute rule, an install wrapper, the
dovecot config, and a setup/test walkthrough) lives in contrib/sieve/.
Because the client fails open, a delivery is never lost if the backend is down.
Milter for Postfix / Sendmail (strix-milter)
strix-milter is a milter (mail filter) front-end for strixd. It runs on the
MTA host, buffers each message, POSTs it to strixd’s /scan, and stamps the
verdict into the message as X-Mailstrix-* headers.
It always accepts the message. It never rejects, defers, discards or
quarantines — it only reports. Turning a verdict into policy is the MTA’s job.
That is deliberate:
- Fail-open is trivial. A scanner outage, timeout or oversized message is
just an
unknown stamp, not a bounce. A bug here can never eat mail.
- Mail policy stays in the MTA, where you already express it, version it, and
can change it without restarting the filter.
- The heavy lifting stays out of the delivery path. Like
strix-scan, this
binary links no CGO / libyara and holds no rules — it is a small pure-Go static
binary. The extractors and the YARA engine stay behind strixd’s admission cap.
# on the MTA host
sudoedit /etc/mailstrix/strix-milter.env # set MAILSTRIX_URL (+ MAILSTRIX_TOKEN)
sudo systemctl enable --now strix-milter
Ready-to-copy MTA config (Postfix main.cf + milter_header_checks, the Sendmail
INPUT_MAIL_FILTER, and a setup/test walkthrough) lives in
contrib/postfix/.
| Header |
Value |
X-Mailstrix-Status |
clean, infected, or unknown |
X-Mailstrix-Rules |
comma-separated actionable rule names (on infected) |
X-Mailstrix-Family |
the malware family, when a rule carried one |
X-Mailstrix-Info |
why the verdict is unknown (outage, no complete verdict, oversized, empty) |
X-Mailstrix-Version |
the strix-milter version |
unknown means not scanned — it is not a clean bill of health. Decide
explicitly what you want to do with it (most people accept and let the rest of the
stack judge; a high-security site may prefer to hold it).
Canary and allowlisted rules (mailstrix_canary=1 / mailstrix_allow=1) are
log-only and never make a message infected — the same rule the other clients
apply, from the same code.
Forged headers are deleted, not just logged. A sender who ships their own
X-Mailstrix-Status: clean would otherwise be read by any downstream consumer
doing a first-match header lookup (net/mail, textproto.Get, most MUA and
Sieve implementations) — so the milter negotiates SMFIF_CHGHDRS and removes
every inbound X-Mailstrix-* header before stamping its own. The forged header is
not fed to the scanner either.
What gets scanned: the milter protocol delivers the header block and the body
separately; strix-milter reassembles them into the complete RFC 5322 message
before posting it — the same bytes strix-scan sends for an .eml. Scanning the
body alone would strip the MIME framing (Content-Type, boundary,
Content-Transfer-Encoding, attachment filename) that the extractor needs.
strixd splits the message into its MIME parts, decodes base64 and
quoted-printable, and unpacks each attachment as if that file had been posted on
its own (at most 256 parts per message; message/rfc822 parts are walked too).
Postfix
# main.cf
smtpd_milters = inet:127.0.0.1:8081
non_smtpd_milters = inet:127.0.0.1:8081
milter_default_action = accept # keep mail flowing if the milter is down
milter_header_checks = pcre:/etc/postfix/milter_header_checks
# /etc/postfix/milter_header_checks — hold anything the scanner called infected
/^X-Mailstrix-Status:\s*infected/ HOLD Mailstrix: malware detected
milter_default_action = accept matters: with tempfail, a milter outage would
defer your entire mailflow. The whole design assumes the filter is allowed to
disappear.
Released messages sit in the hold queue (postsuper -H / -r). Prefer to reject
outright instead? Swap HOLD for REJECT — but note you are then rejecting on a
scanner the MTA cannot see the health of.
Sendmail
INPUT_MAIL_FILTER(`strix', `S=inet:[email protected], F=T, T=S:30s;R:30s;E:5m')
F=T tempfails if the milter is unreachable; use F= (empty) to accept instead,
which matches the fail-open posture above.
Flags
| Flag / env |
Default |
What it does |
-url / MAILSTRIX_URL |
— |
required; base URL of strixd |
-listen / MAILSTRIX_MILTER_LISTEN |
inet:127.0.0.1:8081 |
inet:HOST:PORT or unix:/path.sock |
-token-file / MAILSTRIX_TOKEN |
— |
strixd’s shared secret; -token-file keeps it out of the process list |
-timeout |
20s |
hard per-message deadline; on expiry the message is accepted as unknown |
-max-body |
8 MiB |
a larger message is accepted unscanned rather than scanned as a truncated prefix (which would be a silent miss); the milter path may transiently hold up to ~2x this value per message during buffering |
-max-conns |
64 |
max concurrent MTA connections; bounds memory at roughly max-conns × max-body × 2 for the milter path (due to transient buffering), so a flood of large messages cannot OOM the filter (an OOM restart would, with milter_default_action = accept, let mail through unscanned) |
-cape-policy / MAILSTRIX_CAPE_POLICY |
static-only |
Delivery always follows the current static verdict; this adapter is report-only. Accepted values are static-only and the empty string, which behave identically. An empty environment variable is treated as unset and selects the default. Any other value, including quarantine or temporary-failure policies, is rejected at startup with exit status 2. |
-log-clean |
off |
log clean verdicts too (noisy) |
Keep the listener on loopback or a unix socket: anyone who can reach it can have
messages scanned.
Upgrading from v1.2.0
Changes since v1.2.0 that can stop an existing deployment from starting or
fetching rules:
- Wildcard ICAP/clamd binds are refused. A
MAILSTRIX_ICAP_ADDR or
MAILSTRIX_CLAMD_TCP_ADDR such as :1344, 0.0.0.0:1344 or [::]:1344
(or a hostname resolving to an unspecified address) makes strixd log
wildcard bind requires MAILSTRIX_ALLOW_WILDCARD_BIND=1 and exit with
status 2. Bind a specific address (for example 127.0.0.1:1344), or set
MAILSTRIX_ALLOW_WILDCARD_BIND=1 after confirming the port is firewalled:
these listeners do not enforce the /scan token.
- Plain
http:// rule URLs are refused. A rules URL must be https://;
http:// fails with rules URL must use https (set MAILSTRIX_RULES_ALLOW_HTTP=1 to permit plain http), and any other scheme
or a URL without a host is refused outright. Switch the URL to https://,
or opt in with MAILSTRIX_RULES_ALLOW_HTTP=1 (strixd serve -rules-allow-http, strixd fetch-rules -allow-http). An https-to-http
redirect stays refused even with the opt-in.
- Helm chart image. The chart’s default
image.repository is
eilandert/mailstrix (the Docker Hub image); an interim default of
myguard-labs/mailstrix does not resolve. Charts that pinned the latter
must set image.repository=eilandert/mailstrix.
Configuration
Optional manual attachment detonation has a separate HTTPS listener configured
by MAILSTRIX_CAPE_CONFIG_FILE (strixd serve -cape-config). It is disabled by
default; MAILSTRIX_CAPE_POLICY supports only static-only. See the
CAPE daemon configuration for reference-based
credentials, tenant policy, storage prerequisites and shutdown behavior.
Read the CAPE operator guide for
explicit content/egress consent, retention exceptions and offline examples.
Local tests do not establish physical spool capacity or remote purge;
deployment activation remains conditional on that evidence.
Settings use environment variables; serve -help lists available CLI overrides
(flag > env > default). The optional clamd listener settings below are env-only.
| Env |
Default |
Meaning |
MAILSTRIX_HOST / MAILSTRIX_PORT |
0.0.0.0 / 8079 |
HTTP bind address |
MAILSTRIX_TOKEN[_FILE] |
— |
shared secret for /scan (optional); comma-separated for zero-downtime rotation (e.g. old,new); unset / none / 0 / off ⇒ auth disabled, /scan runs open (warned at startup) |
MAILSTRIX_TOKEN_NEXT[_FILE] |
— |
incoming rotation token accepted alongside the primary; append here then migrate clients, then promote to MAILSTRIX_TOKEN and clear this |
MAILSTRIX_RULES_DIR |
/rules |
dir of *.yar/*.yara compiled at boot and on SIGHUP |
MAILSTRIX_RULES |
— |
a precompiled .yac bundle; loaded instead of RULES_DIR (faster start) |
MAILSTRIX_RULES_MAX_AGE |
172800 (48h) |
seconds; flag rules stale (metric + /ready body); explicit 0 disables. Fail-open: never fails readiness |
MAILSTRIX_RULES_ALLOW_COUNT_DROP |
off |
1/true: install a verified rules bundle with zero rules or under 50% of the current rule count (refused by default) |
MAILSTRIX_RULES_POLL_INTERVAL |
86400 Docker/deb; 0 code default |
seconds; automatic verified update and reload; explicit 0 disables; enabled intervals must be at least 60 seconds |
MAILSTRIX_RULES_FETCH_TIMEOUT |
300 |
seconds; shared deadline for automatic update network and cache-lock waits |
MAILSTRIX_RULES_URL |
GitHub rules-current release |
public bundle/manifest directory override for daemon polling and fetch-rules |
MAILSTRIX_RULES_ALLOW_HTTP |
off |
permit a plain-http MAILSTRIX_RULES_URL; https is required otherwise, and https-to-http redirects are always refused |
MAILSTRIX_RULES_EXTRA_SIGNING_KEYS |
— |
comma-separated extra trusted rules-manifest signing public keys (raw 32-byte ed25519, base64). Additive only: the keys built into the binary stay trusted and cannot be removed. A malformed entry fails startup; a configured key is logged loudly. There is no way to disable signature verification |
MAILSTRIX_SCAN_TIMEOUT |
8 (s) |
per-request libyara budget (raw + all extracted streams share it) |
MAILSTRIX_BACKEND_TIMEOUT |
1 (s) |
how long to wait for an admission / scan slot |
MAILSTRIX_MAX_CONCURRENT |
auto (CPU count, capped by the cgroup CPU limit) |
max concurrent libyara scans (CPU gate) |
MAILSTRIX_MAX_INFLIGHT |
auto (2× concurrent) |
max in-flight requests (admission gate); kept above the scan gate so a slow body/Redis can’t starve scans |
MAILSTRIX_ICAP_MAX_CONNS |
auto (8× in-flight) |
max live ICAP connections, capped at accept() (pre-admission); over the cap the server answers 503 and hangs up, so a slow-loris pool cannot accumulate goroutines/fds |
MAILSTRIX_MAX_BODY |
8388608 (8 MiB) |
max request body, in bytes (checked before reading) |
MAILSTRIX_EXTRACTION_RETAINED_BYTES |
2621440 (2.5 MiB) |
validated per-request retained-output budget setting; accepts 1024–134217728 bytes, invalid values warn and use the default. The ceiling is enforced per whole entry: an extracted entry that does not fit the remaining budget is refused (never truncated) and the scan is marked MAILSTRIX_SCAN_INCOMPLETE; later entries that still fit are admitted |
MAILSTRIX_EFFORT_MAX |
10 |
effort-tier ceiling (1–10); the hard cap a per-request X-MAILSTRIX-Effort header can never exceed (DoS guard) |
MAILSTRIX_EFFORT |
= MAILSTRIX_EFFORT_MAX |
default effort level when no X-MAILSTRIX-Effort header is sent (1 = raw + shallowest extraction, max = full depth). Set to auto (EFFORT-2) to derive the level from admission-gate pressure — full depth when idle, shedding a level at a time as in-flight scans fill the gate, climbing back as it drains (one level/scan; mailstrix_effort_auto_level gauge tracks it). The level scales real work: decode depth, XLM/PDF clamps, reputation feeds and scan timeout are all wired to the resolved profile (EFFORT-4), so a lower level genuinely does less. |
MAILSTRIX_ARCHIVE_PW |
0 (off) |
opt-in: when 1, try to decrypt password-protected archive members (zip ZipCrypto + WinZip-AES, 7z, rar) using candidate passwords scraped from the mail (subject/body/filename) plus an optional wordlist, then scan the recovered payload. Default OFF ⇒ an encrypted member is flagged ARCHIVE-ENCRYPTED and never decrypted (historical behaviour, byte-identical). The brute loop is hard-bounded: ≤64 candidates, a global per-input attempt cap, a tighter sub-cap for KDF formats (7z/rar/AES), a per-attempt wall-clock watchdog, and a per-attempt deadline check. Fail-open everywhere — any error/cap/timeout degrades to skip + keep ARCHIVE-ENCRYPTED. A cracked member emits ARCHIVE-DECRYPTED. |
MAILSTRIX_ARCHIVE_PW_FILE |
— |
optional newline wordlist of extra candidate passwords, loaded once at boot (capped, fail-open) and appended to the per-mail candidates. Consulted only when MAILSTRIX_ARCHIVE_PW=1. |
MAILSTRIX_CACHE_TTL |
3600 (s) |
verdict cache TTL; 0 disables caching |
MAILSTRIX_CACHE_SIZE |
65536 |
in-memory LRU entries |
MAILSTRIX_CACHE_MAX_BYTES |
268435456 (256 MiB) |
estimated retained bytes for complete in-memory LRU entries; values <=0 use the default. Accounting includes cache key/index and entry/list storage, slice capacities, strings and Meta map data; it is not an exact Go heap/RSS or Redis bound |
MAILSTRIX_REDIS_URL |
— |
optional shared L2 cache, e.g. redis://host:6379/6 |
MAILSTRIX_REDIS_PREFIX |
yara:scan: |
Redis key prefix |
MAILSTRIX_REDIS_MAC_KEY (or _FILE) |
— |
optional HMAC-SHA256 key (>= 32 bytes) over Redis L2 values, bound to the Redis key; a missing or bad MAC is a cache miss. Unset = no MAC. Roll the key out on all replicas; values written before the rollout read as misses and repopulate |
MAILSTRIX_METRICS_AUTH |
off |
require the token for /metrics and /version (/health & /ready stay open) |
MAILSTRIX_URLHAUS_KEY[_FILE] |
— |
abuse.ch Auth-Key; enables the URLhaus malware-URL lookup |
MAILSTRIX_URLHAUS_REFRESH |
21600 (6 h) |
URLhaus feed refresh (floor 5 min) |
MAILSTRIX_URLHAUS_MAX_URLS |
64 |
max URLs examined per message |
MAILSTRIX_MBAZAAR_KEY[_FILE] |
— |
abuse.ch Auth-Key (same key); enables the MalwareBazaar hash lookup |
MAILSTRIX_MBAZAAR_REFRESH |
86400 (24 h) |
MalwareBazaar feed refresh (floor 5 min) |
MAILSTRIX_MBAZAAR_FEED |
full dump |
override the feed URL (e.g. the lighter “recent” export) |
MAILSTRIX_THREATFOX_KEY[_FILE] |
— |
abuse.ch Auth-Key (same key); enables the ThreatFox URL/domain IOC lookup |
MAILSTRIX_THREATFOX_REFRESH |
21600 (6 h) |
ThreatFox feed refresh (floor 5 min) |
MAILSTRIX_THREATFOX_MAX_URLS |
64 |
max URLs/domains examined per message |
MAILSTRIX_STATUS_LOG |
off |
log one strixd status: line to stdout every MAILSTRIX_STATUS_INTERVAL: version, uptime, RSS and Go heap, rules identity and poll result/age, feed refresh age/failures, admission and scan-slot use, scan/cache counters, and blocking= (comma-separated degradations such as rules_poll_failing, rules_stale, urlhaus_failing, urlhaus_stale, admission_saturated, unhealthy, or none) |
MAILSTRIX_STATUS_INTERVAL |
900 (15 min) |
seconds between status lines (floor 60; a smaller value is raised to 60, an invalid, zero or negative value uses the default) |
MAILSTRIX_BIGFILE_THRESHOLD |
6291456 (6 MiB) |
buffers larger than this scan against the smaller BIGFILE_RULES set, not the full bundle (cost gate); markers always use the full set; 0 disables the gate |
MAILSTRIX_BIGFILE_RULES |
baked seed |
optional .yac bundle scanned for oversized buffers; unset ⇒ the baked local.yac seed set |
MAILSTRIX_RULE_DENYLIST |
http |
comma-sep rule names to suppress (case-insensitive); set empty to disable |
MAILSTRIX_RULE_ALLOWLIST |
— |
comma-sep rule names to force log-only (kept + tagged mailstrix_allow); deny wins if in both |
MAILSTRIX_DENYLIST_FILE |
— |
optional file of rule names to suppress (one per line, # comments, case-insensitive), merged with MAILSTRIX_RULE_DENYLIST; re-read on SIGHUP; missing or unreadable logs a warning and keeps the env list |
MAILSTRIX_CACHE_DIR |
— (disabled) |
writable dir for the live rule bundle; reseeded from MAILSTRIX_SEED_RULES when its compiled.yac is missing or unreadable |
MAILSTRIX_SEED_RULES |
— |
baked read-only .yac used to (re)seed MAILSTRIX_CACHE_DIR |
MAILSTRIX_CANARY |
0 |
tag every match as log-only canary/shadow output; shipped rspamd/SpamAssassin/Sieve/ICAP integrations observe but do not score/block these hits |
MAILSTRIX_ICAP_ADDR |
— (disabled) |
TCP address for the optional ICAP listener (RFC 3507), e.g. 127.0.0.1:1344. A wildcard host (:1344, 0.0.0.0, ::) is refused unless MAILSTRIX_ALLOW_WILDCARD_BIND=1. When set, strixd also accepts REQMOD/RESPMOD from ICAP-aware proxies (Squid, c-icap). Unset = ICAP disabled. No ICAP-level auth; gate by network/firewall. If the listener cannot bind or stops accepting, /ready answers 503. |
MAILSTRIX_CLAMD_TCP_ADDR |
— (disabled) |
Explicit host:port; a wildcard host needs MAILSTRIX_ALLOW_WILDCARD_BIND=1 |
MAILSTRIX_ALLOW_WILDCARD_BIND |
0 |
permit a wildcard (all-interface) ICAP or clamd TCP bind; these listeners do not check the /scan token |
MAILSTRIX_CLAMD_UNIX_PATH |
— (disabled) |
Absolute socket path |
MAILSTRIX_CLAMD_MAX_CONNS |
64 |
Shared Unix/TCP cap, range 1–1024 |
MAILSTRIX_VERBOSE |
off |
log one line per request |
MAILSTRIX_LOG_STDOUT |
off |
info/access logs to stdout (errors always stderr) |
MAILSTRIX_PPROF |
off |
enable /debug/pprof profiling endpoints (off by default; auth-gated when MAILSTRIX_METRICS_AUTH is set) |
Reload rules: docker kill -s HUP strixd recompiles in place and flushes the
cache. A reload that fails to compile keeps the previous (working) rules — a bad
edit can’t disarm a running scanner. On SIGTERM/SIGINT strixd drains (/ready →
503, in-flight scans finish) before exiting — safe for rolling updates.
Sizing profiles
MAILSTRIX_MAX_CONCURRENT defaults to the CPU count (auto), reduced to the container’s cgroup CPU limit (v2 cpu.max or v1 cfs_quota_us/cfs_period_us) rounded up, minimum 1. On a many-core host
(32+ CPUs) that reserves significant memory. The request-buffer ceiling is set by
the admission gate, not the scan gate: up to MAX_INFLIGHT requests can each hold
a body plus its extracted streams, so the startup log reports a lower bound of
RSS + MAX_INFLIGHT × (MAX_BODY + EXTRACTION_RETAINED_BYTES). The terms, what
the bound excludes and a worked mem_limit derivation are in
Memory sizing. Size mem_limit accordingly and pin
MAX_INFLIGHT (the memory knob) and MAX_CONCURRENT (the CPU knob)
explicitly when the defaults are too aggressive.
MAILSTRIX_MAX_INFLIGHT (default 2×MAX_CONCURRENT) is the admission gate — excess
requests wait up to MAILSTRIX_BACKEND_TIMEOUT for a slot and then receive a
503. Keep it above
MAX_CONCURRENT so a slow body read or Redis round-trip can’t starve scan slots.
Redis/Valkey L2 (MAILSTRIX_REDIS_URL) dramatically improves throughput for repeated
attachments, which is common in mail (bulk campaigns, MTA retries, one body to N
recipients). Without it each scanner instance maintains its own in-process LRU
only.
Set MAILSTRIX_REDIS_MAC_KEY (>= 32 bytes) to authenticate L2 values with an
HMAC bound to the Redis key; tampered, un-MACed, or cross-key-reused values are
cache misses. The MAC is not a freshness check.
| Profile |
MAILSTRIX_MAX_CONCURRENT |
MAILSTRIX_MAX_BODY |
mem_limit |
Redis |
Expected p95 |
RPS capacity |
| Small — single mailhost, <100 msgs/min |
2 |
10485760 (10 MiB) |
128m |
optional (LRU only) |
<500 ms |
~10 |
| Medium — mailhost, 100–1000 msgs/min |
auto (CPU count) |
26214400 (25 MiB) |
256m |
recommended |
<300 ms |
~50 |
| Large — cluster, >1000 msgs/min |
auto |
26214400 (25 MiB) |
512m+ |
required |
<200 ms |
~200+ |
Notes:
- MalwareBazaar full-dump mode (
MAILSTRIX_MBAZAAR_KEY set) adds ~40 MiB resident
plus a refresh spike. The refresh now streams the dump to a disk spool, so the
older ~100–150 MiB spike figure and the ~768m recommendation no longer apply
without a measurement. See Memory sizing and measure the
refresh peak with container stats before raising mem_limit.
- For the Large profile, run multiple replicas behind a load balancer rather than
one container with a very high
MAX_CONCURRENT: smaller per-container concurrency
improves tail latency under burst load and avoids one libyara panic taking all
capacity.
MAILSTRIX_BACKEND_TIMEOUT (default 1s) caps how long a request waits for an
admission slot. Under sustained overload this is the 503 fuse — keep it short
so callers (rspamd) fail fast rather than stacking connections.
Go memory limit (GOMEMLIMIT)
The image sets no GOMEMLIMIT default; leaving it unset keeps the Go runtime’s
default behaviour. The Go soft limit only governs memory the Go runtime
allocates and manages (heap, goroutine stacks). libyara is a C library called
through cgo, so its allocations come from malloc and sit outside that
accounting. Setting GOMEMLIMIT equal to mem_limit therefore lets the Go heap
grow into the whole container budget, and the libyara resident set then has no
room under the cgroup limit.
Derivation:
GOMEMLIMIT = mem_limit - L
L is the measured resident set of libyara © allocations for the rule set in
use. No measured libyara-only RSS figure exists in this repository. The existing
figures (about 90-200 MiB under macro and zip load, about 198 MiB peak) are whole
process numbers, not libyara-only. To estimate L, compare mailstrix_rss_bytes
with mailstrix_heap_inuse_bytes on /metrics after the rules have loaded. The
difference is a rough indicator of L, not a bound. It can overstate L,
because it also contains Go runtime overhead that is not heap in use (idle spans,
goroutine stacks and runtime metadata). It can also understate L, because
malloc’d libyara pages that are not yet touched are absent from RSS and a single
sample after rule load misses scan-time peaks. Measure under representative scan
load as well as after rule load, and re-measure per rule set.
Worked examples, using a placeholder example value of L = 120 MiB that
was not measured. Substitute the figure measured for your rule set:
mem_limit |
L (example value) |
GOMEMLIMIT |
512m |
120 MiB |
392MiB |
768m |
120 MiB |
648MiB |
The formula does not reserve headroom for other non-Go memory that also counts
against the cgroup, such as thread stacks, TLS and other cgo allocations. Any
extra margin on top of it is an operator choice.
GOMEMLIMIT is a soft limit: approaching it makes the garbage collector work
harder, but it does not stop allocations. Set it only after measuring L, and set
it in the operator’s compose or environment, not in the image.
Memory sizing
The startup log line lower bound for peak memory ... reports:
peak lower bound = RSS + N × (B + E)
RSS: the process resident set, sampled at startup after a forced collection.
It includes the loaded rules and any MalwareBazaar snapshot warm-started from
the cache. The first MalwareBazaar fetch runs in the background and may finish
after the sample. When MAILSTRIX_MBAZAAR_KEY is set and no cached snapshot
file existed at startup, add the resident feed set (about 40 MiB, per the feed
notes) to the term, since it was not in the sample. Read RSS from the startup
log (RSS=<n> MiB) or from container stats. Do not use a figure from another
deployment.
N = MAILSTRIX_MAX_INFLIGHT. Default 2 × MAILSTRIX_MAX_CONCURRENT, where
the default MAX_CONCURRENT is the CPU count. An explicit value below
MAX_CONCURRENT is raised to 2 × MAX_CONCURRENT.
B = MAILSTRIX_MAX_BODY, default 8388608 bytes (8 MiB). A request whose
Content-Length exceeds it is refused before the body is read.
E = MAILSTRIX_EXTRACTION_RETAINED_BYTES, default 2621440 bytes (2.5 MiB).
A value outside 1024–134217728 falls back to the default.
The bound is a lower bound, not a cap. The startup log names its exclusions:
ICAP pre-admission buffers, extraction decoder transients, MalwareBazaar feed
refresh spikes, verdict cache growth, libyara C allocations made after startup,
and allocator slack. Add margin for these when choosing mem_limit. If the
estimate exceeds 3/4 of the container limit, strixd logs a WARNING at startup.
With no cgroup limit visible, it warns above 512 MiB.
What each knob affects:
| Setting |
Default |
Effect on memory |
Effect on CPU or other |
MAILSTRIX_MAX_INFLIGHT (N) |
2 × MAX_CONCURRENT |
Multiplies B + E. Each admitted request holds its body and extracted streams until its handler returns. |
A request beyond N waits up to MAILSTRIX_BACKEND_TIMEOUT for a slot, then gets 503. |
MAILSTRIX_MAX_BODY (B) |
8 MiB |
Per-request body ceiling. Multiplied by N. |
Requests over it are refused. |
MAILSTRIX_EXTRACTION_RETAINED_BYTES (E) |
2.5 MiB |
Per-request ceiling on retained extracted output, enforced per whole entry. Multiplied by N. |
Entries that do not fit are refused and the scan is marked incomplete. |
MAILSTRIX_MAX_CONCURRENT |
CPU count |
Not a term in the formula, but it sets the default N: with MAX_INFLIGHT on auto, N = 2 × MAX_CONCURRENT, and an explicit MAX_INFLIGHT below MAX_CONCURRENT is raised to 2 × MAX_CONCURRENT. Set MAX_INFLIGHT explicitly, at or above MAX_CONCURRENT, to size memory independently of CPU. |
The CPU gate: the number of libyara scans that run at once. |
MAILSTRIX_CACHE_MAX_BYTES |
256 MiB |
Not in the formula. It is the separate estimate for the verdict cache. |
Cache hit rate. |
MAILSTRIX_ICAP_MAX_CONNS |
8 × N |
Not in the formula. It caps connections before admission. |
Connection count. |
To reduce the bound, lower MAX_INFLIGHT, MAX_BODY or the retained budget.
Lowering MAX_CONCURRENT reduces CPU contention; it lowers the buffer ceiling only
when N follows it: MAX_INFLIGHT is left on auto, or it is set below
MAX_CONCURRENT and raised to 2 × MAX_CONCURRENT.
Feed refresh (MalwareBazaar, MAILSTRIX_MBAZAAR_KEY set): the zipped dump is
streamed to a spool file, not held in RAM. The spool is bounded at 320 MiB zipped
(maxFeedBytes); the full dump was measured at about 215 MiB zipped in the code
comment. The spool is created inside MAILSTRIX_CACHE_DIR itself, next to the installed
snapshot malwarebazaar.bin. Installing a snapshot keeps a
malwarebazaar.bin.bak rollback copy. During a refresh, the cache volume
therefore has to hold the new spool, the current snapshot and the rollback copy
at the same time. Without MAILSTRIX_CACHE_DIR the spool goes to the OS temp
directory and no snapshot is persisted. No measured refresh-peak figure is
recorded in this README, so measure the refresh peak with container stats.
Worked example with the defaults, on a 4-CPU host with no overrides:
| Term |
Value |
Derivation |
N |
8 |
2 × MAX_CONCURRENT (4 CPUs), with MAX_INFLIGHT left on auto |
B + E |
11,010,048 bytes (10.5 MiB) |
8,388,608 + 2,621,440 |
N × (B + E) |
88,080,384 bytes (84 MiB) |
8 × 11,010,048 |
The startup check passes when RSS + 84 MiB ≤ 3/4 × mem_limit, so:
mem_limit ≥ (RSS + 84 MiB) ÷ 0.75
Substitute the RSS from your startup log. For example, mem_limit=256m avoids
the warning only when RSS ≤ 192 − 84 = 108 MiB. Add the excluded items above
for the real margin, then set GOMEMLIMIT = mem_limit − L as described in the
section above.
Rules
The image bakes eight public rulesets at build time; a daily rebuild
(--build-arg CACHEBUST=$(date +%s)) re-pulls the latest. Full credit to the
authors — strixd only packages their work. Each set keeps its own license:
| Ruleset |
Author / source |
License |
Notes |
| YARA-Forge |
YARAHQ/yara-forge |
aggregator (each rule keeps its upstream license) |
vetted, deduped multi-repo bundle; default tier full (YARAFORGE_SET=core/extended select smaller optional tiers) |
| **signa |
|
|
|
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论