TTOPM commited on
Commit
cc53748
·
verified ·
1 Parent(s): 596bf65

Create scanner/gideon_scanner.py

Browse files
belel-shield/sentinel/scanner/gideon_scanner.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ gideon_scanner.py
4
+ Belel Protocol – Citizen Counter-Surveillance Module (Next-Gen)
5
+
6
+ Monitors active connections for Gideon/Palantir-like surveillance patterns.
7
+ - Blocklist + SHA-256 verification (safe updates from repo/IPFS mirrors)
8
+ - Outbound anomaly detection (3-sigma spike rule)
9
+ - Optional local firewall DROP (Linux iptables only)
10
+ - Optional desktop notifications (plyer)
11
+
12
+ Safe by design: logs locally; never exfiltrates data.
13
+ """
14
+
15
+ import datetime
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import platform
20
+ import socket
21
+ import statistics
22
+ import subprocess
23
+ import time
24
+ import urllib.request
25
+ from pathlib import Path
26
+
27
+ import psutil # pip install psutil
28
+
29
+ # =========================
30
+ # CONFIG (tweak as needed)
31
+ # =========================
32
+ SCAN_INTERVAL = 10 # seconds between scans
33
+ ENABLE_ANOMALY_DETECTION = True
34
+ ANOMALY_WINDOW = 20 # samples kept
35
+ ANOMALY_MIN_SAMPLES = 6 # need this many before checking spikes
36
+ ANOMALY_SIGMA = 3 # 3-sigma rule
37
+
38
+ # Remote blocklist + checksum (point to your repo/mirror raw URLs)
39
+ BASE_URL = "https://raw.githubusercontent.com/TTOPM/be-core-bridge/main/belel-shield/sentinel/blocklists"
40
+ BLOCKLIST_URL = f"{BASE_URL}/belel-blocklist.json"
41
+ CHECKSUM_URL = f"{BASE_URL}/belel-blocklist.checksums.json"
42
+
43
+ AUTO_FETCH_BLOCKLIST_ON_START = True
44
+ REQUIRE_CHECKSUM_MATCH = True
45
+
46
+ # Local actions
47
+ AUTO_FIREWALL = False # set True to auto-DROP flagged IPs (Linux iptables only)
48
+ DESKTOP_NOTIFICATIONS = False # set True if you want pop-up notifications (requires 'plyer')
49
+
50
+ # =========================
51
+ # FILES / STATE
52
+ # =========================
53
+ DATA_DIR = Path.home() / ".belel"
54
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
55
+ LOG_FILE = DATA_DIR / "gideon_alerts.json"
56
+ BLOCKLIST_CACHE = DATA_DIR / "belel-blocklist.json"
57
+ CHECK_FILE = DATA_DIR / "belel-blocklist.checksums.json"
58
+
59
+ # Built-in starter fingerprints (extended by verified blocklist)
60
+ SUSPECT_IP_RANGES = [
61
+ ("104.244.42.0", "104.244.42.255"), # example
62
+ ("185.220.100.0", "185.220.100.255"), # example
63
+ ]
64
+ SUSPECT_DOMAINS = [
65
+ "gideon-surveillance.com",
66
+ "israel-trade-detect.net",
67
+ "nsa-mirror.org",
68
+ ]
69
+
70
+ _outbound_history = [] # for anomaly detection
71
+
72
+ # =========================
73
+ # UTILITIES
74
+ # =========================
75
+ def sha256_file(path: Path) -> str:
76
+ h = hashlib.sha256()
77
+ with open(path, "rb") as f:
78
+ for chunk in iter(lambda: f.read(8192), b""):
79
+ h.update(chunk)
80
+ return h.hexdigest()
81
+
82
+ def now_iso() -> str:
83
+ return datetime.datetime.utcnow().isoformat() + "Z"
84
+
85
+ def notify(title: str, message: str):
86
+ if not DESKTOP_NOTIFICATIONS:
87
+ return
88
+ try:
89
+ from plyer import notification # pip install plyer
90
+ notification.notify(title=title, message=message, timeout=5)
91
+ except Exception:
92
+ # Best-effort; remain silent if plyer or desktop env absent
93
+ pass
94
+
95
+ def log_event(event: dict):
96
+ existing = []
97
+ if LOG_FILE.exists():
98
+ try:
99
+ existing = json.loads(LOG_FILE.read_text())
100
+ except Exception:
101
+ existing = []
102
+ existing.append(event)
103
+ LOG_FILE.write_text(json.dumps(existing, indent=2))
104
+
105
+ def ip_in_range(ip: str, start: str, end: str) -> bool:
106
+ import ipaddress
107
+ ip_obj = ipaddress.ip_address(ip)
108
+ return ipaddress.ip_address(start) <= ip_obj <= ipaddress.ip_address(end)
109
+
110
+ def fetch(url: str, dest: Path) -> bool:
111
+ try:
112
+ urllib.request.urlretrieve(url, dest)
113
+ return True
114
+ except Exception as e:
115
+ print(f"[!] Fetch failed: {url} -> {e}")
116
+ return False
117
+
118
+ def verify_cached_blocklist() -> bool:
119
+ """Download checksum metadata and verify cached blocklist hash."""
120
+ if not REQUIRE_CHECKSUM_MATCH:
121
+ return BLOCKLIST_CACHE.exists()
122
+ ok_meta = fetch(CHECKSUM_URL, CHECK_FILE)
123
+ if not ok_meta:
124
+ print("[!] Could not fetch checksum metadata.")
125
+ return False
126
+ try:
127
+ meta = json.loads(CHECK_FILE.read_text())
128
+ if meta.get("algo") != "sha256" or "hash" not in meta:
129
+ print("[!] Invalid checksum file; refusing cache.")
130
+ return False
131
+ if not BLOCKLIST_CACHE.exists():
132
+ print("[i] No cached blocklist present.")
133
+ return False
134
+ local_hash = sha256_file(BLOCKLIST_CACHE)
135
+ if local_hash.lower() != meta["hash"].lower():
136
+ print("[!] Cached blocklist hash mismatch; ignoring cache.")
137
+ return False
138
+ return True
139
+ except Exception as e:
140
+ print(f"[!] Checksum verification error: {e}")
141
+ return False
142
+
143
+ def try_update_blocklist():
144
+ """Fetch latest blocklist JSON into cache (verification checked separately)."""
145
+ ok = fetch(BLOCKLIST_URL, BLOCKLIST_CACHE)
146
+ if ok:
147
+ print("[+] Downloaded blocklist to cache.")
148
+ return ok
149
+
150
+ def load_blocklist_into_memory():
151
+ try:
152
+ data = json.loads(BLOCKLIST_CACHE.read_text())
153
+ ips = data.get("ip_ranges", [])
154
+ doms = data.get("domains", [])
155
+ added_ip = 0
156
+ for rng in ips:
157
+ if isinstance(rng, (list, tuple)) and len(rng) == 2:
158
+ SUSPECT_IP_RANGES.append((rng[0], rng[1]))
159
+ added_ip += 1
160
+ for d in doms:
161
+ if isinstance(d, str):
162
+ SUSPECT_DOMAINS.append(d)
163
+ print(f"[+] Activated +{added_ip} IP ranges, +{len(doms)} domains from verified blocklist.")
164
+ except Exception as e:
165
+ print(f"[!] Failed loading blocklist cache: {e}")
166
+
167
+ def apply_firewall_block(ip: str):
168
+ """Local firewall DROP rule (Linux iptables). No-op on other OS or failure."""
169
+ if not AUTO_FIREWALL:
170
+ return
171
+ if platform.system().lower() != "linux":
172
+ return
173
+ try:
174
+ # add OUTPUT rule if not present
175
+ subprocess.run(["sudo", "iptables", "-C", "OUTPUT", "-d", ip, "-j", "DROP"],
176
+ check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
177
+ subprocess.run(["sudo", "iptables", "-A", "OUTPUT", "-d", ip, "-j", "DROP"], check=False)
178
+ # add INPUT rule if not present
179
+ subprocess.run(["sudo", "iptables", "-C", "INPUT", "-s", ip, "-j", "DROP"],
180
+ check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
181
+ subprocess.run(["sudo", "iptables", "-A", "INPUT", "-s", ip, "-j", "DROP"], check=False)
182
+ print(f"[FIREWALL] DROP {ip}")
183
+ except Exception as e:
184
+ print(f"[!] Firewall rule failed for {ip}: {e}")
185
+
186
+ # =========================
187
+ # CORE SCANNING
188
+ # =========================
189
+ def scan_connections():
190
+ """Scan active connections and flag suspicious ones."""
191
+ flagged = []
192
+ outbound_count = 0
193
+
194
+ for conn in psutil.net_connections(kind="inet"):
195
+ if not conn.raddr:
196
+ continue
197
+ ip = getattr(conn.raddr, "ip", None)
198
+ port = getattr(conn.raddr, "port", None)
199
+ if not ip:
200
+ continue
201
+ outbound_count += 1
202
+
203
+ try:
204
+ host = socket.gethostbyaddr(ip)[0]
205
+ except Exception:
206
+ host = None
207
+
208
+ # IP range check
209
+ suspicious_ip = False
210
+ for start, end in SUSPECT_IP_RANGES:
211
+ try:
212
+ if ip_in_range(ip, start, end):
213
+ flagged.append((ip, port, host, "range"))
214
+ suspicious_ip = True
215
+ break
216
+ except Exception:
217
+ pass
218
+
219
+ # Domain check
220
+ if (not suspicious_ip) and host and any(d in host for d in SUSPECT_DOMAINS):
221
+ flagged.append((ip, port, host, "domain"))
222
+
223
+ return flagged, outbound_count
224
+
225
+ def anomaly_detection(current_outbound: int):
226
+ """Simple rolling 3-sigma detection of outbound connection spikes."""
227
+ if not ENABLE_ANOMALY_DETECTION:
228
+ return False, None, None
229
+
230
+ _outbound_history.append(current_outbound)
231
+ if len(_outbound_history) > ANOMALY_WINDOW:
232
+ _outbound_history.pop(0)
233
+
234
+ if len(_outbound_history) >= ANOMALY_MIN_SAMPLES:
235
+ mean = statistics.mean(_outbound_history)
236
+ stdev = statistics.stdev(_outbound_history) if len(_outbound_history) > 1 else 0
237
+ if stdev > 0 and current_outbound > mean + ANOMALY_SIGMA * stdev:
238
+ return True, mean, stdev
239
+
240
+ return False, None, None
241
+
242
+ # =========================
243
+ # MAIN
244
+ # =========================
245
+ def main():
246
+ print("🛡️ Belel Gideon Scanner (Next-Gen) running… (Ctrl+C to stop)")
247
+
248
+ # Optional: fetch & verify blocklist at start
249
+ if AUTO_FETCH_BLOCKLIST_ON_START:
250
+ if try_update_blocklist() and verify_cached_blocklist():
251
+ load_blocklist_into_memory()
252
+ else:
253
+ print("[!] Using built-in fingerprints only (no verified blocklist).")
254
+
255
+ print(f"[i] Watching every {SCAN_INTERVAL}s | Firewall={'ON' if AUTO_FIREWALL else 'OFF'} | Notifications={'ON' if DESKTOP_NOTIFICATIONS else 'OFF'}")
256
+
257
+ while True:
258
+ flagged, outbound_count = scan_connections()
259
+
260
+ # Handle flagged connections
261
+ for ip, port, host, reason in flagged:
262
+ event = {
263
+ "timestamp": now_iso(),
264
+ "ip": ip, "port": port, "host": host,
265
+ "reason": reason,
266
+ "alert": "Potential Gideon-like surveillance detected"
267
+ }
268
+ print(f"[ALERT] {reason.upper()} → {ip}:{port} ({host})")
269
+ log_event(event)
270
+ notify("Belel Shield", f"Suspicious connection: {ip}:{port} ({host or 'unknown'})")
271
+ apply_firewall_block(ip)
272
+
273
+ # Anomaly detection
274
+ anomaly, mean, stdev = anomaly_detection(outbound_count)
275
+ if anomaly:
276
+ msg = f"Outbound spike {outbound_count} (μ={mean:.1f}, σ={stdev:.1f})"
277
+ event = {
278
+ "timestamp": now_iso(),
279
+ "outbound_count": outbound_count,
280
+ "mean": round(mean, 2) if mean is not None else None,
281
+ "stdev": round(stdev, 2) if stdev is not None else None,
282
+ "alert": "Outbound traffic anomaly detected"
283
+ }
284
+ print(f"[ANOMALY] {msg}")
285
+ log_event(event)
286
+ notify("Belel Shield", msg)
287
+
288
+ time.sleep(SCAN_INTERVAL)
289
+
290
+ if __name__ == "__main__":
291
+ try:
292
+ main()
293
+ except KeyboardInterrupt:
294
+ print("\n[i] Stopped by user.")