#!/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))