7 — Т2302 — ебедев — на 5

This commit is contained in:
2026-11-22 23:26:17 +03:00
parent 20afc2c790
commit d15f2a3631
179 changed files with 21709 additions and 54 deletions
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Dependency scan по GitHub Advisory Database (формат OSV, только reviewed): зависимости Python приложения
(requirements.txt) и Go-компоненты закреплённых образов (security/components.json). Офлайн: база — git clone.
git clone --depth 1 --filter=blob:none --sparse https://github.com/github/advisory-database /tmp/ghsa
git -C /tmp/ghsa sparse-checkout set advisories/github-reviewed
python3 scripts/dep_scan.py --db /tmp/ghsa [--json evidence/scan/deps.json]
Каждая находка сопоставляется с решением из security/scan-triage.json (applicable / not_applicable /
mitigated / fixed_by_upgrade + обоснование). Находка без решения — ошибка (exit 1): новый CVE нельзя
«не заметить». Образный (OS-пакеты) скан — scripts/scan.sh (Trivy), разбор — тот же файл triage.
"""
import argparse
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def norm(name):
return re.sub(r"[-_.]+", "-", name).lower()
def pep440(v):
from packaging.version import Version # noqa: PLC0415 — packaging есть почти везде (pip)
return Version(v)
_SEMVER = re.compile(r"^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-(.+))?$")
def gover(v):
"""Ключ сравнения Go-версий, включая pseudo-versions vX.Y.Z-YYYYMMDDHHMMSS-hash."""
m = _SEMVER.match(v.strip())
if not m:
return (0, 0, 0, 0, v)
pre = m.group(4) or ""
ts = re.search(r"(\d{14})-[0-9a-f]{12}$", pre)
major, minor, patch = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
if ts: # pseudo-version: упорядочивается по времени коммита
return (major, minor, patch, -1, ts.group(1))
return (major, minor, patch, 0 if pre else 1, pre)
_PSEUDO = re.compile(r"\d{14}-[0-9a-f]{12}$")
def affected(version, ranges, versions, eco, pseudo=None, last_known=None):
"""OSV ranges. Для модулей с pseudo-version: граница-pseudo сравнивается с pseudo компонента (время коммита
тега), обычная semver-граница — с версией релиза. last_known — database_specific.last_known_affected_version_range
GHSA (верхняя граница диапазона без события fixed, например «< 12.3.7»)."""
key = pep440 if eco == "PyPI" else gover
def cmp_value(bound):
return key(pseudo) if pseudo and _PSEUDO.search(bound) else key(version)
if version in (versions or []):
return True
for r in ranges or []:
if r.get("type") not in ("ECOSYSTEM", "SEMVER"):
continue
hit = False
for ev in r.get("events", []):
try:
if "introduced" in ev:
b = ev["introduced"]
hit = b == "0" or cmp_value(b) >= key(b)
elif "fixed" in ev and hit:
if cmp_value(ev["fixed"]) < key(ev["fixed"]):
return True
hit = False
elif "last_affected" in ev and hit:
if cmp_value(ev["last_affected"]) <= key(ev["last_affected"]):
return True
hit = False
except Exception: # noqa: BLE001
hit = False
if hit:
m = re.match(r"^\s*(<=?)\s*(\S+)", last_known or "")
if m: # верхняя граница из database_specific
v, b = cmp_value(m.group(2)), key(m.group(2))
return v <= b if m.group(1) == "<=" else v < b
return True # introduced без fixed — уязвимы все последующие
return False
def components():
out = []
for line in (ROOT / "requirements.txt").read_text().splitlines():
m = re.match(r"^([A-Za-z0-9_.\-\[\]]+)==([^\s;#]+)", line.strip())
if m:
out.append({"ecosystem": "PyPI", "name": re.sub(r"\[.*\]", "", m.group(1)), "version": m.group(2),
"where": "app image (requirements.txt)"})
out += json.loads((ROOT / "security" / "components.json").read_text())["components"]
return out
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--db", required=True)
ap.add_argument("--json")
a = ap.parse_args()
comps = components()
want = {(c["ecosystem"], norm(c["name"]) if c["ecosystem"] == "PyPI" else c["name"]) for c in comps}
triage = json.loads((ROOT / "security" / "scan-triage.json").read_text())["decisions"]
findings = []
files = list(Path(a.db, "advisories", "github-reviewed").rglob("*.json"))
for f in files:
try:
d = json.loads(f.read_text())
except ValueError:
continue
if d.get("withdrawn"):
continue
for aff in d.get("affected", []):
pkg = aff.get("package", {})
eco = pkg.get("ecosystem")
name = norm(pkg.get("name", "")) if eco == "PyPI" else pkg.get("name", "")
if (eco, name) not in want:
continue
for c in comps:
cname = norm(c["name"]) if eco == "PyPI" else c["name"]
if c["ecosystem"] != eco or cname != name:
continue
lk = (aff.get("database_specific") or {}).get("last_known_affected_version_range")
if affected(c["version"], aff.get("ranges"), aff.get("versions"), eco, c.get("pseudo"), lk):
if any(x["id"] == d["id"] and x["package"] == c["name"] for x in findings):
continue
fixed = [ev["fixed"] for r in aff.get("ranges", []) for ev in r.get("events", []) if "fixed" in ev]
sev = (d.get("database_specific") or {}).get("severity", "UNKNOWN")
findings.append({"id": d["id"], "aliases": d.get("aliases", []), "severity": sev,
"package": c["name"], "version": c["version"], "where": c["where"],
"fixed": fixed, "summary": d.get("summary", "")[:160],
"triage": triage.get(d["id"])})
findings.sort(key=lambda x: (["CRITICAL", "HIGH", "MODERATE", "LOW", "UNKNOWN"].index(x["severity"])
if x["severity"] in ("CRITICAL", "HIGH", "MODERATE", "LOW") else 4, x["package"]))
untriaged = [x for x in findings if not x["triage"]]
print("## dependency scan: %d components, %d advisories in DB, %d findings, %d untriaged" % (
len(comps), len(files), len(findings), len(untriaged)))
for x in findings:
t = x["triage"] or {"decision": "UNTRIAGED", "reason": ""}
print("%-9s %-20s %-45s %s %s → fixed %s\n [%s] %s\n triage: %s — %s" % (
x["severity"], x["id"], x["package"][:45], x["version"], "/".join(x["aliases"][:1]),
",".join(x["fixed"][:2]) or "-", x["where"], x["summary"], t["decision"], t["reason"]))
if a.json:
Path(a.json).parent.mkdir(parents=True, exist_ok=True)
Path(a.json).write_text(json.dumps({"components": comps, "findings": findings}, ensure_ascii=False, indent=1))
sys.exit(1 if untriaged else 0)
if __name__ == "__main__":
main()