// Package waf adalah Web Application Firewall per situs untuk Hostora // (v0.4). Stdlib saja — tanpa dependensi eksternal. // // Aturan dijalankan terhadap method, path + query URL, header terpilih // (User-Agent, Referer, Cookie), dan — untuk POST/PUT/PATCH dengan body // kecil — isi body. Mode per situs ("off" | "detect" | "block") disimpan // di store.Site.WAFMode; paket ini tidak tahu tentang store — pemanggil // (internal/server) yang menyediakan mode lewat callback dan menerima // entri log lewat callback. package waf import ( "bytes" "io" "net" "net/http" "net/url" "regexp" "strings" "time" ) // BlockThreshold adalah skor minimum agar request diblokir pada mode // "block". Di bawah ambang ini request hanya dicatat ("dicatat"). const BlockThreshold = 10 // MaxLogEntries adalah jumlah maksimum entri log WAF yang disimpan // (entri terbaru dipertahankan). const MaxLogEntries = 100 // MaxInspectBodySize adalah ukuran body maksimum yang diperiksa // (64 KB). Body yang lebih besar dilewati — bukan diblokir — supaya // upload file besar tidak terbebani inspeksi. const MaxInspectBodySize = 64 * 1024 // MarkerStart / MarkerEnd membatasi blok snippet WAF di dalam file // vhost nginx. Handler server memakai marker yang sama saat // menambah/mengganti/menghapus snippet, sehingga operasi itu idempotent // (tidak pernah menduplikasi blok). const ( MarkerStart = "# Hostora WAF start" MarkerEnd = "# Hostora WAF end" ) // Mode yang dikenal. const ( ModeOff = "off" ModeDetect = "detect" ModeBlock = "block" ) // Rule adalah satu aturan WAF. type Rule struct { ID string `json:"id"` Name string `json:"name"` Pattern *regexp.Regexp `json:"-"` Score int `json:"score"` OWASP string `json:"owasp"` // Matched diisi oleh Inspect dengan cuplikan teks yang cocok // (dipotong maks 120 karakter). Kosong untuk aturan dari Rules(). Matched string `json:"matched,omitempty"` } // PatternString mengembalikan pola regex sebagai string (untuk // serialisasi ke JSON — *regexp.Regexp tidak bisa di-marshal). func (r Rule) PatternString() string { if r.Pattern == nil { return "" } return r.Pattern.String() } func mustRule(id, name, pattern string, score int, owasp string) Rule { return Rule{ ID: id, Name: name, Pattern: regexp.MustCompile(pattern), Score: score, OWASP: owasp, } } // rules adalah daftar aturan yang dikompilasi sekali saat paket dimuat. var rules = []Rule{ mustRule("SQLI-01", "UNION SELECT", `(?i)union\s+(all\s+)?select\b`, 10, "A03:2021"), mustRule("SQLI-02", "DROP/TRUNCATE/DELETE", `(?i)\b(drop\s+table|truncate\s+(table\s+)?|delete\s+from)\b`, 10, "A03:2021"), mustRule("SQLI-03", "OR 1=1", `(?i)(['"]|%27)\s*or\s+(['"]|%27)?1(['"]|%27)?\s*=\s*(['"]|%27)?1`, 10, "A03:2021"), mustRule("XSS-01", "Tag