package webserver import ( "fmt" "regexp" "sort" "strings" "github.com/miaopanel/miaopanel/internal/store" ) // WAFRule is the render-time view of an operator rule. type WAFRule struct { ID int64 Name string MatchOn string // uri | ua | referer | method Op string // contains | prefix | regex Pattern string Action string // block | log Enabled bool } // WAFConfig is the global layer-1 WAF configuration rendered into nginx. type WAFConfig struct { Enabled bool BlockStatus int Rate int Burst int ConnPerIP int BadUA bool BadUAExtra []string Sensitive bool Whitelist []string Blacklist []string Rules []WAFRule // Deep inspection gateway. When enabled, nginx routes the site through a // loopback origin server and the Go gateway inspects the full request. Gateway bool GatewayAddr string GatewayStrict bool GatewayThreshold int // IP threat intelligence. The addresses are kept in IntelFile (one // "address 1;" line each) and included by a geo map, so a large feed never // bloats the per-site server blocks. Intel bool IntelFile string } // DefaultWAF returns the secure defaults used before settings are loaded. func DefaultWAF() WAFConfig { return WAFConfig{ Enabled: true, BlockStatus: 444, Rate: 50, Burst: 200, ConnPerIP: 50, BadUA: true, Sensitive: true, } } func (w WAFConfig) normalized() WAFConfig { if w.Rate <= 0 { w.Rate = 50 } if w.Burst <= 0 { w.Burst = 200 } if w.BlockStatus != 403 { w.BlockStatus = 444 } return w } // active reports whether the WAF applies to a site. func (w WAFConfig) active(s *store.Site) bool { return w.Enabled && s.Options.WAF } var builtinBadUA = []string{ "sqlmap", "nikto", "nmap", "masscan", "acunetix", "nessus", "openvas", "dirbuster", "gobuster", "wpscan", "zgrab", "arachni", "whatweb", "xray", "fscan", } // sensitivePatterns only cover artefacts that are never legitimate to serve. // Archive downloads, /.well-known/, WordPress login endpoints and paths that // merely contain "phpmyadmin" must not be blocked. var sensitivePatterns = []string{ `(^|/)\.(git|svn|hg|bzr)(/|$)`, `(^|/)\.env(\.|/|$)`, `(^|/)\.(DS_Store|aws)(/|$)`, `/(phpmyadmin|adminer)(/|$)`, `\.(sql|bak|swp|swo)$`, } // zonesFor builds the http level snippet (log format, maps, geo, zones). func zonesFor(w WAFConfig) string { w = w.normalized() var b strings.Builder b.WriteString("# managed by MiaoPanel - http level zones\n") b.WriteString(`log_format mp_main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$request_time"';` + "\n") // Maps must be declared before the zones that consume their variables. b.WriteString("map $http_upgrade $connection_upgrade {\n default upgrade;\n '' close;\n}\n") // UA map: built-in scanners plus operator keywords. // An empty User-Agent is not a reliable attack signal (health checks and // some SDKs omit it), so only known scanner signatures are listed. b.WriteString("map $http_user_agent $mp_bad_ua {\n default 0;\n") seen := map[string]bool{} for _, ua := range append(append([]string{}, builtinBadUA...), w.BadUAExtra...) { ua = strings.ToLower(strings.TrimSpace(ua)) if ua == "" || seen[ua] || strings.ContainsAny(ua, "\"\\\n") { continue } seen[ua] = true fmt.Fprintf(&b, " ~*%s 1;\n", ua) } b.WriteString("}\n") // Sensitive path map is rendered only when the feature is enabled. b.WriteString("map $request_uri $mp_sensitive {\n default 0;\n") if w.Sensitive { for _, pattern := range sensitivePatterns { fmt.Fprintf(&b, " ~*%s 1;\n", pattern) } } b.WriteString("}\n") // Whitelist: trusted IPs bypass built-in and custom rules, and are exempt // from rate limiting because nginx ignores an empty limit key. b.WriteString("geo $waf_trusted {\n default 0;\n") for _, ip := range w.Whitelist { if validIPRule(ip) { fmt.Fprintf(&b, " %s 1;\n", ip) } } b.WriteString("}\n") // Static assets never consume the request budget: a single page load can // legitimately issue dozens of them and would otherwise starve API calls. b.WriteString("map $uri $mp_rate_key {\n default $binary_remote_addr;\n") b.WriteString(` ~*\.(css|js|mjs|map|png|jpe?g|gif|svg|webp|ico|woff2?|ttf|otf|eot|mp4|webm|mp3|pdf|txt|xml|json)$ "";` + "\n") b.WriteString("}\n") b.WriteString("map $waf_trusted $waf_limit_key {\n default $mp_rate_key;\n 1 \"\";\n}\n") if w.Intel && w.IntelFile != "" { fmt.Fprintf(&b, "geo $waf_intel {\n default 0;\n include \"%s\";\n}\n", nginxPath(w.IntelFile)) b.WriteString("map \"$waf_trusted$waf_intel\" $mp_intel_block {\n default 0;\n \"01\" 1;\n}\n") } // nginx rejects concatenated variables inside `if`, so the trusted flag is // folded into a map key instead. b.WriteString("map \"$waf_trusted$mp_bad_ua\" $mp_ua_block {\n default 0;\n \"01\" 1;\n}\n") b.WriteString("map \"$waf_trusted$mp_sensitive\" $mp_sensitive_block {\n default 0;\n \"01\" 1;\n}\n") // One map per custom rule keeps the server block free of variable maths. for _, rule := range w.Rules { if !rule.Enabled { continue } name, key, regex, ok := ruleMap(rule) if !ok { continue } fmt.Fprintf(&b, "map \"$waf_trusted%s\" $%s {\n default 0;\n %s 1;\n}\n", key, name, regex) } // mp_req is kept for configurations rendered before the WAF module // existed; changing a shared zone key in place is rejected by nginx on // reload, so new fragments use the separate mp_waf zone. fmt.Fprintf(&b, "limit_req_zone $binary_remote_addr zone=mp_req:20m rate=%dr/s;\n", w.Rate) fmt.Fprintf(&b, "limit_req_zone $waf_limit_key zone=mp_waf:20m rate=%dr/s;\n", w.Rate) // 429 makes throttling distinguishable from an upstream failure. b.WriteString("limit_req_status 429;\nlimit_conn_status 429;\n") b.WriteString("limit_conn_zone $binary_remote_addr zone=mp_conn:20m;\n") b.WriteString("limit_conn_zone $server_name zone=mp_srv:10m;\n") return b.String() } // wafFragment renders the per-site server block snippet. func wafFragment(s *store.Site, w WAFConfig) string { w = w.normalized() var b strings.Builder b.WriteString("# layer 1 waf (managed by MiaoPanel)\n") if w.Rate > 0 { fmt.Fprintf(&b, "limit_req zone=mp_waf burst=%d nodelay;\n", w.Burst) } if w.ConnPerIP > 0 { fmt.Fprintf(&b, "limit_conn mp_conn %d;\n", w.ConnPerIP) } if w.BadUA { fmt.Fprintf(&b, "if ($mp_ua_block) { return %d; }\n", w.BlockStatus) } if w.Sensitive { b.WriteString("if ($mp_sensitive_block) { return 404; }\n") } if w.Intel && w.IntelFile != "" { fmt.Fprintf(&b, "if ($mp_intel_block) { return %d; }\n", w.BlockStatus) } for _, ip := range w.Blacklist { if validIPRule(ip) { fmt.Fprintf(&b, "deny %s;\n", ip) } } for _, rule := range w.Rules { if !rule.Enabled { continue } if name, _, _, ok := ruleMap(rule); ok { fmt.Fprintf(&b, "if ($%s) { return %d; }\n", name, w.BlockStatus) } } return b.String() } // ruleMap returns the map name, matched variable and regex for a rule. func ruleMap(r WAFRule) (name, variable, regex string, ok bool) { pattern := strings.TrimSpace(r.Pattern) if pattern == "" || len(pattern) > 512 { return "", "", "", false } // Never sanitise silently: a pattern that could break out of the quoted // nginx string is rejected by both the API and the renderer. if strings.ContainsAny(pattern, "\"\\\n\r;{}") { return "", "", "", false } if r.Action != "block" { return "", "", "", false } switch r.MatchOn { case "uri": variable = "$request_uri" case "ua": variable = "$http_user_agent" case "referer": variable = "$http_referer" case "method": variable = "$request_method" default: return "", "", "", false } switch r.Op { case "prefix": regex = "~*^0" + regexp.QuoteMeta(pattern) case "regex": // Rules are matched case insensitively; strip inline flags and the // leading anchor before prepending the trusted flag. pattern = strings.TrimPrefix(pattern, "(?i)") pattern = strings.TrimPrefix(pattern, "^") regex = "~*^0(?:" + pattern + ")" default: // contains regex = "~*^0.*" + regexp.QuoteMeta(pattern) } return fmt.Sprintf("mp_rule_%d", r.ID), variable, regex, true } // nginxPath normalises separators so the include works regardless of the host // platform the configuration was rendered on. func nginxPath(p string) string { return strings.ReplaceAll(strings.ReplaceAll(p, "\\", "/"), "\"", "") } func validIPRule(s string) bool { s = strings.TrimSpace(s) if s == "" || len(s) > 64 { return false } for _, r := range s { switch { case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F', r == '.', r == ':', r == '/': default: return false } } return true } // sortedRules keeps rendering deterministic in tests. func sortedRules(rules []WAFRule) []WAFRule { out := append([]WAFRule{}, rules...) sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out }