Files
homeclaw/scripts/npm-suspects.py
T

69 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""NPM 접속 로그 + wol-gate 로그에서 "서버를 깨우려 한 낯선 IP"와 스캐너 후보를 뽑는다.
사용:
ssh truenas_admin@192.168.0.240 "sudo docker exec ix-nginx-proxy-manager-npm-1 sh -c \
'zcat -f /data/logs/proxy-host-*_access.log* /data/logs/fallback_http_access.log*'" > npm_access.txt
ssh truenas_admin@192.168.0.240 "sudo docker logs -t ix-wol-gate-wol-gate-1 2>&1" > wolgate.txt
python3 scripts/npm-suspects.py npm_access.txt wolgate.txt
출력: (1) 실제 매직패킷을 보낸 IP별 횟수 (본인 IP는 OWN으로 표시)
(2) 여러 호스트를 훑거나 스캐너 UA인 후보. deny-cidrs.json에 올릴 대역 판단용(자동 차단 아님).
"""
import re, sys, collections, ipaddress
OWN = {"121.183.66.207"} # 사무실(본인)
OWN_NETS = [ipaddress.ip_network("192.168.0.0/16")]
def is_own(ip):
try:
a = ipaddress.ip_address(ip)
except ValueError:
return False
return ip in OWN or any(a in n for n in OWN_NETS)
def main(npm_path, wol_path=None):
if wol_path:
c = collections.Counter()
for line in open(wol_path, errors="ignore"):
m = re.search(r"waking - triggered by (\S+) ", line)
if m:
c[m.group(1)] += 1
print("== 실제 기상 트리거 (IP별)")
for ip, n in c.most_common(20):
print(f"{ip:18} {n:4} {'OWN' if is_own(ip) else ''}")
subnets = collections.Counter()
for ip, n in c.items():
if not is_own(ip) and ":" not in ip:
subnets[str(ipaddress.ip_network(ip + "/24", strict=False))] += n
print("== /24별 (본인 제외)")
for net, n in subnets.most_common(10):
print(f"{net:20} {n}")
rx = re.compile(r'\[(\d+/\w+/\d+):[\d:]+ [+\d]+\].*? (GET|POST|HEAD|PUT|CONNECT|OPTIONS|DELETE|PROPFIND) (https?) (\S+) "([^"]*)" \[Client ([^\]]+)\].*"([^"]*)" "[^"]*"\s*$')
scan_ua = re.compile(r"Palo Alto|Censys|Shodan|zgrab|masscan|Expanse|Nuclei|python-requests|Go-http-client|curl/|l9explore|BLEXBot", re.I)
ips = collections.defaultdict(lambda: {"n": 0, "hosts": set(), "days": set(), "ua": collections.Counter()})
for line in open(npm_path, errors="ignore"):
m = rx.search(line)
if not m:
continue
day, _meth, _sch, host, _path, ip, ua = m.groups()
d = ips[ip]
d["n"] += 1; d["hosts"].add(host); d["days"].add(day); d["ua"][ua[:60]] += 1
print(f"\n== 스캐너 후보 (서로 다른 호스트 >=4 또는 스캐너 UA, 본인 제외) — 총 IP {len(ips)}개")
rows = []
for ip, d in ips.items():
if is_own(ip):
continue
flags = []
if len(d["hosts"]) >= 4: flags.append(f"호스트{len(d['hosts'])}")
if scan_ua.search(" ".join(d["ua"])): flags.append("스캐너UA")
if flags:
rows.append((d["n"], ip, flags, d["ua"].most_common(1)[0][0]))
for n, ip, flags, ua in sorted(rows, reverse=True)[:30]:
print(f"{ip:18} n={n:6} {','.join(flags):14} {ua[:50]}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print(__doc__); sys.exit(1)
main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)