wol-gate: 요주의 대역(deny-cidrs.json, DENY_CIDRS) 기상 차단 + NPM/wol-gate 로그 점검 스크립트
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d47aed5a9a
commit
42b31e24e2
4 files changed
+86
-1
No files matched your search
@@ -0,0 +1,68 @@
|
||||
#!/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)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY server.js kr-cidrs.json .
|
||||
COPY server.js kr-cidrs.json deny-cidrs.json .
|
||||
ENV LISTEN_PORT=8099
|
||||
EXPOSE 8099
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"_comment": "깨우기를 시도해도 매직패킷을 보내지 않을 IPv4 대역. 환경변수 DENY_CIDRS(쉼표 구분)로도 추가 가능.",
|
||||
"ipv4": [
|
||||
"222.239.104.0/24"
|
||||
]
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
const http = require('http');
|
||||
const dgram = require('dgram');
|
||||
const krCidrs = require('./kr-cidrs.json');
|
||||
const denyFile = require('./deny-cidrs.json');
|
||||
|
||||
const TARGET_HOST = process.env.TARGET_HOST || '192.168.0.5';
|
||||
const TARGET_PORT = parseInt(process.env.TARGET_PORT || '18789', 10);
|
||||
@@ -92,6 +93,11 @@ function inSortedRanges(value, ranges) {
|
||||
const PRIVATE_V4_RANGES = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8']
|
||||
.map(cidrToRangeV4)
|
||||
.sort((a, b) => a[0] - b[0]);
|
||||
// 요주의 대역(IDC 스캐너 등)은 국내 IP여도 깨우지 않는다. deny-cidrs.json + 환경변수 DENY_CIDRS.
|
||||
const DENY_V4_RANGES = [
|
||||
...(denyFile.ipv4 || []),
|
||||
...String(process.env.DENY_CIDRS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
].filter((c) => /^\d+\.\d+\.\d+\.\d+\/\d+$/.test(c)).map(cidrToRangeV4).sort((a, b) => a[0] - b[0]);
|
||||
const KR_V4_RANGES = krCidrs.ipv4.map(cidrToRangeV4).sort((a, b) => a[0] - b[0]);
|
||||
const KR_V6_RANGES = krCidrs.ipv6.map(cidrToRangeV6).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
||||
|
||||
@@ -196,6 +202,11 @@ function describeRequester(req) {
|
||||
|
||||
function maybeWake(req) {
|
||||
const ip = extractClientIp(req);
|
||||
const ipn = ipToInt(ip || '');
|
||||
if (ipn !== null && inSortedRanges(ipn, DENY_V4_RANGES)) {
|
||||
console.log(`[wol-gate] wake denied (watchlist) - triggered by ${describeRequester(req)}`);
|
||||
return;
|
||||
}
|
||||
if (!isDomesticIp(ip)) {
|
||||
console.log(`[wol-gate] wake blocked (non-KR) - triggered by ${describeRequester(req)}`);
|
||||
return;
|
||||
|
||||
Reference in new issue
Block a user