forked from mtusi2026/mtusi2026lab7
7 — Т2302 — ебедев — на 5
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка «секреты не попали в репозиторий/evidence/архив»: ищет закрытые ключи (PEM), значения из secrets/,
|
||||
материал оператора OpenBao (root token, unseal shares), SecretID, токены OpenBao и заголовки Authorization.
|
||||
|
||||
python3 scripts/secret_scan.py [путь ...] # по умолчанию — весь репозиторий, кроме secrets/ и .git/
|
||||
|
||||
Значения секретов используются только для сравнения и не печатаются (печатается файл и тип находки).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SKIP_DIRS = {".git", "secrets", "__pycache__", ".venv", "node_modules"}
|
||||
PATTERNS = {
|
||||
"PEM private key": re.compile(rb"-----BEGIN (?:EC |RSA |ENCRYPTED )?PRIVATE KEY-----"),
|
||||
"OpenBao/Vault token": re.compile(rb"\b(?:s|hvs|hvb)\.[A-Za-z0-9]{24,}\b"),
|
||||
"Authorization: Bearer <token>": re.compile(rb"Authorization:\s*Bearer\s+[A-Za-z0-9_\-]{43}\b"),
|
||||
}
|
||||
|
||||
|
||||
def known_values():
|
||||
vals = {}
|
||||
sec = ROOT / "secrets"
|
||||
for p in sec.rglob("*"):
|
||||
if p.is_file() and p.stat().st_size < 4096 and p.suffix not in (".crt", ".pem", ".json", ".conf"):
|
||||
try:
|
||||
v = p.read_bytes().strip()
|
||||
except PermissionError: # ключи сервисов (0400, uid сервиса): их ловит шаблон PEM
|
||||
continue
|
||||
if len(v) >= 16 and b"BEGIN" not in v:
|
||||
vals[str(p.relative_to(ROOT))] = v
|
||||
op = Path(os.environ.get("MTUSI_OPERATOR_DIR", str(Path.home() / ".mtusi-lab7-operator"))) / "openbao-init.json"
|
||||
if op.exists():
|
||||
d = json.loads(op.read_text())
|
||||
vals["openbao root token"] = d["root_token"].encode()
|
||||
for i, k in enumerate(d["unseal_keys_b64"]):
|
||||
vals["unseal share %d" % (i + 1)] = k.encode()
|
||||
return vals
|
||||
|
||||
|
||||
def main():
|
||||
roots = [Path(x) for x in sys.argv[1:]] or [ROOT]
|
||||
vals = known_values()
|
||||
findings, files = [], 0
|
||||
for root in roots:
|
||||
for dirpath, dirnames, filenames in os.walk(root):
|
||||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
||||
for fn in filenames:
|
||||
p = Path(dirpath) / fn
|
||||
try:
|
||||
data = p.read_bytes()
|
||||
except OSError:
|
||||
continue
|
||||
files += 1
|
||||
rel = str(p.relative_to(ROOT)) if ROOT in p.parents else str(p)
|
||||
for name, rx in PATTERNS.items():
|
||||
if rx.search(data):
|
||||
findings.append((rel, name))
|
||||
for name, v in vals.items():
|
||||
if v in data:
|
||||
findings.append((rel, "value of " + name))
|
||||
for rel, what in findings:
|
||||
print("FOUND %-60s %s" % (rel, what))
|
||||
print("secret scan: %d files, %d known secret values, %d findings" % (files, len(vals), len(findings)))
|
||||
sys.exit(1 if findings else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user