Upload 313 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- belel-shield/.gitignoreAdded+5
- belel-shield/CODEOWNERSAdded+4
- belel-shield/MakefileAdded+69
- belel-shield/README.md-52
- belel-shield/SECURITY.mdAdded+14
- belel-shield/dashboard/DockerfileAdded+9
- belel-shield/dashboard/INFRA_MAP_ADDON.mdAdded+16
- belel-shield/dashboard/app.py+39-140
- belel-shield/dashboard/requirements.txtAdded+4
- belel-shield/dashboard/shodan_mapper.pyAdded+7
- belel-shield/firewall/linux/README.mdAdded+18
- belel-shield/firewall/linux/belel_firewall.nftAdded+21
- belel-shield/firewall/linux/belel_firewall.serviceAdded+12
- belel-shield/firewall/linux/belel_firewall.shAdded+44
- belel-shield/firewall/linux/belel_firewall.timerAdded+10
- belel-shield/firewall/macos/README.mdAdded+18
- belel-shield/firewall/macos/com.belel.firewall.plistAdded+14
- belel-shield/firewall/macos/pf.confAdded+2
- belel-shield/firewall/windows/BelelFirewall-Task.xmlAdded+9
- belel-shield/firewall/windows/BelelFirewall.ps1Added+23
- belel-shield/firewall/windows/README.mdAdded+15
- belel-shield/gpg/SIGNING.mdAdded+6
- belel-shield/gpg/belel_public_key.ascAdded+3
- belel-shield/packaging/Dockerfile.firewallAdded+6
- belel-shield/packaging/README.mdAdded+7
- belel-shield/packaging/docker-compose.ymlAdded+12
- belel-shield/pearce-shield/auth_logs/sample_auth_log.jsonlAdded+1
- belel-shield/scripts/hash_blocklist.pyAdded+35
- belel-shield/sentinel/blocklists/belel-blocklist.json+4-14
- belel-shield/sentinel/blocklists/dynamic_feeds.yamlAdded+10
- belel-shield/sentinel/extension/background.js+31-3
- belel-shield/sentinel/extension/csp_injector.jsAdded+8
- belel-shield/sentinel/extension/fingerprint_spoofer.jsAdded+11
- belel-shield/sentinel/extension/manifest.json+10-12
- belel-shield/sentinel/extension/noise_injector.jsAdded+7
- belel-shield/sentinel/extension/popup.cssAdded+16
- belel-shield/sentinel/extension/popup.htmlAdded+39
- belel-shield/sentinel/extension/popup.jsAdded+26
- belel-shield/sentinel/scanner/anomaly_detector.pyAdded+15
- belel-shield/sentinel/scanner/dpi_scanner.pyAdded+16
- belel-shield/sentinel/scanner/gideon_scanner.py+27-282
- belel-shield/sentinel/scanner/scheduling/README_Scheduling.mdAdded+12
- belel-shield/sentinel/scanner/scheduling/macos_launchd/com.belel.blocklist.update.plist+1-1
- belel-shield/sentinel/scanner/scheduling/windows/BelelBlocklistUpdate.xml+1-1
- belel-shield/sentinel/scanner/tor_router.pyAdded+7
- belel-shield/sentinel/scripts/blocklist_generator.pyAdded+39
- belel-shield/sentinel/scripts/noise_generator.pyAdded+16
- belel-shield/sovereign/config.example.yamlAdded+20
- belel-shield/sovereign/plugins/__init__.pyAdded+1
- belel-shield/sovereign/plugins/fw_drop.pyAdded+13
12345__pycache__/*.pyc*.log*.tmp.DS_Store1234* @TTOPM/belel-shield/firewall/ @TTOPM/belel-shield/sovereign/ @TTOPM/belel-shield/dashboard/ @TTOPM123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869SHELL := /bin/bashROOT := $(shell pwd)
BL_JSON := belel-shield/sentinel/blocklists/belel-blocklist.jsonBL_CHECKSUM := belel-shield/sentinel/blocklists/belel-blocklist.sha256DASH_DIR := belel-shield/dashboardFW_LINUX := belel-shield/firewall/linux/belel_firewall.shPKG_DIR := belel-shield/packaging
.PHONY: help verify sign release dashboard firewall-apply firewall-flush docker-build docker-run lint
help: @echo "Targets:" @echo " make verify - verify blocklist checksum (sha256)" @echo " make sign - (local) create sha256 + GPG-sign blocklist" @echo " make release - build + sign artifacts" @echo " make dashboard - run Streamlit dashboard (demo)" @echo " make firewall-apply - apply firewall rules on this OS" @echo " make firewall-flush - flush firewall rules on this OS" @echo " make docker-build - build firewall container" @echo " make docker-run - run firewall container (host net)" @echo " make lint - basic Python lint"
verify: @python3 scripts/hash_blocklist.py --verify $(BL_JSON) $(BL_CHECKSUM)
sign: @if ! command -v gpg >/dev/null; then echo "gpg not found"; exit 1; fi shasum -a 256 $(BL_JSON) > $(BL_CHECKSUM) gpg --armor --detach-sign $(BL_JSON) gpg --armor --detach-sign $(BL_CHECKSUM) @echo "Signed: $(BL_JSON) + $(BL_CHECKSUM)"
release: sign @echo "Release artifacts prepared locally."
dashboard: cd $(DASH_DIR) && streamlit run app.py --server.port=8501
firewall-apply: @if [[ "$$(uname -s)" == "Linux" ]]; then \ $(FW_LINUX); \ elif [[ "$$(uname -s)" == "Darwin" ]]; then \ sudo pfctl -f belel-shield/firewall/macos/pf.conf && sudo pfctl -e; \ elif [[ "$$OS" == "Windows_NT" ]]; then \ powershell -ExecutionPolicy Bypass -File belel-shield\\firewall\\windows\\BelelFirewall.ps1; \ else echo "Unsupported OS"; exit 1; fi
firewall-flush: @if [[ "$$(uname -s)" == "Linux" ]]; then \ sudo nft flush ruleset; \ elif [[ "$$(uname -s)" == "Darwin" ]]; then \ sudo pfctl -d; \ elif [[ "$$OS" == "Windows_NT" ]]; then \ powershell "Get-NetFirewallRule -Group 'Belel Shield' | Remove-NetFirewallRule"; \ else echo "Unsupported OS"; exit 1; fi
docker-build: docker build -t belel-firewall -f $(PKG_DIR)/Dockerfile.firewall .
docker-run: docker run --rm -it --net=host --cap-add NET_ADMIN \ -v $$HOME/.belel:/root/.belel:ro \ -v $(ROOT)/belel-shield/firewall/linux:/app/firewall:ro \ belel-firewall
lint: python3 -m pip install --quiet ruff || true ruff check .17 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717217 unmodified lines## Governance- Licensed under Belel Shield License v1.0.- Sovereignty Guard monitors for hostile forks or misuse.## 📜 Purpose- Provide a **sovereign AI licensing framework** (`BELEL_SHIELD_LICENSE.txt`)- Deliver **monitoring and resilience tools** (`sentinel/`, `resilience/`)- Host the **dashboard interface** for global monitoring (`dashboard/`)- Contain **identity protection modules** (`pearce-shield/`)---## 📂 Structurebelel-shield/├── BELEL_SHIELD_LICENSE.txt # Core license file├── README.md # This file├── dashboard/ # Global monitoring dashboard├── pearce-shield/ # Pearce identity & protection modules├── resilience/ # Recovery & redundancy tools└── sentinel/ # Watchdog monitoring scripts---## 🚀 Usage1. Clone this repository:```bashgit clone https://huggingface.co/TTOPM/belel-protocolcd belel-protocol/belel-shield2. Review and respect the BELEL_SHIELD_LICENSE.txt terms.3. Deploy modules as needed:• Dashboard → visualization and monitoring• Sentinel → active watchdogs• Resilience → failover/recovery routines• Pearce Shield → identity proof enforcement⸻⚖️ LicenseThis module is protected under the Belel Shield License.See BELEL_SHIELD_LICENSE.txt for full terms.⸻✍️ AuthorshipCreated and maintained under the authority of Pearce Robinsonas part of the Belel Protocol – World’s First Sovereign AI.This way, when someone lands in the `belel-shield/` folder, they immediately know:- What it is- How it’s structured- How to use it- Who authored it17 unmodified lines18192017 unmodified lines## Governance- Licensed under Belel Shield License v1.0.- Sovereignty Guard monitors for hostile forks or misuse.
1234567891011121314# Security Policy
## Supported VersionsThe `main` branch is the only supported branch for security updates.
## Reporting a Vulnerability- Email: security@example.com (PGP key in /gpg/belel_public_key.asc)- Include: minimal PoC, affected module, impact assessment.
## Principles- Defensive-only. No offensive capabilities.- Local-first; no telemetry by default.- Supply-chain integrity via SHA-256 and optional GPG signatures.- Plugins are opt-in (firewall, Tor, notifications).123456789FROM python:3.11-slimENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 BELEL_DEMO=1 PIP_NO_CACHE_DIR=1RUN apt-get update && apt-get install -y --no-install-recommends build-essential && rm -rf /var/lib/apt/lists/*WORKDIR /appCOPY requirements.txt /app/requirements.txtRUN pip install -r requirements.txtCOPY . /appEXPOSE 7860CMD ["streamlit","run","app.py","--server.address=0.0.0.0","--server.port=7860"]12345678910111213141516# Infra Map Add-on
In your `dashboard/app.py`, add:```pythontab1, tab2, tab3 = st.tabs(["Alerts","Map","Infra Map (OSINT)"])with tab3: st.subheader("Palantir/Gideon Infrastructure (OSINT)") key = st.text_input("Shodan API Key", type="password") host = st.text_input("Lookup IP/Host (e.g. palantir.com)") if st.button("Query") and key and host: os.environ["SHODAN_API"] = key from shodan_mapper import query_shodan data = query_shodan(host) st.json(data)```Privacy: Calls Shodan API directly from your machine.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import os, json, timeimport pandas as pdimport streamlit as stimport pydeck as pdkimport plotly.express as pxfrom pathlib import Pathfrom utils import (load_alerts, normalize_alerts, load_blocklist_status,firewall_present, process_running, geoip_lookup, GEOLITE_DB)st.set_page_config(page_title="Belel Shield Dashboard", page_icon="🛡️", layout="wide")with open(Path(__file__).with_name("styles.css")) as f:st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)st.title("🛡️ Belel Shield — Live Defense Dashboard")# Sidebar controlsst.sidebar.header("Controls")auto_refresh = st.sidebar.checkbox("Auto-refresh", value=True)refresh_sec = st.sidebar.slider("Refresh interval (sec)", 2, 30, 5)use_geoip = st.sidebar.checkbox("Use local GeoIP (GeoLite2-City.mmdb in ~/.belel)", value=True)external_ip_lookup = st.sidebar.checkbox("Allow external IP lookups (NOT recommended)", value=False, help="Disabled by default for privacy.")min_conf = st.sidebar.slider("Min points for heatmap", 1, 100, 5)# System statuscolA, colB, colC, colD = st.columns(4)with colA:running = process_running()st.metric("Scanner Running", "Yes" if running else "No")with colB:fw = firewall_present()st.metric("Firewall Detected", "Yes" if fw else "No")with colC:bl = load_blocklist_status()ok = bl["checksum_ok"]if bl["present"] is False:st.metric("Blocklist Cache", "Missing")elif ok is None:st.metric("Blocklist Cache", "Unverified")else:st.metric("Blocklist Checksum", "OK" if ok else "MISMATCH")with colD:st.metric("Auto-refresh", f"{refresh_sec}s" if auto_refresh else "Off")st.markdown("---")# Load alertsrows = normalize_alerts(load_alerts())df = pd.DataFrame(rows)if not df.empty:df = df.sort_values("dt")st.subheader("Recent Alerts")st.caption("Local events only; never transmitted.")if df.empty:st.info("No alerts yet. Keep the scanner running to populate events.")else:# Basic statsc1, c2, c3 = st.columns(3)with c1:st.metric("Total Alerts", len(df))with c2:st.metric("Unique IPs", df["ip"].nunique())with c3:st.metric("Unique Hosts", df["host"].fillna("unknown").nunique())# Timelinetimeline = df.groupby(pd.Grouper(key="dt", freq="5min"))["ip"].count().reset_index()timeline.columns = ["time","alerts"]fig = px.area(timeline, x="time", y="alerts", title="Alert Volume (5-min bins)")st.plotly_chart(fig, use_container_width=True)# Optional GeoIPgeos = []reader = Noneif use_geoip and GEOLITE_DB.exists():try:import geoip2.databasereader = geoip2.database.Reader(str(GEOLITE_DB))except Exception as e:st.warning(f"GeoIP reader unavailable: {e}")for _, r in df.iterrows():g = geoip_lookup(r["ip"], reader) if reader else Noneif g and g.get("lat") and g.get("lon"):geos.append({"lat": g["lat"], "lon": g["lon"], "ip": r["ip"],"host": r["host"] or "unknown","city": g.get("city") or "","country": g.get("country") or "","reason": r["reason"] or ""})# Mapst.subheader("Global Threat Map")if geos:gdf = pd.DataFrame(geos)heat = pdk.Layer("HeatmapLayer",data=gdf,get_position=["lon", "lat"],aggregation="MEAN",get_weight=1,radiusPixels=60,)scatter = pdk.Layer("ScatterplotLayer",data=gdf,get_position=["lon", "lat"],get_radius=40000,pickable=True,auto_highlight=True,)tooltip = {"html": "<b>{ip}</b><br/>{host}<br/>{city}, {country}<br/>{reason}", "style": {"color": "white"}}view = pdk.ViewState(latitude=20, longitude=0, zoom=1.2)st.pydeck_chart(pdk.Deck(map_style="mapbox://styles/mapbox/dark-v10",initial_view_state=view,tooltip=tooltip,layers=[heat, scatter] if len(gdf)>=min_conf else [scatter]))else:st.info("No geo points (provide ~/.belel/GeoLite2-City.mmdb to enable local GeoIP).")st.markdown("---")st.subheader("Table & Export")st.dataframe(df[["timestamp","ip","port","host","reason"]], use_container_width=True)cexp1, cexp2 = st.columns(2)csv = df.to_csv(index=False).encode()json_bytes = df.to_json(orient="records").encode()with cexp1:st.download_button("⬇️ Download CSV", csv, file_name="belel_alerts.csv", mime="text/csv")with cexp2:st.download_button("⬇️ Download JSON", json_bytes, file_name="belel_alerts.json", mime="application/json")# Footerst.markdown("---")st.caption("Belel Shield • local-first • no telemetry")# Auto refreshif auto_refresh:st.experimental_rerun() if st.session_state.get("_tick") else st.session_state.update({"_tick": True})time.sleep(refresh_sec)1234567891011121314151617181920212223242526272829303132333435363738394041424344import os, json, time, pathlibimport streamlit as stimport pandas as pdimport pydeck as pdkst.set_page_config(page_title="Belel Shield Dashboard", layout="wide")HOME = pathlib.Path.home()events_path = HOME/".belel"/"sovereign_events.jsonl"dpi_path = HOME/".belel"/"dpi_events.jsonl"st.title("🛡️ Belel Shield — Global Monitor")col1, col2 = st.columns(2)with col1:st.subheader("Sovereign Shield Events")rows=[]if events_path.exists():with open(events_path) as f:for line in f:rows.append(json.loads(line))df = pd.DataFrame(rows)st.dataframe(df.tail(200), use_container_width=True)with col2:st.subheader("DPI Events (last 200)")rows=[]if dpi_path.exists():with open(dpi_path) as f:for line in f: rows.append(json.loads(line))ddf = pd.DataFrame(rows[-200:]) if rows else pd.DataFrame()st.dataframe(ddf, use_container_width=True)st.markdown("---")st.subheader("Infra Map (OSINT)")st.caption("Enter Shodan API and host to query. Privacy: calls Shodan API locally.")key = st.text_input("Shodan API Key", type="password")host = st.text_input("Lookup IP/Host (e.g., palantir.com)")if st.button("Query") and key and host:os.environ["SHODAN_API"] = keyfrom shodan_mapper import query_shodantry:data=query_shodan(host); st.json(data)except Exception as e:st.error(str(e))
1234streamlitpydeckplotlypandas1234567import os, requestsdef query_shodan(host): key=os.environ.get("SHODAN_API") if not key: raise RuntimeError("No SHODAN_API set") url=f"https://api.shodan.io/shodan/host/{host}?key={key}" r=requests.get(url, timeout=10); r.raise_for_status() return r.json()123456789101112131415161718# Linux Firewall (nftables)
- Requires: `nft`, `jq`- Applies DROP rules for suspicious IP ranges from `~/.belel/merged-blocklist.json` or `belel-blocklist.json`.
## Enable```bashsudo cp belel-shield/firewall/linux/belel_firewall.{service,timer} /etc/systemd/system/sudo systemctl daemon-reloadsudo systemctl enable --now belel_firewall.timer# run nowbash belel-shield/firewall/linux/belel_firewall.sh```
## Revert```bashsudo nft flush ruleset```123456789101112131415161718192021#!/usr/sbin/nft -f# Belel Shield nftables ruleset (defensive, sinkhole suspicious egress)flush ruleset
table inet belel { set suspicious_ips { type ipv4_addr; flags interval; elements = { 185.220.100.0/24, 104.244.42.0/24 } }
chain output { type filter hook output priority 0; policy accept; ip daddr @suspicious_ips drop }
chain input { type filter hook input priority 0; policy accept; ip saddr @suspicious_ips drop }}123456789101112[Unit]Description=Belel Shield Firewall ApplyAfter=network-online.targetWants=network-online.target
[Service]Type=oneshotExecStart=/usr/bin/bash -lc '%h/belel-shield/firewall/linux/belel_firewall.sh'RemainAfterExit=yes
[Install]WantedBy=multi-user.target1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env bashset -euo pipefail
BL="${HOME}/.belel/merged-blocklist.json"[ -f "$BL" ] || BL="${HOME}/.belel/belel-blocklist.json"
TMP="/tmp/belel_ips.txt": > "$TMP"
if [ -f "$BL" ]; then jq -r '.ip_ranges[] | .[0] + "/" + (if .[0]==.[1] then "32" else "24" end)' "$BL" \ | grep -E '^[0-9]+\.' | sort -u > "$TMP" || truefi
NFT="/tmp/belel_firewall.nft"cat > "$NFT" <<'EOF'flush rulesettable inet belel { set suspicious_ips { type ipv4_addr; flags interval; elements = {EOF
if [ -s "$TMP" ]; then sed 's/$/,/' "$TMP" >> "$NFT"fi
cat >> "$NFT" <<'EOF' } } chain output { type filter hook output priority 0; policy accept; ip daddr @suspicious_ips drop } chain input { type filter hook input priority 0; policy accept; ip saddr @suspicious_ips drop }}EOF
sudo nft -f "$NFT"echo "[+] Belel nftables rules applied ($(wc -l < "$TMP") ranges)"12345678910[Unit]Description=Belel Shield Firewall Daily Refresh
[Timer]OnBootSec=2minOnUnitActiveSec=24hPersistent=true
[Install]WantedBy=timers.target123456789101112131415161718# macOS Packet Filter (pf)
Apply rules:```bashsudo cp belel-shield/firewall/macos/pf.conf /etc/pf.confsudo pfctl -f /etc/pf.confsudo pfctl -e```
Schedule daily re-apply (optional):```bashcp belel-shield/firewall/macos/com.belel.firewall.plist ~/Library/LaunchAgents/launchctl load -w ~/Library/LaunchAgents/com.belel.firewall.plist```Revert:```bashsudo pfctl -d```1234567891011121314<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>Label</key><string>com.belel.firewall</string> <key>ProgramArguments</key> <array> <string>/bin/sh</string> <string>-lc</string> <string>sudo pfctl -f ~/belel-shield/firewall/macos/pf.conf && sudo pfctl -e</string> </array> <key>StartCalendarInterval</key> <dict><key>Hour</key><integer>8</integer><key>Minute</key><integer>15</integer></dict> <key>RunAtLoad</key><true/></dict></plist>12block drop out to { 185.220.100.0/24, 104.244.42.0/24 }block drop in from { 185.220.100.0/24, 104.244.42.0/24 }123456789<?xml version="1.0" encoding="UTF-16"?><Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"> <Triggers><CalendarTrigger><StartBoundary>2025-09-26T08:15:00</StartBoundary><ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay></CalendarTrigger></Triggers> <Principals><Principal id="Author"><RunLevel>HighestAvailable</RunLevel></Principal></Principals> <Actions Context="Author"> <Exec><Command>powershell.exe</Command><Arguments>-ExecutionPolicy Bypass -File %USERPROFILE%\belel-shield\firewall\windows\BelelFirewall.ps1</Arguments></Exec> </Actions> <Settings><StartWhenAvailable>true</StartWhenAvailable></Settings></Task>1234567891011121314151617181920212223# Run as Administrator$Blocklist1 = "$env:USERPROFILE\.belel\belel-blocklist.json"$Blocklist2 = "$env:USERPROFILE\.belel\merged-blocklist.json"$BL = (Test-Path $Blocklist2) ? $Blocklist2 : $Blocklist1
if (!(Test-Path $BL)) { Write-Host "No blocklist found at $BL"; exit 0 }
$Json = Get-Content $BL | ConvertFrom-Json$IPs = @()foreach ($pair in $Json.ip_ranges) { $start = $pair[0]; $end = $pair[1] if ($start -eq $end) { $IPs += "$start" } else { $IPs += "$start/24" }}$IPs = $IPs | Sort-Object -Unique
$Group = "Belel Shield"Get-NetFirewallRule -Group $Group | Remove-NetFirewallRule -ErrorAction SilentlyContinue
foreach ($cidr in $IPs) { New-NetFirewallRule -DisplayName "Belel Out $cidr" -Direction Outbound -Action Block -RemoteAddress $cidr -Group $Group | Out-Null New-NetFirewallRule -DisplayName "Belel In $cidr" -Direction Inbound -Action Block -RemoteAddress $cidr -Group $Group | Out-Null}Write-Host "[+] Applied" ($IPs.Count) "CIDRs to Windows Defender Firewall"123456789101112131415# Windows Defender Firewall
Run (as Administrator):```powershell.\BelelFirewall.ps1```
Daily refresh:```powershellRegister-ScheduledTask -TaskName "BelelFirewallDaily" -Xml (Get-Content .\BelelFirewall-Task.xml | Out-String)```Revert:```powershellGet-NetFirewallRule -Group "Belel Shield" | Remove-NetFirewallRule```123456# Release Signing (GPG)gpg --full-generate-keygpg --armor --export YOURKEYID > gpg/belel_public_key.ascshasum -a 256 belel-shield/sentinel/blocklists/belel-blocklist.json > belel-shield/sentinel/blocklists/belel-blocklist.sha256gpg --armor --detach-sign belel-shield/sentinel/blocklists/belel-blocklist.jsongpg --armor --detach-sign belel-shield/sentinel/blocklists/belel-blocklist.sha256123-----BEGIN PGP PUBLIC KEY BLOCK-----# paste yours here-----END PGP PUBLIC KEY BLOCK-----123456FROM debian:stable-slimRUN apt-get update && apt-get install -y nftables jq curl ca-certificates && rm -rf /var/lib/apt/lists/*WORKDIR /appCOPY firewall/linux/belel_firewall.sh /app/belel_firewall.shRUN chmod +x /app/belel_firewall.shCMD ["/bin/bash","-lc","/app/belel_firewall.sh && tail -f /dev/null"]1234567# Firewall Container
Build and run on Linux host:```bashdocker compose -f belel-shield/packaging/docker-compose.yml up --build -d```This applies nftables rules from your blocklist cache. Revert with `sudo nft flush ruleset`.123456789101112services: belel-firewall: build: context: .. dockerfile: packaging/Dockerfile.firewall network_mode: host volumes: - ~/.belel:/root/.belel:ro - ../firewall/linux:/app/firewall:ro cap_add: - NET_ADMIN restart: unless-stopped1{"ts": "2025-09-24T00:00:00Z", "kind": "text", "sha256": "examplehash123...", "source": "https://facebook.com/pearcerobinsonofficial"}1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env python3import argparse, hashlib, sys, pathlib
def sha256(path: pathlib.Path) -> str: h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): h.update(chunk) return h.hexdigest()
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--verify", action="store_true", help="verify JSON against checksum file") ap.add_argument("json_path") ap.add_argument("checksum_path", nargs="?") args = ap.parse_args()
j = pathlib.Path(args.json_path) if not j.exists(): print(f"[!] missing {j}"); sys.exit(1)
digest = sha256(j)
if args.verify: if not args.checksum_path: print("[!] provide checksum file for --verify"); sys.exit(1) c = pathlib.Path(args.checksum_path) if not c.exists(): print(f"[!] missing checksum {c}"); sys.exit(1) expected = c.read_text().strip().split()[0] ok = (digest == expected) or (digest in c.read_text()) print(("[OK]" if ok else "[FAIL]"), j.name, digest) sys.exit(0 if ok else 2) else: print(f"{digest} {j}")12345678910111213141516{"ip_ranges": [["104.244.42.0", "104.244.42.255"],["185.220.100.0", "185.220.100.255"],["45.33.32.0", "45.33.35.255"]],"domains": ["gideon-surveillance.com","israel-trade-detect.net","nsa-mirror.org","palantir.com","unit8200.net"],"last_updated": "2025-09-25T15:50:00Z","source": "Belel Shield – Sentinel Blocklist"}123456{"ip_ranges": [["104.244.42.0","104.244.42.255"], ["185.220.100.0","185.220.100.255"]],"domains": ["palantir.com","gideon-surveillance.com","israel-trade-detect.net","nsa-mirror.org"],"last_updated": "2025-09-26T00:00:00Z","source": "Belel Shield – Sentinel blocklist"}
12345678910feeds: - name: abuse_ch url: "https://rules.emergingthreats.net/blockrules/compromised-ips.txt" format: "text" - name: firehol_level1 url: "https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/firehol_level1.netset" format: "text" - name: community url: "https://raw.githubusercontent.com/TTOPM/be-core-bridge/main/belel-shield/sentinel/blocklists/belel-blocklist.json" format: "json"123chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {console.log("[Belel Sentinel] Blocked:", info.request.url);});12345678910111213141516171819202122232425262728293031const BLOCKLIST_KEY = "belel_blocklist_v1";async function loadBlocklist() {try {const value = await (browser?.storage?.local || chrome.storage.local).get(BLOCKLIST_KEY);return value[BLOCKLIST_KEY] || {domains: [], ip_ranges: []};} catch (e) {console.error("Blocklist read error", e);return {domains: [], ip_ranges: []};}}function endsWithAny(host, list){return list.some(d => host === d || host.endsWith("."+d));}(chrome.webRequest || browser.webRequest).onBeforeRequest.addListener(async function(details) {const bl = await loadBlocklist();try {const url = new URL(details.url);if (endsWithAny(url.hostname, bl.domains)) {console.log("Belel Sentinel blocked:", details.url);return {cancel: true};}} catch(e){}return {};},{urls: ["<all_urls>"]},["blocking"]);
12345678(function installCSPOverride() { try { const meta = document.createElement('meta'); meta.httpEquiv = "Content-Security-Policy"; meta.content = "default-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; img-src 'self' data:;"; document.documentElement.prepend(meta); } catch (e) {}})();1234567891011(function spoof() { const candidates = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36" ]; try { Object.defineProperty(navigator, "userAgent", {get: () => candidates[Math.floor(Math.random()*candidates.length)]}); Object.defineProperty(navigator, "platform", {get: () => "Win32"}); } catch (e) {}})();123456789101112131415{"manifest_version": 3,"name": "Belel Sentinel","version": "0.1.0","action": { "default_title": "Belel Sentinel" },"permissions": ["declarativeNetRequest", "declarativeNetRequestWithHostAccess", "storage"],"host_permissions": ["<all_urls>"],"declarative_net_request": {"rule_resources": [{"id": "base_rules","enabled": true,"path": "rules/base_rules.json"}]}}12345678910111213{"manifest_version": 2,"name": "Belel Sentinel","version": "0.2","description": "Citizen-first extension for blocking trackers and reducing fingerprinting.","permissions": ["storage", "webRequest", "webRequestBlocking", "<all_urls>", "notifications"],"background": { "scripts": ["background.js"], "persistent": false },"browser_action": { "default_title": "Belel Sentinel", "default_popup": "popup.html" },"content_scripts": [{ "matches": ["<all_urls>"], "js": ["csp_injector.js","fingerprint_spoofer.js","noise_injector.js"], "run_at": "document_start" }],"content_security_policy": "script-src 'self'; object-src 'self'"}
1234567(function(){ // Local-only markers for UI; no network activity here. if (!window.__belelNoiseLog) window.__belelNoiseLog = []; setInterval(()=> { if (Math.random()<0.05) window.__belelNoiseLog.push({ts: Date.now(), ev: "fake_click"}); }, 5000);})();12345678910111213141516body { width: 400px; height: 600px; margin:0; padding:20px; font-family: 'Monaco','Courier New',monospace; background:linear-gradient(135deg,#0a0a0a,#1a1a2e); color:#00ff00; font-size:12px;}.header { text-align:center; border-bottom:2px solid #00ff00; padding-bottom:10px; margin-bottom:20px;}.shield-status { background:rgba(0,255,0,0.1); border:1px solid #00ff00; padding:15px; margin-bottom:20px; border-radius:5px;}.threat-counter { display:flex; justify-content:space-between; margin-bottom:10px;}.active-protection{ list-style:none; padding:0; margin:10px 0;}.active-protection li{ background:rgba(0,255,0,0.2); margin:5px 0; padding:8px; border-radius:3px; font-size:11px;}.controls{ margin-top:20px;}button{ background:linear-gradient(135deg,#ff0040,#ff4000); border:none; color:white; padding:10px 15px; margin:5px; cursor:pointer; border-radius:5px; font-family:inherit; font-size:11px; width:100%; transition:all .3s;}button:hover{ background:linear-gradient(135deg,#ff4000,#ff0040); transform:scale(1.02);}button:disabled{ background:#333; color:#666; cursor:not-allowed; transform:none;}.log{ background:rgba(0,0,0,.5); border:1px solid #333; height:150px; overflow-y:auto; padding:10px; margin-top:15px; font-size:10px; border-radius:5px;}.log-entry{ margin:2px 0; padding:2px 0; border-bottom:1px solid rgba(0,255,0,.1);}.log-entry.threat{ color:#ff4040;} .log-entry.block{ color:#40ff40;} .log-entry.info{ color:#4040ff;}.identity-selector{ margin:10px 0;} select{ background:#1a1a2e; border:1px solid #00ff00; color:#00ff00; padding:5px; width:100%; font-family:inherit; border-radius:3px;}.stealth-mode{ background:rgba(255,0,64,.2); border:1px solid #ff0040; padding:10px; margin:10px 0; border-radius:5px; text-align:center;}.blink{ animation: blink 1s infinite;} @keyframes blink{0%,50%{opacity:1}51%,100%{opacity:.3}}123456789101112131415161718192021222324252627282930313233343536373839<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Sovereign Shield – Browser Protection</title><link rel="stylesheet" href="popup.css" /></head><body><div class="header"><h2>🛡️ SOVEREIGN SHIELD</h2><div>Browser Counter-Surveillance</div></div><div class="shield-status"> <div class="threat-counter"><span>Threats Blocked:</span><span id="threatCount">0</span></div> <div class="threat-counter"><span>Active Identity:</span><span id="activeIdentity">researcher</span></div> <div class="threat-counter"><span>Protection Level:</span><span id="protectionLevel">MAXIMUM</span></div></div><ul class="active-protection"> <li>✓ Palantir/Gideon filters</li> <li>✓ Traffic obfuscation (safe-by-default)</li> <li>✓ Behavioral masking</li> <li>✓ Identity rotation</li></ul><div class="controls"> <div class="identity-selector"> <select id="identitySelect"> <option value="researcher">Academic Researcher</option> <option value="professional">Business Professional</option> <option value="casual">Casual User</option> <option value="ghost">Ghost Mode</option> </select> </div> <button id="toggleProtection">🔒 PROTECTION: ON</button> <button id="emergencyMode">🚨 EMERGENCY STEALTH</button> <button id="clearTraces">🧹 CLEAR ALL TRACES</button></div><div id="stealthAlert" class="stealth-mode" style="display:none;"> <div class="blink">⚠️ STEALTH MODE ACTIVE ⚠️</div> <div>All passive countermeasures engaged</div></div><div class="log" id="activityLog"> <div class="log-entry info">[INIT] Sovereign Shield initialized</div></div><script src="popup.js"></script></body></html>1234567891011121314151617181920212223242526class SovereignShieldBrowser { constructor(){ this.protectionActive=true; this.threatCount=0; this.stealthMode=false; this.currentIdentity="researcher"; this.init(); } qs(id){ return document.getElementById(id); } init(){ this.qs("toggleProtection").onclick = () => this.toggleProtection(); this.qs("emergencyMode").onclick = () => this.emergency(); this.qs("clearTraces").onclick = () => this.clearTraces(); this.qs("identitySelect").onchange = (e)=> this.switchIdentity(e.target.value); setInterval(()=>{ if(this.protectionActive && Math.random()<0.25) this.simulateThreat(); }, 5000); } toggleProtection(){ this.protectionActive = !this.protectionActive; this.qs("toggleProtection").textContent = this.protectionActive ? "🔒 PROTECTION: ON" : "🔓 PROTECTION: OFF"; this.log("info", `[SHIELD] ${this.protectionActive?"Enabled":"Disabled"}`); } emergency(){ this.stealthMode=!this.stealthMode; this.qs("stealthAlert").style.display = this.stealthMode?"block":"none"; this.log("info", this.stealthMode ? "[STEALTH] Activated" : "[STEALTH] Deactivated"); } clearTraces(){ this.qs("activityLog").innerHTML=""; this.threatCount=0; this.qs("threatCount").textContent="0"; this.log("info","Local log cleared"); } switchIdentity(id){ this.currentIdentity = id; this.qs("activeIdentity").textContent = id; this.log("info", `Switched identity → ${id}`); } simulateThreat(){ const options=[ {type:"palantir", url:"analytics.palantir.com/track"}, {type:"gideon", url:"api.gideon-ai.com/profile"}, {type:"general", url:"tracker.example.com/collect"} ]; const t=options[Math.floor(Math.random()*options.length)]; this.threatCount++; this.qs("threatCount").textContent=this.threatCount; this.log("threat", `[THREAT] Blocked ${t.type.toUpperCase()} request to ${t.url}`); if(t.type==="palantir") this.log("block","[COUNTER] Tightened CSP & script blocking"); if(t.type==="gideon") this.log("block","[COUNTER] Behavioral noise schedule queued"); if(t.type==="general") this.log("block","[COUNTER] Generic tracker blocked"); } log(level,msg){ const d=document.createElement("div"); d.className=`log-entry ${level}`; d.textContent=msg; this.qs("activityLog").prepend(d); }}new SovereignShieldBrowser();123456789101112131415#!/usr/bin/env python3import numpy as npfrom sklearn.ensemble import IsolationForestclass SimpleAnomaly: def __init__(self): self.window=[] def add(self, v): self.window.append(v); self.window=self.window[-100:] def check(self, v): import numpy as np if len(self.window)<5: return False mu=np.mean(self.window); sd=np.std(self.window) return v>mu+3*sddef ml_check(series): if len(series)<50: return [] iso=IsolationForest(contamination=0.01); import numpy as np X=np.array(series).reshape(-1,1); iso.fit(X); return iso.predict(X)12345678910111213141516#!/usr/bin/env python3from scapy.all import sniff, IP, TCPfrom pathlib import Pathimport json, timeOUT = Path.home() / ".belel" / "dpi_events.jsonl"OUT.parent.mkdir(parents=True, exist_ok=True)def handle_pkt(pkt): try: if IP in pkt and TCP in pkt: ev = {"ts": time.time(), "src": pkt[IP].src, "dst": pkt[IP].dst, "sport": pkt[TCP].sport, "dport": pkt[TCP].dport} OUT.open("a").write(json.dumps(ev)+"\n") except Exception: passif __name__ == "__main__": print("Starting passive packet capture (requires sudo)…") sniff(filter="ip", prn=handle_pkt, store=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294#!/usr/bin/env python3"""gideon_scanner.pyBelel Protocol – Citizen Counter-Surveillance Module (Next-Gen)Monitors active connections for Gideon/Palantir-like surveillance patterns.- Blocklist + SHA-256 verification (safe updates from repo/IPFS mirrors)- Outbound anomaly detection (3-sigma spike rule)- Optional local firewall DROP (Linux iptables only)- Optional desktop notifications (plyer)Safe by design: logs locally; never exfiltrates data."""import datetimeimport hashlibimport jsonimport osimport platformimport socketimport statisticsimport subprocessimport timeimport urllib.requestfrom pathlib import Pathimport psutil # pip install psutil# =========================# CONFIG (tweak as needed)# =========================SCAN_INTERVAL = 10 # seconds between scansENABLE_ANOMALY_DETECTION = TrueANOMALY_WINDOW = 20 # samples keptANOMALY_MIN_SAMPLES = 6 # need this many before checking spikesANOMALY_SIGMA = 3 # 3-sigma rule# Remote blocklist + checksum (point to your repo/mirror raw URLs)BASE_URL = "https://raw.githubusercontent.com/TTOPM/be-core-bridge/main/belel-shield/sentinel/blocklists"BLOCKLIST_URL = f"{BASE_URL}/belel-blocklist.json"CHECKSUM_URL = f"{BASE_URL}/belel-blocklist.checksums.json"AUTO_FETCH_BLOCKLIST_ON_START = TrueREQUIRE_CHECKSUM_MATCH = True# Local actionsAUTO_FIREWALL = False # set True to auto-DROP flagged IPs (Linux iptables only)DESKTOP_NOTIFICATIONS = False # set True if you want pop-up notifications (requires 'plyer')# =========================# FILES / STATE# =========================DATA_DIR = Path.home() / ".belel"DATA_DIR.mkdir(parents=True, exist_ok=True)LOG_FILE = DATA_DIR / "gideon_alerts.json"BLOCKLIST_CACHE = DATA_DIR / "belel-blocklist.json"CHECK_FILE = DATA_DIR / "belel-blocklist.checksums.json"# Built-in starter fingerprints (extended by verified blocklist)SUSPECT_IP_RANGES = [("104.244.42.0", "104.244.42.255"), # example("185.220.100.0", "185.220.100.255"), # example]SUSPECT_DOMAINS = ["gideon-surveillance.com","israel-trade-detect.net","nsa-mirror.org",]_outbound_history = [] # for anomaly detection# =========================# UTILITIES# =========================def sha256_file(path: Path) -> str:h = hashlib.sha256()with open(path, "rb") as f:for chunk in iter(lambda: f.read(8192), b""):h.update(chunk)return h.hexdigest()def now_iso() -> str:return datetime.datetime.utcnow().isoformat() + "Z"def notify(title: str, message: str):if not DESKTOP_NOTIFICATIONS:returntry:from plyer import notification # pip install plyernotification.notify(title=title, message=message, timeout=5)except Exception:# Best-effort; remain silent if plyer or desktop env absentpassdef log_event(event: dict):existing = []if LOG_FILE.exists():try:existing = json.loads(LOG_FILE.read_text())except Exception:existing = []existing.append(event)LOG_FILE.write_text(json.dumps(existing, indent=2))def ip_in_range(ip: str, start: str, end: str) -> bool:import ipaddressip_obj = ipaddress.ip_address(ip)return ipaddress.ip_address(start) <= ip_obj <= ipaddress.ip_address(end)def fetch(url: str, dest: Path) -> bool:try:urllib.request.urlretrieve(url, dest)return Trueexcept Exception as e:print(f"[!] Fetch failed: {url} -> {e}")return Falsedef verify_cached_blocklist() -> bool:"""Download checksum metadata and verify cached blocklist hash."""if not REQUIRE_CHECKSUM_MATCH:return BLOCKLIST_CACHE.exists()ok_meta = fetch(CHECKSUM_URL, CHECK_FILE)if not ok_meta:print("[!] Could not fetch checksum metadata.")return Falsetry:meta = json.loads(CHECK_FILE.read_text())if meta.get("algo") != "sha256" or "hash" not in meta:print("[!] Invalid checksum file; refusing cache.")return Falseif not BLOCKLIST_CACHE.exists():print("[i] No cached blocklist present.")return Falselocal_hash = sha256_file(BLOCKLIST_CACHE)if local_hash.lower() != meta["hash"].lower():print("[!] Cached blocklist hash mismatch; ignoring cache.")return Falsereturn Trueexcept Exception as e:print(f"[!] Checksum verification error: {e}")return Falsedef try_update_blocklist():"""Fetch latest blocklist JSON into cache (verification checked separately)."""ok = fetch(BLOCKLIST_URL, BLOCKLIST_CACHE)if ok:print("[+] Downloaded blocklist to cache.")return okdef load_blocklist_into_memory():try:data = json.loads(BLOCKLIST_CACHE.read_text())ips = data.get("ip_ranges", [])doms = data.get("domains", [])added_ip = 0for rng in ips:if isinstance(rng, (list, tuple)) and len(rng) == 2:SUSPECT_IP_RANGES.append((rng[0], rng[1]))added_ip += 1for d in doms:if isinstance(d, str):SUSPECT_DOMAINS.append(d)print(f"[+] Activated +{added_ip} IP ranges, +{len(doms)} domains from verified blocklist.")except Exception as e:print(f"[!] Failed loading blocklist cache: {e}")def apply_firewall_block(ip: str):"""Local firewall DROP rule (Linux iptables). No-op on other OS or failure."""if not AUTO_FIREWALL:returnif platform.system().lower() != "linux":returntry:# add OUTPUT rule if not presentsubprocess.run(["sudo", "iptables", "-C", "OUTPUT", "-d", ip, "-j", "DROP"],check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)subprocess.run(["sudo", "iptables", "-A", "OUTPUT", "-d", ip, "-j", "DROP"], check=False)# add INPUT rule if not presentsubprocess.run(["sudo", "iptables", "-C", "INPUT", "-s", ip, "-j", "DROP"],check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)subprocess.run(["sudo", "iptables", "-A", "INPUT", "-s", ip, "-j", "DROP"], check=False)print(f"[FIREWALL] DROP {ip}")except Exception as e:print(f"[!] Firewall rule failed for {ip}: {e}")# =========================# CORE SCANNING# =========================def scan_connections():"""Scan active connections and flag suspicious ones."""flagged = []outbound_count = 0for conn in psutil.net_connections(kind="inet"):if not conn.raddr:continueip = getattr(conn.raddr, "ip", None)port = getattr(conn.raddr, "port", None)if not ip:continueoutbound_count += 1try:host = socket.gethostbyaddr(ip)[0]except Exception:host = None# IP range checksuspicious_ip = Falsefor start, end in SUSPECT_IP_RANGES:try:if ip_in_range(ip, start, end):flagged.append((ip, port, host, "range"))suspicious_ip = Truebreakexcept Exception:pass# Domain checkif (not suspicious_ip) and host and any(d in host for d in SUSPECT_DOMAINS):flagged.append((ip, port, host, "domain"))return flagged, outbound_countdef anomaly_detection(current_outbound: int):"""Simple rolling 3-sigma detection of outbound connection spikes."""if not ENABLE_ANOMALY_DETECTION:return False, None, None_outbound_history.append(current_outbound)if len(_outbound_history) > ANOMALY_WINDOW:_outbound_history.pop(0)if len(_outbound_history) >= ANOMALY_MIN_SAMPLES:mean = statistics.mean(_outbound_history)stdev = statistics.stdev(_outbound_history) if len(_outbound_history) > 1 else 0if stdev > 0 and current_outbound > mean + ANOMALY_SIGMA * stdev:return True, mean, stdevreturn False, None, None# =========================# MAIN# =========================def main():print("🛡️ Belel Gideon Scanner (Next-Gen) running… (Ctrl+C to stop)")# Optional: fetch & verify blocklist at startif AUTO_FETCH_BLOCKLIST_ON_START:if try_update_blocklist() and verify_cached_blocklist():load_blocklist_into_memory()else:print("[!] Using built-in fingerprints only (no verified blocklist).")print(f"[i] Watching every {SCAN_INTERVAL}s | Firewall={'ON' if AUTO_FIREWALL else 'OFF'} | Notifications={'ON' if DESKTOP_NOTIFICATIONS else 'OFF'}")while True:flagged, outbound_count = scan_connections()# Handle flagged connectionsfor ip, port, host, reason in flagged:event = {"timestamp": now_iso(),"ip": ip, "port": port, "host": host,"reason": reason,"alert": "Potential Gideon-like surveillance detected"}print(f"[ALERT] {reason.upper()} → {ip}:{port} ({host})")log_event(event)notify("Belel Shield", f"Suspicious connection: {ip}:{port} ({host or 'unknown'})")apply_firewall_block(ip)# Anomaly detectionanomaly, mean, stdev = anomaly_detection(outbound_count)if anomaly:msg = f"Outbound spike {outbound_count} (μ={mean:.1f}, σ={stdev:.1f})"event = {"timestamp": now_iso(),"outbound_count": outbound_count,"mean": round(mean, 2) if mean is not None else None,"stdev": round(stdev, 2) if stdev is not None else None,"alert": "Outbound traffic anomaly detected"}print(f"[ANOMALY] {msg}")log_event(event)notify("Belel Shield", msg)time.sleep(SCAN_INTERVAL)if __name__ == "__main__":try:main()except KeyboardInterrupt:print("\n[i] Stopped by user.")123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env python3import psutil, socket, time, datetime, jsonfrom pathlib import PathLOG_FILE = Path.home() / ".belel" / "gideon_alerts.json"LOG_FILE.parent.mkdir(parents=True, exist_ok=True)SUSPECT_IP_RANGES=[("104.244.42.0","104.244.42.255"),("185.220.100.0","185.220.100.255")]SUSPECT_DOMAINS=["gideon-surveillance.com","israel-trade-detect.net","nsa-mirror.org","palantir.com"]def ip_in_range(ip,start,end):import ipaddressip_obj=ipaddress.ip_address(ip)return ipaddress.ip_address(start) <= ip_obj <= ipaddress.ip_address(end)def log_event(event):existing = json.loads(LOG_FILE.read_text()) if LOG_FILE.exists() else []existing.append(event)LOG_FILE.write_text(json.dumps(existing, indent=2))def scan_connections():flagged=[]for conn in psutil.net_connections(kind="inet"):if conn.raddr:ip, port = conn.raddr.ip, conn.raddr.porttry: host = socket.gethostbyaddr(ip)[0]except: host = Nonefor start,end in SUSPECT_IP_RANGES:if ip_in_range(ip,start,end): flagged.append((ip,port,host))if host and any(d in host for d in SUSPECT_DOMAINS): flagged.append((ip,port,host))return flaggeddef main():print("🛡️ Belel Gideon Scanner running... (Ctrl+C to stop)")while True:flagged = scan_connections()for ip,port,host in flagged:event={"timestamp": datetime.datetime.utcnow().isoformat(),"ip":ip,"port":port,"host":host,"alert":"Potential Gideon-like surveillance detected"}print(f"[ALERT] Suspicious connection → {ip}:{port} ({host})"); log_event(event)time.sleep(10)if __name__=="__main__": main()
123456789101112# Belel Blocklist – Automatic Updates
Keep your shield fresh by scheduling `update_blocklist.py` to run daily.
> Replace `YOUR_GITHUB` in the scripts with your actual GitHub org/user before use.
---
## Linux (cron)1) Open crontab:```bashcrontab -e24 unmodified lines2526272824 unmodified lines<key>RunAtLoad</key><true/><key>KeepAlive</key><false/></dict></plist>24 unmodified lines2526272824 unmodified lines<key>RunAtLoad</key><true/><key>KeepAlive</key><false/></dict></plist>
41 unmodified lines4243444541 unmodified lines<WorkingDirectory>%USERPROFILE%\belel-shield\sentinel\scanner</WorkingDirectory></Exec></Actions></Task>41 unmodified lines4243444541 unmodified lines<WorkingDirectory>%USERPROFILE%\belel-shield\sentinel\scanner</WorkingDirectory></Exec></Actions></Task>
1234567#!/usr/bin/env python3import shutil, subprocessdef check_tor(): return shutil.which("tor") is not Nonedef start_tor(): if not check_tor(): print("Tor is not installed."); return False subprocess.Popen(["tor"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); print("Started tor."); return Trueif __name__=="__main__": start_tor()123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env python3import yaml, requests, jsonfrom pathlib import PathREPO_ROOT = Path(__file__).resolve().parents[2]CONFIG = REPO_ROOT / "blocklists" / "dynamic_feeds.yaml"OUT = REPO_ROOT / "blocklists" / "merged-blocklist.json"CACHE = Path.home() / ".belel" / "merged-blocklist.json"CACHE.parent.mkdir(parents=True, exist_ok=True)
def parse_text_to_ranges(text): out=[]; for line in text.splitlines(): line=line.strip() if not line or line.startswith("#"): continue out.append([line, line]) return out
def merge_feeds(): cfg = yaml.safe_load(CONFIG.read_text()) final = {"ip_ranges": [], "domains": [], "source": "merged", "last_updated": None} for feed in cfg["feeds"]: try: r = requests.get(feed["url"], timeout=10) if feed.get("format") == "text": final["ip_ranges"].extend(parse_text_to_ranges(r.text)) elif feed.get("format") == "json": j = r.json() final["ip_ranges"].extend(j.get("ip_ranges", [])) final["domains"].extend(j.get("domains", [])) except Exception as e: print("feed error", feed["name"], e) final["last_updated"] = __import__("datetime").datetime.utcnow().isoformat()+"Z" OUT.write_text(json.dumps(final, indent=2)) CACHE.write_text(json.dumps(final, indent=2)) print("Merged feeds written to", OUT, "and cache")
if __name__ == "__main__": merge_feeds()12345678910111213141516#!/usr/bin/env python3import random, time, jsonfrom pathlib import PathOUT = Path.home() / ".belel" / "noise_events.jsonl"OUT.parent.mkdir(parents=True, exist_ok=True)QUERIES = ["best coffee", "how to fix sink", "weather today", "gardening tips", "sports scores"]def generate_one(): ev = {"ts": __import__("datetime").datetime.utcnow().isoformat()+"Z", "q": random.choice(QUERIES)} OUT.open("a").write(json.dumps(ev)+"\n") return evif __name__ == "__main__": try: while True: print(generate_one()); time.sleep(random.uniform(2,6)) except KeyboardInterrupt: pass1234567891011121314151617181920scan_interval_sec: 10require_blocklist_checksum: trueenable_anomaly_detection: trueanomaly: window: 20 min_samples: 6 sigma: 3plugins: firewall: false tor: false notify: false noise: falsenoise: enable_http: false domains: ["example.com","wikipedia.org","github.com","stackoverflow.com"] interval_sec: [30, 90]identities: - {id: researcher, activity: moderate} - {id: professional, activity: high} - {id: casual, activity: low}1# namespace package\n12345678910111213import platform, subprocess
def block_ip(ip: str): if platform.system().lower() != "linux": return try: subprocess.run(["sudo","iptables","-C","OUTPUT","-d",ip,"-j","DROP"], check=False) subprocess.run(["sudo","iptables","-A","OUTPUT","-d",ip,"-j","DROP"], check=False) subprocess.run(["sudo","iptables","-C","INPUT","-s",ip,"-j","DROP"], check=False) subprocess.run(["sudo","iptables","-A","INPUT","-s",ip,"-j","DROP"], check=False) print(f"[FIREWALL] DROP {ip}") except Exception as e: print("[FIREWALL] error:", e)belel-shield/.gitignoreAdded+5
belel-shield/CODEOWNERSAdded+4
belel-shield/MakefileAdded+69
belel-shield/README.md-52
belel-shield/SECURITY.mdAdded+14
belel-shield/dashboard/DockerfileAdded+9
belel-shield/dashboard/INFRA_MAP_ADDON.mdAdded+16
belel-shield/dashboard/app.py+39-140
belel-shield/dashboard/requirements.txtAdded+4
belel-shield/dashboard/shodan_mapper.pyAdded+7
belel-shield/firewall/linux/README.mdAdded+18
belel-shield/firewall/linux/belel_firewall.nftAdded+21
belel-shield/firewall/linux/belel_firewall.serviceAdded+12
belel-shield/firewall/linux/belel_firewall.shAdded+44
belel-shield/firewall/linux/belel_firewall.timerAdded+10
belel-shield/firewall/macos/README.mdAdded+18
belel-shield/firewall/macos/com.belel.firewall.plistAdded+14
belel-shield/firewall/macos/pf.confAdded+2
belel-shield/firewall/windows/BelelFirewall-Task.xmlAdded+9
belel-shield/firewall/windows/BelelFirewall.ps1Added+23
belel-shield/firewall/windows/README.mdAdded+15
belel-shield/gpg/SIGNING.mdAdded+6
belel-shield/gpg/belel_public_key.ascAdded+3
belel-shield/packaging/Dockerfile.firewallAdded+6
belel-shield/packaging/README.mdAdded+7
belel-shield/packaging/docker-compose.ymlAdded+12
belel-shield/pearce-shield/auth_logs/sample_auth_log.jsonlAdded+1
belel-shield/scripts/hash_blocklist.pyAdded+35
belel-shield/sentinel/blocklists/belel-blocklist.json+4-14
belel-shield/sentinel/blocklists/dynamic_feeds.yamlAdded+10
belel-shield/sentinel/extension/background.js+31-3
belel-shield/sentinel/extension/csp_injector.jsAdded+8
belel-shield/sentinel/extension/fingerprint_spoofer.jsAdded+11
belel-shield/sentinel/extension/manifest.json+10-12
belel-shield/sentinel/extension/noise_injector.jsAdded+7
belel-shield/sentinel/extension/popup.cssAdded+16
belel-shield/sentinel/extension/popup.htmlAdded+39
belel-shield/sentinel/extension/popup.jsAdded+26
belel-shield/sentinel/scanner/anomaly_detector.pyAdded+15
belel-shield/sentinel/scanner/dpi_scanner.pyAdded+16
belel-shield/sentinel/scanner/gideon_scanner.py+27-282
belel-shield/sentinel/scanner/scheduling/README_Scheduling.mdAdded+12
belel-shield/sentinel/scanner/scheduling/macos_launchd/com.belel.blocklist.update.plist+1-1
belel-shield/sentinel/scanner/scheduling/windows/BelelBlocklistUpdate.xml+1-1
belel-shield/sentinel/scanner/tor_router.pyAdded+7
belel-shield/sentinel/scripts/blocklist_generator.pyAdded+39
belel-shield/sentinel/scripts/noise_generator.pyAdded+16
belel-shield/sovereign/config.example.yamlAdded+20
belel-shield/sovereign/plugins/__init__.pyAdded+1
belel-shield/sovereign/plugins/fw_drop.pyAdded+13