49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Redact secret-like keys/values from an audit JSON export."""
|
|
import argparse
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
|
|
KEY_RE = re.compile(r"(token|secret|password|passwd|api[_-]?key|authorization|cookie)", re.I)
|
|
VAL_RES = [
|
|
re.compile(r"sk-[A-Za-z0-9]{20,}"),
|
|
re.compile(r"ghp_[A-Za-z0-9]{20,}"),
|
|
re.compile(r"AIza[0-9A-Za-z_-]{20,}"),
|
|
re.compile(r"-----BEGIN (RSA|OPENSSH|PRIVATE) KEY-----"),
|
|
re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}"),
|
|
]
|
|
|
|
|
|
def redact(obj):
|
|
if isinstance(obj, dict):
|
|
out = {}
|
|
for k, v in obj.items():
|
|
out[k] = "[REDACTED]" if KEY_RE.search(str(k)) else redact(v)
|
|
return out
|
|
if isinstance(obj, list):
|
|
return [redact(x) for x in obj]
|
|
if isinstance(obj, str):
|
|
for p in VAL_RES:
|
|
if p.search(obj):
|
|
return "[REDACTED]"
|
|
return obj
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("src")
|
|
ap.add_argument("dst")
|
|
args = ap.parse_args()
|
|
data = json.loads(Path(args.src).read_text(encoding="utf-8"))
|
|
red = redact(data)
|
|
Path(args.dst).write_text(json.dumps(red, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
text = Path(args.dst).read_text(encoding="utf-8")
|
|
left = sum(1 for p in VAL_RES if p.search(text))
|
|
print("redacted_bytes=%d residual_patterns=%d" % (len(text), left))
|
|
raise SystemExit(1 if left else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|