scan-gateway 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scan_gateway/__init__.py +11 -0
- scan_gateway/discovery.py +40 -0
- scan_gateway/exceptions.py +58 -0
- scan_gateway/gateway.py +78 -0
- scan_gateway/protocol.py +30 -0
- scan_gateway/scanners/__init__.py +0 -0
- scan_gateway/scanners/clamav.py +99 -0
- scan_gateway/scanners/local_heuristic.py +59 -0
- scan_gateway/scanners/rules/suspicious_pdf.yar +30 -0
- scan_gateway-0.1.1.dist-info/METADATA +176 -0
- scan_gateway-0.1.1.dist-info/RECORD +13 -0
- scan_gateway-0.1.1.dist-info/WHEEL +4 -0
- scan_gateway-0.1.1.dist-info/licenses/LICENSE +21 -0
scan_gateway/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from scan_gateway.exceptions import ScanGatewayError, ScannerUnavailableError, ThreatDetectedError
|
|
2
|
+
from scan_gateway.gateway import ScanGateway
|
|
3
|
+
from scan_gateway.protocol import Scanner
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"ScanGateway",
|
|
7
|
+
"ScanGatewayError",
|
|
8
|
+
"Scanner",
|
|
9
|
+
"ScannerUnavailableError",
|
|
10
|
+
"ThreatDetectedError",
|
|
11
|
+
]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""importlib.metadata-based discovery for third-party scan-gateway plugins."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from importlib.metadata import entry_points
|
|
5
|
+
|
|
6
|
+
from scan_gateway.protocol import Scanner
|
|
7
|
+
|
|
8
|
+
ENTRY_POINT_GROUP = "scan_gateway.scanners"
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def discover_scanner_plugins() -> list[Scanner]:
|
|
14
|
+
"""Load every Scanner registered under the "scan_gateway.scanners" entry-point group.
|
|
15
|
+
|
|
16
|
+
Each entry point must resolve to a zero-argument callable (a class with
|
|
17
|
+
no required constructor args, or a factory function) returning a
|
|
18
|
+
Scanner instance -- any config it needs (host, API key, etc) is the
|
|
19
|
+
plugin's own responsibility to read, e.g. from its own environment
|
|
20
|
+
variables.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
list[Scanner]: One instance per successfully-loaded entry point, in
|
|
24
|
+
whatever order importlib.metadata returns them (not guaranteed
|
|
25
|
+
stable). An entry point that fails to import or instantiate is
|
|
26
|
+
logged and skipped, not fatal -- one broken third-party plugin
|
|
27
|
+
shouldn't take down every scan.
|
|
28
|
+
"""
|
|
29
|
+
discovered: list[Scanner] = []
|
|
30
|
+
for ep in entry_points(group=ENTRY_POINT_GROUP):
|
|
31
|
+
try:
|
|
32
|
+
factory = ep.load()
|
|
33
|
+
scanner = factory()
|
|
34
|
+
except Exception:
|
|
35
|
+
logger.exception(
|
|
36
|
+
"scan-gateway plugin %r (%s) failed to load, skipping", ep.name, ep.value
|
|
37
|
+
)
|
|
38
|
+
continue
|
|
39
|
+
discovered.append(scanner)
|
|
40
|
+
return discovered
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Exception hierarchy raised by scan-gateway and its scanners.
|
|
2
|
+
|
|
3
|
+
Convention: `Scanner.scan(path)` returns None when clean, raises
|
|
4
|
+
ThreatDetectedError when something flags it, and raises
|
|
5
|
+
ScannerUnavailableError when the scanner couldn't complete the scan for
|
|
6
|
+
operational reasons (unreachable, timed out, malformed response) --
|
|
7
|
+
distinct from "flagged" so ScanGateway knows to try the next scanner /
|
|
8
|
+
fall back, rather than rejecting the file.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ScanGatewayError(Exception):
|
|
13
|
+
"""Base class for every exception this package raises."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ThreatDetectedError(ScanGatewayError):
|
|
17
|
+
"""Raised when a scanner positively flags a file.
|
|
18
|
+
|
|
19
|
+
`scanner_name` (that scanner's `.name`) and `verdict` (its own
|
|
20
|
+
description of what it found) are both exposed so a consuming app can
|
|
21
|
+
log/debug which plugin flagged something without knowing scan-gateway's
|
|
22
|
+
internals."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, scanner_name: str, verdict: str):
|
|
25
|
+
"""Initialize with the flagging scanner's name and its verdict.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
scanner_name: The flagging Scanner's `.name`.
|
|
29
|
+
verdict: That scanner's own description of what it found.
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
None.
|
|
33
|
+
"""
|
|
34
|
+
self.scanner_name = scanner_name
|
|
35
|
+
self.verdict = verdict
|
|
36
|
+
super().__init__(f"{scanner_name} flagged: {verdict}")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ScannerUnavailableError(ScanGatewayError):
|
|
40
|
+
"""Raised by a Scanner when it can't complete a scan for operational
|
|
41
|
+
reasons (connection refused, timeout, unparseable response, etc).
|
|
42
|
+
Caught internally by ScanGateway to try the next scanner / fall back --
|
|
43
|
+
not expected to reach the consuming app directly."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, scanner_name: str, reason: str):
|
|
46
|
+
"""Initialize with the unavailable scanner's name and why.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
scanner_name: The unavailable Scanner's `.name`.
|
|
50
|
+
reason: A human-readable description of why the scan couldn't
|
|
51
|
+
be completed (e.g. a connection error or timeout message).
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
None.
|
|
55
|
+
"""
|
|
56
|
+
self.scanner_name = scanner_name
|
|
57
|
+
self.reason = reason
|
|
58
|
+
super().__init__(f"{scanner_name} unavailable: {reason}")
|
scan_gateway/gateway.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""The orchestrator: tries explicitly-registered scanners (in order), then
|
|
2
|
+
any auto-discovered plugins, falling back to the built-in local heuristic
|
|
3
|
+
scanner when none of them can complete a scan."""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from scan_gateway.discovery import discover_scanner_plugins
|
|
9
|
+
from scan_gateway.exceptions import ScannerUnavailableError
|
|
10
|
+
from scan_gateway.protocol import Scanner
|
|
11
|
+
from scan_gateway.scanners.local_heuristic import LocalHeuristicScanner
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ScanGateway:
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
scanners: list[Scanner] | None = None,
|
|
20
|
+
*,
|
|
21
|
+
discover_plugins: bool = True,
|
|
22
|
+
fallback: Scanner | None = None,
|
|
23
|
+
):
|
|
24
|
+
"""Build an orchestrator over explicit and/or auto-discovered scanners.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
scanners: Explicitly-registered instances -- e.g. this app's own
|
|
28
|
+
ClamAVScanner, constructed with real host/port/secrets --
|
|
29
|
+
run first, in the given order.
|
|
30
|
+
discover_plugins: When True (default), third-party plugins
|
|
31
|
+
registered under the "scan_gateway.scanners" entry-point
|
|
32
|
+
group are appended after `scanners`, in whatever order
|
|
33
|
+
importlib.metadata returns (not guaranteed stable).
|
|
34
|
+
fallback: Overrides the built-in local heuristic scanner;
|
|
35
|
+
almost never needed outside tests.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
None.
|
|
39
|
+
"""
|
|
40
|
+
self._scanners: list[Scanner] = list(scanners or [])
|
|
41
|
+
if discover_plugins:
|
|
42
|
+
self._scanners.extend(discover_scanner_plugins())
|
|
43
|
+
self._fallback = fallback or LocalHeuristicScanner()
|
|
44
|
+
|
|
45
|
+
async def scan(self, path: Path) -> None:
|
|
46
|
+
"""Scan `path` through every configured scanner, falling back to the
|
|
47
|
+
built-in local scanner when none of them can complete the scan.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
path: Filesystem path of the file to scan.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
None if the file is clean -- callers don't need to know which
|
|
54
|
+
layer scanned it.
|
|
55
|
+
|
|
56
|
+
Raises:
|
|
57
|
+
ThreatDetectedError: If any configured scanner or the fallback
|
|
58
|
+
flags the file.
|
|
59
|
+
ScannerUnavailableError: If the fallback itself can't complete
|
|
60
|
+
the scan -- propagates uncaught, since that means nothing
|
|
61
|
+
could scan the file at all, a hard failure for the caller
|
|
62
|
+
to decide about, not a silent pass.
|
|
63
|
+
"""
|
|
64
|
+
for scanner in self._scanners:
|
|
65
|
+
try:
|
|
66
|
+
await scanner.scan(path)
|
|
67
|
+
return # first clean/flagged outcome wins -- no need to run the rest
|
|
68
|
+
except ScannerUnavailableError as exc:
|
|
69
|
+
logger.warning("scanner %r unavailable (%s), trying next", scanner.name, exc.reason)
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
if self._scanners:
|
|
73
|
+
logger.warning(
|
|
74
|
+
"no configured scanner could complete a scan for %s, using local fallback", path
|
|
75
|
+
)
|
|
76
|
+
else:
|
|
77
|
+
logger.info("no scanner configured, using local fallback scan for %s", path)
|
|
78
|
+
await self._fallback.scan(path)
|
scan_gateway/protocol.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""The extension point third-party scan-gateway plugins implement."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Protocol, runtime_checkable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@runtime_checkable
|
|
8
|
+
class Scanner(Protocol):
|
|
9
|
+
"""Anything with a `.name` and an async `.scan(path)` satisfies this --
|
|
10
|
+
structural typing (PEP 544), not inheritance, so a third-party package
|
|
11
|
+
has zero import-time coupling to scan-gateway beyond declaring its
|
|
12
|
+
entry point (or being passed to ScanGateway explicitly)."""
|
|
13
|
+
|
|
14
|
+
name: str
|
|
15
|
+
|
|
16
|
+
async def scan(self, path: Path) -> None:
|
|
17
|
+
"""Scan `path` and report the result.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
path: Filesystem path of the file to scan.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
None if the file is clean.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
ThreatDetectedError: If `path` is flagged.
|
|
27
|
+
ScannerUnavailableError: If the scan couldn't be completed for
|
|
28
|
+
operational reasons.
|
|
29
|
+
"""
|
|
30
|
+
...
|
|
File without changes
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Built-in default scanner: streams a file to a clamd instance over TCP
|
|
2
|
+
using ClamAV's own INSTREAM protocol (not HTTP -- clamd doesn't speak
|
|
3
|
+
HTTP). Hand-rolled rather than the stale third-party pyclamd package --
|
|
4
|
+
pure stdlib asyncio/struct, no extra dependency.
|
|
5
|
+
|
|
6
|
+
Not auto-registered via entry-point discovery (see README): its host/port
|
|
7
|
+
are runtime configuration, not static package metadata, so the consuming
|
|
8
|
+
app constructs it explicitly with its own config and passes it to
|
|
9
|
+
ScanGateway's `scanners=[...]`, the same way it would wire any plugin
|
|
10
|
+
that needs secrets/hosts only known at runtime.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import struct
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from scan_gateway.exceptions import ScannerUnavailableError, ThreatDetectedError
|
|
18
|
+
|
|
19
|
+
_CHUNK_SIZE = 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ClamAVScanner:
|
|
23
|
+
name = "clamav"
|
|
24
|
+
|
|
25
|
+
def __init__(self, host: str, port: int = 3310, timeout_seconds: float = 15):
|
|
26
|
+
"""Configure a scanner for a clamd instance reachable at host:port.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
host: Hostname or IP of the clamd instance.
|
|
30
|
+
port: TCP port clamd listens on. Defaults to 3310.
|
|
31
|
+
timeout_seconds: Seconds to wait for a response before raising
|
|
32
|
+
ScannerUnavailableError. Defaults to 15.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
None.
|
|
36
|
+
"""
|
|
37
|
+
self._host = host
|
|
38
|
+
self._port = port
|
|
39
|
+
self._timeout_seconds = timeout_seconds
|
|
40
|
+
|
|
41
|
+
async def scan(self, path: Path) -> None:
|
|
42
|
+
"""Stream `path` to clamd via INSTREAM and raise on a positive match.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
path: Filesystem path of the file to scan.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
None if clamd reports the file clean.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
ThreatDetectedError: If clamd's verdict isn't "OK".
|
|
52
|
+
ScannerUnavailableError: If the connection times out or fails,
|
|
53
|
+
or clamd's response can't be parsed.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
verdict = await asyncio.wait_for(
|
|
57
|
+
self._scan_via_clamd(path), timeout=self._timeout_seconds
|
|
58
|
+
)
|
|
59
|
+
except (TimeoutError, OSError, RuntimeError) as exc:
|
|
60
|
+
raise ScannerUnavailableError(
|
|
61
|
+
self.name, f"{self._host}:{self._port} ({type(exc).__name__}: {exc})"
|
|
62
|
+
) from exc
|
|
63
|
+
|
|
64
|
+
if verdict != "OK":
|
|
65
|
+
raise ThreatDetectedError(self.name, verdict)
|
|
66
|
+
|
|
67
|
+
async def _scan_via_clamd(self, path: Path) -> str:
|
|
68
|
+
"""Speak ClamAV's zINSTREAM protocol over a fresh TCP connection.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
path: Filesystem path of the file to stream to clamd.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
str: "OK" if clean, or clamd's own FOUND/signature text if flagged.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
RuntimeError: If clamd's response contains neither "OK" nor "FOUND".
|
|
78
|
+
"""
|
|
79
|
+
reader, writer = await asyncio.open_connection(self._host, self._port)
|
|
80
|
+
try:
|
|
81
|
+
writer.write(b"zINSTREAM\0")
|
|
82
|
+
with path.open("rb") as f:
|
|
83
|
+
while chunk := f.read(_CHUNK_SIZE):
|
|
84
|
+
writer.write(struct.pack("!L", len(chunk)))
|
|
85
|
+
writer.write(chunk)
|
|
86
|
+
await writer.drain()
|
|
87
|
+
writer.write(struct.pack("!L", 0)) # zero-length chunk signals end of stream
|
|
88
|
+
await writer.drain()
|
|
89
|
+
response = await reader.read(4096)
|
|
90
|
+
finally:
|
|
91
|
+
writer.close()
|
|
92
|
+
await writer.wait_closed()
|
|
93
|
+
|
|
94
|
+
text = response.decode("utf-8", errors="replace").strip("\0").strip()
|
|
95
|
+
if "FOUND" in text:
|
|
96
|
+
return text
|
|
97
|
+
if "OK" in text:
|
|
98
|
+
return "OK"
|
|
99
|
+
raise RuntimeError(f"unexpected ClamAV response: {text!r}")
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Built-in, always-available fallback scanner: YARA pattern matching plus a
|
|
2
|
+
lightweight PDF-structural keyword check. No network/daemon dependency --
|
|
3
|
+
this is what ScanGateway falls back to when no configured scanner could
|
|
4
|
+
complete a scan (none configured, or all unreachable). Narrower coverage
|
|
5
|
+
than a real scanner plugin, not a replacement -- see README.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import yara
|
|
11
|
+
|
|
12
|
+
from scan_gateway.exceptions import ThreatDetectedError
|
|
13
|
+
|
|
14
|
+
_RULES_PATH = Path(__file__).parent / "rules" / "suspicious_pdf.yar"
|
|
15
|
+
_rules = yara.compile(filepath=str(_RULES_PATH))
|
|
16
|
+
|
|
17
|
+
# Raw-byte keyword search (pdfid-style), not a full object-graph walk --
|
|
18
|
+
# content hidden inside a compressed object stream can evade this.
|
|
19
|
+
# Deliberately scoped to the one pattern a pure keyword check can
|
|
20
|
+
# meaningfully flag: script capability combined with something that
|
|
21
|
+
# auto-triggers it without a click ("runs code on open"), not just
|
|
22
|
+
# "contains any PDF action/script feature". /Launch (launch an external
|
|
23
|
+
# program) is rare enough in legitimate PDFs to flag on its own.
|
|
24
|
+
_SCRIPT_KEYWORDS = (b"/JavaScript", b"/JS")
|
|
25
|
+
_AUTOTRIGGER_KEYWORDS = (b"/OpenAction", b"/AA")
|
|
26
|
+
_LAUNCH_KEYWORD = b"/Launch"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class LocalHeuristicScanner:
|
|
30
|
+
name = "local-heuristic"
|
|
31
|
+
|
|
32
|
+
async def scan(self, path: Path) -> None:
|
|
33
|
+
"""Check `path` against the bundled YARA rules and keyword heuristics.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
path: Filesystem path of the file to scan.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
None if nothing matches.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
ThreatDetectedError: If a YARA rule matches, a `/Launch` action
|
|
43
|
+
is present, or a script action is paired with an
|
|
44
|
+
auto-trigger action.
|
|
45
|
+
"""
|
|
46
|
+
data = path.read_bytes()
|
|
47
|
+
|
|
48
|
+
matches = _rules.match(data=data)
|
|
49
|
+
if matches:
|
|
50
|
+
rule_names = ", ".join(m.rule for m in matches)
|
|
51
|
+
raise ThreatDetectedError(self.name, f"YARA: {rule_names}")
|
|
52
|
+
|
|
53
|
+
if _LAUNCH_KEYWORD in data:
|
|
54
|
+
raise ThreatDetectedError(self.name, "/Launch action present")
|
|
55
|
+
|
|
56
|
+
has_script = any(k in data for k in _SCRIPT_KEYWORDS)
|
|
57
|
+
has_autotrigger = any(k in data for k in _AUTOTRIGGER_KEYWORDS)
|
|
58
|
+
if has_script and has_autotrigger:
|
|
59
|
+
raise ThreatDetectedError(self.name, "script action paired with an auto-trigger action")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Hand-written, bundled in this repo rather than pulling in a third-party
|
|
3
|
+
* community ruleset sight-unseen (licensing/trust/size concerns for an
|
|
4
|
+
* external signature file). Intentionally small -- this backs
|
|
5
|
+
* LocalHeuristicScanner, the built-in fallback scanner, not a replacement
|
|
6
|
+
* for a real scanner plugin's (e.g. ClamAV's) much larger signature
|
|
7
|
+
* database.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
rule EICAR_Test_String
|
|
11
|
+
{
|
|
12
|
+
meta:
|
|
13
|
+
description = "Standard EICAR antivirus test string -- not a real virus, used to verify the scanning pipeline end to end."
|
|
14
|
+
strings:
|
|
15
|
+
$eicar = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
|
|
16
|
+
condition:
|
|
17
|
+
$eicar
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
rule Suspicious_PDF_JS_Obfuscation
|
|
21
|
+
{
|
|
22
|
+
meta:
|
|
23
|
+
description = "Common obfuscation patterns seen in malicious PDF embedded JavaScript (heap-spray prep, dynamic eval, string unescaping) -- heuristic, not a signature match."
|
|
24
|
+
strings:
|
|
25
|
+
$unescape = "unescape(" nocase
|
|
26
|
+
$eval = /eval\s*\(/ nocase
|
|
27
|
+
$heapspray = /%u[0-9a-f]{4}%u[0-9a-f]{4}/ nocase
|
|
28
|
+
condition:
|
|
29
|
+
2 of them
|
|
30
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scan-gateway
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Pluggable malware-scan orchestrator: tries configured scanner plugins, falls back to a built-in local heuristic check, decides accept/reject
|
|
5
|
+
Project-URL: Homepage, https://github.com/sanfx/scan-gateway
|
|
6
|
+
Project-URL: Repository, https://github.com/sanfx/scan-gateway
|
|
7
|
+
Author: sanfx
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Requires-Dist: yara-python>=4.5
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
16
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
<img src="logo.png" align="right" width="140" alt="scan-gateway logo" />
|
|
20
|
+
|
|
21
|
+
# scan-gateway
|
|
22
|
+
|
|
23
|
+
A pluggable malware-scan orchestrator for file uploads: tries configured
|
|
24
|
+
scanner plugins (in order), falls back to a built-in local heuristic check
|
|
25
|
+
when none can complete a scan, and raises a typed exception when something
|
|
26
|
+
is flagged. It doesn't scan anything itself -- it's a gateway in front of
|
|
27
|
+
whichever scanners you plug in.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from scan_gateway import ScanGateway, ThreatDetectedError
|
|
33
|
+
from scan_gateway.scanners.clamav import ClamAVScanner
|
|
34
|
+
|
|
35
|
+
gateway = ScanGateway(scanners=[ClamAVScanner(host="clamav.internal")])
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
await gateway.scan(Path("upload.pdf"))
|
|
39
|
+
except ThreatDetectedError as exc:
|
|
40
|
+
print(f"{exc.scanner_name} flagged this: {exc.verdict}")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
If `ClamAVScanner` can't be reached, `ScanGateway` falls back to its
|
|
44
|
+
built-in `LocalHeuristicScanner` (YARA + a couple of PDF-structural
|
|
45
|
+
keyword checks) automatically -- the caller never needs to know which
|
|
46
|
+
layer actually scanned the file.
|
|
47
|
+
|
|
48
|
+
## Writing a scanner plugin
|
|
49
|
+
|
|
50
|
+
This is the whole point of the package, so it comes first.
|
|
51
|
+
|
|
52
|
+
1. Add `scan-gateway` as a dependency (optional at runtime if your plugin
|
|
53
|
+
only relies on structural typing, see below).
|
|
54
|
+
2. Implement a class with:
|
|
55
|
+
- `name: str` -- used in log lines and in exception messages so it's
|
|
56
|
+
obvious which plugin did what.
|
|
57
|
+
- `async def scan(self, path: Path) -> None` -- return `None` when
|
|
58
|
+
clean. Raise `scan_gateway.ThreatDetectedError(self.name, verdict)`
|
|
59
|
+
when the file is flagged. Raise
|
|
60
|
+
`scan_gateway.ScannerUnavailableError(self.name, reason)` when the
|
|
61
|
+
scan itself couldn't be completed for operational reasons
|
|
62
|
+
(connection refused, timeout, malformed response, etc) -- never for
|
|
63
|
+
"clean", and never confuse the two: `ScanGateway` treats
|
|
64
|
+
`ScannerUnavailableError` as "try the next scanner", and
|
|
65
|
+
`ThreatDetectedError` as "stop, this file is rejected".
|
|
66
|
+
|
|
67
|
+
Because `Scanner` is a `typing.Protocol`, your class doesn't need to
|
|
68
|
+
import or subclass anything from `scan_gateway` at all -- structural
|
|
69
|
+
typing means "has a `.name` and a matching `.scan()`" is enough.
|
|
70
|
+
|
|
71
|
+
3. Decide how your plugin gets configured:
|
|
72
|
+
- **Auto-discovered** (zero code change on the consuming app's side):
|
|
73
|
+
your class needs a zero-argument constructor, reading whatever
|
|
74
|
+
config it needs from its own environment variables. Register it in
|
|
75
|
+
*your own* `pyproject.toml`:
|
|
76
|
+
```toml
|
|
77
|
+
[project.entry-points."scan_gateway.scanners"]
|
|
78
|
+
my_scanner = "my_scanner_pkg.plugin:MyScanner"
|
|
79
|
+
```
|
|
80
|
+
Once both packages are installed, `ScanGateway(discover_plugins=True)`
|
|
81
|
+
(the default) finds and instantiates it automatically.
|
|
82
|
+
- **Explicitly registered**: if your plugin needs config only known at
|
|
83
|
+
runtime (hosts, API keys, secrets) that can't reasonably live in an
|
|
84
|
+
environment variable your class reads unprompted, document that
|
|
85
|
+
consuming apps should import and instantiate it themselves, then pass
|
|
86
|
+
the instance to `ScanGateway(scanners=[...])`. This is exactly how
|
|
87
|
+
the bundled `ClamAVScanner` works (see below) -- it is **not**
|
|
88
|
+
auto-discovered, on purpose.
|
|
89
|
+
|
|
90
|
+
Nothing stops you from supporting both: a constructor with defaults
|
|
91
|
+
that fall back to environment variables, auto-discovered for the common
|
|
92
|
+
case, still explicitly constructible when a caller wants to pass
|
|
93
|
+
config directly.
|
|
94
|
+
|
|
95
|
+
4. `pip install` your plugin package alongside `scan-gateway`. That's it --
|
|
96
|
+
no code change required in `scan-gateway` itself.
|
|
97
|
+
|
|
98
|
+
The `"scan_gateway.scanners"` entry-point group name is a stable public
|
|
99
|
+
contract. It will not change in a way that breaks existing plugins without
|
|
100
|
+
a major version bump.
|
|
101
|
+
|
|
102
|
+
## What ships built-in, and why
|
|
103
|
+
|
|
104
|
+
| Scanner | Built-in? | Auto-discovered? |
|
|
105
|
+
|---|---|---|
|
|
106
|
+
| `scanners.clamav.ClamAVScanner` | Yes | No -- needs runtime host/port, same constraint any plugin needing real secrets has |
|
|
107
|
+
| `scanners.local_heuristic.LocalHeuristicScanner` | Yes, and not swappable via entry points | N/A -- it's the fallback `ScanGateway` always has, not a plugin slot |
|
|
108
|
+
|
|
109
|
+
**ClamAV** ships in the box because it's the obvious, free, well-known
|
|
110
|
+
default -- but it's wired the same way any third-party plugin needing
|
|
111
|
+
secrets would be: explicit construction with its own host/port/timeout,
|
|
112
|
+
passed into `ScanGateway(scanners=[...])`. It deliberately does *not*
|
|
113
|
+
register itself via the entry-point mechanism, since that mechanism exists
|
|
114
|
+
to solve "code `scan-gateway` doesn't know about at import time" -- and
|
|
115
|
+
`scan-gateway` does know about its own bundled `ClamAVScanner`.
|
|
116
|
+
|
|
117
|
+
**The local heuristic fallback is intentionally not pluggable.** It's the
|
|
118
|
+
one check every caller is guaranteed to get when nothing else could run --
|
|
119
|
+
letting it be swapped via a `pip install` would mean one bad or malicious
|
|
120
|
+
plugin package could silently disable the only guaranteed scan for anyone
|
|
121
|
+
who installs it. If you genuinely need to replace it (e.g. in tests), use
|
|
122
|
+
the explicit, auditable `ScanGateway(fallback=my_scanner)` constructor
|
|
123
|
+
override -- a code-level decision, not something a package index can
|
|
124
|
+
change out from under a deployment.
|
|
125
|
+
|
|
126
|
+
## Exceptions
|
|
127
|
+
|
|
128
|
+
| Exception | Meaning | Who raises it |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `ScanGatewayError` | Base class for everything this package raises | -- |
|
|
131
|
+
| `ThreatDetectedError` | A scanner positively flagged the file. Carries `.scanner_name` and `.verdict` | Any `Scanner` |
|
|
132
|
+
| `ScannerUnavailableError` | A scanner couldn't complete the scan for operational reasons. Carries `.scanner_name` and `.reason` | Any `Scanner`; caught internally by `ScanGateway`, not expected to reach your code directly |
|
|
133
|
+
|
|
134
|
+
## Contributing
|
|
135
|
+
|
|
136
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for dev setup, commit conventions
|
|
137
|
+
(required for automated releases), and what belongs in core vs. a scanner
|
|
138
|
+
module.
|
|
139
|
+
|
|
140
|
+
## Development
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
python3.11 -m venv .venv
|
|
144
|
+
source .venv/bin/activate
|
|
145
|
+
pip install -e ".[dev]"
|
|
146
|
+
pip install -e tests/fixtures/plugins # enables the real-plugin discovery test
|
|
147
|
+
ruff check .
|
|
148
|
+
pytest
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
The one integration test that needs a real `clamd` instance
|
|
152
|
+
(`tests/integration/test_clamav_live.py`) is skipped unless
|
|
153
|
+
`SCAN_GATEWAY_TEST_CLAMD_HOST` is set.
|
|
154
|
+
|
|
155
|
+
## Releasing
|
|
156
|
+
|
|
157
|
+
Releases are fully automated from [Conventional Commits](https://www.conventionalcommits.org/)
|
|
158
|
+
on `main`:
|
|
159
|
+
|
|
160
|
+
1. [release-please](https://github.com/googleapis/release-please) watches
|
|
161
|
+
every push to `main`, computes the next version from commit prefixes
|
|
162
|
+
(`feat:` → minor, `fix:` → patch, `BREAKING CHANGE:`/`!` → major), and
|
|
163
|
+
keeps a standing "release PR" with the version bump and generated
|
|
164
|
+
`CHANGELOG.md` up to date.
|
|
165
|
+
2. Merging that release PR creates a GitHub Release + tag, which sets
|
|
166
|
+
`release-please`'s own `release_created` output.
|
|
167
|
+
3. A second job in the same `.github/workflows/release-please.yml`,
|
|
168
|
+
gated on that output, builds the sdist/wheel and publishes to PyPI via
|
|
169
|
+
[Trusted Publishing](https://docs.pypi.org/trusted-publishers/) (OIDC)
|
|
170
|
+
-- no stored API token. (Publishing has to live in the *same* workflow
|
|
171
|
+
as release-please itself, not a separate workflow triggered by `on:
|
|
172
|
+
release:` -- a Release created via the default `GITHUB_TOKEN` doesn't
|
|
173
|
+
fire other workflows, by GitHub's own anti-recursion design.)
|
|
174
|
+
|
|
175
|
+
This means every commit to `main` should use a Conventional Commits prefix
|
|
176
|
+
for version bumps to compute correctly.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
scan_gateway/__init__.py,sha256=QYs03F8a_ofnucVeMlWwSI2g8qZicZkE7Vk7RiNuhsE,317
|
|
2
|
+
scan_gateway/discovery.py,sha256=5QIDy-ZkcZCnYT4Me7kSJdbg4RD5Xo76f9tpI4O9yTc,1464
|
|
3
|
+
scan_gateway/exceptions.py,sha256=6qlAsnVdmrQx_DLARncGgSfZT-yxvrQ7IHzLSI1Jbys,2196
|
|
4
|
+
scan_gateway/gateway.py,sha256=NB48NHe3X1Gm7zMQrvo285fOcMyXuU1LsYoXpiPhkKg,3138
|
|
5
|
+
scan_gateway/protocol.py,sha256=xAOxL9ZiewZpwWWCGyfPQUel-17_9f2Vc4dRNutB3vw,918
|
|
6
|
+
scan_gateway/scanners/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
scan_gateway/scanners/clamav.py,sha256=HNu3QL2xXwrVmhc88MXAuqsDRxAh2Mpax0Vj_He3SZc,3601
|
|
8
|
+
scan_gateway/scanners/local_heuristic.py,sha256=sGBr--5ioAoLuVcTsNskpkuvme1DPlq3bnaAGHO9zJ0,2314
|
|
9
|
+
scan_gateway/scanners/rules/suspicious_pdf.yar,sha256=fEP2lvYZp0juGUwvfIJ83_TOenlobGPlU0WTR-aosbY,1084
|
|
10
|
+
scan_gateway-0.1.1.dist-info/METADATA,sha256=0LeOWtbXhGrRuU_5JLrmgt87JevlwGdwu6N3LxaazKw,8041
|
|
11
|
+
scan_gateway-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
scan_gateway-0.1.1.dist-info/licenses/LICENSE,sha256=IDL1shFvnOCahKkEZa_9BbM4ZEJmu1B1IDvavttKPgI,1062
|
|
13
|
+
scan_gateway-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sanfx
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|