Zion is a local-first cyber defense demo that combines:
- FastAPI request interception + enforcement gates
- ML anomaly scoring (Isolation Forest) with a deterministic rules layer for human-readable threat types
- A policy engine (Smolify/HuggingFace optional) that turns detections into mitigation actions
- Optional incident logging to Algorand TestNet and storage via Appwrite (auto-disabled when env vars are not set)
This repo includes a React/Vite dashboard for real-time visibility and several attack simulation scripts (token replay, credential stuffing, DDoS-style floods, endpoint scraping, parameter fuzzing).
- Threat typing (distinct categories):
ddos,rate_flood,token_replay,credential_stuffing,endpoint_scraping,param_fuzzing,anomaly - Mitigations are not “block IP only”:
- DDoS-like traffic → protect endpoint (drop traffic with 503)
- Token replay → revoke token (401 thereafter)
- Rate floods / stuffing / scraping → rate limit (429)
- Real-time logs via WebSocket stream to the frontend
- On-chain logging (Algorand TestNet) for flagged incidents (optional; enabled only when env vars are set)
- Request enters FastAPI
- Middleware
interceptor:- extracts
ip,endpoint,token,status_code,payload_size,timestamp - runs enforcement gates (blocked IP / rate limit / revoked token / protected endpoint)
- scores requests via
ml.detector.score_request()
- extracts
ml.detector:- extracts sliding-window features (
ml.feature_extractor) - computes anomaly
risk_scorevia Isolation Forest - applies a rules layer →
threat_type
- extracts sliding-window features (
policy.smolify_client.generate_policy():- chooses a mitigation action by
threat_type(HuggingFace optional)
- chooses a mitigation action by
policy.executor.execute_action():- enforces
block,rate_limit,invalidate_token,protect_endpoint
- enforces
- Optional incident logging:
blockchain.algorand_loggerlogs flagged incidents to Algorand TestNet- cached records stored via
db.store(Appwrite)
Contracts between modules are documented in CONTRACTS.md.
backend/— FastAPI app, ML detector, policy executor, blockchain loggingfrontend/— React/Vite UI (dashboard + simulation screens)backend/attack/scenarios/— attack simulations (token replay, stuffing, DDoS flood, endpoint scrape, param fuzzing)demo/— traffic generators + quick log inspectionstudy/— threat type explanations
- Python 3.10+ (Windows:
pylauncher is fine) - Node.js 18+ (recommended) + npm
If you enable on-chain logging and cloud persistence, you also need:
- An Algorand TestNet wallet (mnemonic + address)
- An Appwrite project (TablesDB) and API key
Zion loads env vars from backend/.env.
Create backend/.env with the following variables.
ALGO_MNEMONIC="word1 word2 ... word25"
ALGO_ADDRESS="YOUR_ALGORAND_ADDRESS"Generate a new TestNet wallet:
cd backend
py blockchain/generate_wallet.py --writeImportant:
- Never commit
backend/.env(it contains your mnemonic) - Fund the TestNet wallet from a faucet if you want successful TX confirmations
APPWRITE_ENDPOINT="https://YOUR_APPWRITE_HOST/v1"
APPWRITE_PROJECT_ID="..."
APPWRITE_API_KEY="..."
APPWRITE_DATABASE_ID="..."
APPWRITE_COLLECTION_ID="..."If HF_TOKEN is not set, Zion uses deterministic fallback actions per threat type.
HF_TOKEN="hf_..."
HF_API_URL="https://api-inference.huggingface.co/models/smolify/smolified-zion"From repo root (Windows PowerShell):
py -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r backend/requirements.txtRun the API:
cd backend
py main.py releaseBackend base URL: http://127.0.0.1:8000
In a new terminal:
cd frontend
npm install
npm run devFrontend default URL: http://localhost:5173
Start the backend first (cd backend; py main.py release). Then run any scenario below.
Simulates a stolen token reused across many spoofed IPs.
py backend/attack/scenarios/token_replay.pyExpected behavior:
- Detection:
token_replay - Mitigation: invalidate token
- You should see many
401responses after revocation.
Simulates many failed logins against /login.
py backend/attack/scenarios/credential_stuffing.pyExpected behavior:
- Detection:
credential_stuffing - Mitigation: rate_limit (429) for the offending IP
Simulates a multi-worker flood to /test using many spoofed IPs.
py backend/attack/scenarios/rate_abuse.pyExpected behavior:
- Detection:
ddos(distributed/high fan-in) - Mitigation: protect endpoint (503 drops) instead of “blocking 1 IP”
Notes:
- Some requests can still trigger per-IP rate limiting (429) depending on timing and sliding-window state.
- Endpoint protection is the primary DDoS mitigation in this demo.
Simulates an attacker enumerating many distinct endpoints quickly.
py backend/attack/scenarios/endpoint_scrape.pyExpected behavior:
- Detection:
endpoint_scraping - Mitigation: rate_limit (429)
Simulates probing a small set of endpoints at high rate while varying input.
py backend/attack/scenarios/param_fuzzing.pyExpected behavior:
- Detection:
param_fuzzing - Mitigation: rate_limit (429)
py demo/normal_traffic.pypy demo/attack_traffic.pypy demo/check_scores.pyBase: http://127.0.0.1:8000
GET /→{ "msg": "Zion API running" }GET|POST /test→{ "msg": "hit" }POST /login→ always401unless password iscorrect_password
GET /dashboard/stats- returns counts: blocked IPs, rate-limited IPs, revoked tokens, protected endpoints, total threats
GET /dashboard/raw_logs?limit=200- snapshot recent logs (for scripts/debug)
WS /dashboard/logs- live stream of log entries (frontend consumes this)
POST /simulate/spam?target=http://127.0.0.1:8000/test
GET /anomalies/→ basic suspicious IP counts from in-memory logs
POST /rl/start?episodes=10GET /rl/status
POST /chain/analyze— score an arbitrary request payload; if flagged, logs in backgroundGET /chain/chain?limit=20— returns cached chain historyGET /chain/chain/{tx_id}— fetch pending transaction info from Algorand node
See study/TYPES OF THREAT.md for details.
In short:
ddos: many IPs + elevated short-window volume → protect endpointrate_flood: very high rate from one/few IPs → rate limittoken_replay: token reused across IPs → revoke tokencredential_stuffing: repeated failed logins → rate limitendpoint_scraping: high endpoint variety → rate limitparam_fuzzing: high-rate probing of a small endpoint set → rate limitanomaly: doesn’t match a named pattern strongly
If you see errors about missing ALGO_MNEMONIC / ALGO_ADDRESS:
- Create
backend/.envand set the variables - Or generate a wallet:
py backend/blockchain/generate_wallet.py --write
If you see Appwrite errors, verify all APPWRITE_* variables.
PowerShell aliases curl to Invoke-WebRequest and may prompt about script parsing.
Use either:
- Python:
py -c "import requests; print(requests.get('http://127.0.0.1:8000/dashboard/stats').text)" - Or:
Invoke-WebRequest -UseBasicParsing http://127.0.0.1:8000/dashboard/stats
Some blockchain tests depend on external services and local credentials; test collection can fail if environment variables are not set.
This is a demo system.
- Do not use the included attack scripts against systems you don’t own or have explicit permission to test.
- Do not commit secrets (Algorand mnemonic, Appwrite API key) to Git.
See LICENSE.