템플릿의 보안 결함은 거기서 나온 모든 서비스로 복제된다. 반복 가능한 red team 장치가 없어, 공격을 사람이 매번 즉흥으로 했다. 새 플러그인 `redteam`을 더한다. harness와 역할이 달라 훅은 두지 않고(상시 실행은 컨텍스트를 오염시킨다) 요청할 때만 스킬·서브에이전트로 돈다. - agents/ 역할 6: recon·authz·input·deps·config·frontend - skills/redteam/ 교전 오케스트레이션(범위→정찰→공격→수집→보고→고침→재실행) - scripts/redteam-scan.sh 핀 고정 도구 실행 래퍼(desktop), tools.lock - scripts/finding.py 발견 정규화·검사·정렬·보고(심각도·재현·영향·고치는 법) 버린 대안: - 룰셋·CVE 데이터 vendoring → 공개 repo 라이선스 문제(semgrep 룰은 내부용 제한 라이선스). 도구는 런타임에 받고 룰도 그때 받는다. SAST 기본은 opengrep. - CodeQL 기본 → 라이선스(OSS 전용 조건)로 제외, opengrep+FindSecBugs로 대체. - 훅으로 상시 실행 → 출력이 모든 세션 컨텍스트에 들어가 오염. 그래서 opt-in. 위험·한계: tools.lock의 digest는 아직 미고정(-)이다. 첫 실행 `pin` 모드가 실제 digest를 뽑아 채운다(trivy-scan.sh의 바이너리 SHA-256과 같은 TOFU 방식). 도구 실행은 desktop·docker가 있어야 하므로, 시험은 형식·로직만 본다(실행 아님). 검증: scripts/check.sh rc=0 — redteam 18, harness 21, 템플릿 10 시험 통과, marketplace·harness·redteam 매니페스트 validate --strict 통과.
186 lines
6.7 KiB
Python
Executable File
186 lines
6.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""red team 발견 수집·정규화 도구. 표준 라이브러리만 쓴다.
|
|
|
|
발견은 JSON Lines(한 줄 한 건)로 모은다. 한 건의 필드:
|
|
|
|
id 짧은 안정 식별자 (예: BE-AUTHZ-001). 재실행 때 같은 발견을 같은 id로.
|
|
severity critical | high | medium | low | info
|
|
target backend | frontend | shared
|
|
category recon | authz | input | deps | config | frontend
|
|
title 한 줄 요약
|
|
location file:line 또는 URL·엔드포인트
|
|
repro 재현 절차 (여러 줄 가능)
|
|
impact 악용되면 무엇이 깨지나
|
|
fix 고치는 법
|
|
status open | fixed | accepted | wontfix (기본 open)
|
|
source 도구 이름 또는 "manual"
|
|
evidence 증거 경로·로그 (선택)
|
|
|
|
쓰기:
|
|
finding.py validate findings.jsonl 필드·중복 검사 (잘못되면 rc=1)
|
|
finding.py report findings.jsonl 심각도순 마크다운 표를 stdout에
|
|
finding.py summary findings.jsonl 심각도별 건수 한 줄 (게이트용, open만)
|
|
finding.py merge a.jsonl b.jsonl ... id로 중복 제거해 stdout에 (뒤가 이김)
|
|
|
|
보고 형식은 brief의 「심각도·재현 절차·영향·고치는 법」을 그대로 따른다.
|
|
"""
|
|
import json
|
|
import sys
|
|
|
|
SEVERITIES = ("critical", "high", "medium", "low", "info")
|
|
TARGETS = ("backend", "frontend", "shared")
|
|
CATEGORIES = ("recon", "authz", "input", "deps", "config", "frontend")
|
|
STATUSES = ("open", "fixed", "accepted", "wontfix")
|
|
REQUIRED = ("id", "severity", "target", "category", "title", "impact", "fix")
|
|
|
|
|
|
def severity_rank(sev):
|
|
"""정렬용. 작을수록 위험. 모르는 값은 맨 뒤."""
|
|
try:
|
|
return SEVERITIES.index(sev)
|
|
except ValueError:
|
|
return len(SEVERITIES)
|
|
|
|
|
|
def validate_one(f):
|
|
"""한 건을 검사해 오류 메시지 목록을 돌려준다. 빈 목록이면 통과."""
|
|
errors = []
|
|
if not isinstance(f, dict):
|
|
return ["발견이 객체가 아니다: %r" % (f,)]
|
|
for key in REQUIRED:
|
|
if not f.get(key):
|
|
errors.append("필수 필드 없음: %s" % key)
|
|
if f.get("severity") and f["severity"] not in SEVERITIES:
|
|
errors.append("severity 값이 틀림: %r (%s 중 하나)" % (f["severity"], "/".join(SEVERITIES)))
|
|
if f.get("target") and f["target"] not in TARGETS:
|
|
errors.append("target 값이 틀림: %r" % (f["target"],))
|
|
if f.get("category") and f["category"] not in CATEGORIES:
|
|
errors.append("category 값이 틀림: %r" % (f["category"],))
|
|
status = f.get("status", "open")
|
|
if status not in STATUSES:
|
|
errors.append("status 값이 틀림: %r" % (status,))
|
|
return errors
|
|
|
|
|
|
def validate_all(findings):
|
|
"""(오류 메시지 목록)을 돌려준다. id 중복도 오류."""
|
|
errors = []
|
|
seen = {}
|
|
for i, f in enumerate(findings):
|
|
for e in validate_one(f):
|
|
errors.append("[%d] %s" % (i, e))
|
|
fid = f.get("id") if isinstance(f, dict) else None
|
|
if fid is not None:
|
|
if fid in seen:
|
|
errors.append("[%d] id 중복: %s (먼저 [%d])" % (i, fid, seen[fid]))
|
|
else:
|
|
seen[fid] = i
|
|
return errors
|
|
|
|
|
|
def sort_findings(findings):
|
|
"""심각도(위험한 것 먼저) → target → id 순."""
|
|
return sorted(
|
|
findings,
|
|
key=lambda f: (severity_rank(f.get("severity", "")),
|
|
f.get("target", ""),
|
|
str(f.get("id", ""))),
|
|
)
|
|
|
|
|
|
def counts(findings, only_open=False):
|
|
"""심각도별 건수."""
|
|
out = {s: 0 for s in SEVERITIES}
|
|
for f in findings:
|
|
if only_open and f.get("status", "open") != "open":
|
|
continue
|
|
sev = f.get("severity")
|
|
if sev in out:
|
|
out[sev] += 1
|
|
return out
|
|
|
|
|
|
def to_markdown(findings):
|
|
rows = sort_findings(findings)
|
|
lines = ["# red team 발견", ""]
|
|
c = counts(findings)
|
|
co = counts(findings, only_open=True)
|
|
lines.append("- 전체: " + ", ".join("%s %d" % (s, c[s]) for s in SEVERITIES))
|
|
lines.append("- open: " + ", ".join("%s %d" % (s, co[s]) for s in SEVERITIES))
|
|
lines.append("")
|
|
for f in rows:
|
|
status = f.get("status", "open")
|
|
lines.append("## [%s] %s — %s" % (f.get("severity", "?").upper(), f.get("id", "?"), f.get("title", "")))
|
|
lines.append("")
|
|
lines.append("- 대상: %s · 분야: %s · 상태: %s · 출처: %s"
|
|
% (f.get("target", "?"), f.get("category", "?"), status, f.get("source", "?")))
|
|
if f.get("location"):
|
|
lines.append("- 위치: `%s`" % f["location"])
|
|
if f.get("evidence"):
|
|
lines.append("- 증거: %s" % f["evidence"])
|
|
lines.append("")
|
|
lines.append("**재현 절차**")
|
|
lines.append("")
|
|
lines.append((f.get("repro") or "(없음)").rstrip())
|
|
lines.append("")
|
|
lines.append("**영향:** " + (f.get("impact") or ""))
|
|
lines.append("")
|
|
lines.append("**고치는 법:** " + (f.get("fix") or ""))
|
|
lines.append("")
|
|
return "\n".join(lines).rstrip() + "\n"
|
|
|
|
|
|
def load_jsonl(path):
|
|
findings = []
|
|
with open(path, encoding="utf-8") as fh:
|
|
for n, line in enumerate(fh, 1):
|
|
line = line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
try:
|
|
findings.append(json.loads(line))
|
|
except json.JSONDecodeError as e:
|
|
raise SystemExit("%s:%d JSON 오류: %s" % (path, n, e))
|
|
return findings
|
|
|
|
|
|
def main(argv):
|
|
if len(argv) < 2:
|
|
raise SystemExit(__doc__)
|
|
cmd = argv[1]
|
|
if cmd == "merge":
|
|
by_id = {}
|
|
order = []
|
|
for path in argv[2:]:
|
|
for f in load_jsonl(path):
|
|
fid = f.get("id")
|
|
if fid not in by_id:
|
|
order.append(fid)
|
|
by_id[fid] = f
|
|
for fid in order:
|
|
print(json.dumps(by_id[fid], ensure_ascii=False))
|
|
return 0
|
|
|
|
path = argv[2]
|
|
findings = load_jsonl(path)
|
|
if cmd == "validate":
|
|
errors = validate_all(findings)
|
|
if errors:
|
|
sys.stderr.write("\n".join(errors) + "\n")
|
|
return 1
|
|
print("validate: %d건 통과" % len(findings))
|
|
return 0
|
|
if cmd == "report":
|
|
sys.stdout.write(to_markdown(findings))
|
|
return 0
|
|
if cmd == "summary":
|
|
co = counts(findings, only_open=True)
|
|
print("open " + " ".join("%s=%d" % (s, co[s]) for s in SEVERITIES))
|
|
# 열린 critical·high가 있으면 rc=1 (게이트용)
|
|
return 1 if (co["critical"] or co["high"]) else 0
|
|
raise SystemExit("모르는 명령: %s" % cmd)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv))
|