Files

54 lines
1.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""Сторож секретов: находит пароли/токены в Matrix и редактирует сообщения."""
import json
import re
import time
import urllib.request
ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0"
HS = "http://192.168.1.155:8008"
PATTERNS = [
re.compile(r"(?i)(пароль|password|passwd|token|api[_-]?key|secret)\s*[:=]\s*\S{4,}"),
re.compile(r"sk-[A-Za-z0-9]{10,}"),
re.compile(r"-----BEGIN (RSA |OPENSSH |EC )?PRIVATE KEY-----"),
]
def req(method, url, data=None, token=None):
headers = {"Content-Type": "application/json"}
r = urllib.request.Request(url, data=json.dumps(data).encode() if data else None,
headers=headers, method=method)
with urllib.request.urlopen(r, timeout=20) as resp:
return resp.status, resp.read().decode()
def main():
tok = open("/root/.matrix-admin-token").read().strip()
try:
st, body = req("GET", "%s/_matrix/client/v3/rooms/%s/messages?dir=b&limit=100&access_token=%s"
% (HS, ROOM, tok), token=tok)
d = json.loads(body)
except Exception as e:
print("fetch:", e)
return 0
hits = 0
for e in d.get("chunk", []):
if e.get("type") != "m.room.message":
continue
body = (e.get("content") or {}).get("body") or ""
if any(p.search(body) for p in PATTERNS):
eid = e["event_id"]
txn = "sec-%d-%s" % (int(time.time() * 1000), eid[-8:])
try:
req("PUT", "%s/_matrix/client/v3/rooms/%s/redact/%s/%s?access_token=%s"
% (HS, ROOM, eid, txn, tok), data={"reason": "secret detected"}, token=tok)
hits += 1
except Exception as ex:
print("redact:", ex)
print("redacted:", hits)
return 0
if __name__ == "__main__":
raise SystemExit(main())