Spaces:
Running
Running
Download scripts/parse_live.py from ereezy/sentry-intel: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/spaces/ereezy/sentry-intel/resolve/main/scripts/parse_live.py
- Command line
-
hf download hf://spaces/ereezy/sentry-intel/scripts/parse_live.py
-
curl -L -o parse_live.py https://huggingface.co/spaces/ereezy/sentry-intel/resolve/main/scripts/parse_live.py
17.1 kB
| """ | |
| Sentry Intel — LIVE corpus parser. | |
| Reads the *currently active* sensors on the sentry host (not the frozen | |
| Oct-08 log set) and emits data/intel.json for the static Space. | |
| Sources (all live, written within the last minutes): | |
| /opt/attacker-intel/beacon_sessions.jsonl protocol honeypot session ledger (postgres/redis/mysql/s3/http) | |
| /opt/attacker-intel/poison_hits.log nginx decoy path hits (/.env, /.git/config, ...) | |
| /opt/attacker-intel/honeypot_sessions.jsonl SSH-protocol session ledger | |
| /opt/attacker-intel/beacon_alerts.log HIGH-severity C2 beacon alerts | |
| Geo is resolved OFFLINE at build time with a local GeoLite2-City.mmdb so the | |
| Space makes zero runtime network calls. | |
| Usage: | |
| python scripts/parse_intel.py --dir . --mmdb geo/GeoLite2-City.mmdb --out data/intel.json | |
| """ | |
| import argparse, collections, hashlib, json, os, re | |
| # ---------------------------------------------------------------- helpers | |
| def sha256_of(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def b2s(b, limit=512): | |
| """bytes -> printable text, escaping control chars.""" | |
| try: | |
| s = b.decode("utf-8", "replace") | |
| except Exception: | |
| s = "" | |
| out = [] | |
| for ch in s: | |
| if ch == "\n": | |
| out.append("\\n") | |
| elif ch == "\r": | |
| out.append("\\r") | |
| elif ch == "\t": | |
| out.append("\\t") | |
| elif ord(ch) < 32 or ord(ch) == 127: | |
| out.append("\\x%02x" % ord(ch)) | |
| else: | |
| out.append(ch) | |
| return "".join(out)[:limit] | |
| def classify_payload(raw): | |
| if not raw: | |
| return "empty" | |
| head = raw[:16] | |
| if head.startswith(b"SSH-"): | |
| return "SSH banner" | |
| if b"\x03\x00" in head[:4] or head[:3] == b"\x16\x03\x01": | |
| return "TLS ClientHello" | |
| if head.startswith(b"\xffSMB") or head[:4] == b"\x00\x00\x00\x85": | |
| return "SMB negotiate" | |
| if head.startswith(b"GET ") or head.startswith(b"POST ") or head.startswith(b"HEAD "): | |
| return "HTTP request" | |
| if b"\x03\x00\x00" == raw[:3]: | |
| return "RDP X.224" | |
| if raw[:4] == b"\x05\x01\x00" or raw[:3] == b"\x05\x02\x00": | |
| return "SOCKS5" | |
| try: | |
| raw.decode("ascii") | |
| return "text protocol" | |
| except Exception: | |
| return "binary" | |
| def is_public_ip(ip): | |
| try: | |
| a, b = int(ip.split(".")[0]), int(ip.split(".")[1]) | |
| except Exception: | |
| return False | |
| if a in (10, 127, 0): | |
| return False | |
| if a == 192 and b == 168: | |
| return False | |
| if a == 172 and 16 <= b <= 31: | |
| return False | |
| return True | |
| # ---------------------------------------------------------------- parse | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dir", default=".") | |
| ap.add_argument("--mmdb", default="geo/GeoLite2-City.mmdb") | |
| ap.add_argument("--out", default="data/intel.json") | |
| ap.add_argument("--recent", type=int, default=300) | |
| args = ap.parse_args() | |
| d = args.dir | |
| P = lambda n: os.path.join(d, n) | |
| src_beacon = P("beacon_sessions.jsonl") | |
| src_poison = P("poison_hits.log") | |
| src_honeypot = P("honeypot_sessions.jsonl") | |
| src_alerts = P("beacon_alerts.log") | |
| # ---- offline geo ---- | |
| geo_note = "no geo database present at build time" | |
| reader = None | |
| for cand in (args.mmdb, P("GeoLite2-City.mmdb")): | |
| if os.path.exists(cand): | |
| try: | |
| import maxminddb | |
| reader = maxminddb.open_database(cand) | |
| geo_note = ("IP->lat/lon resolved offline at build time with " | |
| "GeoLite2-City.mmdb; zero runtime geo API calls") | |
| break | |
| except Exception as e: | |
| geo_note = "geo db present but unreadable: %s" % e | |
| geo_cache = {} | |
| def geo_for(ip): | |
| if ip in geo_cache: | |
| return geo_cache[ip] | |
| rec = {"country": "", "country_name": "", "city": "", "lat": None, "lon": None} | |
| if reader is not None: | |
| try: | |
| r = reader.get(ip) or {} | |
| c = r.get("country") or {} | |
| cy = r.get("city") or {} | |
| loc = r.get("location") or {} | |
| rec["country"] = c.get("iso_code") or "" | |
| rec["country_name"] = (c.get("names") or {}).get("en", "") or "" | |
| rec["city"] = (cy.get("names") or {}).get("en", "") or "" | |
| rec["lat"] = loc.get("latitude") | |
| rec["lon"] = loc.get("longitude") | |
| except Exception: | |
| pass | |
| geo_cache[ip] = rec | |
| return rec | |
| # ---- accumulators ---- | |
| protocols = collections.Counter() | |
| events = collections.Counter() | |
| tools = collections.Counter() | |
| paths = collections.Counter() | |
| attack_paths = collections.Counter() | |
| c2_urls = collections.Counter() | |
| url_total = collections.Counter() | |
| url_in_payload = collections.Counter() | |
| scanner_ids = collections.Counter() | |
| ip_counts = collections.Counter() | |
| subnet_counts = collections.Counter() | |
| hourly = collections.Counter() | |
| daily = collections.Counter() | |
| recent = [] | |
| honeypot_types = collections.Counter() | |
| decoy_keys = set() | |
| credential_rows = [] | |
| first_ts = last_ts = None | |
| n_beacon = 0 | |
| # ===== beacon_sessions.jsonl ===== | |
| if os.path.exists(src_beacon): | |
| with open(src_beacon, encoding="utf-8", errors="replace") as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| r = json.loads(line) | |
| except Exception: | |
| continue | |
| n_beacon += 1 | |
| ts = r.get("ts") or "" | |
| ip = r.get("ip") or "" | |
| if ts: | |
| if not first_ts or ts < first_ts: | |
| first_ts = ts | |
| if not last_ts or ts > last_ts: | |
| last_ts = ts | |
| hourly[ts[:13]] += 1 | |
| daily[ts[:10]] += 1 | |
| if ip and is_public_ip(ip): | |
| ip_counts[ip] += 1 | |
| subnet_counts[".".join(ip.split(".")[:3]) + ".0/24"] += 1 | |
| if r.get("protocol"): | |
| protocols[r["protocol"]] += 1 | |
| ev = r.get("event") or "" | |
| if ev: | |
| events[ev] += 1 | |
| if r.get("tool"): | |
| tools[str(r["tool"])[:70]] += 1 | |
| if r.get("path"): | |
| paths[str(r["path"])[:80]] += 1 | |
| # URLs found in a session. CRITICAL: the raw `c2_urls` field mixes | |
| # two unrelated things — (a) endpoints the attacker actually used, | |
| # which appear INSIDE the captured payload, and (b) URLs that are | |
| # merely part of a client's User-Agent string (openai.com/gptbot, | |
| # about.censys.io, google.com/bot.html...). Calling the latter "C2" | |
| # is simply wrong. Split them and keep the evidence for each. | |
| pl = r.get("payload") | |
| pl_s = json.dumps(pl) if isinstance(pl, (dict, list)) else str(pl or "") | |
| for u in (r.get("c2_urls") or []): | |
| if isinstance(u, str): | |
| uk = u[:160] | |
| url_total[uk] += 1 | |
| if u and u in pl_s: | |
| url_in_payload[uk] += 1 | |
| if r.get("access_key"): | |
| decoy_keys.add(str(r["access_key"])[:80]) | |
| if ev == "credential": | |
| g = geo_for(ip) if ip else {} | |
| credential_rows.append({ | |
| "ts": ts, "ip": ip, "protocol": r.get("protocol"), | |
| "user": str(r.get("user") or "")[:80], | |
| "country": g.get("country", ""), | |
| }) | |
| if len(recent) < args.recent: | |
| g = geo_for(ip) if ip else {} | |
| raw = r.get("payload") | |
| if isinstance(raw, (dict, list)): | |
| phex = json.dumps(raw)[:2048] | |
| ptext = json.dumps(raw)[:512] | |
| else: | |
| phex = str(raw or "")[:2048] | |
| ptext = str(raw or "")[:512] | |
| recent.append({ | |
| "ts": ts, "ip": ip, "port": r.get("src_port"), | |
| "proto": r.get("protocol"), "event": ev, | |
| "tool": str(r.get("tool") or "")[:60], | |
| "path": str(r.get("path") or "")[:80], | |
| "country": g.get("country", ""), | |
| "lat": g.get("lat"), "lon": g.get("lon"), | |
| "payload_hex": phex, "payload_text": ptext, | |
| }) | |
| # ===== poison_hits.log : "IP: x | File: /p | UA: ..." ===== | |
| n_poison = 0 | |
| if os.path.exists(src_poison): | |
| rx = re.compile(r"^IP:\s*(\S+)\s*\|\s*File:\s*(\S+)\s*\|\s*UA:\s*(.*)$") | |
| with open(src_poison, encoding="utf-8", errors="replace") as f: | |
| for line in f: | |
| m = rx.match(line.strip()) | |
| if not m: | |
| continue | |
| n_poison += 1 | |
| ip, path, _ua = m.group(1), m.group(2), m.group(3) | |
| attack_paths[path[:80]] += 1 | |
| if is_public_ip(ip): | |
| ip_counts[ip] += 1 | |
| subnet_counts[".".join(ip.split(".")[:3]) + ".0/24"] += 1 | |
| # ===== honeypot_sessions.jsonl ===== | |
| n_hp = 0 | |
| if os.path.exists(src_honeypot): | |
| with open(src_honeypot, encoding="utf-8", errors="replace") as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| r = json.loads(line) | |
| except Exception: | |
| continue | |
| n_hp += 1 | |
| if r.get("type"): | |
| honeypot_types[r["type"]] += 1 | |
| ip = r.get("ip") or "" | |
| ts = r.get("timestamp") or "" | |
| if ts: | |
| if not first_ts or ts < first_ts: | |
| first_ts = ts | |
| if not last_ts or ts > last_ts: | |
| last_ts = ts | |
| hourly[ts[:13]] += 1 | |
| daily[ts[:10]] += 1 | |
| if ip and is_public_ip(ip): | |
| ip_counts[ip] += 1 | |
| subnet_counts[".".join(ip.split(".")[:3]) + ".0/24"] += 1 | |
| # ===== beacon_alerts.log : "[ts] HIGH {json}" ===== | |
| n_alerts = 0 | |
| alert_ips = collections.Counter() | |
| if os.path.exists(src_alerts): | |
| rx = re.compile(r"^\[([^\]]+)\]\s+(\w+)\s+(\{.*\})\s*$") | |
| with open(src_alerts, encoding="utf-8", errors="replace") as f: | |
| for line in f: | |
| m = rx.match(line.strip()) | |
| if not m: | |
| continue | |
| n_alerts += 1 | |
| try: | |
| j = json.loads(m.group(3)) | |
| if j.get("ip"): | |
| alert_ips[j["ip"]] += 1 | |
| except Exception: | |
| pass | |
| # ---- sources with hashes ---- | |
| sources = [] | |
| for label, p in (("beacon_sessions.jsonl", src_beacon), | |
| ("poison_hits.log", src_poison), | |
| ("honeypot_sessions.jsonl", src_honeypot), | |
| ("beacon_alerts.log", src_alerts)): | |
| if os.path.exists(p): | |
| sources.append({ | |
| "name": label, | |
| "remote_path": "/opt/attacker-intel/" + label, | |
| "bytes": os.path.getsize(p), | |
| "sha256": sha256_of(p), | |
| }) | |
| # ---- split URL-like strings: attacker endpoints vs crawler self-IDs ---- | |
| ip_host = re.compile(r"^https?://\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?(?:/|$)", re.I) | |
| payload_artifact = re.compile(r"(\.sh|/kworker|cc\.txt|/ndt\.sh|init\.sh)(\?|$)", re.I) | |
| # XML namespace / schema URIs are structural markup inside SOAP payloads, | |
| # not endpoints anyone contacted. Drop them or the panel is polluted. | |
| NOISE = ("w3.org/2001/xmlschema", "schemas.xmlsoap.org", "w3.org/2001/xml", | |
| "xmlsoap.org/soap/envelope") | |
| for uk, tot in url_total.items(): | |
| low = uk.lower() | |
| if any(nz in low for nz in NOISE): | |
| continue | |
| # a bare/short host from a truncated payload is not a usable endpoint | |
| if len(uk.split("://", 1)[-1].split("/", 1)[0]) < 4: | |
| continue | |
| ratio = (url_in_payload.get(uk, 0) / tot) if tot else 0.0 | |
| host_ip = bool(ip_host.match(uk)) | |
| artifact = bool(payload_artifact.search(uk)) | |
| if host_ip or artifact or ratio > 0.5: | |
| c2_urls[uk] = tot | |
| else: | |
| scanner_ids[uk] = tot | |
| # ---- subnet aggregates ---- | |
| subnets = [] | |
| for sn, cnt in subnet_counts.most_common(40): | |
| members = [ip for ip in ip_counts if ip.rsplit(".", 1)[0] == sn.rsplit(".", 1)[0]] | |
| sample = max(members, key=lambda i: ip_counts[i]) if members else "" | |
| g = geo_for(sample) if sample else {} | |
| lats = [geo_for(i)["lat"] for i in members[:40] if geo_for(i)["lat"] is not None] | |
| lons = [geo_for(i)["lon"] for i in members[:40] if geo_for(i)["lon"] is not None] | |
| subnets.append({ | |
| "subnet": sn, "count": cnt, "ips": len(members), | |
| "sample_ip": sample, | |
| "lat": (sum(lats) / len(lats)) if lats else None, | |
| "lon": (sum(lons) / len(lons)) if lons else None, | |
| "country": g.get("country", ""), | |
| "country_name": g.get("country_name", ""), | |
| "city": g.get("city", ""), | |
| }) | |
| top_ips = [] | |
| for ip, cnt in ip_counts.most_common(60): | |
| g = geo_for(ip) | |
| top_ips.append({"ip": ip, "count": cnt, "country": g.get("country", ""), | |
| "country_name": g.get("country_name", ""), | |
| "city": g.get("city", ""), | |
| "lat": g.get("lat"), "lon": g.get("lon")}) | |
| out = { | |
| "generated_at": _now_iso(), | |
| "feed": "live", | |
| "geo_note": geo_note, | |
| "window": {"first": first_ts, "last": last_ts}, | |
| "sources": sources, | |
| "totals": { | |
| "sessions": n_beacon, | |
| "poison_hits": n_poison, | |
| "honeypot_sessions": n_hp, | |
| "events": n_beacon + n_poison + n_hp, | |
| "unique_ips": len(ip_counts), | |
| "unique_subnets": len(subnet_counts), | |
| "high_alerts": n_alerts, | |
| "alert_ips": len(alert_ips), | |
| "c2_urls": len(c2_urls), | |
| "scanner_ids": len(scanner_ids), | |
| "decoy_keys": len(decoy_keys), | |
| "credential_events": len(credential_rows), | |
| }, | |
| "protocols": [{"name": k, "count": v} for k, v in protocols.most_common(12)], | |
| "events": [{"name": k, "count": v} for k, v in events.most_common(12)], | |
| "tools": [{"name": k, "count": v} for k, v in tools.most_common(14)], | |
| "paths": [{"name": k, "count": v} for k, v in paths.most_common(14)], | |
| "attack_paths": [{"name": k, "count": v} for k, v in attack_paths.most_common(16)], | |
| "c2_urls": [{"url": k, "count": v, | |
| "payload_hits": url_in_payload.get(k, 0), | |
| "in_payload": url_in_payload.get(k, 0) > 0} | |
| for k, v in c2_urls.most_common(25)], | |
| "scanner_ids": [{"url": k, "count": v} for k, v in scanner_ids.most_common(20)], | |
| "timeline": [{"t": k, "count": v} for k, v in sorted(hourly.items())], | |
| "daily": [{"d": k, "count": v} for k, v in sorted(daily.items())], | |
| "top_ips": top_ips, | |
| "subnets": subnets, | |
| "recent": recent, | |
| "credentials": credential_rows[:100], | |
| "honeypot": {"rows": n_hp, "types": [{"name": k, "count": v} | |
| for k, v in honeypot_types.most_common(10)]}, | |
| "decoy_keys": sorted(decoy_keys)[:20], | |
| } | |
| os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) | |
| with open(args.out, "w", encoding="utf-8") as f: | |
| json.dump(out, f, separators=(",", ":")) | |
| print("wrote %s (%d bytes)" % (args.out, os.path.getsize(args.out))) | |
| print(" events=%d sessions=%d poison=%d honeypot=%d alerts=%d" % ( | |
| out["totals"]["events"], n_beacon, n_poison, n_hp, n_alerts)) | |
| print(" unique_ips=%d subnets=%d c2_urls=%d decoy_keys=%d credentials=%d" % ( | |
| out["totals"]["unique_ips"], out["totals"]["unique_subnets"], | |
| out["totals"]["c2_urls"], out["totals"]["decoy_keys"], len(credential_rows))) | |
| print(" window: %s -> %s" % (first_ts, last_ts)) | |
| print(" geo: %s" % geo_note) | |
| def _now_iso(): | |
| import datetime | |
| return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| if __name__ == "__main__": | |
| main() | |