Initial commit — migrated from GitHub (account suspended)
This commit is contained in:
commit
09d0ee68c8
65 files changed
+23255
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package waf
|
||||
|
||||
import "strings"
|
||||
|
||||
// NginxRules menghasilkan snippet konfigurasi nginx untuk sebuah situs.
|
||||
//
|
||||
// Snippet ini HANYA berupa string — paket waf tidak pernah menulis file.
|
||||
// Yang menulisnya adalah handler server (internal/server/waf.go), dan
|
||||
// hanya bila file vhost nginx situs itu memang ada (Site.VhostPath).
|
||||
// Blok yang dihasilkan selalu dibatasi MarkerStart/MarkerEnd supaya
|
||||
// handler bisa mengganti/menghapusnya secara idempotent.
|
||||
//
|
||||
// - mode "block": aturan aktif — request yang cocok dijawab 403 oleh
|
||||
// nginx, sebelum sampai ke aplikasi.
|
||||
// - mode "detect": nginx TIDAK punya mode "hanya mencatat", jadi
|
||||
// aturan ditulis sebagai komentar (nonaktif). Deteksi pada mode
|
||||
// ini tetap berjalan di middleware Go panel; snippet nginx sengaja
|
||||
// tidak memblokir supaya perilaku "detect" tidak berubah jadi
|
||||
// "block" diam-diam. Hapus tanda komentar untuk mengaktifkan
|
||||
// pemblokiran di nginx.
|
||||
// - mode "off" atau tidak dikenal: "" (tidak ada snippet).
|
||||
func NginxRules(siteDomain, mode string) string {
|
||||
switch mode {
|
||||
case ModeBlock:
|
||||
return nginxRulesActive(siteDomain, mode)
|
||||
case ModeDetect:
|
||||
return nginxRulesDetect(siteDomain)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func nginxRulesActive(siteDomain, mode string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(MarkerStart + " — " + siteDomain + " (mode: " + mode + ")\n")
|
||||
b.WriteString("# Aturan WAF Hostora untuk nginx. Request yang cocok dijawab 403.\n")
|
||||
// SQL injection di URI (path + query).
|
||||
b.WriteString("if ($request_uri ~* \"union[+\\s]+(all[+\\s]+)?select\") { return 403; }\n")
|
||||
b.WriteString("if ($request_uri ~* \"(drop[+\\s]+table|truncate[+\\s]+table|delete[+\\s]+from)\") { return 403; }\n")
|
||||
b.WriteString("if ($request_uri ~* \"(%27|'|%22|\\\")\\s*or\\s+1\\s*=\\s*1\") { return 403; }\n")
|
||||
// XSS.
|
||||
b.WriteString("if ($request_uri ~* \"<\\s*script\") { return 403; }\n")
|
||||
b.WriteString("if ($request_uri ~* \"(javascript\\s*:|onerror\\s*=)\") { return 403; }\n")
|
||||
// Path traversal dan null byte.
|
||||
b.WriteString("if ($request_uri ~* \"(\\.\\./|\\.\\.%2f|%2e%2e|%252e)\") { return 403; }\n")
|
||||
b.WriteString("if ($request_uri ~* \"%00\") { return 403; }\n")
|
||||
// Scanner berdasarkan User-Agent.
|
||||
b.WriteString("if ($http_user_agent ~* \"(nikto|sqlmap|nmap|masscan|dirbuster|gobuster)\") { return 403; }\n")
|
||||
// File sensitif: tolak langsung.
|
||||
b.WriteString("location ~* (wp-config\\.php|\\.env|config\\.php) { deny all; }\n")
|
||||
b.WriteString(MarkerEnd + "\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func nginxRulesDetect(siteDomain string) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(MarkerStart + " — " + siteDomain + " (mode: detect)\n")
|
||||
b.WriteString("# Mode detect: aturan di bawah ini NONAKTIF di nginx (dikomentari).\n")
|
||||
b.WriteString("# nginx tidak punya mode \"hanya mencatat\"; deteksi berjalan di\n")
|
||||
b.WriteString("# middleware WAF Go panel. Hapus tanda \"#\" untuk memblokir di nginx.\n")
|
||||
for _, line := range strings.Split(strings.TrimSuffix(nginxRulesActive(siteDomain, ModeBlock), "\n"), "\n") {
|
||||
if line == MarkerStart+" — "+siteDomain+" (mode: "+ModeBlock+")" || line == MarkerEnd {
|
||||
continue
|
||||
}
|
||||
b.WriteString("# " + line + "\n")
|
||||
}
|
||||
b.WriteString(MarkerEnd + "\n")
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// 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 <script>", `(?i)<\s*script\b`, 10, "A03:2021"),
|
||||
mustRule("XSS-02", "javascript: / onerror=", `(?i)(javascript\s*:|onerror\s*=)`, 8, "A03:2021"),
|
||||
mustRule("TRAV-01", "Path traversal", `(?i)(\.\.(/|%2f|%5c)|%2e%2e|%252e)`, 10, "A01:2021"),
|
||||
mustRule("SENS-01", "File sensitif", `(?i)(wp-config\.php|\.env|config\.php)`, 10, "A01:2021"),
|
||||
mustRule("SCAN-01", "Scanner User-Agent", `(?i)(nikto|sqlmap|nmap|masscan|dirbuster|gobuster)`, 10, "A05:2021"),
|
||||
mustRule("NULL-01", "Null byte", `(%00|\x00)`, 10, "A03:2021"),
|
||||
}
|
||||
|
||||
// Rules mengembalikan salinan daftar aturan (tanpa Matched).
|
||||
func Rules() []Rule {
|
||||
out := make([]Rule, len(rules))
|
||||
copy(out, rules)
|
||||
return out
|
||||
}
|
||||
|
||||
// LogEntry adalah satu request yang ditandai WAF, dalam bentuk yang
|
||||
// dipakai callback log Middleware. Bentuknya sengaja sama dengan
|
||||
// store.WAFLogEntry supaya handler server tinggal menyalin field-nya;
|
||||
// paket ini tidak mengimpor store (stdlib saja).
|
||||
type LogEntry struct {
|
||||
Time time.Time `json:"time"`
|
||||
Site string `json:"site"`
|
||||
IP string `json:"ip"`
|
||||
Score int `json:"score"`
|
||||
RuleID string `json:"rule_id"` // ID aturan dipisah koma bila lebih dari satu
|
||||
Matched string `json:"matched"`
|
||||
Action string `json:"action"` // "diblokir" | "dicatat"
|
||||
}
|
||||
|
||||
// TrimLog mempertahankan paling banyak MaxLogEntries entri terbaru.
|
||||
// Fungsi generik murni supaya pemanggil bisa memakainya untuk
|
||||
// []store.WAFLogEntry tanpa paket ini mengimpor store.
|
||||
func TrimLog[T any](entries []T) []T {
|
||||
if len(entries) <= MaxLogEntries {
|
||||
return entries
|
||||
}
|
||||
return entries[len(entries)-MaxLogEntries:]
|
||||
}
|
||||
|
||||
// snippet memotong cuplikan di sekitar kecocokan pertama menjadi
|
||||
// maks 120 karakter (dihitung per rune).
|
||||
func snippet(haystack string, loc []int) string {
|
||||
if len(loc) < 2 {
|
||||
return ""
|
||||
}
|
||||
start := loc[0] - 20
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
end := loc[1] + 20
|
||||
if end > len(haystack) {
|
||||
end = len(haystack)
|
||||
}
|
||||
s := strings.TrimSpace(haystack[start:end])
|
||||
r := []rune(s)
|
||||
if len(r) > 120 {
|
||||
return string(r[:120])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Inspect memeriksa satu request terhadap semua aturan.
|
||||
//
|
||||
// mode "off" -> tidak ada inspeksi: (nil, 0, "").
|
||||
// mode "detect" -> request yang cocok mendapat aksi "dicatat".
|
||||
// mode "block" -> aksi "diblokir" bila total skor >= BlockThreshold,
|
||||
// selain itu "dicatat".
|
||||
// mode lain -> diperlakukan seperti "detect".
|
||||
//
|
||||
// Bila tidak ada aturan yang cocok, aksi yang dikembalikan "".
|
||||
// Inspect tidak pernah panic pada request yang malformed (r atau
|
||||
// r.URL boleh nil) dan mengembalikan body yang sudah dibaca ke
|
||||
// r.Body supaya handler di hilir tetap bisa membacanya.
|
||||
func Inspect(r *http.Request, mode string) (matched []Rule, score int, action string) {
|
||||
if r == nil || mode == ModeOff {
|
||||
return nil, 0, ""
|
||||
}
|
||||
|
||||
// --- Kumpulkan teks yang diperiksa. ---
|
||||
var pathQuery, rawURI string
|
||||
if r.URL != nil {
|
||||
pathQuery = r.URL.Path
|
||||
if r.URL.RawQuery != "" {
|
||||
pathQuery += "?" + r.URL.RawQuery
|
||||
}
|
||||
rawURI = r.URL.String()
|
||||
}
|
||||
if r.RequestURI != "" {
|
||||
rawURI = r.RequestURI
|
||||
}
|
||||
|
||||
ua := ""
|
||||
referer := ""
|
||||
cookie := ""
|
||||
if r.Header != nil {
|
||||
ua = r.Header.Get("User-Agent")
|
||||
referer = r.Header.Get("Referer")
|
||||
cookie = r.Header.Get("Cookie")
|
||||
}
|
||||
|
||||
// Body: hanya POST/PUT/PATCH dan hanya bila <= 64 KB. Body yang
|
||||
// dibaca dikembalikan ke r.Body.
|
||||
body := ""
|
||||
if r.Body != nil {
|
||||
switch r.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
if r.ContentLength == 0 || r.ContentLength <= MaxInspectBodySize {
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, MaxInspectBodySize+1))
|
||||
_ = r.Body.Close()
|
||||
r.Body = io.NopCloser(bytes.NewReader(raw))
|
||||
if err == nil && len(raw) <= MaxInspectBodySize {
|
||||
body = string(raw)
|
||||
}
|
||||
} else {
|
||||
// Body terlalu besar: jangan dibaca (biarkan untuk handler).
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bentuk ter-decode dari URI/query, supaya pola seperti %2e%2e
|
||||
// dan %27 juga tertangkap setelah di-decode (selain bentuk mentahnya).
|
||||
decoded := ""
|
||||
if rawURI != "" {
|
||||
if d, err := url.QueryUnescape(rawURI); err == nil && d != rawURI {
|
||||
decoded = d
|
||||
}
|
||||
}
|
||||
|
||||
// Haystack umum: method + URL (mentah + ter-decode) + header + body.
|
||||
var sb strings.Builder
|
||||
sb.WriteString(r.Method)
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(rawURI)
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(pathQuery)
|
||||
sb.WriteString("\n")
|
||||
if decoded != "" {
|
||||
sb.WriteString(decoded)
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
if referer != "" {
|
||||
sb.WriteString(referer)
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
if cookie != "" {
|
||||
sb.WriteString(cookie)
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
if body != "" {
|
||||
sb.WriteString(body)
|
||||
}
|
||||
haystack := sb.String()
|
||||
|
||||
for _, rule := range rules {
|
||||
var target string
|
||||
switch rule.ID {
|
||||
case "SENS-01":
|
||||
// Hanya path + query — isi body/header yang menyebut
|
||||
// nama file sensitif bukan serangan.
|
||||
target = pathQuery
|
||||
if decoded != "" {
|
||||
target += "\n" + decoded
|
||||
}
|
||||
case "SCAN-01":
|
||||
// Hanya User-Agent.
|
||||
target = ua
|
||||
default:
|
||||
target = haystack
|
||||
// UA juga diperiksa aturan umum (mis. SQLi di UA),
|
||||
// jadi sertakan di haystack umum.
|
||||
if ua != "" {
|
||||
target += "\n" + ua
|
||||
}
|
||||
}
|
||||
if target == "" || rule.Pattern == nil {
|
||||
continue
|
||||
}
|
||||
loc := rule.Pattern.FindStringIndex(target)
|
||||
if loc == nil {
|
||||
continue
|
||||
}
|
||||
hit := rule
|
||||
hit.Matched = snippet(target, loc)
|
||||
matched = append(matched, hit)
|
||||
score += rule.Score
|
||||
}
|
||||
|
||||
if len(matched) == 0 {
|
||||
return nil, 0, ""
|
||||
}
|
||||
if mode == ModeBlock && score >= BlockThreshold {
|
||||
return matched, score, "diblokir"
|
||||
}
|
||||
return matched, score, "dicatat"
|
||||
}
|
||||
|
||||
// SiteFromHost mengambil nama situs dari header Host: buang port,
|
||||
// buang awalan "www.", huruf kecil. Mengembalikan "" bila host kosong.
|
||||
func SiteFromHost(host string) string {
|
||||
host = strings.TrimSpace(strings.ToLower(host))
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
host = strings.TrimSuffix(host, ".")
|
||||
host = strings.TrimPrefix(host, "www.")
|
||||
return host
|
||||
}
|
||||
|
||||
// clientIP mengambil IP dari X-Forwarded-For (bila ada) atau RemoteAddr.
|
||||
// Tidak pernah panic pada RemoteAddr yang malformed.
|
||||
func clientIP(r *http.Request) string {
|
||||
if r == nil {
|
||||
return ""
|
||||
}
|
||||
if r.Header != nil {
|
||||
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
||||
if ip := strings.TrimSpace(strings.Split(fwd, ",")[0]); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func ruleIDs(matched []Rule) string {
|
||||
ids := make([]string, 0, len(matched))
|
||||
for _, m := range matched {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
return strings.Join(ids, ",")
|
||||
}
|
||||
|
||||
// blockedPage adalah halaman 403 berbahasa Indonesia untuk request
|
||||
// yang diblokir.
|
||||
func blockedPage(matched []Rule) string {
|
||||
return `<!doctype html><html lang="id"><head><meta charset="utf-8">` +
|
||||
`<title>Akses diblokir</title></head><body>` +
|
||||
`<h1>Akses diblokir oleh WAF Hostora</h1>` +
|
||||
`<p>Request Anda ditandai sebagai berbahaya dan diblokir.</p>` +
|
||||
`<p>Rule: ` + ruleIDs(matched) + `</p>` +
|
||||
`</body></html>` + "\n"
|
||||
}
|
||||
|
||||
// Middleware memeriksa setiap request dengan Inspect memakai mode
|
||||
// dari modeForSite (lookup situs berdasarkan Host). Bila aksi
|
||||
// "diblokir", request dijawab 403 dan tidak diteruskan ke next;
|
||||
// bila tidak, next dipanggil, dan bila ada aturan yang cocok, log
|
||||
// dipanggil dengan satu entri (juga untuk request yang diblokir,
|
||||
// sebelum respons 403 dikirim — supaya blokir tercatat di log).
|
||||
//
|
||||
// Middleware tidak pernah crash pada request yang malformed: panic
|
||||
// dari Inspect/next ditangkap dan request diteruskan ke next (atau
|
||||
// dijawab 500 bila next sendiri yang panic — di sini diteruskan saja
|
||||
// dengan http.Error agar koneksi tidak menggantung).
|
||||
//
|
||||
// modeForSite atau log boleh nil: mode dianggap "off", dan tanpa
|
||||
// log tidak ada entri yang dicatat.
|
||||
func Middleware(next http.Handler, modeForSite func(r *http.Request) string, log func(LogEntry)) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
// Jangan pernah menjatuhkan server karena request aneh.
|
||||
if rec := recover(); rec != nil {
|
||||
http.Error(w, "kesalahan internal", http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
if next == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
mode := ModeOff
|
||||
if modeForSite != nil {
|
||||
// modeForSite sendiri dijaga dari panic (mis. store rusak).
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
if m := modeForSite(r); m != "" {
|
||||
mode = m
|
||||
}
|
||||
}()
|
||||
}
|
||||
if mode == ModeOff {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
matched, score, action := Inspect(r, mode)
|
||||
if len(matched) == 0 || action == "" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if log != nil {
|
||||
entry := LogEntry{
|
||||
Time: time.Now(),
|
||||
Site: SiteFromHost(r.Host),
|
||||
IP: clientIP(r),
|
||||
Score: score,
|
||||
RuleID: ruleIDs(matched),
|
||||
Matched: matched[0].Matched,
|
||||
Action: action,
|
||||
}
|
||||
func() {
|
||||
defer func() { _ = recover() }()
|
||||
log(entry)
|
||||
}()
|
||||
}
|
||||
if action == "diblokir" {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(blockedPage(matched)))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// New mengembalikan middleware WAF sebagai func(http.Handler) http.Handler,
|
||||
// siap dibungkuskan ke mux panel maupun ke handler file statis per situs:
|
||||
//
|
||||
// mux := waf.New(s.wafModeForSite, s.logWAFRequest)(mux)
|
||||
//
|
||||
// Gunakan Middleware bila pembungkusan langsung lebih jelas.
|
||||
func New(modeForSite func(r *http.Request) string, log func(LogEntry)) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return Middleware(next, modeForSite, log)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user