#!/usr/bin/env python3
"""Mengirim peristiwa SIMULASI ke mesin deteksi (lingkungan lokal saja).
Payload hanyalah teks yang dicocokkan dengan pola; tidak dieksekusi dan tidak menyerang target apa pun.

Pemakaian: python3 scripts/simulate_events.py [--url http://127.0.0.1:8000] [--code sim-linux-01] [--key SIM-KEY-LINUX-01]
"""
import argparse
import hashlib
import json
import urllib.request


def send(url, code, key, events):
    req = urllib.request.Request(f"{url}/api/v1/ingest", method="POST",
                                 data=json.dumps({"sensor_code": code, "hostname": "simulasi", "events": events}).encode(),
                                 headers={"Content-Type": "application/json", "X-Sensor-Key": key})
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.loads(r.read())


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--url", default="http://127.0.0.1:8000")
    ap.add_argument("--code", default="sim-linux-01")
    ap.add_argument("--key", default="SIM-KEY-LINUX-01")
    a = ap.parse_args()
    scenarios = {
        "lalu lintas normal": [{"type": "http_request", "ip": "10.0.0.5", "method": "GET", "path": "/index.php", "query": "page=2"}],
        "SQL injection (teks pola)": [{"type": "http_request", "ip": "203.0.113.9", "method": "GET", "path": "/products.php",
                                       "query": "id=1' OR '1'='1' UNION SELECT username,password FROM users&token=RAHASIA"}],
        "XSS (teks pola)": [{"type": "http_request", "ip": "203.0.113.44", "method": "GET", "path": "/comment.php",
                             "query": "msg=%3Cscript%3Ealert(1)%3C/script%3E"}],
        "path traversal": [{"type": "http_request", "ip": "203.0.113.44", "method": "GET", "path": "/download.php", "query": "f=../../etc/passwd"}],
        "brute force (8 login gagal)": [{"type": "login", "ip": "198.51.100.99", "username": "admin", "success": False}] * 8,
        "port scan (25 port)": [{"type": "firewall", "ip": "192.0.2.123", "dst_port": p} for p in range(20, 45)],
        "metrik CPU tinggi": [{"type": "metrics", "metrics": {"cpu": 96, "mem": 55, "disk": 61}, "services": {"nginx": "running", "mysql": "running"}}],
        "file integrity (baseline)": [{"type": "file_integrity", "files": [{"path": "/etc/hosts", "hash": hashlib.sha256(b"v1").hexdigest()}]}],
        "file integrity (diubah)": [{"type": "file_integrity", "files": [{"path": "/etc/hosts", "hash": hashlib.sha256(b"v2").hexdigest()}]}],
        "syslog gagal login": [{"type": "syslog", "os": "linux", "message": "Failed password for invalid user test from 198.51.100.99 port 4242"}],
    }
    for name, evs in scenarios.items():
        print(f"{name:32s} -> {send(a.url, a.code, a.key, evs)}")


if __name__ == "__main__":
    main()
