FFFF GitHub - koodoxz/tameng: ๐Ÿ›ก๏ธ Single-binary, ML-assisted Web Application Firewall in Go โ€” signature engine, actor tracking, DDoS escalation, honeypots. No sidecars. ยท GitHub
[go: up one dir, main page]

Skip to content
koodoxzPublic

About

๐Ÿ›ก๏ธ Single-binary, ML-assisted Web Application Firewall in Go โ€” signature engine, actor tracking, DDoS escalation, honeypots. No sidecars.

Topics

Resources

Contributing

Security policy

Stars

3 stars

Watchers

2 watching

Forks

Latest commit

ย 

History

55 Commits

Folders and files

Repository files navigation

CI Status Go 1.26+ License: AGPL-3.0 Single Binary MECOB Ecosystem Made in Indonesia

๐Ÿ›ก๏ธ Tameng

A single-binary, ML-assisted Web Application Firewall, written in Go.
No Python sidecar for real-time threat detection. No external inference service for WAF scoring. No 12-container stack. One binary, one YAML file, one systemd unit.

๐Ÿ‡ฎ๐Ÿ‡ฉ Designed and built in Indonesia, by a solo security engineer, in the open.

Tameng starting up and blocking a SQLi+XSS attack live

Bahasa Indonesia ยท English ยท Quick Start ยท Contributing ยท License


Bahasa Indonesia

Daftar Isi

Tentang Tameng ๐Ÿ›ก๏ธ

Perisai Web Application Firewall dengan Deteksi Ancaman Bertenaga ML

Tameng adalah Web Application Firewall (WAF) berkinerja tinggi dengan deteksi ancaman berbasis machine learning, ditulis dalam Go untuk keamanan memori dan performa yang luar biasa.

Tameng menawarkan perlindungan lapisan aplikasi yang komprehensif melalui satu biner Go tunggal, satu file YAML, dan satu layanan systemd โ€” tanpa ketergantungan sidecar eksternal.

Kenapa "Tameng"?

Tameng adalah kata bahasa Indonesia untuk perisai โ€” alat pelindung yang berdiri di depan, menahan serangan sebelum mencapai apa yang dilindunginya. Nama ini dipilih dengan sengaja: proyek ini dibangun oleh seorang developer Indonesia, dan harapannya sederhana โ€” menjadi salah satu perisai nyata untuk infrastruktur digital, mulai dari yang dibangun sendiri, lalu siapa pun yang membutuhkannya. Bukan sekadar nama produk, tapi cita-cita: keamanan siber berkualitas yang lahir dan tumbuh dari Indonesia, dibuka untuk semua orang.

Note

Catatan Penamaan: Nama internal (module Go, binary, komentar kode) tetap menggunakan "Svalinn" (nama penutup dalam mitologi Nordik yang melindungi matahari dari kehancuran) โ€” kebetulan bertema sama: perisai. Ini adalah keputusan deliberate untuk menghindari refactoring invasif pada sistem produksi aktif. Dokumentasi publik dan branding menggunakan "Tameng".

Differensiator Teknis

Dibandingkan dengan WAF open-source lainnya seperti Coraza (library WAF murni, kompatibel ModSecurity):

  • Baterai Lengkap: Satu biner menggabungkan mesin WAF + penilaian ML + pelacakan aktor dua-tahap + eskalasi DDoS 3-fase + lapisan honeypot/deception + integrasi threat intelligence (STIX/TAXII) + pemetaan MITRE ATT&CK
  • Keamanan Regex: Engine WAF menggunakan RE2 Go (bukan Oniguruma/PCRE) โ€” ReDoS (regex backtracking bencana) mustahil secara struktural, bukan hanya mitigated
  • ML Asli: Inferensi model berbasis LightGBM berjalan asli dalam Go (via library leaves) untuk threat scoring real-time per-request โ€” tidak ada proses Python sidecar di jalur request. Tameng juga menyertakan fitur forecasting tren opsional berbasis Prophet (forecasting volume gray-zone/alert) yang memang membutuhkan runtime Python 3 lokal โ€” ini subsistem terpisah dan opsional (nonaktif secara default), bukan bagian dari jalur WAF/scoring inti. Lihat Forecasting Opsional
  • Tracking Aktor: Melacak aktor dalam dua tahap (lightweight counters โ†’ full profiles) dengan eviction LRU aman memori, bahkan di bawah beban korban DDoS
  • Transparansi Pengujian Adversarial: Historik pengujian mendalam dengan alat pembuat serangan khusus (dibuat oleh penulis yang sama). Kami mempublikasikan eksperimen yang gagal juga โ€” kebanyakan security tools tidak pernah mengumumkan ketika sebuah pendekatan tidak membantu.

Adversarial Red-Teaming (Ratatoskr) โšก

Tameng diuji secara internal menggunakan Ratatoskr โ€” tool pembuat serangan/payload generator khusus (dibangun oleh penulis yang sama, belum dirilis publik) yang dirancang untuk menguji batas fungsionalitas WAF di bawah beban kerja ekstrem (high-load) dan skenario evasion nyata, bukan sekadar unit test sintetis.

Metrik Pengujian Hasil Metodologi Red-Team
๐ŸŽฏ Evasion Payload Blocking 100% (13/13) Varian serangan terobfuskasi & teknik evasion nyata, lewat endpoint yang sama sepanjang engagement pengujian
๐Ÿ“ฅ STIX/TAXII Payload Ingestion 100% (13/13) SQLi/XSS/traversal/command-injection via endpoint TAXII nyata & teregistrasi (unauthenticated by design) โ€” endpoint yang sama yang sempat kena bug konfigurasi block-threshold, sekarang sudah diperbaiki dan diverifikasi ulang secara live
๐Ÿ” Integritas Endpoint Ecosystem 100% (4/4) Laporan HEIMDALL/DNS palsu ditolak oleh IP allowlist; feed baca tanpa autentikasi ditolak oleh middleware auth
๐Ÿงช Ketahanan Resource / Crash-Safety 0 Bypass, 0 Crash Probe body-size, nesting JSON, dan parameter limit yang dibatasi terhadap handler nyata; target tetap sehat sebelum dan sesudah
๐Ÿ›ก๏ธ ReDoS Fuzzing Stability 0 Crashes 8 juta+ eksekusi fuzzed payload di seluruh permukaan deteksi, pada Go RE2 regex engine
๐Ÿ”ง Perbaikan Produksi Nyata 16+ Fixes Termasuk kasus yang gagal di percobaan pertama, bukan cuma yang langsung berhasil

Tip

Transparansi Radikal: Seluruh klaim telemetry, memory limit, dan blocking rate dalam dokumentasi ini murni berasal dari simulasi red-team riil Ratatoskr โ€” bukan angka microbenchmark buatan, dan termasuk mempublikasikan perbaikan dari percobaan pertama yang sempat gagal.

Fitur Keamanan Inti

Fitur Deskripsi
Mesin WAF (200+ signature) SQL Injection, XSS, Path Traversal, Command Injection, SSRF, Log4Shell, Scanner/Bot detection
Proteksi DDoS Deteksi EWMA + eskalasi 3-fase (Challenge โ†’ Throttle โ†’ Block)
Pelacakan Aktor Dua-tahap dengan fingerprinting behavioral DNA, penyimpanan memory-safe, integrasi Reserse
Deception Layer 100+ honeypot/canary traps untuk mengalihkan dan mengidentifikasi penyerang
Fingerprinting JA3 TLS + HTTP behavior profiling
Deteksi Kill Chain Korelasi serangan multi-tahap, deteksi Command & Control (C2)
Threat Intelligence Integrasi STIX/TAXII, pemetaan MITRE ATT&CK, feed IOC
Guard Protokol Deteksi request smuggling, GraphQL depth limiting, WebSocket rate limiting
Analisis Behavioral Baseline deviation detection, credential stuffing identification, anomaly correlation

Egress Data Loss Prevention (DLP) ๐Ÿ”

Tameng bertindak sebagai Reverse Proxy yang secara aktif mengintersepsi traffic outbound (response body stream) yang keluar dari backend menuju client untuk mencegah kebocoran data sensitif (seperti NIK, NPWP, BPJS, nomor HP Indonesia, JWT, dan API Key cloud) secara real-time.

sequenceDiagram
    autonumber
    actor Client as ๐ŸŒ Client / Attacker
    participant Proxy as ๐Ÿ›ก๏ธ Tameng WAF (Reverse Proxy)
    participant Engine as ๐Ÿ” Egress DLP Scanner (Stream Engine)
    participant Backend as ๐Ÿ–ฅ๏ธ Backend App / Database

    Note over Client,Backend: INBOUND TRAFFIC (Request Inspection)
    Client->>Proxy: 1. HTTP Request (GET /customer/123)
    Proxy->>Proxy: 2. WAF Signatures + ML Threat Scoring
    Proxy->>Backend: 3. Forward Clean Request

    Note over Client,Backend: OUTBOUND TRAFFIC (Egress Interception & DLP Inspection)
    Backend-->>Proxy: 4. HTTP Response Stream (Body containing NIK / Credentials)
    Proxy->>Engine: 5. Inspect Response Body (Buffered Stream Scanning, up to 200KB scan limit)

    alt Mode: Alert (Default - Non-Disruptive)
        Engine->>Proxy: 6a. Match Found: Log Telemetry & Alert (SECRET_LEAK)
        Proxy-->>Client: 7a. Deliver Response (200 OK)
    else Mode: Block (Enforced Policy)
        Engine->>Proxy: 6b. Policy Violation: Reject Response
        Proxy-->>Client: 7b. 403 Forbidden (Original Response Discarded)
    end

    Note over Proxy,Engine: Response di atas 200KB tidak bisa diblokir karena bytes sudah terlanjur streaming ke client saat scan baru dimulai.
    Note over Proxy,Engine: Untuk kasus ini, hanya Alert (deteksi dan catat) yang berlaku, apa pun mode yang dikonfigurasi.
Loading

Ringkasan Kapabilitas Intersepsi Egress DLP:

Pilar Kapabilitas Mekanisme Teknis Dampak Operasional
๐Ÿ”„ Outbound Stream Interception Mengintersepsi chunked response body langsung dari aplikasi backend sebelum terkirim ke socket TCP client. Tidak memerlukan perubahan kode aplikasi di backend sama sekali.
๐Ÿ‡ฎ๐Ÿ‡ฉ Pola Deteksi PII Indonesia Pattern matching berbasis RE2 + entropy scanning untuk NIK (KTP), NPWP, BPJS, dan Nomor HP Indonesia. Deteksi spesifik untuk kebutuhan kepatuhan regulasi data di Indonesia (UU PDP).
๐Ÿ”‘ Deteksi Kredensial & Secrets Deteksi otomatis AWS/GCP API Keys, Private Keys (PEM), JWT tokens, dan DB connection strings. Mencegah accidental secret exposure dari endpoint API debug/error log backend.
๐ŸŽ›๏ธ Dual Interception Modes Mode Alert (default, non-disruptive): deteksi + catat telemetry, traffic tidak terganggu.
Mode Block: 403 Forbidden โ€” seluruh response ditolak (bukan redaksi/masking).
Fleksibilitas deployment: amati false-positive dulu sebelum mengaktifkan penindakan aktif.

Tameng Egress DLP Telemetry & Leak Alert Demo

Note

Sensitivitas PII & Mode Detection: Secara default, deteksi PII (seperti NIK dan nomor HP) berjalan dalam mode Alert (deteksi dan catat telemetry) sehingga operator dapat mengamati tingkat false-positive pada traffic produksi sebelum mengaktifkan mode Block.

Warning

Batasan yang jujur kami sampaikan: blokir reputasi-IP saat ini berdurasi tetap dan berlaku untuk seluruh IP sumber yang terdeteksi โ€” pada jaringan dengan IP keluar bersama (NAT/proxy korporat/CDN), ini bisa berdampak ke pengguna lain di IP yang sama. Durasi dapat diatur lewat konfigurasi. Lihat Keamanan & Pelaporan Kerentanan kalau kamu menemukan dampak ini di deploymentmu.

Deteksi Anti-Eksfiltrasi Egress (Non-DLP) ๐Ÿ•ต๏ธ

Kebanyakan WAF di pasaran hanya fokus pada traffic inbound. Engine egress yang sama di atas (internal/egress/advanced.go) juga menjalankan tiga pemeriksaan tambahan terhadap setiap response yang lewat Tameng โ€” relevan untuk skenario backend yang sudah disusupi (webshell, malware) dan mencoba mengirim data keluar lewat jalur HTTP normal.

graph TD
    Response[Response Backend Anda ke Client, lewat Tameng] --> Engine[Tameng Egress Engine]

    Engine -->|1. Base64 / Entropy Scan| Encoded{Blob Base64 lebih dari 10KB?}
    Encoded -- Ya --> BlockEncoded[BLOCK otomatis: ENCODED_DATA critical]
    Encoded -- Tidak, tapi entropy lebih dari 4.5 bit per byte --> AlertEncoded[ALERT saja: ENCODED_DATA medium]

    Engine -->|2. Anomali Volume Velocity| Velocity{Lonjakan 5x dari baseline, atau lebih dari 10MB per menit?}
    Velocity -- Ya --> AlertVelocity[ALERT saja - engine ini tidak memiliki kemampuan block]

    Engine -->|3. Geofencing Destinasi| Geo{Negara tujuan ada di blocked_countries?}
    Geo -- Ya, default --> AlertGeo[ALERT default: GEOFENCE]
    Geo -- Ya, jika mode diset ke block --> BlockGeo[BLOCK jika dikonfigurasi: GEOFENCE]

    Engine -->|4. Pattern Secret/PII, lihat Egress DLP di atas| Secret{NIK, AWS Key, atau JWT terdeteksi?}
    Secret -- Kredensial cloud standar --> BlockSecret[BLOCK otomatis: SECRET_LEAK]
    Secret -- PII atau pattern false-positif tinggi --> AlertSecret[ALERT default, bisa diset ke block]
Loading
Pilar Mekanisme Teknis Perilaku Default
๐Ÿ“ฆ Deteksi Payload Terenkode Blob Base64 >10KB di response body โ†’ block otomatis (severity critical). Body dengan Shannon entropy >4.5 bit/byte (>500 byte) โ†’ alert (medium), indikasi data terenkripsi/di-obfuscate. Base64 besar: block. Entropy tinggi saja: alert.
๐Ÿ“ˆ Anomali Volume (Velocity) Baseline dinamis per-user/IP; lonjakan โ‰ฅ5ร— dari rata-rata historis, atau >10MB/menit, memicu alert. Alert saja โ€” engine ini tidak memiliki kemampuan block sama sekali, di severity apa pun.
๐ŸŒ Geofencing Destinasi Response menuju negara di blocked_countries (default: RU, CN, KP, IR, BY, SY) terdeteksi via GeoIP dari IP client sebenarnya, bukan Host header. Alert secara default (geofence_mode: alert) โ€” ubah ke block di config untuk penegakan aktif.

Important

Batasan cakupan yang jujur kami sampaikan: ketiga pemeriksaan di atas (dan DLP sebelumnya) hanya menganalisis response HTTP yang mengalir kembali melalui Tameng ke client โ€” baik dari handler Tameng sendiri maupun dari backend yang di-reverse-proxy di baliknya. Tameng adalah WAF Layer-7 di jalur request/response, bukan firewall level jaringan/host yang mengawasi seluruh traffic keluar server. Malware yang membuka koneksi outbound sendiri secara langsung (misal reverse shell yang connect keluar ke C2, atau C2 lewat DNS tunneling) tidak terlihat oleh engine ini โ€” itu di luar jangkauan arsitektur reverse-proxy L7 mana pun, bukan keterbatasan khusus Tameng.

Mulai Cepat

Prasyarat

  • Go 1.26+ (build dari sumber) โ€” build pure Go, tidak perlu CGO atau C compiler

Opsi 1: Docker (Direkomendasikan)


10BC8
# Clone repo
git clone https://github.com/koodoxz/tameng.git
cd tameng

# Copy environment template
cp .env.example .env

# Edit .env dengan nilai Anda (SVALINN_GOD_KEY, SVALINN_API_KEY, dll)
nano .env

# Build dan jalankan
docker-compose up -d

# Periksa health
curl http://localhost:10000/health

# Lihat logs
docker-compose logs -f svalinn

Port default: 10000 (HTTP), 10443 (HTTPS)

Opsi 2: Dari Sumber

# Prerequisites: Go 1.26+ (pure Go build, no CGO needed)

git clone https://github.com/koodoxz/tameng.git
cd tameng
cp .env.example .env
nano .env

go build -o tameng ./cmd/svalinn
./tameng -config configs/svalinn.yaml

Konfigurasi

Semua konfigurasi melalui environment variables dan file configs/svalinn.yaml. Lihat .env.example untuk daftar lengkap.

Kunci Wajib:

  • SVALINN_GOD_KEY โ€” Kunci autentikasi untuk /api/v9/* endpoints (admin saja)
  • SVALINN_API_KEY โ€” Kunci untuk akses programmatic (threat reporting, actor queries)
  • SVALINN_RESERSE_USER / SVALINN_RESERSE_PASS โ€” Kredensial modul tracking aktor lanjutan (Reserse). Server menolak untuk start jika kosong (fail-closed by design).

Kunci Opsional (Ekosistem MECOB):

  • ODIN_API_KEY โ€” Kunci integrasi opsional dengan layanan gateway/DNS internal ekosistem MECOB (belum rilis publik)

Tuning Lanjutan: Threshold WAF/DDoS, batas jumlah aktor di memory, dan toggle fitur (ML scoring, deception, dll) dikonfigurasi langsung lewat configs/svalinn.yaml โ€” bukan environment variable. Lihat file tersebut untuk daftar lengkap opsi (WAF, DDoS, ML, deception, SIEM, CVE feeds, TLS, dll).

Menjalankan di Depan Aplikasi Anda (Reverse Proxy)

Sejak versi ini, Tameng bisa berdiri langsung di jalur trafik aplikasi Anda, bukan cuma sebagai layanan intelligence-as-a-service yang berdiri sendiri. Set server.backend_url di configs/svalinn.yaml:

server:
  backend_url: "http://127.0.0.1:8080"  # aplikasi Anda

Request yang tidak cocok dengan rute Tameng sendiri (health, metrics, TAXII, API, dll) akan diteruskan ke backend_url setelah melewati seluruh middleware chain (WAF, DDoS, actor-tracking, deception) โ€” bukan sebelumnya. Kosongkan (default) untuk menjalankan Tameng standalone seperti sebelumnya.

Keterbatasan yang jujur kami sampaikan (implementasi awal ini):

  • Belum mendukung WebSocket upgrade atau streaming SSE/chunked ke backend (akan gagal/di-buffer) โ€” belum cocok untuk backend berbasis WebSocket.
  • Body request di atas 8 KiB ditolak (413) โ€” belum ada streaming upload.
  • Beberapa path administratif/decoy bawaan Tameng selalu menutupi backend Anda kalau aplikasi Anda memakai path yang sama โ€” cek configs/svalinn.yaml dan source internal/server/server.go untuk daftar lengkapnya sebelum menentukan struktur routing aplikasi Anda.
  • X-Forwarded-Proto yang diteruskan ke backend hanya benar kalau TLS langsung terminate di Tameng sendiri โ€” kalau TLS di-terminate di nginx/reverse-proxy lain di depan Tameng, backend akan selalu melihat "http".
  • Jangan arahkan backend_url ke Tameng sendiri (loop) atau ke alamat yang tidak Anda kendalikan.
  • Sama seperti WAF secara umum, blokir reputasi-IP di depan backend Anda berdurasi tetap dan berlaku untuk seluruh IP sumber โ€” pada jaringan dengan IP keluar bersama (NAT/proxy korporat/CDN), ini bisa berdampak ke pengguna lain di IP yang sama yang mencoba mengakses aplikasi Anda. Lihat catatan lengkap di Fitur Keamanan Inti.

Endpoint API

Endpoint Metode Deskripsi
/health GET Health check
/metrics GET Prometheus metrics
/api/v1/stats GET Server statistics
/api/v1/threats GET Recent threats
/api/v1/actors GET Active actors
/api/v1/config GET Current config
/api/v9/reload POST Reload config (God Mode)
/api/v9/block POST Block IP (God Mode; durasi block eskalasi otomatis per pelanggaran berulang, tidak diisi oleh caller)
/api/v9/unblock POST Unblock IP (God Mode)
/api/v9/intel/stats GET Statistik IOC blocklist Threat Intel Hub (God Mode)
/api/v9/intel/block POST Tambah IOC (type: ip/domain, value, threat_level: low/medium/high/critical, source) ke blocklist Threat Intel Hub (God Mode)
/api/v9/intel/unblock POST Hapus IOC (type, value) dari blocklist Threat Intel Hub (God Mode)
/reserse/actors GET Reserse actor details (Basic Auth)
/reserse/actors/{id}/timeline GET Timeline event untuk satu profil aktor (Basic Auth)
/reserse/actors/by-ip/{ip}/timeline GET Timeline event berdasarkan IP (Basic Auth)
/reserse/graph GET Actor relationship graph (Basic Auth)
/taxii GET TAXII discovery document
/taxii/collections GET Daftar koleksi TAXII
/taxii/collections/default/objects GET Baca STIX indicator (public)
/taxii/collections/default/objects POST Submit STIX indicator (perlu SVALINN_API_KEY)

Catatan Threat Intel Hub: IOC blocklist hanya tersimpan di memori dan hilang setiap kali restart (tidak ada persistence layer, berbeda dengan blocklist countermeasures). /health dan semua path /api/v9/intel/* dikecualikan dari IOC blocking, sehingga operator yang IP-nya sendiri ter-IOC tetap bisa mengakses /api/v9/intel/unblock (tetap butuh autentikasi God-Mode) untuk membatalkannya, dan Docker healthcheck tidak akan terkunci oleh entri IOC pada loopback/hostname.

Arsitektur

internal/
โ”œโ”€โ”€ actor/          # Two-stage actor tracking (lightweight โ†’ full profiles)
โ”œโ”€โ”€ behavior/       # Behavioral baseline + deviation analysis
โ”œโ”€โ”€ collector/      # Threat intelligence collectors
โ”œโ”€โ”€ config/         # YAML config loader with env expansion
โ”œโ”€โ”€ countermeasures/ # Active response mechanisms
โ”œโ”€โ”€ dataloader/     # JSON-backed import of gray-zone/attacker-memory/forecast/evolved-rules data
โ”œโ”€โ”€ ddos/           # EWMA + 3-phase escalation
โ”œโ”€โ”€ deception/      # Honeypots + canary tokens
โ”œโ”€โ”€ detect/         # Kill chain + C2 detection
โ”œโ”€โ”€ ecosystem/      # MECOB ecosystem integration (internal gateway/DNS services)
โ”œโ”€โ”€ egress/         # Egress filtering
โ”œโ”€โ”€ fingerprint/    # JA3 + HTTP fingerprinting
โ”œโ”€โ”€ geoip/          # MaxMind GeoIP lookups
โ”œโ”€โ”€ hardening/      # Memory + security hardening
โ”œโ”€โ”€ heuristics/     # Threat scoring heuristics
โ”œโ”€โ”€ honeypot/       # Dedicated honeypot engine
โ”œโ”€โ”€ intel/          # MITRE ATT&CK + IOC + STIX
โ”œโ”€โ”€ literalextract/ # Aho-Corasick literal prefilter, skips regex evaluation when required literals are absent
โ”œโ”€โ”€ logger/         # zerolog structured logging
โ”œโ”€โ”€ logic/          # Business logic abuse detection
โ”œโ”€โ”€ malware/        # Malware behavior analysis
โ”œโ”€โ”€ ml/             # LightGBM ML bridge (native Go)
โ”œโ”€โ”€ netutil/        # Dependency-free client-IP/network helpers shared across detection packages
โ”œโ”€โ”€ observatory/    # Top actors cache (Hall of Fame)
โ”œโ”€โ”€ orchestrator/   # Detection orchestration
โ”œโ”€โ”€ payload/        # YARA/Sigma/Snort signatures
โ”œโ”€โ”€ preattack/      # Pre-attack detection (recon/scanning)
โ”œโ”€โ”€ protocol/       # Request smuggling, GraphQL depth, WebSocket
โ”œโ”€โ”€ proxy/          # Reverse-proxy forwarding to a protected backend_url
โ”œโ”€โ”€ response/       # Response encryption + PoW challenges
โ”œโ”€โ”€ scanbudget/     # Wall-clock scan budget + randomized pattern-evaluation order
โ”œโ”€โ”€ security/       # Security hardening utilities
โ”œโ”€โ”€ semantic/       # Semantic payload analysis
โ”œโ”€โ”€ server/         # HTTP/TLS server + middleware pipeline
โ”œโ”€โ”€ session/        # Session tracking
โ”œโ”€โ”€ siem/           # SIEM integration
โ””โ”€โ”€ waf/            # WAF signature engine (200+)
graph LR
    Req[Incoming Request] --> Pipeline

    subgraph Pipeline[Middleware Pipeline]
        direction LR
        Regex["WAF Engine<br/>RE2 Regex (ReDoS-safe)"] --> ML["ML Scoring<br/>LightGBM via leaves"]
        ML --> ActorTrack["Actor Tracking<br/>Two-Stage (ringan โ†’ profil penuh)"]
        ActorTrack --> DDoS["DDoS Escalation<br/>Challenge โ†’ Throttle โ†’ Block"]
    end

    Pipeline --> Deception{Trap / Honeypot?}
    Deception -- Ya --> Block[Block / Challenge / Encrypt]
    Deception -- Tidak --> Backend[Forward to Backend]
Loading

Data Flow: Request masuk โ†’ middleware pipeline โ†’ WAF signature check + ML scoring โ†’ actor tracking + behavioral analysis โ†’ DDoS detection โ†’ deception/honeypot checks โ†’ response shaping (encryption, PoW) โ†’ SIEM/intel logging โ†’ forward to backend (atau block/challenge).

Keterbatasan yang Diketahui

Cakupan Layer-7 (bukan L3/L4): Tameng adalah WAF Layer-7 yang berjalan sebagai reverse proxy โ€” deteksi DDoS-nya (EWMA + eskalasi 3-fase) bekerja pada level pola request HTTP per-IP sumber, bukan traffic level jaringan. Ini tidak menggantikan proteksi volumetrik L3/L4 (SYN flood, UDP flood, amplifikasi DNS), yang membutuhkan CDN atau scrubbing-layer jaringan di depan server (mis. Cloudflare atau provider anti-DDoS jaringan lain). Untuk deployment yang menghadap internet langsung tanpa CDN/LB di depan, pertimbangkan menambahkan layer tersebut.

Pemindaian pattern/signature punya batas waktu wall-clock, dan bisa fail-open โ€” bahkan dari satu request saja, bukan cuma di bawah beban tinggi: empat subsistem pemindaian (internal/waf, internal/detect, internal/semantic, internal/malware) masing-masing punya budget wall-clock 100ms sendiri-sendiri (signatureScanBudget, checkPatternsBudget, analyzeBudget, detectBehaviorsBudget), dengan urutan evaluasi diacak per panggilan supaya batas waktu itu tidak secara konsisten memudahkan evasion pada subset pattern yang sama. Batas ini ada untuk membatasi biaya pemindaian terburuk melawan attacker adaptif yang mengalahkan literal-prefilter Aho-Corasick dengan mengisi body request dengan semua literal yang dibutuhkan. Kalau budget terlampaui sebelum semua pattern sempat dicek, sisa pattern yang belum dievaluasi (bisa jadi semuanya, kalau prefilter sendiri sudah menghabiskan waktu) dilewati untuk request/pemanggilan itu โ€” bukan otomatis diblok. Pengukuran internal kami sendiri menunjukkan sebuah body 8 KiB yang di-pad secara adaptif (ukuran maksimum yang diizinkan) sudah bisa memakan ~15ms di hardware pengembangan โ€” dengan margin sekitar 10% dari budget 100ms setelah disesuaikan untuk throughput single-thread VPS produksi kami yang ~6x lebih lambat, jadi eksploitasi ini tidak memerlukan beban tinggi sama sekali, satu request yang dibuat dengan tepat pun cukup; beban tinggi berkelanjutan (CPU contention/tekanan scheduler menaikkan biaya wall-clock per request) cuma memperbesar peluangnya. Ini trade-off yang disengaja (blok otomatis saat timeout justru menjadi vektor denial-of-service tersendiri) โ€” mitigasi yang sudah ada hari ini adalah batas ukuran body 8 KiB yang diberlakukan sebelum semua pemindaian ini berjalan (lihat catatan reverse-proxy di atas), yang membatasi biaya pemindaian terburuk. Belum ada logging/counter/statistik saat budget ini terlampaui, budget-nya juga masih konstanta compile-time (bukan opsi YAML), dan angka 100ms sendiri diset dari pengukuran hardware pengembangan plus margin perkiraan โ€” belum divalidasi di hardware kelas produksi. Kurva detection-rate-vs-beban yang terukur secara nyata belum kami publikasikan; observability, konfigurabilitas, dan kurva ini ada di roadmap kami.

Tidak melindungi dari IDOR (Insecure Direct Object Reference): Tameng tidak dapat mencegah bug otorisasi level objek pada aplikasi Anda. Ini bukan celah implementasi yang bisa ditambal โ€” state kepemilikan objek (mis. "user A boleh akses order #123, user B tidak boleh") hidup di database/sesi aplikasi yang dilindungi, dan sepenuhnya tidak terlihat oleh WAF perimeter mana pun, termasuk Tameng. Dua detektor yang paling relevan di sini:

  • internal/logic (Business Logic Abuse, mode: "detect" secara default) menghitung volume aksi dan hit ke path sensitif per sesi โ€” bukan mendeteksi akses ke objek milik user lain.
  • Pengecekan sequential-path recon di internal/preattack hanya menyumbang skor 0.1 dari ambang 0.7 BLOCK / 0.4 MONITOR, dan mensyaratkan dua path dengan panjang string persis sama yang berbeda satu karakter (mis. /orders/9 โ†’ /orders/10 tidak akan terdeteksi) โ€” heuristik enumerasi yang lemah, bukan pengganti otorisasi objek.

Otorisasi level objek harus diterapkan di aplikasi Anda sendiri.

Catatan instalasi (data/ harus writable): Dockerfile meng-chown data/ ke user non-root secara otomatis, tapi hanya berlaku untuk docker run tanpa bind mount. Deployment yang direkomendasikan di README ini pakai docker-compose up -d, dan docker-compose.yml mem-bind-mount ./data:/app/data โ€” bind mount menimpa direktori image sepenuhnya dan memakai ownership dari host, sehingga chown Dockerfile tidak berlaku. Kalau repo di-clone sebagai root (mis. sudo git clone ke /opt), jalankan mkdir -p data && sudo chown -R 1000:1000 data (1000 = uid user svalinn di image) sebelum docker-compose up. Saat deploy dengan systemd, jalankan mkdir -p /opt/svalinn/data && chown svalinn:svalinn /opt/svalinn/data sebelum start pertama.

Keterbacaan sertifikat TLS: Jika tls_cert/tls_key diarahkan ke /etc/letsencrypt/live/... (biasanya 0700 root-only), service yang berjalan sebagai user non-root svalinn tidak akan bisa membacanya. Salin sertifikat ke lokasi yang readable oleh user svalinn, atau berikan ACL tambahan.

Permukaan false-positive baru di target query (signature SQLi pasca-decode): REQ SVALINN-WAF-QUERYDECODE-001 menambahkan pass fallback ter-decode +/percent-encoding supaya signature seperti SQLI-004 (UNION\s+(ALL\s+)?SELECT) bisa mendeteksi bentuk encoded yang realistis dari serangan nyata di wire โ€” tapi decoding yang sama juga membuat teks query yang wajar dalam gaya application/x-www-form-urlencoded ikut cocok. Query pencarian seperti q=learn+sql+union+select+tutorial sekarang hard-block di SQLI-004, semata-mata karena "union" dan "select" dipisahkan oleh whitespace hasil decode, tanpa indikator serangan lain sama sekali. Ini kelas eksposur yang sama yang sudah lebih dulu dimiliki target path dan body sebelum fix ini; eksposur ini tidak ada di target query sampai pass decode ditambahkan. Belum ada mitigasi yang diimplementasikan โ€” dicatat di sini supaya tidak salah dikira sebagai regresi baru saat terlihat di log produksi.

Batas ukuran query-string keras 8KiB, tidak bisa dikonfigurasi: REQ SVALINN-WAF-QUERYLEN-414-001 menolak request mana pun yang query string-nya melebihi 8KiB dengan 414 URI Too Long, meniru sikap batas ukuran body yang sudah ada. Berbeda dari kebanyakan ambang batas aplikasi ini, nilai ini adalah konstanta Go compile-time (maxScannedQueryBytes), tidak ada di configs/svalinn.yaml โ€” tidak ada tombol runtime untuk menaikkannya. Beberapa protokol legitimate membawa parameter query jauh melebihi 8KiB (SAMLResponse pada SAML HTTP-Redirect binding, parameter state/request OAuth yang panjang); deployment yang menghadap backend semacam itu akan melihat request yang valid dan nyata kena 414 tanpa opsi override hari ini.

Testing

go test ./internal/...                                  # Unit tests
go test -race ./internal/...                             # Dengan race detector
go test -coverprofile=coverage.out ./internal/...        # Coverage
go tool cover -func=coverage.out
go test ./internal/waf/...                                # Specific package
go test -bench=. -benchmem ./internal/...                # Benchmarks

Lihat file *_test.go untuk differential fuzz tests, mutation tests, dan adversarial test cases.

Keamanan & Pelaporan Kerentanan

Tameng menjalankan /.well-known/security.txt di setiap instance yang jalan (lihat /security-policy untuk kebijakan lengkap). Untuk melaporkan kerentanan atau perilaku tak terduga (termasuk dampak dari desain blokir-reputasi-IP di atas), hubungi koodoxz@gmail.com. Target respons awal: 24 jam. Triage: 72 jam.

Mohon jangan buka issue publik untuk kerentanan yang belum di-patch โ€” laporkan lewat email dulu.

Kerangka Regulasi & Tata Kelola ๐Ÿ“‹

Tameng dirancang dengan mempertimbangkan prinsip-prinsip dari kerangka tata kelola AI/TI OJK ("Tata Kelola Kecerdasan Artifisial Perbankan Indonesia") โ€” reliability, accountability, transparency, data privacy, human oversight. Ini bukan klaim sertifikasi atau kepatuhan formal; kerangka tersebut sendiri berstatus panduan/acuan minimal bagi sektor jasa keuangan, bukan regulasi yang mengikat. Institusi jasa keuangan yang mengoperasikan Tameng tetap bertanggung jawab penuh atas kepatuhan mereka sendiri terhadap regulasi yang berlaku (SEOJK 29/2022, POJK 11/2022, UU PDP, dll).

Audit Data-Handling Tameng vs UU PDP 27/2022

Tameng melacak aktor (untuk deteksi ancaman) menggunakan data berikut: alamat IP, User-Agent, path yang diakses, fingerprint TLS/HTTP, negara (GeoIP), dan ASN. Data ini masuk kategori "dapat diidentifikasi secara tidak langsung" di bawah definisi luas UU PDP.

Selain data aktor di atas, Tameng juga memeriksa (bukan menyimpan) body request dan response yang lewat untuk mendeteksi kebocoran PII โ€” lihat bagian Egress Data Loss Prevention (DLP) di atas. Pemeriksaan ini transien: yang tercatat ke telemetry hanya jenis pola yang cocok dan jumlah kecocokan (contoh: {"type": "NIK", "count": 2}), bukan nilai yang cocok itu sendiri. Nomor NIK/NPWP/HP yang terdeteksi tidak pernah ditulis ke log maupun disimpan.

Kontrol yang sudah ada untuk data aktor:

  • Penyimpanan in-memory dibatasi dua lapis: LRU eviction (bounded oleh max_actors di config) dan pembersihan berbasis usia โ€” aktor yang tidak diblokir dan idle lebih dari 1 jam otomatis dihapus dari memori (aktor yang sedang diblokir dikecualikan dari pembersihan ini)
  • Akses baca ke data aktor (endpoint /api/v1/actors dan endpoint Reserse) memerlukan autentikasi (API key atau Basic Auth Reserse), fail-closed jika kredensial kosong

Warning

Batasan yang jujur kami sampaikan: penyimpanan on-disk (attacker-memory.json) saat ini bersifat append/merge-only โ€” tidak ada mekanisme retention/TTL otomatis, dan Tameng belum menyediakan tooling bagi operator untuk memenuhi permintaan hak hapus data (right to erasure) di bawah UU PDP untuk kategori data ini. Untuk saat ini, satu-satunya jalur penghapusan adalah manual: mengedit langsung file attacker-memory.json di server tempat Tameng berjalan. Tercatat di roadmap.

Forecasting Opsional

Tameng menyertakan subsistem forecasting tren opsional (internal/ml/prophet.go, anomaly.go) yang shell-out ke proses Python 3 lokal untuk memprediksi tren volume gray-zone/alert. Fitur ini nonaktif secara default dan tidak dibutuhkan untuk perlindungan WAF, pencocokan signature, atau threat scoring LightGBM โ€” ketiganya berjalan sepenuhnya di dalam satu biner Go tanpa proses eksternal apa pun.

Mengaktifkan forecasting membutuhkan instalasi Python 3 lokal dengan script di bawah .harvest/scripts/ (berbasis Prophet) tersedia di host. Kalau kamu tidak butuh forecasting tren, kamu tetap mendapat pengalaman single-binary tanpa sidecar sepenuhnya, langsung dari awal.

Roadmap

  • Publikasikan CI build terverifikasi penuh (GitHub Actions, cross-platform)
  • Konfigurasi durasi blokir reputasi-IP per-kategori (bukan durasi tetap tunggal)
  • Dokumentasi deployment reverse-proxy (di depan backend generik)
  • Ekspansi signature WAF untuk kategori LFI/RFI
  • Mekanisme retention/TTL otomatis + endpoint penghapusan data aktor (pemenuhan hak hapus UU PDP)
  • Kurva detection-rate-vs-beban yang terukur secara nyata (lihat catatan fail-open scan-budget di atas)
  • Logging/metrik saat scan budget terlampaui
  • Scan budget yang dapat dikonfigurasi (saat ini konstanta compile-time)

Punya usulan lain? Buka issue.

Berkontribusi

Lihat CONTRIBUTING.md untuk panduan lengkap: proses issue/PR, gaya kode Go, running tests.

Secara singkat:

  • Fork, branch, commit dengan pesan deskriptif
  • Jalankan go fmt, go vet, go test -race
  • Coverage minimal 80% untuk kode baru
  • Jelaskan perubahan dengan jelas di PR, termasuk implikasi keamanan jika ada

Tentang Pembuat

Tameng dikembangkan dan dirawat oleh satu orang developer/security engineer asal Indonesia, sebagai proyek open-source pertama yang dirilis ke publik. Dibangun, diuji secara adversarial, dan didokumentasikan secara transparan โ€” termasuk kegagalan-kegagalannya. Kontak: koodoxz@gmail.com.

Lisensi

AGPL-3.0 โ€” Kode sumber harus tersedia untuk semua pengguna dari versi yang dimodifikasi, termasuk ketika dijalankan sebagai layanan jaringan (ini yang membedakan AGPL dari GPL biasa). Provider hosting/cloud tidak dapat mengambil kode ini, memodifikasinya, dan menawarkannya sebagai layanan bersaing tanpa merilis modifikasi mereka. Teks lengkap: LICENSE.

AGPL-3.0 untuk penggunaan komunitas/open-source. Butuh lisensi dengan syarat berbeda (komersial)? Hubungi koodoxz@gmail.com.


English

Table of Contents

About Tameng ๐Ÿ›ก๏ธ

Web Application Firewall with ML-Powered Threat Detection

Tameng is a high-performance Web Application Firewall (WAF) with machine learning-powered threat detection, written in Go for memory safety and exceptional performance.

Tameng delivers comprehensive application-layer protection through a single Go binary, one YAML file, and one systemd service โ€” with no external sidecar dependencies.

Why "Tameng"?

Tameng is the Indonesian word for shield โ€” something that stands in front, absorbing an attack before it reaches whatever it protects. The name was chosen deliberately: this project is built by an Indonesian developer, and the hope behind it is simple โ€” to be one real shield for digital infrastructure, starting with what its author builds, then for whoever else needs it. Not just a product name, but an intent: security tooling that's genuinely good, born and grown in Indonesia, and given away to everyone.

Note

Naming Note: The internal codebase (Go module path, binary name, code comments) still uses the codename "Svalinn" (the shield in Norse mythology that protects the sun from destruction) โ€” fittingly, the same theme. This is a deliberate choice to avoid invasive refactoring on a live production system. Public documentation and branding use "Tameng."

Technical Differentiation

Compared to other open-source WAFs like Coraza (a pure WAF library, ModSecurity-compatible):

  • Batteries Included: One binary combines WAF signature engine + ML threat scoring + two-stage actor tracking + 3-phase DDoS escalation (Challenge โ†’ Throttle โ†’ Block) + honeypot/deception layer + STIX/TAXII threat intelligence + MITRE ATT&CK mapping
  • Regex Safety: WAF engine uses Go's RE2 regex engine (not Oniguruma/PCRE) โ€” ReDoS (catastrophic backtracking) is structurally impossible, not just mitigated
  • Native ML: LightGBM model inference runs natively in Go (via the leaves library) for real-time per-request threat scoring โ€” no Python sidecar in the request path. Tameng also ships an optional Prophet-based trend-forecasting feature (gray-zone/alert volume forecasting) that does require a local Python 3 runtime โ€” this is a separate, optional subsystem (disabled by default), not part of the core WAF/scoring path. See Optional Forecasting
  • Actor Tracking: Tracks threat actors in two stages (lightweight counters โ†’ full behavioral profiles) with memory-safe LRU eviction, even under DDoS victim load
  • Adversarial Testing Transparency: Deep red-team history with a purpose-built companion attack tool. We publish failed optimization attempts too โ€” most security tools never announce when an approach didn't help.

Adversarial Red-Teaming (Ratatoskr) โšก

Tameng is tested internally using Ratatoskr โ€” a custom payload generator and attack simulation tool (built by the same author, not itself open source) designed to stress-test WAF functional boundaries under high load and real evasion scenarios, not just synthetic unit tests.

Test Metric Result Red-Team Methodology
๐ŸŽฏ Evasion Payload Blocking 100% (13/13) Real-world obfuscated attack variants & evasion techniques, fired through the same endpoint used throughout this testing engagement
๐Ÿ“ฅ STIX/TAXII Payload Ingestion 100% (13/13) SQLi/XSS/traversal/command-injection via the real, registered TAXII endpoint (unauthenticated by design) โ€” the same endpoint previously affected by a block-threshold configuration bug, now fixed and reverified live
๐Ÿ” Ecosystem Endpoint Integrity 100% (4/4) Forged HEIMDALL/DNS reports rejected by the IP allowlist; unauthenticated read feeds rejected by auth middleware
๐Ÿงช Resource Exhaustion / Crash-Safety 0 Bypasses, 0 Crashes Bounded body-size, JSON-nesting, and limit-parameter probes against real handlers; target remained healthy before and after
๐Ÿ›ก๏ธ ReDoS Fuzzing Stability 0 Crashes 8M+ fuzzed payload executions across the full detection surface, on Go's RE2 regex engine
๐Ÿ”ง Real Production Fixes 16+ Fixes Including cases we got wrong on the first attempt, not just the ones that worked immediately

Tip

Radical Transparency: All telemetry, memory limits, and blocking rates claimed throughout this README come directly from real Ratatoskr red-team simulations โ€” not synthetic microbenchmarks, including published iterations from initial failed passes.

Core Security Features

Feature Description
WAF Signatures (200+) SQL Injection, XSS, Path Traversal, Command Injection, SSRF, Log4Shell, Scanner/Bot detection
DDoS Protection EWMA rate detection + 3-phase escalation (Challenge โ†’ Throttle โ†’ Block)
Actor Tracking Two-stage with behavioral DNA fingerprinting, memory-safe storage, Reserse integration
Deception Layer 100+ honeypots and canary tokens for actor redirection and identification
Fingerprinting JA3 TLS + HTTP behavior profiling
Kill Chain Detection Multi-stage attack correlation, Command & Control (C2) detection
Threat Intelligence STIX/TAXII integration, MITRE ATT&CK mapping, IOC feeds
Protocol Guards Request smuggling detection, GraphQL depth limiting, WebSocket rate limiting
Behavioral Analysis Baseline deviation detection, credential stuffing identification, anomaly correlation

Egress Data Loss Prevention (DLP) ๐Ÿ”

Tameng operates as an inline Reverse Proxy that actively intercepts outbound response body streams leaving backend applications to detect and prevent sensitive data leaks (such as Indonesian NIK, NPWP, BPJS, phone numbers, JWTs, and cloud API keys) in real-time.

sequenceDiagram
    autonumber
    actor Client as ๐ŸŒ Client / Attacker
    participant Proxy as ๐Ÿ›ก๏ธ Tameng WAF (Reverse Proxy)
    participant
10BC8
 Engine as ๐Ÿ” Egress DLP Scanner (Stream Engine)
    participant Backend as ๐Ÿ–ฅ๏ธ Backend App / Database

    Note over Client,Backend: INBOUND TRAFFIC (Request Inspection)
    Client->>Proxy: 1. HTTP Request (GET /customer/123)
    Proxy->>Proxy: 2. WAF Signatures + ML Threat Scoring
    Proxy->>Backend: 3. Forward Clean Request

    Note over Client,Backend: OUTBOUND TRAFFIC (Egress Interception & DLP Inspection)
    Backend-->>Proxy: 4. HTTP Response Stream (Body containing NIK / Credentials)
    Proxy->>Engine: 5. Inspect Response Body (Buffered Stream Scanning, up to 200KB scan limit)

    alt Mode: Alert (Default - Non-Disruptive)
        Engine->>Proxy: 6a. Match Found: Log Telemetry & Alert (SECRET_LEAK)
        Proxy-->>Client: 7a. Deliver Response (200 OK)
    else Mode: Block (Enforced Policy)
        Engine->>Proxy: 6b. Policy Violation: Reject Response
        Proxy-->>Client: 7b. 403 Forbidden (Original Response Discarded)
    end

    Note over Proxy,Engine: Responses larger than 200KB cannot be blocked because bytes are already streaming to the client by the time scanning starts.
    Note over Proxy,Engine: Only Alert (detect and log) applies in that case, regardless of configured mode.
Loading

Egress DLP Interception Summary:

Feature Pillar Technical Mechanism Operational Value
๐Ÿ”„ Outbound Stream Interception Intercepts chunked response bodies directly from backend applications before writing to client TCP sockets. Zero backend application code modifications required.
๐Ÿ‡ฎ๐Ÿ‡ฉ Indonesian PII Patterns RE2 pattern matching + entropy scanning for NIK (KTP), NPWP, BPJS, and Indonesian Phone Numbers. Detection tailored to Indonesian data-protection requirements (UU PDP).
๐Ÿ”‘ Credentials & Secrets Detection Automated pattern matching for AWS/GCP API Keys, Private Keys (PEM), JWT tokens, and DB connection strings. Prevents accidental secret exposure in backend debug/error log endpoints.
๐ŸŽ›๏ธ Dual Interception Modes Alert Mode (default, non-disruptive): detect + log telemetry, traffic unaffected.
Block Mode: 403 Forbidden -- the entire response is rejected (no redaction/masking).
Deployment flexibility: monitor false-positive rates before enabling active blocking.

Tameng Egress DLP Telemetry & Leak Alert Demo

Note

PII Sensitivity & Detection Mode: By default, PII detection operates in Alert mode (detect & log telemetry) allowing security operators to monitor production traffic patterns before promoting rules to Block mode.

Warning

Honest limitation: IP-reputation blocking currently uses a fixed duration applied to the entire source IP once triggered โ€” on networks with shared egress IPs (NAT, corporate proxy, CDN), this can affect other users behind the same IP. Duration is configurable. See Security & Vulnerability Reporting if you observe this impact in your deployment.

Egress Anti-Exfiltration Detection (Beyond DLP) ๐Ÿ•ต๏ธ

Most WAFs on the market focus almost entirely on inbound traffic. The same egress engine above (internal/egress/advanced.go) also runs three additional checks against every response passing through Tameng โ€” relevant for a compromised-backend scenario (webshell, malware) attempting to move data out over normal HTTP.

graph TD
    Response[Your Backend's Response to Client, via Tameng] --> Engine[Tameng Egress Engine]

    Engine -->|1. Base64 / Entropy Scan| Encoded{Base64 blob larger than 10KB?}
    Encoded -- Yes --> BlockEncoded[Auto-BLOCK: ENCODED_DATA critical]
    Encoded -- No, but entropy above 4.5 bits per byte --> AlertEncoded[ALERT only: ENCODED_DATA medium]

    Engine -->|2. Velocity Volume Anomaly| Velocity{5x spike from baseline, or above 10MB per minute?}
    Velocity -- Yes --> AlertVelocity[ALERT only - this engine has no block capability]

    Engine -->|3. Destination Geofencing| Geo{Destination country in blocked_countries?}
    Geo -- Yes, default --> AlertGeo[Default ALERT: GEOFENCE]
    Geo -- Yes, if mode set to block --> BlockGeo[BLOCK if configured: GEOFENCE]

    Engine -->|4. Secret/PII Pattern, see Egress DLP above| Secret{NIK, AWS Key, or JWT detected?}
    Secret -- Standard cloud credential --> BlockSecret[Auto-BLOCK: SECRET_LEAK]
    Secret -- PII or high-false-positive pattern --> AlertSecret[Default ALERT, can be set to block]
Loading
Pillar Technical Mechanism Default Behavior
๐Ÿ“ฆ Encoded Payload Detection A Base64 blob >10KB in the response body โ†’ auto-block (critical severity). A body with Shannon entropy >4.5 bits/byte (>500 bytes) โ†’ alert (medium), indicating encrypted/obfuscated data. Large Base64: block. High entropy alone: alert.
๐Ÿ“ˆ Volume Anomaly (Velocity) Dynamic per-user/IP baseline; a spike โ‰ฅ5ร— the historical average, or >10MB/minute, triggers an alert. Alert only โ€” this engine has no block capability at all, at any severity.
๐ŸŒ Destination Geofencing A response destined for a country in blocked_countries (default: RU, CN, KP, IR, BY, SY), resolved via GeoIP on the real client IP, not the Host header. Alert by default (geofence_mode: alert) โ€” set to block in config for active enforcement.

Important

Honest scope limitation: the three checks above (and DLP before them) only analyze HTTP responses that flow back through Tameng to the client โ€” whether from Tameng's own handlers or from a backend reverse-proxied behind it. Tameng is a Layer-7 WAF sitting in the request/response path, not a network- or host-level firewall monitoring all outbound traffic from the server. Malware that opens its own independent outbound connection (e.g. a reverse shell connecting directly out to a C2 server, or C2 over DNS tunneling) is invisible to this engine โ€” that's outside the reach of any L7 reverse-proxy architecture, not a Tameng-specific gap.

Quick Start (EN)

Prerequisites

  • Go 1.26+ (to build from source) โ€” pure Go build, no CGO or C compiler needed

Option 1: Docker (Recommended)

git clone https://github.com/koodoxz/tameng.git
cd tameng

cp .env.example .env
nano .env   # SVALINN_GOD_KEY, SVALINN_API_KEY, etc.

docker-compose up -d
curl http://localhost:10000/health
docker-compose logs -f svalinn

Default ports: 10000 (HTTP), 10443 (HTTPS)

Option 2: From Source

# Prerequisites: Go 1.26+ (pure Go build, no CGO needed)

git clone https://github.com/koodoxz/tameng.git
cd tameng
cp .env.example .env
nano .env

go build -o tameng ./cmd/svalinn
./tameng -config configs/svalinn.yaml

Configuration

All configuration is via environment variables and the configs/svalinn.yaml file. See .env.example for the complete list.

Required Keys:

  • SVALINN_GOD_KEY โ€” Authentication key for /api/v9/* endpoints (admin only)
  • SVALINN_API_KEY โ€” Key for programmatic access (threat reporting, actor queries)
  • SVALINN_RESERSE_USER / SVALINN_RESERSE_PASS โ€” Credentials for the advanced actor-tracking module (Reserse). The server refuses to start if these are empty (fail-closed by design).

Optional Keys (MECOB Ecosystem):

  • ODIN_API_KEY โ€” Optional integration key for an internal MECOB ecosystem gateway/DNS service (not yet publicly released)

Advanced Tuning: WAF/DDoS thresholds, actor memory limits, and feature toggles (ML scoring, deception, etc.) are configured directly in configs/svalinn.yaml โ€” not via environment variables. See that file for the full list of options (WAF, DDoS, ML, deception, SIEM, CVE feeds, TLS, etc.).

Running In Front Of Your Application (Reverse Proxy)

As of this version, Tameng can sit directly in your application's traffic path, not just run as a standalone intelligence-as-a-service. Set server.backend_url in configs/svalinn.yaml:

server:
  backend_url: "http://127.0.0.1:8080"  # your application

Any request that doesn't match one of Tameng's own routes (health, metrics, TAXII, API, etc.) is forwarded to backend_url after passing through the full middleware chain (WAF, DDoS, actor-tracking, deception) โ€” never before it. Leave empty (default) to run Tameng standalone, as before.

Honest limitations of this initial implementation:

  • No WebSocket upgrade or SSE/chunked streaming support to the backend yet (fails or buffers) โ€” not yet suitable for WebSocket-based backends.
  • Request bodies over 8 KiB are rejected (413) โ€” no streaming uploads yet.
  • Several built-in administrative/decoy paths Tameng already owns always shadow your backend if your app uses the same paths โ€” check configs/svalinn.yaml and the internal/server/server.go source for the full list before finalizing your app's routing.
  • The X-Forwarded-Proto header forwarded to the backend is only accurate when TLS terminates directly at Tameng โ€” if TLS terminates at an upstream nginx/reverse-proxy in front of Tameng instead, the backend will always see "http".
  • Don't point backend_url at Tameng's own listener (creates a loop) or at an address you don't control.
  • Same as WAF blocking in general, IP-reputation blocking in front of your backend uses a fixed duration applied to the entire source IP โ€” on networks with shared egress IPs (NAT, corporate proxy, CDN), this can affect other users behind the same IP trying to reach your application. See the full note in Core Security Features.

API Endpoints

Endpoint Method Description
/health GET Health check
/metrics GET Prometheus metrics
/api/v1/stats GET Server statistics
/api/v1/threats GET Recent threats
/api/v1/actors GET Active actors
/api/v1/config GET Current config
/api/v9/reload POST Reload config (God Mode)
/api/v9/block POST Block IP (God Mode; block duration escalates automatically per repeat offense, not caller-supplied)
/api/v9/unblock POST Unblock IP (God Mode)
/api/v9/intel/stats GET Threat intel Hub IOC blocklist statistics (God Mode)
/api/v9/intel/block POST Add an IOC (type: ip/domain, value, threat_level: low/medium/high/critical, source) to the threat intel Hub blocklist (God Mode)
/api/v9/intel/unblock POST Remove an IOC (type, value) from the threat intel Hub blocklist (God Mode)
/reserse/actors GET Reserse actor details (Basic Auth)
/reserse/actors/{id}/timeline GET Timeline events for a single actor profile (Basic Auth)
/reserse/actors/by-ip/{ip}/timeline GET Timeline events by IP (Basic Auth)
/reserse/graph GET Actor relationship graph (Basic Auth)
/taxii GET TAXII discovery document
/taxii/collections GET List TAXII collections
/taxii/collections/default/objects GET Read STIX indicators (public)
/taxii/collections/default/objects POST Submit a STIX indicator (requires SVALINN_API_KEY)

Threat intel Hub notes: the IOC blocklist is in-memory only and is cleared on every restart (no persistence layer, unlike the countermeasures block list). /health and every /api/v9/intel/* path are exempt from IOC blocking, so an operator whose own IP gets IOC'd can always reach /api/v9/intel/unblock (still God-Mode authenticated) to undo it, and the Docker healthcheck can't be bricked by an IOC'd loopback/hostname entry.

Architecture

internal/
โ”œโ”€โ”€ actor/          # Two-stage actor tracking (lightweight โ†’ full profiles)
โ”œโ”€โ”€ behavior/       # Behavioral baseline + deviation analysis
โ”œโ”€โ”€ collector/      # Threat intelligence collectors
โ”œโ”€โ”€ config/         # YAML config loader with env expansion
โ”œโ”€โ”€ countermeasures/ # Active response mechanisms
โ”œโ”€โ”€ dataloader/     # JSON-backed import of gray-zone/attacker-memory/forecast/evolved-rules data
โ”œโ”€โ”€ ddos/           # EWMA + 3-phase escalation
โ”œโ”€โ”€ deception/      # Honeypots + canary tokens
โ”œโ”€โ”€ detect/         # Kill chain + C2 detection
โ”œโ”€โ”€ ecosystem/      # MECOB ecosystem integration (internal gateway/DNS services)
โ”œโ”€โ”€ egress/         # Egress filtering
โ”œโ”€โ”€ fingerprint/    # JA3 + HTTP fingerprinting
โ”œโ”€โ”€ geoip/          # MaxMind GeoIP lookups
โ”œโ”€โ”€ hardening/      # Memory + security hardening
โ”œโ”€โ”€ heuristics/     # Threat scoring heuristics
โ”œโ”€โ”€ honeypot/       # Dedicated honeypot engine
โ”œโ”€โ”€ intel/          # MITRE ATT&CK + IOC + STIX
โ”œโ”€โ”€ literalextract/ # Aho-Corasick literal prefilter, skips regex evaluation when required literals are absent
โ”œโ”€โ”€ logger/         # zerolog structured logging
โ”œโ”€โ”€ logic/          # Business logic abuse detection
โ”œโ”€โ”€ malware/        # Malware behavior analysis
โ”œโ”€โ”€ ml/             # LightGBM ML bridge (native Go)
โ”œโ”€โ”€ netutil/        # Dependency-free client-IP/network helpers shared across detection packages
โ”œโ”€โ”€ observatory/    # Top actors cache (Hall of Fame)
โ”œโ”€โ”€ orchestrator/   # Detection orchestration
โ”œโ”€โ”€ payload/        # YARA/Sigma/Snort signatures
โ”œโ”€โ”€ preattack/      # Pre-attack detection (recon/scanning)
โ”œโ”€โ”€ protocol/       # Request smuggling, GraphQL depth, WebSocket
โ”œโ”€โ”€ proxy/          # Reverse-proxy forwarding to a protected backend_url
โ”œโ”€โ”€ response/       # Response encryption + PoW challenges
โ”œโ”€โ”€ scanbudget/     # Wall-clock scan budget + randomized pattern-evaluation order
โ”œโ”€โ”€ security/       # Security hardening utilities
โ”œโ”€โ”€ semantic/       # Semantic payload analysis
โ”œโ”€โ”€ server/         # HTTP/TLS server + middleware pipeline
โ”œโ”€โ”€ session/        # Session tracking
โ”œโ”€โ”€ siem/           # SIEM integration
โ””โ”€โ”€ waf/            # WAF signature engine (200+)
graph LR
    Req[Incoming Request] --> Pipeline

    subgraph Pipeline[Middleware Pipeline]
        direction LR
        Regex["WAF Engine<br/>RE2 Regex (ReDoS-safe)"] --> ML["ML Scoring<br/>LightGBM via leaves"]
        ML --> ActorTrack["Actor Tracking<br/>Two-Stage (lightweight โ†’ full profile)"]
        ActorTrack --> DDoS["DDoS Escalation<br/>Challenge โ†’ Throttle โ†’ Block"]
    end

    Pipeline --> Deception{Trap / Honeypot?}
    Deception -- Yes --> Block[Block / Challenge / Encrypt]
    Deception -- No --> Backend[Forward to Backend]
Loading

Data Flow: Incoming request โ†’ middleware pipeline โ†’ WAF signature check + ML scoring โ†’ actor tracking + behavioral analysis โ†’ DDoS detection โ†’ deception/honeypot checks โ†’ response shaping (encryption, PoW) โ†’ SIEM/intel logging โ†’ forward to backend (or block/challenge).

Known Limitations

Layer-7 scope (not L3/L4): Tameng is a Layer-7 WAF running as a reverse proxy โ€” its DDoS detection (EWMA + 3-phase escalation) operates on per-source-IP HTTP request patterns, not network-level traffic. It does not replace volumetric L3/L4 protection (SYN floods, UDP floods, DNS amplification), which needs a CDN or a network scrubbing layer in front of the server (e.g. Cloudflare or another network-level anti-DDoS provider). For deployments facing the internet directly without a CDN/LB in front, consider adding that layer.

Pattern/signature scanning has a wall-clock time budget, and can fail open โ€” from a single request, not only under load: four scanning subsystems (internal/waf, internal/detect, internal/semantic, internal/malware) each carry their own 100ms wall-clock budget (signatureScanBudget, checkPatternsBudget, analyzeBudget, detectBehaviorsBudget), with evaluation order shuffled per call so the time limit can't consistently favor evasion of the same pattern subset. This bound exists to cap worst-case scan cost against an adaptive attacker who defeats the Aho-Corasick literal prefilter by padding the request body with every literal a signature requires. If the budget is exceeded before all patterns are checked, the remaining unevaluated patterns (potentially all of them, if the prefilter itself consumes the budget) are skipped for that request/call โ€” not blocked outright. Our own internal measurements show an adaptively-padded 8KiB body (the maximum allowed) can already cost ~15ms on dev hardware โ€” roughly 10% headroom against the 100ms budget once adjusted for our production VPS's independently-known ~6x slower single-thread throughput โ€” so this does not require sustained load at all; a single well-crafted request is enough. Sustained high load (CPU contention/scheduler pressure raising per-request wall-clock cost) only widens the odds further. This is a deliberate trade-off (an automatic block on timeout would itself be a denial-of-service vector) โ€” today's existing mitigation is the 8KiB body size cap enforced ahead of all of this scanning (see the reverse-proxy note above), which bounds worst-case scan cost. There is currently no logging, counter, or stat exposed when this budget is hit, the budget itself is a compile-time constant (not a YAML option), and the 100ms figure was set from dev-hardware measurement plus an estimated margin โ€” not yet validated on production-class hardware. We have not yet published a real measured detection-rate-vs-load curve; observability, configurability, and that curve are all on our roadmap.

Does not protect against IDOR (Insecure Direct Object Reference): Tameng cannot prevent object-level authorization bugs in your application. This isn't a patchable implementation gap โ€” object-ownership state (e.g. "user A may access order #123, user B may not") lives in the protected application's database/session, entirely invisible to any perimeter WAF, including this one. The two most relevant detectors here:

  • internal/logic (Business Logic Abuse, mode: "detect" by default) counts action volume and sensitive-path hits per session โ€” it does not detect access to another user's objects.
  • The sequential-path recon check in internal/preattack contributes only a 0.1 score against a 0.7 BLOCK / 0.4 MONITOR threshold, and requires two paths of exactly equal string length differing by one character (e.g. /orders/9 โ†’ /orders/10 will not match) โ€” a weak enumeration heuristic, not a substitute for object authorization.

Object-level authorization must be enforced in your own application.

Install note (writable data/): The Dockerfile chowns data/ to the non-root user automatically, but only for docker run without a bind mount. This README's recommended deployment uses docker-compose up -d, and docker-compose.yml bind-mounts ./data:/app/data โ€” a bind mount shadows the image directory entirely and takes host ownership instead, so the Dockerfile's chown doesn't apply. If the repo was cloned as root (e.g. sudo git clone into /opt), run mkdir -p data && sudo chown -R 1000:1000 data (1000 = the svalinn user's uid in the image) before docker-compose up. When deploying with systemd, run mkdir -p /opt/svalinn/data && chown svalinn:svalinn /opt/svalinn/data before the first start.

TLS cert readability: If tls_cert/tls_key point at /etc/letsencrypt/live/... (typically 0700 root-only), a service running as the non-root svalinn user won't be able to read it. Copy the cert to a location readable by svalinn, or grant it an additional ACL.

New false-positive surface on the query target (post-decode SQLi signatures): a +/percent-decoded fallback pass lets signatures like SQLI-004 (UNION\s+(ALL\s+)?SELECT) match the wire-realistic encoded form of a real attack โ€” but the same decoding also makes benign application/x-www-form-urlencoded-style query text match. A search query like q=learn+sql+union+select+tutorial now hard-blocks on SQLI-004, purely because "union" and "select" are separated by decoded whitespace, with no other attack indicator present. This is the same class of exposure the path and body targets already had; it did not exist on the query target until this decode pass was added. No mitigation is implemented yet โ€” noted here so it isn't mistaken for a new regression when observed in production logs.

Hard, non-configurable 8KiB query-string cap: requests whose query string exceeds 8KiB get rejected with 414 URI Too Long, mirroring the existing body-size cap's posture. Unlike most of this app's thresholds, this value is a compile-time Go constant, not present in configs/svalinn.yaml โ€” there is no runtime knob to raise it. Some legitimate protocols carry query parameters well past 8KiB (SAML HTTP-Redirect binding's SAMLResponse, long OAuth state/request parameters); a deployment fronting such a backend will see real, valid requests 414 with no override available today.

Testing (EN)

go test ./internal/...                                  # Unit tests
go test -race ./internal/...                             # With race detector
go test -coverprofile=coverage.out ./internal/...        # Coverage
go tool cover -func=coverage.out
go test ./internal/waf/...                                # Specific package
go test -bench=. -benchmem ./internal/...                # Benchmarks

See *_test.go files for differential fuzz tests, mutation tests, and adversarial test cases.

Security & Vulnerability Reporting

Every running Tameng instance serves /.well-known/security.txt (see /security-policy for the full policy). To report a vulnerability or unexpected behavior (including impact from the IP-reputation blocking design noted above), contact koodoxz@gmail.com. Initial response target: 24 hours. Triage: 72 hours.

Please do not open a public issue for unpatched vulnerabilities โ€” email first.

Regulatory Framework & Governance ๐Ÿ“‹

Tameng is designed with consideration for principles from OJK's AI/IT governance framework ("Tata Kelola Kecerdasan Artifisial Perbankan Indonesia") โ€” reliability, accountability, transparency, data privacy, human oversight. This is not a certification or formal compliance claim; the framework itself is guidance / a minimum reference for the financial services sector, not binding regulation. Financial institutions operating Tameng remain fully responsible for their own compliance with applicable regulations (SEOJK 29/2022, POJK 11/2022, UU PDP, etc.).

Tameng's Data-Handling Audit vs. UU PDP 27/2022

Tameng tracks actors (for threat detection) using: IP address, User-Agent, accessed paths, TLS/HTTP fingerprint, country (GeoIP), and ASN. This data falls under UU PDP's broad "indirectly identifiable" definition.

Beyond the actor data above, Tameng also inspects (does not store) request and response bodies passing through it to detect PII leaks โ€” see the Egress Data Loss Prevention (DLP) section above. This inspection is transient: telemetry records only the pattern type matched and the match count (e.g. {"type": "NIK", "count": 2}), never the matched value itself. Detected NIK/NPWP/phone numbers are never written to logs or persisted.

Existing controls for actor data:

  • In-memory storage is bounded two ways: LRU eviction (capped by max_actors in config) and age-based cleanup โ€” non-blocked actors idle for more than 1 hour are automatically purged from memory (currently-blocked actors are exempt from this cleanup)
  • Read access to actor data (/api/v1/actors and the Reserse endpoints) requires authentication (API key or Reserse Basic Auth), fail-closed if credentials are empty

Warning

Honest limitation: on-disk persistence (attacker-memory.json) is currently append/merge-only โ€” there is no automatic retention/TTL mechanism, and Tameng does not yet give operators tooling to fulfil a UU PDP right-to-erasure request for this data category. For now, the only deletion path is manual: directly editing the attacker-memory.json file on the server running Tameng. Tracked on the roadmap.

Optional Forecasting (EN)

Tameng includes an optional trend-forecasting subsystem (internal/ml/prophet.go, anomaly.go) that shells out to a local Python 3 process for gray-zone/alert-volume trend prediction. This is disabled by default and is not required for WAF protection, signature matching, or LightGBM threat scoring โ€” all three run entirely inside the single Go binary with no external process.

Enabling forecasting requires a local Python 3 installation with the scripts under .harvest/scripts/ (Prophet-based) available on the host. If you don't need trend forecasting, you get the full single-binary, no-sidecar experience out of the box.

Roadmap (EN)

  • Fully verified CI build (GitHub Actions, cross-platform)
  • Per-category configurable IP-reputation block duration (not a single fixed duration)
  • Reverse-proxy deployment documentation (in front of a generic backend)
  • WAF signature expansion for LFI/RFI categories
  • Automated actor-data retention/TTL + deletion endpoint (UU PDP right-to-erasure fulfillment)
  • Real measured detection-rate-vs-load curve (see the fail-open scan-budget note above)
  • Logging/metric exposed when a scan budget is exceeded
  • Configurable scan budgets (currently compile-time constants)

Have another idea? Open a feature request.

Contributing (EN)

See CONTRIBUTING.md for full guidelines: issue/PR process, Go code style, running tests.

In short:

  • Fork, branch, commit with descriptive messages
  • Run go fmt, go vet, go test -race
  • Minimum 80% coverage for new code
  • Describe changes clearly in PR, including security implications if any

About the Author

Tameng is built and maintained by a solo Indonesian developer/security engineer, as their first project released to the public as open source. Built, adversarially tested, and documented transparently โ€” failures included. Contact: koodoxz@gmail.com.

License

AGPL-3.0 โ€” Source code must be available to all users of any modified version, including when run as a network service (this is what distinguishes AGPL from plain GPL). A cloud/hosting provider cannot take this code, modify it, and offer it as a competing service without releasing their modifications. Full text: LICENSE.

AGPL-3.0 for community/open-source use. Need different (commercial) licensing terms? Contact koodoxz@gmail.com.

๐Ÿ‡ฎ๐Ÿ‡ฉ Made in Indonesia.

About

๐Ÿ›ก๏ธ Single-binary, ML-assisted Web Application Firewall in Go โ€” signature engine, actor tracking, DDoS escalation, honeypots. No sidecars.

Topics

Resources

Contributing

Security policy

Stars

3 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0