feat: build wahrwelt A/D toolkit
This commit is contained in:
1 parent
303438d206
commit
653924d8c6
564 files changed
+36310
-49998
No files matched your search
@@ -1,151 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Back up explicitly approved scalar JSON settings, never whole config files."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
MAX_FILE = 1024 * 1024
|
||||
SENSITIVE = re.compile(r"password|passwd|pwd|secret|token|credential|auth|cookie|"
|
||||
r"privatekey|apikey|accesskey|session|dsn|url|uri|connectionstring")
|
||||
|
||||
|
||||
def sensitive_key(key):
|
||||
return bool(SENSITIVE.search(re.sub(r"[^a-z0-9]", "", key.lower())))
|
||||
|
||||
|
||||
def unique_object(pairs):
|
||||
obj = {}
|
||||
for key, value in pairs:
|
||||
if key in obj:
|
||||
raise ValueError("duplicate JSON key")
|
||||
obj[key] = value
|
||||
return obj
|
||||
|
||||
|
||||
def reject_constant(value):
|
||||
raise ValueError("non-finite JSON number")
|
||||
|
||||
|
||||
def read_json(path):
|
||||
if not stat.S_ISREG(path.lstat().st_mode):
|
||||
raise ValueError("expected regular JSON file")
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(MAX_FILE + 1)
|
||||
if len(data) > MAX_FILE:
|
||||
raise ValueError("JSON file exceeds 1 MiB")
|
||||
return json.loads(data, object_pairs_hook=unique_object, parse_constant=reject_constant)
|
||||
|
||||
|
||||
def source_path(root, relative):
|
||||
if not isinstance(relative, str) or "\\" in relative or ":" in relative:
|
||||
raise ValueError("expected relative POSIX path")
|
||||
parts = relative.split("/")
|
||||
if any(part in {"", ".", ".."} for part in parts):
|
||||
raise ValueError("empty or traversal path component")
|
||||
rel = PurePosixPath(relative)
|
||||
if rel.suffix != ".json" or len(parts) > 16:
|
||||
raise ValueError("only relative JSON paths are supported")
|
||||
current = root
|
||||
for part in parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
raise ValueError("source symlinks are not supported")
|
||||
return current
|
||||
|
||||
|
||||
def project_settings(source, allowed):
|
||||
if not isinstance(allowed, list) or not 1 <= len(allowed) <= 256:
|
||||
raise ValueError("allow must contain 1..256 key paths")
|
||||
output, seen = {}, set()
|
||||
for keys in allowed:
|
||||
if (not isinstance(keys, list) or not 1 <= len(keys) <= 16
|
||||
or any(not isinstance(k, str) or not k or len(k) > 128 for k in keys)):
|
||||
raise ValueError("each key path must be a nonempty list of strings")
|
||||
if any(sensitive_key(k) for k in keys):
|
||||
raise ValueError("sensitive field name is not allowed")
|
||||
key_tuple = tuple(keys)
|
||||
if key_tuple in seen:
|
||||
raise ValueError("duplicate key path")
|
||||
seen.add(key_tuple)
|
||||
value = source
|
||||
for key in keys:
|
||||
if not isinstance(value, dict) or key not in value:
|
||||
raise ValueError("selected field is missing")
|
||||
value = value[key]
|
||||
if isinstance(value, (dict, list)):
|
||||
raise ValueError("select scalar leaves, not entire objects or lists")
|
||||
# Never implicitly retain an unselected sibling or nested value.
|
||||
target = output
|
||||
for key in keys[:-1]:
|
||||
target = target.setdefault(key, {})
|
||||
target[keys[-1]] = value
|
||||
return output
|
||||
|
||||
|
||||
def backup(root, manifest, output):
|
||||
root = root.resolve(strict=True)
|
||||
if not root.is_dir():
|
||||
raise ValueError("root must be a directory")
|
||||
if not isinstance(manifest, dict) or set(manifest) != {"files"}:
|
||||
raise ValueError("manifest needs only the files field")
|
||||
files = manifest["files"]
|
||||
if not isinstance(files, list) or not 1 <= len(files) <= 64:
|
||||
raise ValueError("files must contain 1..64 entries")
|
||||
prepared, seen = [], set()
|
||||
for entry in files:
|
||||
if not isinstance(entry, dict) or set(entry) != {"path", "allow"}:
|
||||
raise ValueError("file entry needs path and allow")
|
||||
source = source_path(root, entry["path"])
|
||||
if entry["path"] in seen:
|
||||
raise ValueError("duplicate source path")
|
||||
seen.add(entry["path"])
|
||||
selected = project_settings(read_json(source), entry["allow"])
|
||||
payload = (json.dumps(selected, ensure_ascii=True, indent=2, allow_nan=False) + "\n").encode()
|
||||
prepared.append((entry["path"], payload))
|
||||
|
||||
# Validate and sanitize every source before creating any backup files.
|
||||
output.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
session = Path(tempfile.mkdtemp(prefix="config-", dir=output))
|
||||
try:
|
||||
session.chmod(0o700)
|
||||
index = {"format": 1, "kind": "selected-settings", "files": []}
|
||||
for number, (source, payload) in enumerate(prepared, 1):
|
||||
name = f"settings-{number:03d}.json"
|
||||
dest = session / name
|
||||
with dest.open("xb") as stream:
|
||||
stream.write(payload)
|
||||
dest.chmod(0o600)
|
||||
index["files"].append({"source": source, "backup": name,
|
||||
"sha256": hashlib.sha256(payload).hexdigest()})
|
||||
index_path = session / "manifest.json"
|
||||
index_path.write_text(json.dumps(index, ensure_ascii=True, indent=2) + "\n", encoding="utf-8")
|
||||
index_path.chmod(0o600)
|
||||
except BaseException:
|
||||
shutil.rmtree(session)
|
||||
raise
|
||||
return session
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("manifest", type=Path)
|
||||
parser.add_argument("--root", required=True, type=Path, help="directory containing source configs")
|
||||
parser.add_argument("--output", type=Path, default=Path("artifacts/config-backups"))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
session = backup(args.root, read_json(args.manifest), args.output)
|
||||
print(session)
|
||||
return 0
|
||||
except (OSError, ValueError, TypeError, RecursionError) as exc:
|
||||
print(f"config backup: {type(exc).__name__}; no source values printed", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,47 +0,0 @@
|
||||
"""Small shared helpers; Python 3.10+, standard library only."""
|
||||
import argparse
|
||||
import math
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def opener():
|
||||
# Direct connections and no redirects: do not forward farm credentials.
|
||||
return build_opener(ProxyHandler({}), NoRedirect())
|
||||
|
||||
|
||||
def http_url(value):
|
||||
p = urlsplit(value)
|
||||
if p.scheme not in {"http", "https"} or not p.hostname:
|
||||
raise ValueError("expected an absolute http(s) URL")
|
||||
if p.username is not None or p.password is not None or p.fragment:
|
||||
raise ValueError("userinfo and fragments are not allowed in URLs")
|
||||
_ = p.port # Validate malformed/out-of-range ports.
|
||||
return value
|
||||
|
||||
|
||||
def positive_float(value):
|
||||
n = float(value)
|
||||
if not math.isfinite(n) or n <= 0:
|
||||
raise argparse.ArgumentTypeError("must be finite and greater than zero")
|
||||
return n
|
||||
|
||||
|
||||
def flag_pattern(value):
|
||||
pattern = re.compile(value)
|
||||
if pattern.search("") is not None:
|
||||
raise ValueError("flag regex must not match the empty string")
|
||||
return pattern
|
||||
|
||||
|
||||
def limited_read(response, limit=1024 * 1024):
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError(f"response exceeds {limit} bytes")
|
||||
return data
|
||||
+30
-33
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare two saved defense_scan JSON reports offline; never open source paths."""
|
||||
"""Сравнение двух сохраненных отчетов сканера без чтения исходников."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
@@ -14,12 +14,12 @@ import sys
|
||||
|
||||
MAX_REPORT_BYTES = 32 * 1024 * 1024
|
||||
MAX_FINDINGS = 100000
|
||||
SCOPE_SCHEMA = "durkahelper.scanner-scope.v2"
|
||||
LEGACY_SCOPE_SCHEMA = "durkahelper.scanner-scope.v1"
|
||||
SCOPE_SCHEMA = "wahrwelt.scanner-scope.v2"
|
||||
LEGACY_SCOPE_SCHEMA = "wahrwelt.scanner-scope.v1"
|
||||
PATH_SEMANTICS = "root-relative-posix.v1"
|
||||
NOTE = ("Matches exact path, line and rule ID without comparing source code. Moving lines creates a "
|
||||
"new/not-observed pair. A disappearing signal does not prove a fix. "
|
||||
"A clean comparison requires identical verified scopes.")
|
||||
NOTE = ("Сопоставляются путь, строка и правило без сравнения исходников. Перенос строк дает пару "
|
||||
"новая/не обнаружена. Исчезновение сигнала не доказывает исправление. "
|
||||
"Полное сравнение требует одинаковой подтвержденной области проверки.")
|
||||
|
||||
|
||||
def file_identity(metadata):
|
||||
@@ -116,12 +116,8 @@ def load_report(filename, max_bytes=MAX_REPORT_BYTES):
|
||||
requested_metadata = requested.lstat()
|
||||
if stat.S_ISLNK(requested_metadata.st_mode):
|
||||
raise ValueError("symlink report")
|
||||
# Resolve ordinary symlinked ancestors (notably macOS /tmp -> /private/tmp)
|
||||
# before the no-follow leaf open. This prevents an ancestor swap from
|
||||
# redirecting the descriptor while preserving the leaf-symlink boundary.
|
||||
# Path.resolve() may require extra handle permissions on Windows. The
|
||||
# macOS/Linux branch canonicalizes ancestors; Windows retains the absolute
|
||||
# path after the explicit leaf-symlink check.
|
||||
# Канонизируем родительские каталоги, но не конечную ссылку.
|
||||
# На Windows resolve может требовать дополнительных прав на дескриптор.
|
||||
path = requested if os.name == "nt" else requested.parent.resolve(strict=True) / requested.name
|
||||
canonical_metadata = path.lstat()
|
||||
if stat.S_ISLNK(canonical_metadata.st_mode):
|
||||
@@ -156,7 +152,8 @@ def load_report(filename, max_bytes=MAX_REPORT_BYTES):
|
||||
|
||||
|
||||
def validate_report(data):
|
||||
if not isinstance(data, dict) or data.get("tool") != "DurkaHelper defense_scan":
|
||||
if not isinstance(data, dict) or data.get("tool") not in {
|
||||
"wahrwelt defense_scan"}:
|
||||
raise ValueError("not a scanner report")
|
||||
if data.get("offline") is not True or type(data.get("partial")) is not bool:
|
||||
raise ValueError("invalid report status")
|
||||
@@ -193,7 +190,7 @@ def validate_report(data):
|
||||
key = (path, line, rule)
|
||||
if key in indexed:
|
||||
raise ValueError("duplicate finding")
|
||||
# Do not copy source text, patches, arbitrary descriptions or issue payloads.
|
||||
# Не переносим исходники, патчи и произвольные данные из отчета.
|
||||
indexed[key] = {"path": path, "line": line, "rule": rule}
|
||||
return {"version": version, "created_at": created_at, "scope": scope,
|
||||
"scope_sha256": scope["sha256"] if scope is not None else None,
|
||||
@@ -218,7 +215,7 @@ def compare_reports(before, after):
|
||||
added = [new[key] for key in sorted(new.keys() - old.keys())]
|
||||
existing = [new[key] for key in sorted(new.keys() & old.keys())]
|
||||
absent = [old[key] for key in sorted(old.keys() - new.keys())]
|
||||
return {"tool": "DurkaHelper defense_diff", "offline": True,
|
||||
return {"tool": "wahrwelt defense_diff", "offline": True,
|
||||
"matching": ["path", "line", "rule"], "scope_verified": scope_verified,
|
||||
"before": {"version": before["version"], "partial": before["partial"],
|
||||
"issue_count": before["issue_count"],
|
||||
@@ -239,12 +236,12 @@ def printable(value):
|
||||
def positive(value):
|
||||
number = int(value)
|
||||
if number <= 0:
|
||||
raise argparse.ArgumentTypeError("expected a positive integer")
|
||||
raise argparse.ArgumentTypeError("ожидалось положительное целое число")
|
||||
return number
|
||||
|
||||
|
||||
def configure_text_output():
|
||||
"""Keep CLI diagnostics printable on legacy Windows code pages."""
|
||||
"""Сохраняем читаемый вывод в старых кодировках Windows."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
reconfigure = getattr(stream, "reconfigure", None)
|
||||
if reconfigure is not None:
|
||||
@@ -256,37 +253,37 @@ def configure_text_output():
|
||||
|
||||
def main(argv=None):
|
||||
configure_text_output()
|
||||
parser = argparse.ArgumentParser(description="Compare two defense_scan JSON reports without reading source files.")
|
||||
parser.add_argument("before", help="previous JSON report")
|
||||
parser.add_argument("after", help="current JSON report")
|
||||
parser.add_argument("--json", action="store_true", help="structured JSON result")
|
||||
parser.add_argument("--show-existing", action="store_true", help="also show unchanged signals in text output")
|
||||
parser.add_argument("--max-bytes", type=positive, default=MAX_REPORT_BYTES, help="size limit for each report; default 32 MiB")
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("before", help="предыдущий JSON-отчет")
|
||||
parser.add_argument("after", help="текущий JSON-отчет")
|
||||
parser.add_argument("--json", action="store_true", help="результат в JSON")
|
||||
parser.add_argument("--show-existing", action="store_true", help="показать также неизменившиеся находки")
|
||||
parser.add_argument("--max-bytes", type=positive, default=MAX_REPORT_BYTES, help="лимит размера каждого отчета; по умолчанию 32 MiB")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
report = compare_reports(load_report(args.before, args.max_bytes), load_report(args.after, args.max_bytes))
|
||||
except (OSError, ValueError, OverflowError, RecursionError, MemoryError) as exc:
|
||||
# Exception messages can contain report contents, paths or secret fields.
|
||||
# Сообщение исключения может содержать секреты из отчета.
|
||||
error = {"error": "invalid_or_unreadable_report", "type": type(exc).__name__, "exit_code": 2}
|
||||
print(json.dumps(error) if args.json else "ERROR: invalid or unreadable report (" + type(exc).__name__ + ").")
|
||||
print(json.dumps(error) if args.json else "Ошибка: некорректный или недоступный отчет (" + type(exc).__name__ + ").")
|
||||
return 2
|
||||
if args.json:
|
||||
print(json.dumps(report, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
for field, label in (("new", "NEW"), ("not_observed", "NOT OBSERVED"), ("existing", "EXISTING")):
|
||||
for field, label in (("new", "НОВАЯ"), ("not_observed", "НЕ ОБНАРУЖЕНА"), ("existing", "ПРЕЖНЯЯ")):
|
||||
if field == "existing" and not args.show_existing:
|
||||
continue
|
||||
for finding in report[field]:
|
||||
print(f"{label}: {printable(finding['path'])}:{finding['line']} [{finding['rule']}]")
|
||||
counts = report["counts"]
|
||||
print(f"New: {counts['new']}; existing: {counts['existing']}; not observed: {counts['not_observed']}.")
|
||||
print(f"Новых: {counts['new']}; прежних: {counts['existing']}; не обнаружено: {counts['not_observed']}.")
|
||||
if report["warnings"]:
|
||||
descriptions = {"before_partial": "previous scan is partial",
|
||||
"after_partial": "current scan is partial",
|
||||
"scanner_version_changed": "scanner versions differ",
|
||||
"scope_unverified": "scope is missing or unverified",
|
||||
"scope_changed": "report scopes differ"}
|
||||
print("Incomplete comparison: " + ", ".join(descriptions[item] for item in report["warnings"]))
|
||||
descriptions = {"before_partial": "предыдущая проверка неполная",
|
||||
"after_partial": "текущая проверка неполная",
|
||||
"scanner_version_changed": "версии сканера различаются",
|
||||
"scope_unverified": "область проверки неизвестна",
|
||||
"scope_changed": "область проверки изменилась"}
|
||||
print("Неполное сравнение: " + ", ".join(descriptions[item] for item in report["warnings"]))
|
||||
print(NOTE)
|
||||
return report["exit_code"]
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+112
-124
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline, read-only source triage. Python 3.10+, standard library only.
|
||||
"""Локальная проверка исходников без записи. Только стандартная библиотека.
|
||||
|
||||
Never imports or executes scanned code. Rules are loaded only from the toolkit's
|
||||
own rules directory, never discovered inside the target. No network/update API.
|
||||
Код проекта не импортируется и не запускается. Правила берутся только из этого
|
||||
репозитория; поиск правил внутри проверяемого проекта не выполняется.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,8 +24,8 @@ import io
|
||||
import unicodedata
|
||||
|
||||
VERSION = "1.8.0"
|
||||
SCOPE_SCHEMA = "durkahelper.scanner-scope.v2"
|
||||
CONTEXT_SCHEMA = "durkahelper.scanner-context.v1"
|
||||
SCOPE_SCHEMA = "wahrwelt.scanner-scope.v2"
|
||||
CONTEXT_SCHEMA = "wahrwelt.scanner-context.v1"
|
||||
SEMANTIC_REVISION = "bounded-source-signals.v3"
|
||||
INFRASTRUCTURE = {"docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"}
|
||||
PATH_SEMANTICS = "root-relative-posix.v1"
|
||||
@@ -86,7 +86,7 @@ def _canonical_json(value):
|
||||
|
||||
|
||||
def validate_context(value=None):
|
||||
"""Allow only non-secret context enums; context never filters detectors."""
|
||||
"""Контекст содержит только разрешенные значения и не отключает правила."""
|
||||
if value is None:
|
||||
value = {"schema": CONTEXT_SCHEMA, "infrastructure": [], "role": "both"}
|
||||
if not isinstance(value, dict) or set(value) != {"schema", "infrastructure", "role"}:
|
||||
@@ -115,16 +115,16 @@ def load_context(filename):
|
||||
|
||||
|
||||
def review_metadata(rule, context):
|
||||
"""Return authored explanations only, never strings taken from the target."""
|
||||
"""Пояснения берутся из правил, а не из проверяемых исходников."""
|
||||
notes = []
|
||||
active = set(context["infrastructure"])
|
||||
family = rule["family"]
|
||||
if active & {"compose", "docker-desktop"} and family == "container-isolation":
|
||||
notes.append("Review this setting in the resolved deployment model; source text is not runtime evidence.")
|
||||
notes.append("Проверьте эту настройку в итоговой конфигурации; исходный текст не подтверждает поведение runtime.")
|
||||
if active & {"team-lan", "s4dfarm", "neo", "packmate"} and family in {"authentication", "secret-handling", "network-exposure"}:
|
||||
notes.append("Check access from a separate authorized LAN client and keep credentials out of logs and broadcasts.")
|
||||
notes.append("Проверьте доступ с отдельного разрешенного клиента LAN; не выводите учетные данные в логи и трансляцию.")
|
||||
if "vulnbox" in active and family in {"injection", "file-access", "authentication"}:
|
||||
notes.append("Verify the service contract and checker behavior before applying a patch to a Vulnbox service.")
|
||||
notes.append("До изменения сервиса проверьте его контракт и поведение проверяющей системы.")
|
||||
return {"family": family, "cwe": list(rule["cwe"]),
|
||||
"review_priority": "high" if notes else rule["review_priority"],
|
||||
"signal_kind": rule["signal_kind"], "limitations": rule["limitations"],
|
||||
@@ -132,7 +132,7 @@ def review_metadata(rule, context):
|
||||
|
||||
|
||||
def rules_fingerprint(rules):
|
||||
"""Hash only authored rule data, never runtime regex objects."""
|
||||
"""Хешируем данные правил без скомпилированных регулярных выражений."""
|
||||
portable = []
|
||||
for rule in sorted(rules, key=lambda item: item["id"]):
|
||||
portable.append({key: value for key, value in rule.items()
|
||||
@@ -141,10 +141,10 @@ def rules_fingerprint(rules):
|
||||
|
||||
|
||||
def scan_scope(root, rules, exclude, max_bytes, max_files, max_findings, context=None):
|
||||
"""Return a deterministic, non-secret description of scan comparability."""
|
||||
"""Описание области проверки для сравнения отчетов, без секретов."""
|
||||
normalized_root = unicodedata.normalize("NFC", os.path.normcase(str(root)))
|
||||
root_digest = hashlib.sha256(
|
||||
("durkahelper-root-v1\0" + normalized_root).encode(
|
||||
("wahrwelt-root-v1\0" + normalized_root).encode(
|
||||
"utf-8", errors="surrogatepass"
|
||||
)
|
||||
).hexdigest()
|
||||
@@ -178,12 +178,12 @@ def language(path):
|
||||
|
||||
|
||||
class PythonSignals(ast.NodeVisitor):
|
||||
"""Syntactic signals only. No claim of type resolution or data-flow analysis."""
|
||||
"""Синтаксические признаки без вывода типов и анализа потоков данных."""
|
||||
|
||||
def __init__(self):
|
||||
self.aliases = {}
|
||||
# Only immutable scalar/string-expression facts from straight-line code.
|
||||
# No mutable dict/list propagation, execution or interprocedural analysis.
|
||||
# Учитываем только неизменяемые скалярные факты в линейном коде.
|
||||
# Не вычисляем код, изменяемые коллекции и связи между функциями.
|
||||
self.values = {}
|
||||
self.hits = set()
|
||||
self.issues = set()
|
||||
@@ -194,10 +194,9 @@ class PythonSignals(ast.NodeVisitor):
|
||||
|
||||
@staticmethod
|
||||
def literal_dict(node):
|
||||
"""Known keys of an inline dict, respecting last-write-wins unpacking.
|
||||
"""Ключи литерала словаря с учетом порядка распаковки.
|
||||
|
||||
Unknown spreads/keys invalidate earlier facts; no dict variable is
|
||||
evaluated or treated as an immutable copy of a mutable object.
|
||||
Неизвестные ключи отменяют предыдущие факты. Переменные не вычисляются.
|
||||
"""
|
||||
result = {}
|
||||
if not isinstance(node, ast.Dict):
|
||||
@@ -239,7 +238,7 @@ class PythonSignals(ast.NodeVisitor):
|
||||
return self.TAR_FACTORIES.get(factory, self.INSTANCE_FACTORIES.get(factory, ""))
|
||||
|
||||
def known_binding(self, node):
|
||||
"""Whether the new narrow detectors have an explicit local name fact."""
|
||||
"""Есть ли для имени явный локальный факт."""
|
||||
if isinstance(node, ast.Name):
|
||||
return node.id in self.aliases and self.aliases[node.id] != "<local>"
|
||||
if isinstance(node, ast.Attribute):
|
||||
@@ -286,7 +285,7 @@ class PythonSignals(ast.NodeVisitor):
|
||||
|
||||
def visit_AnnAssign(self, node):
|
||||
if node.value is not None:
|
||||
# Reuse assignment handling, retaining the original line number.
|
||||
# Повторно используем обработку присваивания, сохраняя номер строки.
|
||||
assignment = ast.Assign(targets=[node.target], value=node.value)
|
||||
ast.copy_location(assignment, node)
|
||||
self.visit_Assign(assignment)
|
||||
@@ -306,8 +305,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
self.forget(target)
|
||||
|
||||
def visit_branch(self, node):
|
||||
# Do not carry scalar facts across branches, loops, exception handlers,
|
||||
# comprehensions or context managers. Scan each statement list locally.
|
||||
# Факты не переходят через ветвления, циклы, обработчики исключений,
|
||||
# генераторы и менеджеры контекста. Каждый блок проверяется отдельно.
|
||||
self.values = {}
|
||||
saved = self.aliases.copy()
|
||||
for _, value in ast.iter_fields(node):
|
||||
@@ -323,7 +322,7 @@ class PythonSignals(ast.NodeVisitor):
|
||||
self.values = {}
|
||||
|
||||
def invalidate_region_aliases(self, node, saved):
|
||||
# Any store/import in a conditional region makes that alias uncertain.
|
||||
# Присваивание или импорт внутри условия делает псевдоним неоднозначным.
|
||||
self.aliases = saved
|
||||
for child in ast.walk(node):
|
||||
if isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)):
|
||||
@@ -333,9 +332,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
self.aliases[alias.asname or alias.name.split(".")[0]] = "<local>"
|
||||
|
||||
def visit_context(self, node, *, asynchronous):
|
||||
# Retain only known constructor types with the matching context API.
|
||||
# Scalar facts never cross a context manager; __enter__/__exit__ may
|
||||
# affect application state and are never executed by this scanner.
|
||||
# Сохраняем лишь известные конструкторы с подходящим API контекста.
|
||||
# __enter__/__exit__ могут менять состояние; сканер их не исполняет.
|
||||
allowed = {"httpx.AsyncClient"} if asynchronous else {"tarfile.TarFile", "requests.Session", "httpx.Client"}
|
||||
saved = self.aliases.copy()
|
||||
self.values = {}
|
||||
@@ -395,8 +393,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
saved, saved_values = self.aliases.copy(), self.values.copy()
|
||||
auth_seen = False
|
||||
for decorator in node.decorator_list:
|
||||
# Decorators are listed outermost first. Flask's registration
|
||||
# decorator must wrap the authentication decorator, not vice versa.
|
||||
# Внешние декораторы идут первыми. Декоратор маршрута Flask
|
||||
# должен оборачивать декоратор аутентификации.
|
||||
if self.name(decorator) == "flask_login.login_required" and self.known_binding(decorator):
|
||||
auth_seen = True
|
||||
if (auth_seen and isinstance(decorator, ast.Call)
|
||||
@@ -412,7 +410,7 @@ class PythonSignals(ast.NodeVisitor):
|
||||
if default is not None:
|
||||
self.visit(default)
|
||||
self.values = {}
|
||||
# Parameters shadow imports. Function-local scalar facts do not escape.
|
||||
# Параметры скрывают импорты. Факты функции не выходят за ее границы.
|
||||
arguments = node.args.posonlyargs + node.args.args + node.args.kwonlyargs
|
||||
arguments += [arg for arg in (node.args.vararg, node.args.kwarg) if arg]
|
||||
for arg in arguments:
|
||||
@@ -453,8 +451,7 @@ class PythonSignals(ast.NodeVisitor):
|
||||
|
||||
@staticmethod
|
||||
def literal_string(node):
|
||||
# Recognize syntax only: no evaluation, formatting, arbitrary constant
|
||||
# folding or recursive expansion of names (which may be self-referential).
|
||||
# Проверяем синтаксис без вычислений и рекурсивного раскрытия имен.
|
||||
if isinstance(node, ast.Constant):
|
||||
return isinstance(node.value, str)
|
||||
if isinstance(node, ast.JoinedStr):
|
||||
@@ -481,11 +478,10 @@ class PythonSignals(ast.NodeVisitor):
|
||||
self.hit("CFG-COOKIE-FLAGS", node)
|
||||
|
||||
def psycopg_sql(self, node, depth=0, active=None):
|
||||
"""Return safe/unsafe/unknown for a narrow, imported composable tree.
|
||||
"""Оцениваем дерево SQL-композиции: safe, unsafe или unknown.
|
||||
|
||||
SQL() never escapes its argument. Only literal SQL snippets and known
|
||||
quoting constructors are suppressed; unknown pieces remain reviewable.
|
||||
This says nothing about authorization to select an identifier.
|
||||
SQL() не экранирует аргумент. Исключаем только литералы и известные
|
||||
конструкторы экранирования. Права на выбор идентификатора не проверяются.
|
||||
"""
|
||||
node = self.resolved(node)
|
||||
active = set() if active is None else active
|
||||
@@ -526,8 +522,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
self.hits.add((rule, node.lineno))
|
||||
|
||||
def visit_Assert(self, node):
|
||||
# Runtime security checks must survive python -O; ordinary test asserts
|
||||
# are deliberately omitted by this name-based heuristic.
|
||||
# Защитные проверки должны работать с python -O.
|
||||
# Обычные тестовые assert исключены этой эвристикой по имени.
|
||||
sensitive = re.compile(r"(?:auth|permission|owner|admin|token|session|password|allowed)", re.I)
|
||||
if any(isinstance(item, ast.Name) and sensitive.search(item.id)
|
||||
or isinstance(item, ast.Attribute) and sensitive.search(item.attr)
|
||||
@@ -567,8 +563,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
if (self.known_binding(node.func) and name.rsplit(".", 1)[0] in {"logging", "logging.Logger", "flask.Flask.logger"}
|
||||
and tail in {"debug", "info", "warning", "warn", "error", "exception", "critical", "log"}):
|
||||
sensitive = {"password", "passwd", "secret", "token", "access_token", "refresh_token", "api_key", "authorization"}
|
||||
# Only direct values/format expressions, not arguments to a
|
||||
# potential redaction/hash helper. No source text is exported.
|
||||
# Только прямые значения, без аргументов функций очистки или хеша.
|
||||
# Исходный текст в отчет не попадает.
|
||||
def exposes(value):
|
||||
if isinstance(value, ast.Name):
|
||||
return value.id.lower() in sensitive
|
||||
@@ -612,8 +608,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
"joblib.load", "pandas.read_pickle"}:
|
||||
self.hit("PY-DESERIALIZE", node)
|
||||
if name in {"numpy.load", "numpy.lib.format.read_array"}:
|
||||
# These APIs default to rejecting pickle; signal only an explicit
|
||||
# opt-in. Starred argv prevent a reliable positional index.
|
||||
# Эти API запрещают pickle по умолчанию; ищем явное разрешение.
|
||||
# Распаковка аргументов мешает определить позиционный индекс.
|
||||
position = 2 if name == "numpy.load" else 1
|
||||
allow_pickle = kwargs.get("allow_pickle")
|
||||
if (allow_pickle is None and len(node.args) > position
|
||||
@@ -659,8 +655,8 @@ class PythonSignals(ast.NodeVisitor):
|
||||
jwt_args = kwargs.copy()
|
||||
valid_binding = True
|
||||
if known_modern:
|
||||
# Generic jwt.decode is version-dependent: PyJWT 1.x placed
|
||||
# verify third. Only these exact APIs have this known layout.
|
||||
# В PyJWT 1.x verify был третьим аргументом.
|
||||
# Такое расположение известно только для этих точных API.
|
||||
for argument, position in (("algorithms", 2), ("options", 3)):
|
||||
if (len(node.args) > position
|
||||
and not any(isinstance(arg, ast.Starred) for arg in node.args[:position + 1])):
|
||||
@@ -732,10 +728,9 @@ class PythonSignals(ast.NodeVisitor):
|
||||
|
||||
|
||||
def javascript_alias_patterns(source):
|
||||
"""Bounded import-name hints, not a JavaScript parser or scope analysis.
|
||||
"""Подсказки по импортам без полного разбора JavaScript и областей видимости.
|
||||
|
||||
Source is never evaluated. Only exact known module/member pairs contribute
|
||||
patterns, and every target-controlled identifier is escaped first.
|
||||
Учитываются лишь известные пары модуль-член; имена экранируются.
|
||||
"""
|
||||
ident = r"[A-Za-z_$][\w$]{0,127}"
|
||||
module = r"['\"]((?:node:)?child_process|jsonwebtoken|jose)['\"]"
|
||||
@@ -785,12 +780,11 @@ def javascript_alias_patterns(source):
|
||||
|
||||
|
||||
def javascript_boundary_signals(source):
|
||||
"""Small bounded token contracts, NOT a JS parser or taint engine.
|
||||
"""Ограниченные шаблоны токенов без полного разбора JS и потоков данных.
|
||||
|
||||
Exact imports/constructors, inline objects and direct request properties
|
||||
only. Any observed redeclaration, parameter shadow or reassignment makes
|
||||
that binding unusable throughout this file. Regex literals, destructured
|
||||
imports, dynamic spreads/keys, wrappers and cross-file facts stay manual.
|
||||
Учитываются точные импорты, конструкторы, литералы объектов и поля запроса.
|
||||
Повторное объявление или присваивание отменяет факт во всем файле.
|
||||
Динамические ключи, обертки и связи между файлами требуют ручной проверки.
|
||||
"""
|
||||
issues, tokens = [], []
|
||||
token_pattern = re.compile(r"[A-Za-z_$][\w$]*|[0-9]+|=>|\.\.\.|\?\.|===|==|!=|\+=|-=|\+\+|--|[^\s]")
|
||||
@@ -812,8 +806,8 @@ def javascript_boundary_signals(source):
|
||||
start = i
|
||||
if (source[i] == "/"
|
||||
and (not tokens or tokens[-1][0] in {"=", "(", "[", ":", ",", "return", "=>", "!", "?", ";"})):
|
||||
# Common regex-literal positions only; division and ambiguous
|
||||
# statement contexts are not resolved as by a full JS grammar.
|
||||
# Учитываем обычные позиции regex-литералов.
|
||||
# Неоднозначность с оператором деления требует ручной проверки.
|
||||
end, character_class = i + 1, False
|
||||
while end < len(source) and source[end] not in "\r\n":
|
||||
if source[end] == "\\":
|
||||
@@ -869,7 +863,7 @@ def javascript_boundary_signals(source):
|
||||
closing_pairs = {right: left for left, right in pairs.items()}
|
||||
|
||||
def fields(begin, end):
|
||||
"""Split top-level commas only, under a fixed expression budget."""
|
||||
"""Разделяем по запятым верхнего уровня с ограничением размера выражения."""
|
||||
if end - begin > 2048:
|
||||
issues.append("javascript_expression_limit")
|
||||
return []
|
||||
@@ -896,7 +890,7 @@ def javascript_boundary_signals(source):
|
||||
if re.fullmatch(r"[A-Za-z_$][\w$]*", key):
|
||||
result[key] = (left + 2, right)
|
||||
continue
|
||||
# Unknown spreads/computed keys may override any preceding key.
|
||||
# Неизвестная распаковка или вычисляемый ключ отменяет предыдущие.
|
||||
result.clear()
|
||||
return result
|
||||
|
||||
@@ -944,7 +938,7 @@ def javascript_boundary_signals(source):
|
||||
pos += 1
|
||||
return False # Calls (including alleged redactors) are not traced.
|
||||
|
||||
# Parameters are a conservative file-wide uncertainty, not scope typing.
|
||||
# Параметры считаются неоднозначными во всем файле, без вывода типов.
|
||||
parameter_names = set()
|
||||
for pos, value in enumerate(texts):
|
||||
if value == "(" and pos in pairs and pairs[pos] + 1 < len(texts) and texts[pairs[pos] + 1] == "{":
|
||||
@@ -975,7 +969,7 @@ def javascript_boundary_signals(source):
|
||||
following = texts[pos + 1] if pos + 1 < len(texts) else ""
|
||||
if previous in {"const", "let", "var", "function", "class", "import"} or following in {"=", "+=", "-=", "++", "--"}:
|
||||
return False
|
||||
# Known API member replaced with a local function/value.
|
||||
# Член известного API заменен локальной функцией или значением.
|
||||
if following in {".", "?."}:
|
||||
end = pos + 1
|
||||
while end + 1 < len(texts) and texts[end] in {".", "?."}:
|
||||
@@ -983,7 +977,7 @@ def javascript_boundary_signals(source):
|
||||
if end < len(texts) and texts[end] in {"=", "+=", "-=", "++", "--"}:
|
||||
return False
|
||||
if previous in {"{", ","} and following in {"}", ","}:
|
||||
# Destructured declarations/imports cannot establish a fact.
|
||||
# Деструктуризация в объявлениях и импортах не создает факт.
|
||||
left = max(0, pos - 128)
|
||||
if any(texts[k] in {"const", "let", "var", "import"} for k in range(left, pos)):
|
||||
return False
|
||||
@@ -1009,7 +1003,7 @@ def javascript_boundary_signals(source):
|
||||
bindings[texts[local_pos]] = (mod, module_pos + 1)
|
||||
if len(bindings) > 128:
|
||||
return set(), ["javascript_alias_limit"]
|
||||
# Direct default/namespace driver factories; named imports remain manual.
|
||||
# Фабрики из default/namespace; именованные импорты проверяются вручную.
|
||||
for pos, value in enumerate(texts):
|
||||
if value not in {"const", "let", "var"} or pos + 7 >= len(texts) or texts[pos + 2] != "=":
|
||||
continue
|
||||
@@ -1070,11 +1064,11 @@ def javascript_boundary_signals(source):
|
||||
|
||||
|
||||
def redis_acl_passwordless(line):
|
||||
"""Conservative shared token subset of redis.conf and external ACL files.
|
||||
"""Общее подмножество токенов redis.conf и файлов ACL.
|
||||
|
||||
This reads a complete physical line, not an effective ACL. Quotes, escapes,
|
||||
selectors, unknown operations and interior non-space whitespace stay manual.
|
||||
Never include tokens (which can contain passwords) in a report.
|
||||
Читаем полную строку, не вычисляя итоговую ACL. Кавычки, экранирование,
|
||||
селекторы и неизвестные операции требуют проверки. Токены могут содержать
|
||||
пароли и не должны попадать в отчет.
|
||||
"""
|
||||
line = line.strip(" \t\r\n")
|
||||
if any(char in line for char in "\"'\\()") or any(char.isspace() and char != " " for char in line):
|
||||
@@ -1097,8 +1091,8 @@ def redis_acl_passwordless(line):
|
||||
elif operation == "nopass":
|
||||
passwordless = True
|
||||
elif operation == "resetpass" or token.startswith(">"):
|
||||
# Even a lone > adds the empty password and clears the nopass flag;
|
||||
# absence of this signal does not establish password strength.
|
||||
# Даже одиночный > добавляет пустой пароль и снимает nopass.
|
||||
# Отсутствие сигнала не подтверждает стойкость пароля.
|
||||
passwordless = False
|
||||
elif token.startswith("#"):
|
||||
if not re.fullmatch(r"#[0-9a-f]{64}", token):
|
||||
@@ -1109,8 +1103,8 @@ def redis_acl_passwordless(line):
|
||||
return False
|
||||
elif (operation in neutral or token.startswith(("<", "~", "&", "+", "-"))
|
||||
or operation.startswith(("%r~", "%w~", "%rw~"))):
|
||||
# Access grants/revocations and password removals do not change
|
||||
# either flag. Validity and least privilege are separate reviews.
|
||||
# Разрешения и удаление паролей не меняют эти флаги.
|
||||
# Корректность и минимальность прав проверяются отдельно.
|
||||
continue
|
||||
else:
|
||||
return False
|
||||
@@ -1118,12 +1112,10 @@ def redis_acl_passwordless(line):
|
||||
|
||||
|
||||
def bounded_regex_windows(lines):
|
||||
"""Whole LF lines only; never invent an end-of-token by slicing a line.
|
||||
"""Окна из целых LF-строк: до 12 строк и 8192 символов, включая CR/LF.
|
||||
|
||||
Each window has at most 12 lines and 8192 characters, including CR/LF.
|
||||
Adaptive overlap retains every supported line after a size boundary. A
|
||||
multi-line match beyond these window bounds remains outside the contract.
|
||||
Only actually skipped oversized lines make the analysis partial.
|
||||
Перекрытие сохраняет строки на границе окон. Более длинные совпадения
|
||||
не поддерживаются. Пропуск слишком длинной строки делает отчет неполным.
|
||||
"""
|
||||
windows = []
|
||||
skipped_line = False
|
||||
@@ -1141,7 +1133,7 @@ def bounded_regex_windows(lines):
|
||||
if end == len(lines):
|
||||
break
|
||||
if len(lines[end]) > 8192:
|
||||
# Do not concatenate supported lines across omitted input.
|
||||
# Не склеиваем строки через пропущенный участок.
|
||||
start = end
|
||||
else:
|
||||
start = max(start + 1, end - 6)
|
||||
@@ -1149,11 +1141,10 @@ def bounded_regex_windows(lines):
|
||||
|
||||
|
||||
def lexical_noncode(source, lang):
|
||||
"""Bounded lexical exclusions for opt-in new rules, not a full parser.
|
||||
"""Исключение обычных строковых литералов и комментариев для части правил.
|
||||
|
||||
Common quoted literals/comments are recognized. Language-specific regex
|
||||
literals, macros, heredocs and complex interpolation still need review.
|
||||
Offsets and physical line numbers are never changed.
|
||||
Regex-литералы, макросы, heredoc и сложная интерполяция требуют проверки.
|
||||
Смещения и физические номера строк сохраняются.
|
||||
"""
|
||||
excluded = bytearray(len(source))
|
||||
issues = []
|
||||
@@ -1196,7 +1187,7 @@ def lexical_noncode(source, lang):
|
||||
quote = source[i]
|
||||
if (lang == "rust" and quote == "'"
|
||||
and not re.match(r"'(?:[^'\\\n]|\\(?:[nrt0'\"\\]|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]{1,8}\}))'", source[i:i + 16])):
|
||||
# Rust lifetimes/labels are not character literals.
|
||||
# Времена жизни и метки Rust не являются символьными литералами.
|
||||
i += 1
|
||||
continue
|
||||
i += 1
|
||||
@@ -1235,10 +1226,10 @@ def scan_text(source, lang, rules):
|
||||
hits.update(visitor.hits)
|
||||
problems.extend(sorted(visitor.issues))
|
||||
except (SyntaxError, ValueError, RecursionError, MemoryError) as exc:
|
||||
# Avoid including offending source/secret text from SyntaxError.
|
||||
# SyntaxError может содержать исходный текст и секреты.
|
||||
problems.append("python_parse_failed:" + type(exc).__name__)
|
||||
# str.splitlines also treats VT/FF/NEL/Unicode separators as line breaks.
|
||||
# Regex MULTILINE and import hints use LF; preserve that physical layout.
|
||||
# splitlines также разделяет по VT/FF/NEL/Unicode.
|
||||
# Regex MULTILINE и подсказки импортов используют только LF.
|
||||
parts = source.split("\n")
|
||||
lines = [line + "\n" for line in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
|
||||
line_offsets = []
|
||||
@@ -1252,8 +1243,8 @@ def scan_text(source, lang, rules):
|
||||
problems.extend(boundary_issues)
|
||||
try:
|
||||
newlines = [i for i, char in enumerate(source) if char == "\n"]
|
||||
# Import declarations and call sites may be far apart. Known call
|
||||
# prefixes are searched under the file-size and alias-count limits.
|
||||
# Импорт и вызов могут быть далеко друг от друга.
|
||||
# Поиск ограничен размером файла и числом псевдонимов.
|
||||
for rid, pattern, declaration_end in javascript_alias_patterns(source):
|
||||
for match in pattern.finditer(source, declaration_end):
|
||||
hits.add((rid, bisect_right(newlines, match.start()) + 1))
|
||||
@@ -1273,15 +1264,14 @@ def scan_text(source, lang, rules):
|
||||
for match in pattern.finditer(window):
|
||||
absolute = line_offsets[start] + match.start()
|
||||
if rule.get("code_only") and noncode[absolute]:
|
||||
# Only flag uncertain lexical exclusions when they hide a
|
||||
# candidate for these opt-in rules. This is not a general
|
||||
# syntax validator for all legacy textual rules.
|
||||
# Отмечаем неоднозначность, лишь если она скрывает совпадение
|
||||
# этих правил. Это не общая проверка синтаксиса языка.
|
||||
if lexical_issues and "lexical_unterminated" not in problems:
|
||||
problems.append("lexical_unterminated")
|
||||
continue
|
||||
if rule["id"] == "PHP-SHELL" and re.search(r"(?:->|::)\s*$", source[max(0, absolute - 128):absolute]):
|
||||
# PDO::exec is SQL, not PHP's exec(). Receiver semantics
|
||||
# for arbitrary user methods require manual review.
|
||||
# PDO::exec выполняет SQL, в отличие от PHP exec().
|
||||
# Назначение произвольных методов проверяется вручную.
|
||||
continue
|
||||
line = start + window.count("\n", 0, match.start()) + 1
|
||||
if rule["id"] == "CFG-REDIS-ACL":
|
||||
@@ -1302,19 +1292,17 @@ def secret_file(name):
|
||||
|
||||
|
||||
def canonical_scan_root(path):
|
||||
"""Resolve ancestor links while retaining a no-symlink file boundary.
|
||||
"""Разрешаем ссылки в родительских каталогах, но не в конечном пути.
|
||||
|
||||
macOS exposes ordinary locations such as /tmp through a symlinked ancestor.
|
||||
Resolve only ancestors so a leaf swap cannot be followed by canonicalization.
|
||||
The final entry supplied as the root must never itself be a symlink.
|
||||
Это поддерживает системные ссылки macOS вроде /tmp и сохраняет запрет
|
||||
на символическую ссылку вместо выбранного файла или каталога.
|
||||
"""
|
||||
requested = Path(os.path.abspath(path))
|
||||
metadata = requested.lstat()
|
||||
if stat.S_ISLNK(metadata.st_mode):
|
||||
raise ValueError("root leaf is a symlink")
|
||||
# Path.resolve() calls a privileged handle API on Windows and can fail for
|
||||
# otherwise readable files in managed environments. Windows does not need
|
||||
# the macOS ancestor canonicalization this branch exists to support.
|
||||
# На Windows resolve может требовать дополнительных прав на дескриптор.
|
||||
# Канонизация системных ссылок macOS на Windows не нужна.
|
||||
canonical = requested if os.name == "nt" else requested.parent.resolve(strict=True) / requested.name
|
||||
canonical_metadata = canonical.lstat()
|
||||
if stat.S_ISLNK(canonical_metadata.st_mode):
|
||||
@@ -1332,8 +1320,8 @@ def file_identity(metadata):
|
||||
|
||||
|
||||
def read_regular(path, limit):
|
||||
# Prevent leaf symlink swaps and FIFO hangs. Parents should be quiescent:
|
||||
# this is a local snapshot reader, not an OS sandbox for racing attackers.
|
||||
# Защищаемся от подмены конечного пути ссылкой и зависания на FIFO.
|
||||
# Родительские каталоги должны быть неизменны во время чтения.
|
||||
flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) |
|
||||
getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
||||
fd = os.open(path, flags)
|
||||
@@ -1367,7 +1355,7 @@ def scan(root, rules, *, exclude=(), max_bytes=1048576, max_files=20000, max_fin
|
||||
raise ValueError("root must be an existing regular file or directory")
|
||||
exclude = tuple(sorted(set(exclude)))
|
||||
by_id = {r["id"]: r for r in rules}
|
||||
report = {"tool": "DurkaHelper defense_scan", "version": VERSION, "offline": True,
|
||||
report = {"tool": "wahrwelt defense_scan", "version": VERSION, "offline": True,
|
||||
"created_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
"scope": scan_scope(root, rules, exclude, max_bytes, max_files, max_findings, context),
|
||||
"findings": [], "issues": [], "skipped": {}, "files_scanned": 0,
|
||||
@@ -1386,7 +1374,7 @@ def scan(root, rules, *, exclude=(), max_bytes=1048576, max_files=20000, max_fin
|
||||
while stack:
|
||||
directory = stack.pop()
|
||||
try:
|
||||
# Bound enumeration even when a directory has millions of entries.
|
||||
# Ограничиваем перебор даже для каталогов с миллионами записей.
|
||||
entries = []
|
||||
with os.scandir(directory) as items:
|
||||
for entry in items:
|
||||
@@ -1461,19 +1449,19 @@ def scan(root, rules, *, exclude=(), max_bytes=1048576, max_files=20000, max_fin
|
||||
|
||||
|
||||
def terminal(value):
|
||||
# Escape filenames/control characters instead of interpreting terminal escapes.
|
||||
# Экранируем управляющие символы и последовательности терминала в именах.
|
||||
return json.dumps(str(value), ensure_ascii=True)[1:-1] if not str(value).isprintable() else str(value)
|
||||
|
||||
|
||||
def positive(value):
|
||||
number = int(value)
|
||||
if number < 1:
|
||||
raise argparse.ArgumentTypeError("must be positive")
|
||||
raise argparse.ArgumentTypeError("значение должно быть положительным")
|
||||
return number
|
||||
|
||||
|
||||
def configure_text_output():
|
||||
"""Keep CLI diagnostics printable on legacy Windows code pages."""
|
||||
"""Сохраняем читаемый вывод в старых кодировках Windows."""
|
||||
for stream in (sys.stdout, sys.stderr):
|
||||
reconfigure = getattr(stream, "reconfigure", None)
|
||||
if reconfigure is not None:
|
||||
@@ -1486,13 +1474,13 @@ def configure_text_output():
|
||||
def main(argv=None):
|
||||
configure_text_output()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("root", nargs="?", help="local source directory or file")
|
||||
parser.add_argument("--json", action="store_true", help="JSON report to stdout, including patch templates")
|
||||
parser.add_argument("--patches", action="store_true", help="show before/after templates in text output")
|
||||
parser.add_argument("--list-rules", action="store_true")
|
||||
parser.add_argument("--explain", metavar="RULE_ID")
|
||||
parser.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="relative path glob; repeatable")
|
||||
parser.add_argument("--context", metavar="CONTEXT.json", help="non-secret infrastructure context; never disables rules")
|
||||
parser.add_argument("root", nargs="?", help="локальный каталог или файл с исходниками")
|
||||
parser.add_argument("--json", action="store_true", help="вывести JSON-отчет")
|
||||
parser.add_argument("--patches", action="store_true", help="показать примеры до и после")
|
||||
parser.add_argument("--list-rules", action="store_true", help="показать список правил")
|
||||
parser.add_argument("--explain", metavar="RULE_ID", help="показать карточку правила")
|
||||
parser.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="маска относительного пути; можно повторять")
|
||||
parser.add_argument("--context", metavar="CONTEXT.json", help="не секретный контекст; не отключает правила")
|
||||
parser.add_argument("--max-bytes", type=positive, default=1048576)
|
||||
parser.add_argument("--max-files", type=positive, default=20000)
|
||||
parser.add_argument("--max-findings", type=positive, default=10000)
|
||||
@@ -1507,39 +1495,39 @@ def main(argv=None):
|
||||
if args.explain:
|
||||
rule = next((r for r in rules if r["id"] == args.explain), None)
|
||||
if rule is None:
|
||||
parser.error("unknown rule ID")
|
||||
parser.error("неизвестный идентификатор правила")
|
||||
print(json.dumps({k: v for k, v in rule.items()
|
||||
if k not in {"compiled", "compiled_languages", "pattern", "language_patterns"}},
|
||||
ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
if not args.root:
|
||||
parser.error("provide a root, --list-rules, or --explain")
|
||||
parser.error("укажите путь, --list-rules или --explain")
|
||||
report = scan(args.root, rules, exclude=args.exclude, max_bytes=args.max_bytes,
|
||||
max_files=args.max_files, max_findings=args.max_findings,
|
||||
context=load_context(args.context) if args.context else None)
|
||||
except (OSError, ValueError, KeyError, re.error, RecursionError, MemoryError) as exc:
|
||||
error = {"error": "invalid input or rule pack", "type": type(exc).__name__, "exit_code": 2}
|
||||
print(json.dumps(error) if args.json else "ERROR: invalid input or rule pack (" + type(exc).__name__ + ")")
|
||||
print(json.dumps(error) if args.json else "ОШИБКА: некорректный ввод или набор правил (" + type(exc).__name__ + ")")
|
||||
return 2
|
||||
if args.json:
|
||||
print(json.dumps(report, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
for finding in report["findings"]:
|
||||
print(f"{terminal(finding['path'])}:{finding['line']} [{finding['rule']}] {finding['title']}")
|
||||
print(" Why review:", finding["reason"])
|
||||
print(" Remediation:", finding["fix"])
|
||||
print(" Verify:", finding["check"])
|
||||
print(" Reference:", finding["doc"])
|
||||
print(" Review priority:", finding["review_priority"], "|", finding["signal_kind"])
|
||||
print(" Причина проверки:", finding["reason"])
|
||||
print(" Исправление:", finding["fix"])
|
||||
print(" Проверка:", finding["check"])
|
||||
print(" Карточка:", finding["doc"])
|
||||
print(" Приоритет:", finding["review_priority"], "|", finding["signal_kind"])
|
||||
for note in finding["context_notes"]:
|
||||
print(" Context:", note)
|
||||
print(" Контекст:", note)
|
||||
if args.patches:
|
||||
print(" Before example:\n" + finding["patch_example"]["before"])
|
||||
print(" After example:\n" + finding["patch_example"]["after"])
|
||||
print(" Пример до:\n" + finding["patch_example"]["before"])
|
||||
print(" Пример после:\n" + finding["patch_example"]["after"])
|
||||
for issue in report["issues"]:
|
||||
print("ISSUE:", terminal(issue["path"]), issue["reason"])
|
||||
print(f"Scanned: {report['files_scanned']}; findings: {len(report['findings'])}; partial: {report['partial']}; skipped: {report['skipped']}")
|
||||
print("Signals require review; zero findings is not a security verdict. Offline templates: --explain RULE_ID / --patches.")
|
||||
print("ПРОБЛЕМА:", terminal(issue["path"]), issue["reason"])
|
||||
print(f"Проверено файлов: {report['files_scanned']}; находок: {len(report['findings'])}; неполный отчет: {report['partial']}; пропущено: {report['skipped']}")
|
||||
print("Находки требуют ручной проверки; отсутствие находок не подтверждает безопасность. Примеры: --explain RULE_ID / --patches.")
|
||||
return report["exit_code"]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,778 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Локальный запуск Semgrep и Trivy без сборки анализируемого проекта."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import selectors
|
||||
import shutil
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unicodedata
|
||||
|
||||
|
||||
SCHEMA = "wahrwelt.external-scan.v1"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SEMGREP_RULES = ROOT / "rules" / "semgrep.yml"
|
||||
MAX_OUTPUT = 16 * 1024 * 1024
|
||||
MAX_FINDINGS = 10000
|
||||
MAX_RULE_BYTES = 1024 * 1024
|
||||
MAX_TREE_FILES = 100000
|
||||
MAX_FILE_BYTES = 16 * 1024 * 1024
|
||||
MAX_TREE_BYTES = 1024 * 1024 * 1024
|
||||
MAX_PREFLIGHT_ISSUES = 1000
|
||||
SKIP_DIRS = {
|
||||
".git", ".hg", ".svn", ".venv", "venv", "node_modules", "vendor",
|
||||
"__pycache__", ".cache", ".ssh", ".aws", "artifacts", "dist", "build",
|
||||
"target", "obj", "bin",
|
||||
}
|
||||
SEVERITIES = {"INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL", "UNKNOWN"}
|
||||
SEMGREP_SEVERITIES = {"INFO": "INFO", "WARNING": "MEDIUM", "ERROR": "HIGH"}
|
||||
|
||||
|
||||
def _canonical_json(value):
|
||||
return json.dumps(value, ensure_ascii=True, sort_keys=True,
|
||||
separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def _digest(value):
|
||||
return hashlib.sha256(value).hexdigest()
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _positive(value):
|
||||
try:
|
||||
number = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise argparse.ArgumentTypeError("ожидалось целое число") from exc
|
||||
if number < 1 or number > 1800:
|
||||
raise argparse.ArgumentTypeError("значение должно быть от 1 до 1800")
|
||||
return number
|
||||
|
||||
|
||||
def canonical_root(value):
|
||||
requested = Path(os.path.abspath(os.fspath(value)))
|
||||
metadata = requested.lstat()
|
||||
if stat.S_ISLNK(metadata.st_mode):
|
||||
raise ValueError("корень scan не может быть символической ссылкой")
|
||||
canonical = requested.resolve(strict=True)
|
||||
canonical_metadata = canonical.lstat()
|
||||
if (metadata.st_dev, metadata.st_ino, stat.S_IFMT(metadata.st_mode)) != (
|
||||
canonical_metadata.st_dev, canonical_metadata.st_ino,
|
||||
stat.S_IFMT(canonical_metadata.st_mode)):
|
||||
raise ValueError("корень изменился при проверке")
|
||||
if not (stat.S_ISDIR(canonical_metadata.st_mode) or stat.S_ISREG(canonical_metadata.st_mode)):
|
||||
raise ValueError("корень должен быть обычным файлом или каталогом")
|
||||
return canonical
|
||||
|
||||
|
||||
def _root_id(root):
|
||||
normalized = unicodedata.normalize("NFC", os.path.normcase(str(root)))
|
||||
return "sha256:" + _digest(("wahrwelt-root-v1\0" + normalized).encode(
|
||||
"utf-8", errors="surrogatepass"))
|
||||
|
||||
|
||||
def _rule_pack_digest():
|
||||
metadata = SEMGREP_RULES.lstat()
|
||||
if not stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
|
||||
raise ValueError("локальный набор Semgrep должен быть обычным файлом")
|
||||
if metadata.st_size > MAX_RULE_BYTES:
|
||||
raise ValueError("локальный набор Semgrep слишком велик")
|
||||
data = SEMGREP_RULES.read_bytes()
|
||||
if len(data) != metadata.st_size:
|
||||
raise ValueError("локальный набор Semgrep изменился при чтении")
|
||||
return _digest(data)
|
||||
|
||||
|
||||
def _preflight(root):
|
||||
"""Останавливает внешний scan, если дерево выходит за границу root."""
|
||||
if root.is_file():
|
||||
try:
|
||||
size = root.stat().st_size
|
||||
except OSError:
|
||||
return [_issue("file_unreadable", path=".")]
|
||||
if size > MAX_FILE_BYTES:
|
||||
return [_issue("file_size_limit", path=".", limit=MAX_FILE_BYTES)]
|
||||
return []
|
||||
issues = []
|
||||
file_count = 0
|
||||
total_bytes = 0
|
||||
|
||||
def add_issue(issue):
|
||||
if len(issues) < MAX_PREFLIGHT_ISSUES:
|
||||
issues.append(issue)
|
||||
|
||||
def onerror(exc):
|
||||
name = Path(getattr(exc, "filename", root))
|
||||
try:
|
||||
rel = name.relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
rel = "."
|
||||
add_issue({"code": "directory_unreadable", "path": rel})
|
||||
|
||||
for base, dirs, files in os.walk(root, topdown=True, followlinks=False, onerror=onerror):
|
||||
kept = []
|
||||
for name in sorted(dirs):
|
||||
if name in SKIP_DIRS:
|
||||
continue
|
||||
path = Path(base) / name
|
||||
if path.is_symlink():
|
||||
add_issue({"code": "symlink_in_scan_tree", "path": path.relative_to(root).as_posix()})
|
||||
else:
|
||||
kept.append(name)
|
||||
dirs[:] = kept
|
||||
for name in sorted(files):
|
||||
if name in SKIP_DIRS:
|
||||
continue
|
||||
path = Path(base) / name
|
||||
try:
|
||||
metadata = path.lstat()
|
||||
except OSError:
|
||||
add_issue({"code": "file_unreadable", "path": path.relative_to(root).as_posix()})
|
||||
continue
|
||||
if stat.S_ISLNK(metadata.st_mode):
|
||||
add_issue({"code": "symlink_in_scan_tree", "path": path.relative_to(root).as_posix()})
|
||||
elif not stat.S_ISREG(metadata.st_mode):
|
||||
add_issue({"code": "non_regular_file", "path": path.relative_to(root).as_posix()})
|
||||
else:
|
||||
file_count += 1
|
||||
total_bytes += metadata.st_size
|
||||
rel = path.relative_to(root).as_posix()
|
||||
if metadata.st_size > MAX_FILE_BYTES:
|
||||
add_issue({"code": "file_size_limit", "path": rel, "limit": MAX_FILE_BYTES})
|
||||
if file_count > MAX_TREE_FILES:
|
||||
add_issue({"code": "file_count_limit", "limit": MAX_TREE_FILES})
|
||||
return issues
|
||||
if total_bytes > MAX_TREE_BYTES:
|
||||
add_issue({"code": "tree_size_limit", "limit": MAX_TREE_BYTES})
|
||||
return issues
|
||||
if any(issue["code"] == "directory_unreadable" for issue in issues):
|
||||
break
|
||||
if len(issues) >= MAX_PREFLIGHT_ISSUES:
|
||||
break
|
||||
return issues
|
||||
|
||||
|
||||
def _has_semgrepignore(root):
|
||||
if root.is_file():
|
||||
return False
|
||||
for base, dirs, files in os.walk(root, topdown=True, followlinks=False):
|
||||
dirs[:] = [name for name in dirs if name not in SKIP_DIRS]
|
||||
if ".semgrepignore" in files:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _environment():
|
||||
env = {}
|
||||
for name in ("PATH", "HOME", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL"):
|
||||
if name in os.environ:
|
||||
env[name] = os.environ[name]
|
||||
env.setdefault("PATH", os.defpath)
|
||||
env.setdefault("HOME", str(Path.home()))
|
||||
env["LANG"] = "C"
|
||||
env["LC_ALL"] = "C"
|
||||
env["SEMGREP_SEND_METRICS"] = "off"
|
||||
env["SEMGREP_ENABLE_VERSION_CHECK"] = "0"
|
||||
return env
|
||||
|
||||
|
||||
def _terminate(proc):
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
except OSError:
|
||||
try:
|
||||
proc.terminate()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=0.5)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
except OSError:
|
||||
try:
|
||||
proc.kill()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
proc.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
|
||||
def run_command(argv, *, cwd, timeout, output_limit=MAX_OUTPUT):
|
||||
"""Запускает только argv без shell, ограничивая время и суммарный вывод."""
|
||||
if os.name != "posix":
|
||||
return {"status": "unsupported_platform", "returncode": None,
|
||||
"stdout": b"", "stderr": b"", "stdout_bytes": 0, "stderr_bytes": 0}
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
list(argv), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=str(cwd), env=_environment(),
|
||||
close_fds=True, start_new_session=True, shell=False,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return {"status": "unavailable", "returncode": None,
|
||||
"stdout": b"", "stderr": b"", "stdout_bytes": 0, "stderr_bytes": 0}
|
||||
except OSError:
|
||||
return {"status": "launch_error", "returncode": None,
|
||||
"stdout": b"", "stderr": b"", "stdout_bytes": 0, "stderr_bytes": 0}
|
||||
|
||||
selector = selectors.DefaultSelector()
|
||||
buffers = {"stdout": bytearray(), "stderr": bytearray()}
|
||||
sizes = {"stdout": 0, "stderr": 0}
|
||||
status = "complete"
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
for name, stream in (("stdout", proc.stdout), ("stderr", proc.stderr)):
|
||||
os.set_blocking(stream.fileno(), False)
|
||||
selector.register(stream, selectors.EVENT_READ, name)
|
||||
while selector.get_map():
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
status = "timeout"
|
||||
_terminate(proc)
|
||||
break
|
||||
events = selector.select(min(remaining, 0.25))
|
||||
for key, _ in events:
|
||||
name = key.data
|
||||
try:
|
||||
chunk = os.read(key.fileobj.fileno(), 65536)
|
||||
except BlockingIOError:
|
||||
continue
|
||||
if not chunk:
|
||||
selector.unregister(key.fileobj)
|
||||
key.fileobj.close()
|
||||
continue
|
||||
sizes[name] += len(chunk)
|
||||
if sizes["stdout"] + sizes["stderr"] > output_limit:
|
||||
status = "output_limit_exceeded"
|
||||
_terminate(proc)
|
||||
break
|
||||
buffers[name].extend(chunk)
|
||||
if status != "complete":
|
||||
break
|
||||
if proc.poll() is None:
|
||||
try:
|
||||
proc.wait(timeout=max(0.0, deadline - time.monotonic()))
|
||||
except subprocess.TimeoutExpired:
|
||||
status = "timeout"
|
||||
_terminate(proc)
|
||||
finally:
|
||||
selector.close()
|
||||
for stream in (proc.stdout, proc.stderr):
|
||||
try:
|
||||
stream.close()
|
||||
except OSError:
|
||||
pass
|
||||
if proc.poll() is None:
|
||||
_terminate(proc)
|
||||
return {"status": status, "returncode": proc.returncode,
|
||||
"stdout": bytes(buffers["stdout"]), "stderr": bytes(buffers["stderr"]),
|
||||
"stdout_bytes": sizes["stdout"], "stderr_bytes": sizes["stderr"]}
|
||||
|
||||
|
||||
def _safe_version(data):
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
match = re.search(r"(?<![0-9])([0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?)", text)
|
||||
return match.group(1) if match else "unknown"
|
||||
|
||||
|
||||
def _tool(binary, cwd, timeout=10):
|
||||
path = shutil.which(binary)
|
||||
if not path:
|
||||
return None, {"status": "unavailable", "version": None, "state": {}}
|
||||
try:
|
||||
resolved = Path(path).resolve(strict=True)
|
||||
metadata = resolved.stat()
|
||||
except OSError:
|
||||
return None, {"status": "unavailable", "version": None, "state": {}}
|
||||
if not stat.S_ISREG(metadata.st_mode) or not os.access(resolved, os.X_OK):
|
||||
return None, {"status": "unavailable", "version": None, "state": {}}
|
||||
result = run_command([str(resolved), "--version"], cwd=cwd, timeout=timeout,
|
||||
output_limit=8192)
|
||||
if result["status"] != "complete" or result["returncode"] != 0:
|
||||
return str(resolved), {"status": "version_error", "version": None, "state": {}}
|
||||
output = result["stdout"].decode("utf-8", errors="replace")
|
||||
return str(resolved), {"status": "complete", "version": _safe_version(result["stdout"]),
|
||||
"output": output}
|
||||
|
||||
|
||||
def _base_result(engine, status="partial", *, version=None, findings=None, issues=None, scope=None):
|
||||
return {
|
||||
"engine": engine,
|
||||
"version": version,
|
||||
"status": status,
|
||||
"findings": findings or [],
|
||||
"issues": issues or [],
|
||||
"scope": scope or {},
|
||||
}
|
||||
|
||||
|
||||
def _issue(code, **fields):
|
||||
return {"code": code, **fields}
|
||||
|
||||
|
||||
def _relative_path(value, root):
|
||||
if not isinstance(value, str) or not value:
|
||||
return None
|
||||
candidate = Path(value)
|
||||
try:
|
||||
if candidate.is_absolute():
|
||||
relative = candidate.resolve(strict=False).relative_to(root).as_posix()
|
||||
else:
|
||||
relative = PurePosixPath(value.replace("\\", "/")).as_posix()
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
pure = PurePosixPath(relative)
|
||||
if pure.is_absolute() or ".." in pure.parts:
|
||||
return None
|
||||
return relative or "."
|
||||
|
||||
|
||||
def _semgrep_finding(item, root):
|
||||
extra = item.get("extra") if isinstance(item, dict) else None
|
||||
if not isinstance(extra, dict):
|
||||
return None
|
||||
start = item.get("start")
|
||||
if not isinstance(start, dict):
|
||||
return None
|
||||
path = _relative_path(item.get("path"), root)
|
||||
line = start.get("line")
|
||||
rule_id = item.get("check_id")
|
||||
if (path is None or type(line) is not int or line < 1 or
|
||||
not isinstance(rule_id, str) or len(rule_id) > 200):
|
||||
return None
|
||||
source_severity = str(extra.get("severity", "UNKNOWN")).upper()
|
||||
severity = SEMGREP_SEVERITIES.get(source_severity, "UNKNOWN")
|
||||
metadata = extra.get("metadata") if isinstance(extra.get("metadata"), dict) else {}
|
||||
cwe = metadata.get("cwe", [])
|
||||
if isinstance(cwe, str):
|
||||
cwe = [cwe]
|
||||
if not isinstance(cwe, list):
|
||||
cwe = []
|
||||
cwe = [item for item in cwe if isinstance(item, str) and re.fullmatch(r"CWE-[1-9][0-9]*", item)][:8]
|
||||
title = extra.get("message", rule_id)
|
||||
if not isinstance(title, str):
|
||||
title = rule_id
|
||||
title = "".join(ch for ch in title if ch.isprintable())[:300] or rule_id
|
||||
return {"engine": "semgrep", "rule_id": rule_id, "path": path, "line": line,
|
||||
"severity": severity if severity in SEVERITIES else "UNKNOWN",
|
||||
"source_severity": source_severity, "confidence": "review",
|
||||
"title": title, "cwe": cwe}
|
||||
|
||||
|
||||
def _semgrep(root, root_id, timeout, local_rules_sha):
|
||||
binary, tool = _tool("semgrep", ROOT)
|
||||
if binary is None or tool["status"] != "complete":
|
||||
code = "binary_unavailable" if binary is None else "version_unavailable"
|
||||
return _base_result("semgrep", "unavailable" if binary is None else "partial",
|
||||
issues=[_issue(code)])
|
||||
if tool["version"] == "unknown":
|
||||
return _base_result("semgrep", "partial", issues=[_issue("version_unreadable")])
|
||||
scope_body = {"root": root_id, "engine": "semgrep", "version": tool["version"],
|
||||
"rules_sha256": local_rules_sha, "path_semantics": "root-relative-posix.v1",
|
||||
"max_target_bytes": MAX_FILE_BYTES, "local_config": True}
|
||||
scope = {**scope_body, "sha256": _digest(_canonical_json(scope_body))}
|
||||
argv = [binary, "scan", "--config", str(SEMGREP_RULES), "--oss-only",
|
||||
"--metrics=off", "--disable-version-check", "--disable-nosem",
|
||||
"--no-git-ignore", f"--max-target-bytes={MAX_FILE_BYTES}", "--json"]
|
||||
for name in sorted(SKIP_DIRS):
|
||||
argv.extend(["--exclude", name])
|
||||
argv.append(str(root))
|
||||
run = run_command(argv, cwd=ROOT, timeout=timeout)
|
||||
if run["status"] != "complete":
|
||||
return _base_result("semgrep", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue(run["status"], stdout_bytes=run["stdout_bytes"],
|
||||
stderr_bytes=run["stderr_bytes"])])
|
||||
try:
|
||||
data = json.loads(run["stdout"].decode("utf-8"))
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError, MemoryError):
|
||||
return _base_result("semgrep", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("invalid_json", returncode=run["returncode"])])
|
||||
if not isinstance(data, dict) or not isinstance(data.get("results"), list):
|
||||
return _base_result("semgrep", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("invalid_report_shape", returncode=run["returncode"])])
|
||||
findings = []
|
||||
issues = []
|
||||
for item in data["results"]:
|
||||
finding = _semgrep_finding(item, root)
|
||||
if finding is None:
|
||||
issues.append(_issue("invalid_finding"))
|
||||
elif len(findings) < MAX_FINDINGS:
|
||||
findings.append(finding)
|
||||
else:
|
||||
issues.append(_issue("finding_limit_reached", limit=MAX_FINDINGS))
|
||||
break
|
||||
errors = data.get("errors", [])
|
||||
if isinstance(errors, list) and errors:
|
||||
issues.append(_issue("semgrep_report_errors", count=len(errors)))
|
||||
elif not isinstance(errors, list):
|
||||
issues.append(_issue("invalid_error_list"))
|
||||
paths = data.get("paths", {})
|
||||
if isinstance(paths, dict):
|
||||
scanned = paths.get("scanned", [])
|
||||
skipped = paths.get("skipped", [])
|
||||
if isinstance(skipped, list) and skipped:
|
||||
issues.append(_issue("semgrep_skipped_paths", count=len(skipped)))
|
||||
if not isinstance(scanned, list) or not isinstance(skipped, list):
|
||||
issues.append(_issue("invalid_path_summary"))
|
||||
else:
|
||||
scanned = []
|
||||
issues.append(_issue("missing_path_summary"))
|
||||
if run["returncode"] not in (0, 1) or (run["returncode"] == 1 and not findings):
|
||||
issues.append(_issue("scanner_exit", returncode=run["returncode"]))
|
||||
if _has_semgrepignore(root):
|
||||
issues.append(_issue("target_semgrepignore_present"))
|
||||
status = "partial" if issues else "complete"
|
||||
return {**_base_result("semgrep", status, version=tool["version"], findings=findings,
|
||||
issues=issues, scope=scope),
|
||||
"files_scanned": len(scanned) if isinstance(scanned, list) else 0}
|
||||
|
||||
|
||||
def _parse_time(value):
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
match = re.match(r"^(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)(?:\.(\d+))? ([+-]\d{4})", value)
|
||||
if not match:
|
||||
return None
|
||||
fraction = (match.group(3) or "")[:6].ljust(6, "0")
|
||||
normalized = f"{match.group(1)} {match.group(2)}.{fraction} {match.group(4)}"
|
||||
try:
|
||||
return datetime.strptime(normalized, "%Y-%m-%d %H:%M:%S.%f %z").astimezone(timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _trivy_state(text):
|
||||
state = {}
|
||||
key_names = {"updatedat": "updated_at", "nextupdate": "next_update",
|
||||
"downloadedat": "downloaded_at"}
|
||||
current = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if line in {"Vulnerability DB:", "Java DB:", "Check Bundle:"}:
|
||||
current = line[:-1].lower().replace(" ", "_")
|
||||
state[current] = {}
|
||||
elif current and ":" in line:
|
||||
key, value = line.split(":", 1)
|
||||
normalized = key.strip().lower().replace(" ", "_")
|
||||
normalized = key_names.get(normalized.replace("_", ""), normalized)
|
||||
state[current][normalized] = value.strip()
|
||||
return state
|
||||
|
||||
|
||||
def _has_java_artifacts(root):
|
||||
if root.is_file():
|
||||
return root.name.lower() in {"pom.xml", "gradle.lockfile", "build.gradle", "build.gradle.kts"} or root.suffix.lower() == ".jar"
|
||||
for base, dirs, files in os.walk(root, topdown=True, followlinks=False):
|
||||
dirs[:] = [name for name in dirs if name not in SKIP_DIRS]
|
||||
if any(name.lower() in {"pom.xml", "gradle.lockfile", "build.gradle", "build.gradle.kts"}
|
||||
or name.lower().endswith(".jar") for name in files):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _trivy_finding(item, kind, root):
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
if kind == "vulnerability":
|
||||
rule_id = item.get("VulnerabilityID")
|
||||
title = item.get("Title") or item.get("PkgName") or rule_id
|
||||
severity = item.get("Severity", "UNKNOWN")
|
||||
line = None
|
||||
category = "dependency"
|
||||
elif kind == "misconfiguration":
|
||||
rule_id = item.get("ID") or item.get("AVDID")
|
||||
title = item.get("Title") or rule_id
|
||||
severity = item.get("Severity", "UNKNOWN")
|
||||
cause = item.get("CauseMetadata")
|
||||
line = cause.get("StartLine") if isinstance(cause, dict) else None
|
||||
category = "misconfiguration"
|
||||
else:
|
||||
rule_id = item.get("RuleID")
|
||||
title = item.get("Title") or rule_id
|
||||
severity = item.get("Severity", "UNKNOWN")
|
||||
line = item.get("StartLine")
|
||||
category = "secret"
|
||||
if not isinstance(rule_id, str) or len(rule_id) > 200:
|
||||
return None
|
||||
target = item.get("Target", item.get("PkgPath", "."))
|
||||
path = _relative_path(target, root)
|
||||
if path is None:
|
||||
return None
|
||||
if type(line) is not int or line < 1:
|
||||
line = None
|
||||
if not isinstance(title, str):
|
||||
title = rule_id
|
||||
title = "".join(ch for ch in title if ch.isprintable())[:300] or rule_id
|
||||
severity = str(severity).upper()
|
||||
finding = {"engine": "trivy", "category": category, "rule_id": rule_id,
|
||||
"path": path, "line": line,
|
||||
"severity": severity if severity in SEVERITIES else "UNKNOWN",
|
||||
"confidence": "review", "title": title}
|
||||
if kind == "vulnerability":
|
||||
for field, key, limit in (("package", "PkgName", 200),
|
||||
("installed_version", "InstalledVersion", 100),
|
||||
("fixed_version", "FixedVersion", 100)):
|
||||
value = item.get(key)
|
||||
if isinstance(value, str):
|
||||
value = "".join(ch for ch in value if ch.isprintable())[:limit].strip()
|
||||
if value:
|
||||
finding[field] = value
|
||||
primary_url = item.get("PrimaryURL")
|
||||
if (isinstance(primary_url, str) and len(primary_url) <= 500 and
|
||||
re.fullmatch(r"https?://[^\s\x00-\x1f]+", primary_url)):
|
||||
finding["primary_url"] = primary_url
|
||||
return finding
|
||||
|
||||
|
||||
def _trivy(root, root_id, timeout, update_db):
|
||||
binary, tool = _tool("trivy", ROOT)
|
||||
if binary is None or tool["status"] != "complete":
|
||||
code = "binary_unavailable" if binary is None else "version_unavailable"
|
||||
return _base_result("trivy", "unavailable" if binary is None else "partial",
|
||||
issues=[_issue(code)])
|
||||
version_text = tool.get("output", "")
|
||||
version_state = _trivy_state(version_text)
|
||||
state_digest = _digest(version_text.encode("utf-8", errors="replace"))
|
||||
scope_body = {"root": root_id, "engine": "trivy", "version": tool["version"],
|
||||
"tool_state_sha256": state_digest, "scanners": ["vuln", "misconfig", "secret"],
|
||||
"path_semantics": "root-relative-posix.v1", "offline_scan": True,
|
||||
"database_update_enabled": update_db}
|
||||
scope = {**scope_body, "sha256": _digest(_canonical_json(scope_body))}
|
||||
argv = [binary, "fs", "--format", "json", "--quiet", "--config", os.devnull,
|
||||
"--scanners", "vuln,misconfig,secret", "--offline-scan",
|
||||
"--disable-telemetry", "--skip-version-check", "--skip-vex-repo-update",
|
||||
"--ignorefile", os.devnull, "--secret-config="]
|
||||
if not update_db:
|
||||
argv.extend(["--skip-db-update", "--skip-java-db-update", "--skip-check-update"])
|
||||
argv.extend(["--skip-dirs", ",".join(sorted(SKIP_DIRS))])
|
||||
argv.append(str(root))
|
||||
run = run_command(argv, cwd=ROOT, timeout=timeout)
|
||||
if run["status"] != "complete":
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue(run["status"], stdout_bytes=run["stdout_bytes"],
|
||||
stderr_bytes=run["stderr_bytes"])],
|
||||
findings=[])
|
||||
try:
|
||||
data = json.loads(run["stdout"].decode("utf-8"))
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError, MemoryError):
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("invalid_json", returncode=run["returncode"])])
|
||||
if not isinstance(data, dict):
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("invalid_report_shape", returncode=run["returncode"])])
|
||||
schema_version = data.get("SchemaVersion")
|
||||
if type(schema_version) is not int:
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("missing_schema_version", returncode=run["returncode"])])
|
||||
if schema_version != 2:
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("unsupported_schema_version", version=schema_version)])
|
||||
if (not isinstance(data.get("Trivy"), dict) or
|
||||
not isinstance(data["Trivy"].get("Version"), str) or
|
||||
not isinstance(data.get("Results"), (list, type(None)))):
|
||||
return _base_result("trivy", "partial", version=tool["version"], scope=scope,
|
||||
issues=[_issue("invalid_report_shape", returncode=run["returncode"])])
|
||||
findings = []
|
||||
issues = []
|
||||
for result in data.get("Results") or []:
|
||||
if not isinstance(result, dict):
|
||||
issues.append(_issue("invalid_result"))
|
||||
continue
|
||||
target = result.get("Target", ".")
|
||||
kind_keys = (("Vulnerabilities", "vulnerability"),
|
||||
("Misconfigurations", "misconfiguration"),
|
||||
("Secrets", "secret"))
|
||||
for key, kind in kind_keys:
|
||||
entries = result.get(key) or []
|
||||
if not isinstance(entries, list):
|
||||
issues.append(_issue("invalid_finding_list", category=kind))
|
||||
continue
|
||||
for item in entries:
|
||||
normalized = _trivy_finding({**item, "Target": target}, kind, root) if isinstance(item, dict) else None
|
||||
if normalized is None:
|
||||
issues.append(_issue("invalid_finding", category=kind))
|
||||
elif len(findings) < MAX_FINDINGS:
|
||||
findings.append(normalized)
|
||||
else:
|
||||
issues.append(_issue("finding_limit_reached", limit=MAX_FINDINGS))
|
||||
break
|
||||
if run["returncode"] != 0:
|
||||
issues.append(_issue("scanner_exit", returncode=run["returncode"]))
|
||||
if update_db:
|
||||
post = run_command([binary, "--version"], cwd=ROOT, timeout=10, output_limit=8192)
|
||||
if post["status"] == "complete" and post["returncode"] == 0:
|
||||
version_state = _trivy_state(post["stdout"].decode("utf-8", errors="replace"))
|
||||
state_digest = _digest(post["stdout"])
|
||||
scope["tool_state_sha256"] = state_digest
|
||||
scope_body["tool_state_sha256"] = state_digest
|
||||
scope["sha256"] = _digest(_canonical_json(scope_body))
|
||||
else:
|
||||
issues.append(_issue("database_state_unavailable"))
|
||||
required = ["vulnerability_db", "check_bundle"]
|
||||
if _has_java_artifacts(root):
|
||||
required.append("java_db")
|
||||
for key in required:
|
||||
entry = version_state.get(key)
|
||||
if not entry:
|
||||
issues.append(_issue("database_metadata_missing", database=key))
|
||||
continue
|
||||
next_update = _parse_time(entry.get("next_update"))
|
||||
if not update_db and next_update is not None and next_update <= datetime.now(timezone.utc):
|
||||
issues.append(_issue("database_expired", database=key,
|
||||
next_update=entry.get("next_update")))
|
||||
if key == "check_bundle" and not entry.get("digest", "").startswith("sha256:"):
|
||||
issues.append(_issue("checks_bundle_missing"))
|
||||
status = "partial" if issues else "complete"
|
||||
return {**_base_result("trivy", status, version=tool["version"], findings=findings,
|
||||
issues=issues, scope=scope),
|
||||
"data": {key: value for key, value in version_state.items() if key in required}}
|
||||
|
||||
|
||||
def scan(root, engine="all", *, timeout=180, update_trivy_db=False):
|
||||
if engine not in {"semgrep", "trivy", "all"}:
|
||||
raise ValueError("неизвестный движок scan")
|
||||
root = canonical_root(root)
|
||||
root_id = _root_id(root)
|
||||
selected = ["semgrep", "trivy"] if engine == "all" else [engine]
|
||||
report = {"schema": SCHEMA, "created_at": _now(), "root": root_id,
|
||||
"network": "trivy-db-update-enabled" if update_trivy_db else "disabled",
|
||||
"status": "complete", "results": [], "exit_code": 0}
|
||||
try:
|
||||
rules_sha = _rule_pack_digest() if "semgrep" in selected else None
|
||||
except (OSError, ValueError):
|
||||
rules_sha = None
|
||||
preflight = _preflight(root)
|
||||
for name in selected:
|
||||
if preflight:
|
||||
result = _base_result(name, "partial", issues=preflight)
|
||||
elif name == "semgrep":
|
||||
if rules_sha is None:
|
||||
result = _base_result(name, "partial", issues=[_issue("local_rules_unavailable")])
|
||||
else:
|
||||
result = _semgrep(root, root_id, timeout, rules_sha)
|
||||
elif name == "trivy":
|
||||
result = _trivy(root, root_id, timeout, update_trivy_db)
|
||||
else:
|
||||
result = _base_result(name, "unavailable", issues=[_issue("unknown_engine")])
|
||||
report["results"].append(result)
|
||||
if any(result["status"] != "complete" for result in report["results"]):
|
||||
report["status"] = "partial"
|
||||
report["exit_code"] = 2
|
||||
elif any(result["findings"] for result in report["results"]):
|
||||
report["exit_code"] = 1
|
||||
return report
|
||||
|
||||
|
||||
def _terminal(value):
|
||||
text = str(value)
|
||||
return json.dumps(text, ensure_ascii=True)[1:-1] if not text.isprintable() else text
|
||||
|
||||
|
||||
def _issue_text(issue):
|
||||
messages = {
|
||||
"binary_unavailable": "исполняемый файл движка не найден",
|
||||
"version_unavailable": "не удалось получить версию движка",
|
||||
"version_unreadable": "версия движка не распознана",
|
||||
"timeout": "превышен лимит времени",
|
||||
"output_limit_exceeded": "превышен лимит вывода процесса",
|
||||
"invalid_json": "движок вернул некорректный JSON",
|
||||
"invalid_report_shape": "структура отчета движка не распознана",
|
||||
"missing_schema_version": "в отчете Trivy отсутствует версия формата",
|
||||
"unsupported_schema_version": "версия формата отчета Trivy не поддерживается",
|
||||
"scanner_exit": "движок завершился с ошибкой",
|
||||
"database_expired": "локальная база Trivy просрочена",
|
||||
"database_metadata_missing": "нет метаданных локальной базы Trivy",
|
||||
"checks_bundle_missing": "локальный набор Trivy checks не найден",
|
||||
"symlink_in_scan_tree": "дерево содержит символическую ссылку",
|
||||
"target_semgrepignore_present": "Semgrep ignore-файл может скрыть часть дерева",
|
||||
"file_size_limit": "файл превышает допустимый размер",
|
||||
"file_count_limit": "дерево содержит слишком много файлов",
|
||||
"tree_size_limit": "дерево превышает допустимый общий размер",
|
||||
"directory_unreadable": "часть каталогов недоступна для чтения",
|
||||
"file_unreadable": "часть файлов недоступна для чтения",
|
||||
"local_rules_unavailable": "локальные правила Semgrep недоступны",
|
||||
"unknown_engine": "запрошен неизвестный движок",
|
||||
}
|
||||
code = issue.get("code", "unknown") if isinstance(issue, dict) else "unknown"
|
||||
return messages.get(code, "неполный результат или ошибка движка")
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("root", help="локальный файл или каталог с исходниками")
|
||||
parser.add_argument("--engine", choices=("semgrep", "trivy", "all"), default="all",
|
||||
help="движок scan; по умолчанию запускаются оба")
|
||||
parser.add_argument("--timeout", type=_positive, default=180,
|
||||
help="лимит времени для одного процесса, секунды (1-1800)")
|
||||
parser.add_argument("--update-trivy-db", action="store_true",
|
||||
help="разрешить Trivy обновить локальные базы через сеть")
|
||||
parser.add_argument("--json", action="store_true", help="вывести версионированный JSON-отчет")
|
||||
args = parser.parse_args(argv)
|
||||
if args.update_trivy_db and args.engine == "semgrep":
|
||||
parser.error("--update-trivy-db применим только к Trivy")
|
||||
try:
|
||||
report = scan(args.root, args.engine, timeout=args.timeout,
|
||||
update_trivy_db=args.update_trivy_db)
|
||||
except (OSError, ValueError, RecursionError, MemoryError) as exc:
|
||||
report = {"schema": SCHEMA, "created_at": _now(), "root": None,
|
||||
"network": "trivy-db-update-enabled" if args.update_trivy_db else "disabled",
|
||||
"status": "partial", "results": [],
|
||||
"issues": [_issue("invalid_scan_input", reason=type(exc).__name__)],
|
||||
"exit_code": 2}
|
||||
if args.json:
|
||||
print(json.dumps(report, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
for result in report["results"]:
|
||||
for finding in result["findings"]:
|
||||
location = finding["path"] + (":" + str(finding["line"]) if finding.get("line") else "")
|
||||
details = []
|
||||
if finding.get("package"):
|
||||
package = finding["package"]
|
||||
installed = finding.get("installed_version", "")
|
||||
fixed = finding.get("fixed_version", "")
|
||||
version = f" {installed}" if installed else ""
|
||||
if fixed:
|
||||
version += f" -> исправить до {fixed}"
|
||||
details.append(f"пакет {package}{version}")
|
||||
if finding.get("primary_url"):
|
||||
details.append(f"источник {finding['primary_url']}")
|
||||
suffix = " (" + "; ".join(_terminal(value) for value in details) + ")" if details else ""
|
||||
print(f"{_terminal(location)} [{finding['engine']}:{_terminal(finding['rule_id'])}] "
|
||||
f"{finding['severity']} {_terminal(finding['title'])}{suffix}")
|
||||
for issue in result["issues"]:
|
||||
code = issue.get("code", "unknown")
|
||||
print(f"Проблема: {result['engine']} - {_issue_text(issue)} ({_terminal(code)})")
|
||||
status = {"complete": "полный", "partial": "частичный", "unavailable": "недоступен"}.get(
|
||||
result["status"], "неизвестен")
|
||||
print(f"Утилита: {result['engine']}; результат: {status}; находок: {len(result['findings'])}")
|
||||
if report.get("issues"):
|
||||
for issue in report["issues"]:
|
||||
code = issue.get("code", "unknown")
|
||||
print(f"Проблема: {_issue_text(issue)} ({_terminal(code)})")
|
||||
status = {"complete": "полный", "partial": "частичный"}.get(report["status"], "неизвестен")
|
||||
print(f"Итог: {status}; код завершения: {report['exit_code']}")
|
||||
print("Все находки требуют ручной проверки; чистый отчет не доказывает отсутствие уязвимостей.")
|
||||
return report["exit_code"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,75 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-pass HTTP status/content checks against an explicit JSON service list."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
|
||||
from common import http_url, limited_read, opener, positive_float
|
||||
|
||||
|
||||
def validate(config):
|
||||
if not isinstance(config, list) or not 1 <= len(config) <= 128:
|
||||
raise ValueError("config must be a list of 1..128 checks")
|
||||
for item in config:
|
||||
if not isinstance(item, dict) or not isinstance(item.get("name"), str):
|
||||
raise ValueError("each check needs a string name")
|
||||
if not item["name"].strip() or len(item["name"]) > 120:
|
||||
raise ValueError("name must contain 1..120 characters")
|
||||
if set(item) - {"name", "url", "status", "contains"}:
|
||||
raise ValueError("unknown check field")
|
||||
if not isinstance(item.get("url"), str) or any(c.isspace() for c in item["url"]):
|
||||
raise ValueError("url must be a string without whitespace")
|
||||
http_url(item["url"])
|
||||
expected = item.get("status", 200)
|
||||
if type(expected) is not int or not 100 <= expected <= 599:
|
||||
raise ValueError("status must be an integer HTTP status")
|
||||
if "contains" in item and not isinstance(item["contains"], str):
|
||||
raise ValueError("contains must be a string")
|
||||
return config
|
||||
|
||||
|
||||
def probe(item, timeout):
|
||||
started = time.monotonic()
|
||||
result = {"name": item["name"], "ok": False, "status": None}
|
||||
try:
|
||||
req = Request(item["url"], headers={"User-Agent": "DurkaHelper/0.1"})
|
||||
try:
|
||||
response = opener().open(req, timeout=timeout)
|
||||
except HTTPError as exc:
|
||||
response = exc # An expected 403/404 is a legitimate probe outcome.
|
||||
with response:
|
||||
result["status"] = response.code
|
||||
body = limited_read(response).decode("utf-8", errors="replace")
|
||||
result["ok"] = (result["status"] == item.get("status", 200)
|
||||
and item.get("contains", "") in body)
|
||||
except (OSError, ValueError) as exc:
|
||||
result["error"] = type(exc).__name__
|
||||
result["ms"] = round((time.monotonic() - started) * 1000)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("config", help="JSON list with name, url, status and optional contains")
|
||||
parser.add_argument("--timeout", type=positive_float, default=3.0)
|
||||
parser.add_argument("--workers", type=int, choices=range(1, 17), default=4)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
with open(args.config, encoding="utf-8") as f:
|
||||
config = validate(json.load(f))
|
||||
with ThreadPoolExecutor(max_workers=args.workers) as pool:
|
||||
results = list(pool.map(lambda x: probe(x, args.timeout), config))
|
||||
for result in results:
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
return 0 if all(r["ok"] for r in results) else 1
|
||||
except (KeyError, TypeError, ValueError, OSError) as exc:
|
||||
print(f"probe configuration: {type(exc).__name__}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize a local JSONL log without printing messages or arbitrary fields."""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
|
||||
MAX_LINE = 256 * 1024
|
||||
MAX_FILE = 64 * 1024 * 1024
|
||||
LEVELS = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
||||
ALIASES = {"WARN": "WARNING", "FATAL": "CRITICAL"}
|
||||
|
||||
|
||||
def summarize(stream, max_bytes=MAX_FILE):
|
||||
result = {"lines": 0, "records": 0, "blank_lines": 0, "invalid_lines": 0,
|
||||
"invalid_fields": 0, "http_errors": 0}
|
||||
levels, statuses = Counter(), Counter()
|
||||
consumed = 0
|
||||
while True:
|
||||
raw = stream.readline(MAX_LINE + 1)
|
||||
if not raw:
|
||||
break
|
||||
consumed += len(raw)
|
||||
too_long = len(raw) > MAX_LINE
|
||||
# Drain one oversized record without retaining it in memory.
|
||||
while len(raw) == MAX_LINE + 1 and not raw.endswith(b"\n"):
|
||||
if consumed > max_bytes:
|
||||
raise ValueError("log exceeds byte limit")
|
||||
raw = stream.readline(MAX_LINE + 1)
|
||||
consumed += len(raw)
|
||||
if consumed > max_bytes:
|
||||
raise ValueError("log exceeds byte limit")
|
||||
result["lines"] += 1
|
||||
if too_long:
|
||||
result["invalid_lines"] += 1
|
||||
continue
|
||||
if not raw.strip():
|
||||
result["blank_lines"] += 1
|
||||
continue
|
||||
try:
|
||||
record = json.loads(raw)
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError("expected object")
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
result["invalid_lines"] += 1
|
||||
continue
|
||||
result["records"] += 1
|
||||
if "level" in record:
|
||||
level = record["level"]
|
||||
if isinstance(level, str):
|
||||
level = ALIASES.get(level.upper(), level.upper())
|
||||
if not isinstance(level, str) or level not in LEVELS:
|
||||
result["invalid_fields"] += 1
|
||||
else:
|
||||
levels[level] += 1
|
||||
if "status" in record:
|
||||
status = record["status"]
|
||||
if type(status) is not int or not 100 <= status <= 599:
|
||||
result["invalid_fields"] += 1
|
||||
else:
|
||||
statuses[str(status)] += 1
|
||||
result["http_errors"] += int(status >= 400)
|
||||
result["levels"] = dict(sorted(levels.items()))
|
||||
result["statuses"] = dict(sorted(statuses.items()))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("log", type=Path, help="local UTF-8 JSONL file, at most 64 MiB")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
info = args.log.lstat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE:
|
||||
raise ValueError("expected a regular file within size limit")
|
||||
with args.log.open("rb") as stream:
|
||||
result = summarize(stream)
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return 1 if result["invalid_lines"] or result["invalid_fields"] else 0
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"log summary: {type(exc).__name__}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,220 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded publication hygiene checks. Findings contain locations, never values.
|
||||
|
||||
Checks the tracked/non-ignored worktree by default. --history inspects only
|
||||
commits reachable from explicitly selected --ref values (HEAD by default).
|
||||
This heuristic gate does not replace manual review of images, CI artifacts,
|
||||
PR discussions, licenses, or the remote repository's publication settings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LIMIT = 8 * 1024 * 1024
|
||||
MAX_FILES = 20000
|
||||
PATTERNS = {
|
||||
"private-key": re.compile(br"-----BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY-----"),
|
||||
"access-token": re.compile(br"\b(?:gh[pousr]_[A-Za-z0-9]{30,255}|github_pat_[A-Za-z0-9_]{30,255}|AKIA[0-9A-Z]{16})\b"),
|
||||
"ssh-identity": re.compile(br"\b(?:ssh-ed25519|ssh-rsa) [A-Za-z0-9+/]{40,}={0,3}(?: |$)"),
|
||||
"personal-home": re.compile(br"(?:[A-Za-z]:[\\/]Users[\\/](?!Public\b|USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+|/Users/(?!USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+|/home/(?!USER\b|USERNAME\b|example\b)[A-Za-z0-9_.-]+)"),
|
||||
"url-credentials": re.compile(br"\b(?:https?|ssh)://[^\s/:@]{1,100}:[^\s/@]{4,200}@"),
|
||||
}
|
||||
FORBIDDEN_PARTS = {".ssh", ".aws", ".gnupg", ".codex-remote-attachments", "local", "artifacts", "upstream", ".git", "secrets"}
|
||||
FORBIDDEN_SUFFIXES = {".pcap", ".pcapng", ".pem", ".key", ".p12", ".pfx", ".sqlite", ".db", ".log"}
|
||||
REVIEW_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".pdf", ".zip", ".tar", ".gz"}
|
||||
|
||||
|
||||
class CheckError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def git(root, *args, limit=LIMIT):
|
||||
# No shell, filters, target commands, or network operations.
|
||||
command = ["git", "--no-pager", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(root), *args]
|
||||
environment = {key: value for key, value in os.environ.items() if not key.upper().startswith("GIT_")}
|
||||
environment.update({"GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0",
|
||||
"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull})
|
||||
with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=environment) as process:
|
||||
def stop():
|
||||
try:
|
||||
process.kill()
|
||||
except OSError:
|
||||
pass
|
||||
deadline = threading.Timer(30, stop)
|
||||
deadline.daemon = True
|
||||
deadline.start()
|
||||
try:
|
||||
output = process.stdout.read(limit + 1)
|
||||
if len(output) > limit:
|
||||
raise CheckError("Git output exceeds the publication audit limit")
|
||||
if process.wait(timeout=30):
|
||||
raise CheckError("Git could not read the selected publication scope")
|
||||
return output
|
||||
finally:
|
||||
deadline.cancel()
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def safe_path(value):
|
||||
parts = value.split("/")
|
||||
if (not value or value.startswith("/") or "\\" in value or ":" in value or
|
||||
any(p in {"", ".", ".."} for p in parts) or any(ord(c) < 32 for c in value)):
|
||||
raise CheckError("non-portable path in publication scope")
|
||||
return value
|
||||
|
||||
|
||||
def finding(path, category, line=0, ref="worktree", fingerprint=None):
|
||||
value = {"path": path, "category": category, "line": line, "ref": ref}
|
||||
if fingerprint is not None:
|
||||
value["fingerprint"] = fingerprint
|
||||
return value
|
||||
|
||||
|
||||
def scan_bytes(path, data, ref="worktree", private_terms=()):
|
||||
rows = []
|
||||
suffix = Path(path).suffix.lower()
|
||||
if (set(p.lower() for p in path.split("/")) & FORBIDDEN_PARTS or suffix in FORBIDDEN_SUFFIXES or
|
||||
Path(path).name == ".env" or (Path(path).name.startswith(".env.") and Path(path).name != ".env.example")):
|
||||
rows.append(finding(path, "private-or-runtime-file", ref=ref))
|
||||
if suffix in REVIEW_SUFFIXES or b"\x00" in data:
|
||||
rows.append(finding(path, "manual-asset-review", ref=ref))
|
||||
for number, line in enumerate(data.splitlines(), 1):
|
||||
fingerprint = hashlib.sha256(line).hexdigest()
|
||||
for category, pattern in PATTERNS.items():
|
||||
if pattern.search(line):
|
||||
rows.append(finding(path, category, number, ref, fingerprint))
|
||||
if any(term in line for term in private_terms):
|
||||
rows.append(finding(path, "private-environment-reference", number, ref, fingerprint))
|
||||
return rows
|
||||
|
||||
|
||||
def read_file(path):
|
||||
before = path.lstat()
|
||||
if not stat.S_ISREG(before.st_mode) or before.st_size > LIMIT:
|
||||
raise CheckError("publication input is not a bounded regular file")
|
||||
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
||||
fd = os.open(path, flags)
|
||||
try:
|
||||
signature = lambda s: (s.st_dev, s.st_ino, s.st_mode, s.st_size, s.st_mtime_ns, s.st_ctime_ns)
|
||||
opened = os.fstat(fd)
|
||||
if signature(opened) != signature(before) or not stat.S_ISREG(opened.st_mode):
|
||||
raise CheckError("publication input changed while opening")
|
||||
with os.fdopen(fd, "rb", closefd=False) as stream:
|
||||
data = stream.read(LIMIT + 1)
|
||||
if len(data) > LIMIT or signature(os.fstat(fd)) != signature(opened) or signature(path.lstat()) != signature(opened):
|
||||
raise CheckError("publication input changed while reading")
|
||||
return data
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def audit(root, *, history=False, refs=("HEAD",), max_commits=500, private_terms=(), allowlist=()):
|
||||
root = Path(root).resolve(strict=True)
|
||||
rows, issues, files = [], [], 0
|
||||
seen = set()
|
||||
if history:
|
||||
if not 1 <= max_commits <= 10000 or not 1 <= len(refs) <= 32:
|
||||
raise CheckError("invalid history scope limits")
|
||||
resolved = []
|
||||
for ref in refs:
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_./-]{0,200}", ref):
|
||||
raise CheckError("invalid publication ref")
|
||||
resolved.append(git(root, "rev-parse", "--verify", ref + "^{commit}").decode("ascii").strip())
|
||||
commits = git(root, "rev-list", "--max-count=" + str(max_commits + 1), *resolved).decode("ascii").splitlines()
|
||||
if len(commits) > max_commits:
|
||||
issues.append("history_commit_limit")
|
||||
for commit in commits[:max_commits]:
|
||||
entries = git(root, "ls-tree", "-r", "-z", commit).split(b"\x00")
|
||||
for entry in filter(None, entries):
|
||||
metadata, raw_name = entry.split(b"\t", 1)
|
||||
mode, kind, oid = metadata.decode("ascii").split()
|
||||
name = safe_path(raw_name.decode("utf-8"))
|
||||
if (oid, name) in seen:
|
||||
continue
|
||||
seen.add((oid, name))
|
||||
if files >= MAX_FILES:
|
||||
issues.append("history_file_limit")
|
||||
break
|
||||
files += 1
|
||||
if kind != "blob" or mode not in {"100644", "100755"}:
|
||||
rows.append(finding(name, "unreviewed-link-or-submodule", ref=commit))
|
||||
continue
|
||||
if int(git(root, "cat-file", "-s", oid)) > LIMIT:
|
||||
issues.append("oversized_history_blob")
|
||||
continue
|
||||
rows.extend(scan_bytes(name, git(root, "cat-file", "blob", oid), commit, private_terms))
|
||||
if "history_file_limit" in issues:
|
||||
break
|
||||
scope = {"kind": "selected-history", "refs": resolved, "commits": min(len(commits), max_commits)}
|
||||
else:
|
||||
names = git(root, "ls-files", "--cached", "--others", "--exclude-standard", "-z").split(b"\x00")
|
||||
names = sorted(set(filter(None, names)))
|
||||
if len(names) > MAX_FILES:
|
||||
issues.append("worktree_file_limit")
|
||||
for raw_name in names[:MAX_FILES]:
|
||||
name = safe_path(raw_name.decode("utf-8"))
|
||||
path = root / name
|
||||
files += 1
|
||||
if any(parent.is_symlink() for parent in [path, *path.parents] if parent != root.parent):
|
||||
rows.append(finding(name, "unreviewed-link-or-submodule"))
|
||||
continue
|
||||
try:
|
||||
rows.extend(scan_bytes(name, read_file(path), private_terms=private_terms))
|
||||
except (CheckError, OSError):
|
||||
rows.append(finding(name, "unreadable-or-unstable-input"))
|
||||
scope = {"kind": "tracked-and-nonignored-worktree"}
|
||||
accepted = set()
|
||||
for entry in allowlist:
|
||||
if (not isinstance(entry, dict) or set(entry) != {"path", "category", "fingerprint", "reason"} or
|
||||
entry["category"] not in PATTERNS or not isinstance(entry["reason"], str) or
|
||||
not 10 <= len(entry["reason"]) <= 512 or
|
||||
not isinstance(entry["fingerprint"], str) or not re.fullmatch(r"[0-9a-f]{64}", entry["fingerprint"])):
|
||||
raise CheckError("allowlist requires exact path, category, line digest and review reason")
|
||||
accepted.add((safe_path(entry["path"]), entry["category"], entry["fingerprint"]))
|
||||
suppressed = [r for r in rows if (r["path"], r["category"], r.get("fingerprint")) in accepted]
|
||||
rows = [r for r in rows if r not in suppressed]
|
||||
partial = bool(issues) or any(r["category"] in {"manual-asset-review", "unreadable-or-unstable-input", "unreviewed-link-or-submodule"} for r in rows)
|
||||
return {"schema": "durkahelper.publication-check.v1", "scope": scope, "files_checked": files,
|
||||
"findings": rows, "issues": sorted(set(issues)), "reviewed_exceptions": len(suppressed),
|
||||
"external_surfaces": "NOT_RUN: CI artifacts, PR content, remote refs/settings, asset visual review",
|
||||
"exit_code": 2 if partial else 1 if rows else 0}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", default=".")
|
||||
parser.add_argument("--history", action="store_true")
|
||||
parser.add_argument("--ref", action="append")
|
||||
parser.add_argument("--max-commits", type=int, default=500)
|
||||
parser.add_argument("--private-denylist", help="ignored local JSON array; never copied into a report")
|
||||
parser.add_argument("--allowlist", help="JSON array of exact reviewed synthetic line exceptions")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
terms = json.loads(read_file(Path(args.private_denylist))) if args.private_denylist else []
|
||||
if not isinstance(terms, list) or len(terms) > 256 or any(not isinstance(t, str) or not 4 <= len(t) <= 1024 for t in terms):
|
||||
raise CheckError("invalid private denylist")
|
||||
allowlist = json.loads(read_file(Path(args.allowlist))) if args.allowlist else []
|
||||
if not isinstance(allowlist, list) or len(allowlist) > 1000:
|
||||
raise CheckError("invalid reviewed exceptions")
|
||||
result = audit(args.root, history=args.history, refs=args.ref or ["HEAD"], max_commits=args.max_commits,
|
||||
private_terms=[t.encode("utf-8") for t in terms], allowlist=allowlist)
|
||||
print(json.dumps(result, ensure_ascii=True, sort_keys=True))
|
||||
return result["exit_code"]
|
||||
except (CheckError, OSError, UnicodeError, ValueError, subprocess.SubprocessError) as exc:
|
||||
print(json.dumps({"error": type(exc).__name__, "exit_code": 2, "details": "suppressed"}))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+11
-13
@@ -1,10 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build an honest offline rule/language coverage ledger from inert fixtures.
|
||||
"""Покрытие правил независимыми положительными и отрицательными примерами.
|
||||
|
||||
Authored before/after examples are not independent cases. Legacy gaps are
|
||||
reported, not invented; every rule introduced in 1.7.0 requires two distinct
|
||||
positive and two negative independent sources per claimed language. Expanded
|
||||
forms opt in per language with coverage_required; legacy gaps stay visible.
|
||||
Примеры из самих карточек не считаются независимыми проверками. Для правил
|
||||
с обязательным покрытием нужны по два примера каждого вида на каждый язык.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,7 +13,7 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
_SCANNER_SPEC = importlib.util.spec_from_file_location("durkahelper_coverage_scanner", ROOT / "scripts/defense_scan.py")
|
||||
_SCANNER_SPEC = importlib.util.spec_from_file_location("wahrwelt_coverage_scanner", ROOT / "scripts/defense_scan.py")
|
||||
scanner = importlib.util.module_from_spec(_SCANNER_SPEC)
|
||||
_SCANNER_SPEC.loader.exec_module(scanner)
|
||||
|
||||
@@ -57,7 +55,7 @@ def build_ledger(rules=None, cases=None, *, run_checks=False):
|
||||
pair = (rid, case["language"])
|
||||
if pair not in coverage:
|
||||
raise ValueError("fixture rule/language mismatch")
|
||||
# A duplicate or pasted authored example is never extra coverage.
|
||||
# Дубликаты и примеры из карточек не увеличивают покрытие.
|
||||
source = case["source"].strip()
|
||||
if source not in {by_id[rid]["before"].strip(), by_id[rid]["after"].strip()}:
|
||||
coverage[pair][category].add(hashlib.sha256(source.encode("utf-8")).hexdigest())
|
||||
@@ -81,7 +79,7 @@ def build_ledger(rules=None, cases=None, *, run_checks=False):
|
||||
"limitations": by_id[rid]["limitations"]})
|
||||
unmet = [{"rule": row["rule"], "language": row["language"]} for row in rows
|
||||
if row["required_for_release"] and not row["meets_independent_target"]]
|
||||
return {"schema": "durkahelper.scanner-coverage.v1", "scanner_version": scanner.VERSION,
|
||||
return {"schema": "wahrwelt.scanner-coverage.v1", "scanner_version": scanner.VERSION,
|
||||
"rules_sha256": scanner.rules_fingerprint(rules), "rule_count": len(rules),
|
||||
"rule_language_pairs": len(rows), "independent_fixture_records": len(cases),
|
||||
"authored_examples_counted": False, "checks_executed": run_checks,
|
||||
@@ -92,8 +90,8 @@ def build_ledger(rules=None, cases=None, *, run_checks=False):
|
||||
def main(argv=None):
|
||||
scanner.configure_text_output()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--json", action="store_true", help="print the complete deterministic coverage ledger")
|
||||
parser.add_argument("--check", action="store_true", help="also run inert fixture detector checks; no target code is executed")
|
||||
parser.add_argument("--json", action="store_true", help="полный отчет о покрытии в JSON")
|
||||
parser.add_argument("--check", action="store_true", help="проверить срабатывания на примерах, не исполняя их код")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
ledger = build_ledger(run_checks=args.check)
|
||||
@@ -103,9 +101,9 @@ def main(argv=None):
|
||||
if args.json:
|
||||
print(json.dumps(ledger, ensure_ascii=True, indent=2))
|
||||
else:
|
||||
print(f"Rules: {ledger['rule_count']}; rule/language pairs: {ledger['rule_language_pairs']}; independent records: {ledger['independent_fixture_records']}")
|
||||
print("Authored examples excluded. Legacy gaps remain visible; this is not proof of complete vulnerability coverage.")
|
||||
print(f"Checks executed: {ledger['checks_executed']}; failed cases: {len(ledger['failing_case_ids'])}; unmet release pairs: {len(ledger['unmet_release_pairs'])}")
|
||||
print(f"Правил: {ledger['rule_count']}; пар правило-язык: {ledger['rule_language_pairs']}; независимых примеров: {ledger['independent_fixture_records']}")
|
||||
print("Примеры из карточек исключены. Покрытие примерами не гарантирует обнаружение всех уязвимостей.")
|
||||
print(f"Проверки выполнены: {ledger['checks_executed']}; ошибок: {len(ledger['failing_case_ids'])}; непокрытых обязательных пар: {len(ledger['unmet_release_pairs'])}")
|
||||
return ledger["exit_code"]
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,340 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check a private offline cache and prepare the strict v2 assembly manifest.
|
||||
|
||||
This does not download, execute installers, inspect Docker, or prove cold-start
|
||||
readiness. Pins authenticate an explicitly reviewed cache recipe; source archive
|
||||
provenance and license suitability still require operator review.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location("inventory_bundle", Path(__file__).with_name("toolchain_bundle.py"))
|
||||
kit = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(kit)
|
||||
ops, Error = kit.ops, kit.Error
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCHEMA = "durkahelper.toolchain-inventory.v1"
|
||||
REPORT_SCHEMA = "durkahelper.toolchain-readiness.v1"
|
||||
NATIVE_COMPONENTS = {"container-runtime", "python", "ripgrep"}
|
||||
ID = re.compile(r"[a-z0-9][a-z0-9_.-]{0,63}")
|
||||
SHA = re.compile(r"[0-9a-f]{64}")
|
||||
COMMIT = re.compile(r"[0-9a-f]{40}")
|
||||
ASSET_FIELDS = {"id", "path", "kind", "component", "architecture", "version", "sha256", "size",
|
||||
"license", "redistribution", "source_pins"}
|
||||
|
||||
|
||||
def _matches(pattern, value):
|
||||
return isinstance(value, str) and pattern.fullmatch(value) is not None
|
||||
|
||||
|
||||
def _path(value):
|
||||
value = ops._portable_relative_posix(value, "cache member")
|
||||
if (set(part.casefold() for part in value.split("/")) & kit.FORBIDDEN or
|
||||
any(part.casefold().startswith(".env.") for part in value.split("/")) or
|
||||
Path(value).suffix.lower() in {".key", ".pem", ".pcap", ".pcapng", ".db", ".sqlite", ".log"}):
|
||||
raise Error("private operational data is not an inventory member")
|
||||
return value
|
||||
|
||||
|
||||
def recipe(value):
|
||||
fields = {"schema", "release_commit", "target", "receipt", "image_export", "artifacts"}
|
||||
ops._strict_keys(value, fields, fields, "toolchain inventory")
|
||||
if value["schema"] != SCHEMA or not _matches(COMMIT, value["release_commit"]):
|
||||
raise Error("invalid inventory schema or release")
|
||||
ops._strict_keys(value["target"], {"id", "platform"}, {"id", "platform"}, "inventory target")
|
||||
if not _matches(ID, value["target"]["id"]):
|
||||
raise Error("invalid target identity")
|
||||
ops._deployment_enum(value["target"]["platform"], kit.NATIVE_PLATFORMS, "target platform")
|
||||
for key in ("receipt", "image_export"):
|
||||
reference = value[key]
|
||||
ops._strict_keys(reference, {"path", "sha256"}, {"path", "sha256"}, "inventory reference")
|
||||
_path(reference["path"])
|
||||
if not _matches(SHA, reference["sha256"]):
|
||||
raise Error("inventory reference requires a detached checksum")
|
||||
if value["receipt"]["path"].casefold() == value["image_export"]["path"].casefold():
|
||||
raise Error("ambiguous inventory references")
|
||||
assets = value["artifacts"]
|
||||
if not isinstance(assets, list) or len(assets) > 128:
|
||||
raise Error("inventory requires at most 128 non-image artifacts")
|
||||
ids, paths, component_kinds = set(), set(), set()
|
||||
total = 0
|
||||
for asset in assets:
|
||||
ops._strict_keys(asset, ASSET_FIELDS, ASSET_FIELDS, "inventory artifact")
|
||||
if not _matches(ID, asset["id"]) or not _matches(ID, asset["component"]):
|
||||
raise Error("invalid artifact identity")
|
||||
component, kind = asset["component"], asset["kind"]
|
||||
if (not isinstance(kind, str) or component not in kit.REQUIRED_COMPONENT_KINDS or
|
||||
kind == "image" or kind not in kit.REQUIRED_COMPONENT_KINDS[component]):
|
||||
raise Error("artifact outside the maintained component contract")
|
||||
path = _path(asset["path"])
|
||||
if (asset["id"] in ids or path.casefold() in paths or
|
||||
(component, kind) in component_kinds or path.casefold() == "manifest.json" or
|
||||
path.casefold() in {value[key]["path"].casefold() for key in ("receipt", "image_export")}):
|
||||
raise Error("ambiguous cache artifact")
|
||||
ids.add(asset["id"])
|
||||
paths.add(path.casefold())
|
||||
component_kinds.add((component, kind))
|
||||
ops._deployment_enum(asset["architecture"], {"all", *kit.NATIVE_PLATFORMS}, "artifact architecture")
|
||||
if asset["architecture"] not in {"all", value["target"]["platform"]}:
|
||||
raise Error("cache artifact architecture does not match target")
|
||||
if kind in {"client", "runtime", "installer"} and asset["architecture"] != value["target"]["platform"]:
|
||||
raise Error("native artifacts require the exact target platform")
|
||||
version = asset["version"]
|
||||
if (not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+:/@-]{0,127}", version) or
|
||||
set(re.split(r"[:/@._+-]+", version.casefold())) & kit.FLOATING_VERSIONS):
|
||||
raise Error("artifact requires an exact version")
|
||||
if not _matches(SHA, asset["sha256"]):
|
||||
raise Error("artifact checksum required")
|
||||
ops._positive_int(asset["size"], "artifact size", kit.MAX_ARTIFACT)
|
||||
total += asset["size"]
|
||||
if not isinstance(asset["license"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}", asset["license"]):
|
||||
raise Error("artifact license reference required")
|
||||
if asset["redistribution"] != "local-only":
|
||||
raise Error("inventory preparation is local-only, not redistribution approval")
|
||||
pins = asset["source_pins"]
|
||||
if not isinstance(pins, dict) or len(pins) > 32:
|
||||
raise Error("invalid source pin inventory")
|
||||
for name, commit in pins.items():
|
||||
if name != ".":
|
||||
_path(name)
|
||||
if not _matches(COMMIT, commit):
|
||||
raise Error("source pin must be a full commit")
|
||||
if kind == "source":
|
||||
if pins.get(".") != version:
|
||||
raise Error("source archive must declare its root commit")
|
||||
elif pins:
|
||||
raise Error("only source archives declare source pins")
|
||||
if kind == "core" and version != value["release_commit"]:
|
||||
raise Error("core release differs from inventory release")
|
||||
if total > kit.MAX_TOTAL:
|
||||
raise Error("inventory exceeds total byte budget")
|
||||
return value
|
||||
|
||||
|
||||
def _json_member(root, identity, reference):
|
||||
"""Read a checksum-bound JSON member without following cache ancestor links."""
|
||||
descriptor = ops._open_anchored_regular(root, reference["path"], identity)
|
||||
try:
|
||||
before = os.fstat(descriptor)
|
||||
if not stat.S_ISREG(before.st_mode) or before.st_size > ops.MAX_PROFILE_BYTES:
|
||||
raise Error("inventory reference exceeds limit")
|
||||
with os.fdopen(descriptor, "rb", closefd=False) as stream:
|
||||
raw = stream.read(ops.MAX_PROFILE_BYTES + 1)
|
||||
if len(raw) > ops.MAX_PROFILE_BYTES or ops._stat_identity(before) != ops._stat_identity(os.fstat(descriptor)):
|
||||
raise Error("inventory reference changed")
|
||||
if hashlib.sha256(raw).hexdigest() != reference["sha256"]:
|
||||
raise Error("inventory reference checksum mismatch")
|
||||
return json.loads(raw.decode("utf-8"), object_pairs_hook=ops._unique_object,
|
||||
parse_constant=ops._reject_constant)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _receipt(value):
|
||||
fields = {"schema", "compose_sha256", "runtime_sha256", "images"}
|
||||
ops._strict_keys(value, fields, fields, "deployment receipt")
|
||||
if (value["schema"] != "durkahelper.deployment-build.v2" or
|
||||
not _matches(SHA, value["compose_sha256"]) or not _matches(SHA, value["runtime_sha256"]) or
|
||||
not isinstance(value["images"], dict) or set(value["images"]) != set(kit.MAINTAINED_ROLES) or
|
||||
any(not isinstance(i, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", i) for i in value["images"].values())):
|
||||
raise Error("receipt must pin exactly the maintained runtime roles")
|
||||
for group in kit.SHARED_IMAGE_IDENTITY_GROUPS:
|
||||
if len({value["images"][role] for role in group}) != 1:
|
||||
raise Error("receipt shared image identities disagree")
|
||||
return value
|
||||
|
||||
|
||||
def _pin_problem(asset, lock, platform):
|
||||
"""Return a safe category, never a URL, path, checksum or lock value."""
|
||||
component, kind = asset["component"], asset["kind"]
|
||||
if kind in {"core", "license"}:
|
||||
return None
|
||||
pinned = lock.get("components", {}).get(component, {})
|
||||
if kind == "source":
|
||||
commit = pinned.get("source", {}).get("commit")
|
||||
submodules = pinned.get("submodules", {})
|
||||
if not _matches(COMMIT, commit) or submodules.get("status") != "EXISTING":
|
||||
return "unresolved-source-pin"
|
||||
expected = {".": commit}
|
||||
for entry in submodules.get("items", []):
|
||||
if not isinstance(entry, dict) or not _matches(COMMIT, entry.get("commit")):
|
||||
return "unresolved-submodule-pin"
|
||||
expected[entry.get("path")] = entry["commit"]
|
||||
return None if asset["source_pins"] == expected else "source-pin-mismatch"
|
||||
if kind == "client":
|
||||
system, arch = platform.split("/")
|
||||
candidates = [entry for entry in pinned.get("release", {}).get("assets", [])
|
||||
if entry.get("os") == system and entry.get("architecture") == arch]
|
||||
version = pinned.get("version")
|
||||
if not version or len(candidates) != 1:
|
||||
return "unresolved-client-pin"
|
||||
candidate = candidates[0]
|
||||
if (asset["version"].removeprefix("v") != str(version).removeprefix("v") or
|
||||
asset["sha256"] != candidate.get("published_sha256") or asset["size"] != candidate.get("size")):
|
||||
return "client-pin-mismatch"
|
||||
return None
|
||||
# Native prerequisites need a platform-specific official asset pin in the
|
||||
# maintained lock. A locally measured hash cannot authenticate its origin.
|
||||
candidate = pinned.get("asset", {})
|
||||
candidates = pinned.get("assets", [])
|
||||
if candidates:
|
||||
candidates = [entry for entry in candidates if entry.get("platform") == platform]
|
||||
candidate = candidates[0] if len(candidates) == 1 else {}
|
||||
elif not any(entry.get("arch") == platform.split("/")[1] and
|
||||
entry.get("os") in ({"darwin", "macos"} if platform.startswith("darwin/") else {platform.split("/")[0]})
|
||||
for entry in pinned.get("architectures", [])):
|
||||
candidate = {}
|
||||
checksum = candidate.get("sha256") or candidate.get("digest")
|
||||
if isinstance(checksum, str):
|
||||
checksum = checksum.removeprefix("sha256:")
|
||||
if not _matches(SHA, checksum) or not pinned.get("version"):
|
||||
return "unresolved-prerequisite-pin"
|
||||
if (asset["sha256"] != checksum or asset["version"] != pinned["version"] or
|
||||
(candidate.get("size") is not None and asset["size"] != candidate["size"])):
|
||||
return "prerequisite-pin-mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def inspect(root, value, lock):
|
||||
"""Return a sanitized report and, only when complete, a validated manifest."""
|
||||
value = recipe(value)
|
||||
if not isinstance(lock, dict) or lock.get("schema") != "durkahelper.toolchain-lock.v1" or not isinstance(lock.get("components"), dict):
|
||||
raise Error("invalid maintained toolchain lock")
|
||||
root = ops._canonical_root_directory(Path(root))
|
||||
identity = ops._root_anchor_identity(root.lstat())
|
||||
receipt = _receipt(_json_member(root, identity, value["receipt"]))
|
||||
exported = kit.manifest(_json_member(root, identity, value["image_export"]), expected_scope="image-export")
|
||||
kit._check_release_commit(exported, value["release_commit"])
|
||||
if set(receipt["images"].values()) != {i for item in exported["artifacts"] for i in item["image_ids"]}:
|
||||
raise Error("image export does not exactly cover the deployment receipt")
|
||||
target_platform = value["target"]["platform"]
|
||||
container_platform = "linux/" + target_platform.split("/")[1]
|
||||
sources = {item["component"]: item["id"] for item in value["artifacts"] if item["kind"] == "source"}
|
||||
artifacts, issues = [], []
|
||||
export_parent = PurePosixPath(value["image_export"]["path"]).parent
|
||||
for exported_item in exported["artifacts"]:
|
||||
item = copy.deepcopy(exported_item)
|
||||
roles = sorted(role for role, image in receipt["images"].items() if image in item["image_ids"])
|
||||
components = {kit.ROLE_IMAGE_COMPONENTS[role] for role in roles}
|
||||
platforms = {kit.FIXED_ROLE_PLATFORMS.get(role, container_platform) for role in roles}
|
||||
if len(components) != 1 or platforms != {item["architecture"]}:
|
||||
raise Error("image archive cannot map unambiguously to target roles")
|
||||
item["component"] = components.pop()
|
||||
item["path"] = _path((export_parent / item["path"]).as_posix())
|
||||
item["runtime_roles"] = roles
|
||||
item["compatible_with"] = [sources[item["component"]]] if item["component"] in sources else []
|
||||
item["redistribution"] = "local-only"
|
||||
artifacts.append(item)
|
||||
ids = {item["id"] for item in artifacts}
|
||||
paths = {item["path"].casefold() for item in artifacts}
|
||||
reference_paths = {value[key]["path"].casefold() for key in ("receipt", "image_export")}
|
||||
if paths & reference_paths:
|
||||
raise Error("image payload collides with an inventory reference")
|
||||
worker = next(item["id"] for item in artifacts if "neo-worker" in item["runtime_roles"])
|
||||
for original in value["artifacts"]:
|
||||
item = {key: val for key, val in original.items() if key != "source_pins"}
|
||||
if item["id"] in ids or item["path"].casefold() in paths:
|
||||
raise Error("image and artifact inventory collide")
|
||||
ids.add(item["id"])
|
||||
paths.add(item["path"].casefold())
|
||||
item.update(image_ids=[], runtime_roles=[], compatible_with=[])
|
||||
if item["kind"] == "client" and "neo" in sources:
|
||||
item["compatible_with"] = [worker, sources["neo"]]
|
||||
try:
|
||||
problem = _pin_problem(original, lock, target_platform)
|
||||
except (AttributeError, KeyError, TypeError):
|
||||
problem = "invalid-component-pin"
|
||||
if problem:
|
||||
issues.append({"component": item["component"], "kind": item["kind"], "issue": problem})
|
||||
artifacts.append(item)
|
||||
if sum(item["size"] for item in artifacts) > kit.MAX_TOTAL:
|
||||
raise Error("complete cache exceeds byte budget")
|
||||
# Verify each declared file independently so all missing/corrupt items are
|
||||
# reported in one pass. Exceptions are deliberately not copied to evidence.
|
||||
for item in artifacts:
|
||||
if ops._root_anchor_identity(root.lstat()) != identity:
|
||||
raise Error("cache root changed during inventory")
|
||||
try:
|
||||
kit.check_files(root, {"artifacts": [item]})
|
||||
except (Error, OSError, ValueError, kit.tarfile.TarError):
|
||||
issues.append({"component": item["component"], "kind": item["kind"], "issue": "cache-file-unverified"})
|
||||
if ops._root_anchor_identity(root.lstat()) != identity:
|
||||
raise Error("cache root changed during inventory")
|
||||
have = {(item["component"], item["kind"]) for item in artifacts}
|
||||
for component, kinds in sorted(kit.REQUIRED_COMPONENT_KINDS.items()):
|
||||
for kind in sorted(kinds):
|
||||
if (component, kind) not in have:
|
||||
issues.append({"component": component, "kind": kind, "issue": "missing-artifact"})
|
||||
issues = sorted({(item["component"], item["kind"], item["issue"]) for item in issues})
|
||||
issues = [dict(zip(("component", "kind", "issue"), item)) for item in issues]
|
||||
existing_issues = [item for item in issues if item["component"] not in NATIVE_COMPONENTS]
|
||||
candidate = None
|
||||
if not issues:
|
||||
candidate = kit.manifest({
|
||||
"schema": kit.SCHEMA, "release_commit": value["release_commit"], "scope": "complete-target",
|
||||
"required_ids": [item["id"] for item in artifacts], "artifacts": artifacts,
|
||||
"targets": [{**value["target"],
|
||||
"container_platforms": sorted({container_platform, *kit.FIXED_ROLE_PLATFORMS.values()}),
|
||||
"deployment_contract_sha256": kit.DEPLOYMENT_CONTRACT_SHA256,
|
||||
"runtime_roles": [{"id": role, "component": component,
|
||||
"platform": kit.FIXED_ROLE_PLATFORMS.get(role, container_platform),
|
||||
"image_id": receipt["images"][role]} for role, component in kit.MAINTAINED_ROLES.items()],
|
||||
"artifact_ids": [item["id"] for item in artifacts]}]})
|
||||
report = {
|
||||
"schema": REPORT_SCHEMA, "status": "PASS" if candidate else "BLOCKED", "action": "inventory",
|
||||
"target_platform": target_platform, "release_commit": value["release_commit"],
|
||||
"artifacts_declared": len(artifacts), "runtime_roles_bound": len(receipt["images"]),
|
||||
"existing_runtime_inventory": "PASS" if not existing_issues else "BLOCKED",
|
||||
"clean_machine_inventory": "PASS" if candidate else "BLOCKED", "issues": issues,
|
||||
"manifest_sha256": hashlib.sha256(ops._canonical(candidate)).hexdigest() if candidate else None,
|
||||
"complete_target": candidate is not None, "offline_runtime": "NOT_RUN", "competition_ready": False,
|
||||
"installed_prerequisites": "NOT_CHECKED", "source_provenance": "DECLARED_NOT_VERIFIED",
|
||||
"redistribution": "local-only", "daemon_checked": False,
|
||||
"verification_scope": "receipt identities, declared pins, payload hashes and image structure; not installation or runtime acceptance",
|
||||
}
|
||||
return report, candidate
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", required=True, help="Private cache directory; files are never modified")
|
||||
parser.add_argument("--inventory", required=True, help="Operator-reviewed inventory recipe JSON")
|
||||
parser.add_argument("--expected-inventory-sha256", required=True, help="Detached trusted recipe digest")
|
||||
parser.add_argument("--lock", default=str(ROOT / "config/toolchain.lock.json"))
|
||||
parser.add_argument("--emit-manifest", help="Create a NEW assembly manifest only when the full inventory passes")
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument("--approval-id")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.apply and (not args.emit_manifest or not args.approval_id or not ops.APPROVAL_ID.fullmatch(args.approval_id)):
|
||||
raise Error("manifest publication requires output and a non-secret approval ID")
|
||||
value, raw = ops._read_json(args.inventory, ops.MAX_PROFILE_BYTES)
|
||||
kit._check_manifest_digest(raw, args.expected_inventory_sha256, required=True)
|
||||
lock, _ = ops._read_json(args.lock, ops.MAX_PROFILE_BYTES)
|
||||
report, candidate = inspect(args.root, value, lock)
|
||||
if args.emit_manifest:
|
||||
report["manifest_written"] = False
|
||||
if candidate and args.apply:
|
||||
ops._atomic_write_new(args.emit_manifest, ops._canonical(candidate))
|
||||
report["manifest_written"] = True
|
||||
elif candidate:
|
||||
report["action"] = "manifest-preview"
|
||||
print(json.dumps(report, sort_keys=True))
|
||||
return 0 if candidate else 2
|
||||
except (Error, OSError, ValueError, TypeError, RecursionError, kit.tarfile.TarError):
|
||||
print(json.dumps({"schema": REPORT_SCHEMA, "status": "BLOCKED", "error": "invalid-or-unreadable-inventory", "details": "suppressed", "exit_code": 2}, sort_keys=True))
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user