仰望星辰工作室

miaopanel

miaopanel/ internal/webserver/waf.go 8.9 KB · 284 行 原始文件
1package webserver
2
3import (
4 "fmt"
5 "regexp"
6 "sort"
7 "strings"
8
9 "github.com/miaopanel/miaopanel/internal/store"
10)
11
12// WAFRule is the render-time view of an operator rule.
13type WAFRule struct {
14 ID int64
15 Name string
16 MatchOn string // uri | ua | referer | method
17 Op string // contains | prefix | regex
18 Pattern string
19 Action string // block | log
20 Enabled bool
21}
22
23// WAFConfig is the global layer-1 WAF configuration rendered into nginx.
24type WAFConfig struct {
25 Enabled bool
26 BlockStatus int
27 Rate int
28 Burst int
29 ConnPerIP int
30 BadUA bool
31 BadUAExtra []string
32 Sensitive bool
33 Whitelist []string
34 Blacklist []string
35 Rules []WAFRule
36
37 // Deep inspection gateway. When enabled, nginx routes the site through a
38 // loopback origin server and the Go gateway inspects the full request.
39 Gateway bool
40 GatewayAddr string
41 GatewayStrict bool
42 GatewayThreshold int
43
44 // IP threat intelligence. The addresses are kept in IntelFile (one
45 // "address 1;" line each) and included by a geo map, so a large feed never
46 // bloats the per-site server blocks.
47 Intel bool
48 IntelFile string
49}
50
51// DefaultWAF returns the secure defaults used before settings are loaded.
52func DefaultWAF() WAFConfig {
53 return WAFConfig{
54 Enabled: true, BlockStatus: 444, Rate: 50, Burst: 200, ConnPerIP: 50,
55 BadUA: true, Sensitive: true,
56 }
57}
58
59func (w WAFConfig) normalized() WAFConfig {
60 if w.Rate <= 0 {
61 w.Rate = 50
62 }
63 if w.Burst <= 0 {
64 w.Burst = 200
65 }
66 if w.BlockStatus != 403 {
67 w.BlockStatus = 444
68 }
69 return w
70}
71
72// active reports whether the WAF applies to a site.
73func (w WAFConfig) active(s *store.Site) bool {
74 return w.Enabled && s.Options.WAF
75}
76
77var builtinBadUA = []string{
78 "sqlmap", "nikto", "nmap", "masscan", "acunetix", "nessus", "openvas",
79 "dirbuster", "gobuster", "wpscan", "zgrab", "arachni", "whatweb", "xray", "fscan",
80}
81
82// sensitivePatterns only cover artefacts that are never legitimate to serve.
83// Archive downloads, /.well-known/, WordPress login endpoints and paths that
84// merely contain "phpmyadmin" must not be blocked.
85var sensitivePatterns = []string{
86 `(^|/)\.(git|svn|hg|bzr)(/|$)`,
87 `(^|/)\.env(\.|/|$)`,
88 `(^|/)\.(DS_Store|aws)(/|$)`,
89 `/(phpmyadmin|adminer)(/|$)`,
90 `\.(sql|bak|swp|swo)$`,
91}
92
93// zonesFor builds the http level snippet (log format, maps, geo, zones).
94func zonesFor(w WAFConfig) string {
95 w = w.normalized()
96 var b strings.Builder
97 b.WriteString("# managed by MiaoPanel - http level zones\n")
98 b.WriteString(`log_format mp_main '$remote_addr - $remote_user [$time_local] "$request" '
99 '$status $body_bytes_sent "$http_referer" '
100 '"$http_user_agent" "$request_time"';` + "\n")
101
102 // Maps must be declared before the zones that consume their variables.
103 b.WriteString("map $http_upgrade $connection_upgrade {\n default upgrade;\n '' close;\n}\n")
104
105 // UA map: built-in scanners plus operator keywords.
106 // An empty User-Agent is not a reliable attack signal (health checks and
107 // some SDKs omit it), so only known scanner signatures are listed.
108 b.WriteString("map $http_user_agent $mp_bad_ua {\n default 0;\n")
109 seen := map[string]bool{}
110 for _, ua := range append(append([]string{}, builtinBadUA...), w.BadUAExtra...) {
111 ua = strings.ToLower(strings.TrimSpace(ua))
112 if ua == "" || seen[ua] || strings.ContainsAny(ua, "\"\\\n") {
113 continue
114 }
115 seen[ua] = true
116 fmt.Fprintf(&b, " ~*%s 1;\n", ua)
117 }
118 b.WriteString("}\n")
119
120 // Sensitive path map is rendered only when the feature is enabled.
121 b.WriteString("map $request_uri $mp_sensitive {\n default 0;\n")
122 if w.Sensitive {
123 for _, pattern := range sensitivePatterns {
124 fmt.Fprintf(&b, " ~*%s 1;\n", pattern)
125 }
126 }
127 b.WriteString("}\n")
128
129 // Whitelist: trusted IPs bypass built-in and custom rules, and are exempt
130 // from rate limiting because nginx ignores an empty limit key.
131 b.WriteString("geo $waf_trusted {\n default 0;\n")
132 for _, ip := range w.Whitelist {
133 if validIPRule(ip) {
134 fmt.Fprintf(&b, " %s 1;\n", ip)
135 }
136 }
137 b.WriteString("}\n")
138
139 // Static assets never consume the request budget: a single page load can
140 // legitimately issue dozens of them and would otherwise starve API calls.
141 b.WriteString("map $uri $mp_rate_key {\n default $binary_remote_addr;\n")
142 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")
143 b.WriteString("}\n")
144 b.WriteString("map $waf_trusted $waf_limit_key {\n default $mp_rate_key;\n 1 \"\";\n}\n")
145
146 if w.Intel && w.IntelFile != "" {
147 fmt.Fprintf(&b, "geo $waf_intel {\n default 0;\n include \"%s\";\n}\n", nginxPath(w.IntelFile))
148 b.WriteString("map \"$waf_trusted$waf_intel\" $mp_intel_block {\n default 0;\n \"01\" 1;\n}\n")
149 }
150
151 // nginx rejects concatenated variables inside `if`, so the trusted flag is
152 // folded into a map key instead.
153 b.WriteString("map \"$waf_trusted$mp_bad_ua\" $mp_ua_block {\n default 0;\n \"01\" 1;\n}\n")
154 b.WriteString("map \"$waf_trusted$mp_sensitive\" $mp_sensitive_block {\n default 0;\n \"01\" 1;\n}\n")
155
156 // One map per custom rule keeps the server block free of variable maths.
157 for _, rule := range w.Rules {
158 if !rule.Enabled {
159 continue
160 }
161 name, key, regex, ok := ruleMap(rule)
162 if !ok {
163 continue
164 }
165 fmt.Fprintf(&b, "map \"$waf_trusted%s\" $%s {\n default 0;\n %s 1;\n}\n", key, name, regex)
166 }
167
168 // mp_req is kept for configurations rendered before the WAF module
169 // existed; changing a shared zone key in place is rejected by nginx on
170 // reload, so new fragments use the separate mp_waf zone.
171 fmt.Fprintf(&b, "limit_req_zone $binary_remote_addr zone=mp_req:20m rate=%dr/s;\n", w.Rate)
172 fmt.Fprintf(&b, "limit_req_zone $waf_limit_key zone=mp_waf:20m rate=%dr/s;\n", w.Rate)
173 // 429 makes throttling distinguishable from an upstream failure.
174 b.WriteString("limit_req_status 429;\nlimit_conn_status 429;\n")
175 b.WriteString("limit_conn_zone $binary_remote_addr zone=mp_conn:20m;\n")
176 b.WriteString("limit_conn_zone $server_name zone=mp_srv:10m;\n")
177 return b.String()
178}
179
180// wafFragment renders the per-site server block snippet.
181func wafFragment(s *store.Site, w WAFConfig) string {
182 w = w.normalized()
183 var b strings.Builder
184 b.WriteString("# layer 1 waf (managed by MiaoPanel)\n")
185 if w.Rate > 0 {
186 fmt.Fprintf(&b, "limit_req zone=mp_waf burst=%d nodelay;\n", w.Burst)
187 }
188 if w.ConnPerIP > 0 {
189 fmt.Fprintf(&b, "limit_conn mp_conn %d;\n", w.ConnPerIP)
190 }
191 if w.BadUA {
192 fmt.Fprintf(&b, "if ($mp_ua_block) { return %d; }\n", w.BlockStatus)
193 }
194 if w.Sensitive {
195 b.WriteString("if ($mp_sensitive_block) { return 404; }\n")
196 }
197 if w.Intel && w.IntelFile != "" {
198 fmt.Fprintf(&b, "if ($mp_intel_block) { return %d; }\n", w.BlockStatus)
199 }
200 for _, ip := range w.Blacklist {
201 if validIPRule(ip) {
202 fmt.Fprintf(&b, "deny %s;\n", ip)
203 }
204 }
205 for _, rule := range w.Rules {
206 if !rule.Enabled {
207 continue
208 }
209 if name, _, _, ok := ruleMap(rule); ok {
210 fmt.Fprintf(&b, "if ($%s) { return %d; }\n", name, w.BlockStatus)
211 }
212 }
213 return b.String()
214}
215
216// ruleMap returns the map name, matched variable and regex for a rule.
217func ruleMap(r WAFRule) (name, variable, regex string, ok bool) {
218 pattern := strings.TrimSpace(r.Pattern)
219 if pattern == "" || len(pattern) > 512 {
220 return "", "", "", false
221 }
222 // Never sanitise silently: a pattern that could break out of the quoted
223 // nginx string is rejected by both the API and the renderer.
224 if strings.ContainsAny(pattern, "\"\\\n\r;{}") {
225 return "", "", "", false
226 }
227 if r.Action != "block" {
228 return "", "", "", false
229 }
230 switch r.MatchOn {
231 case "uri":
232 variable = "$request_uri"
233 case "ua":
234 variable = "$http_user_agent"
235 case "referer":
236 variable = "$http_referer"
237 case "method":
238 variable = "$request_method"
239 default:
240 return "", "", "", false
241 }
242 switch r.Op {
243 case "prefix":
244 regex = "~*^0" + regexp.QuoteMeta(pattern)
245 case "regex":
246 // Rules are matched case insensitively; strip inline flags and the
247 // leading anchor before prepending the trusted flag.
248 pattern = strings.TrimPrefix(pattern, "(?i)")
249 pattern = strings.TrimPrefix(pattern, "^")
250 regex = "~*^0(?:" + pattern + ")"
251 default: // contains
252 regex = "~*^0.*" + regexp.QuoteMeta(pattern)
253 }
254 return fmt.Sprintf("mp_rule_%d", r.ID), variable, regex, true
255}
256
257// nginxPath normalises separators so the include works regardless of the host
258// platform the configuration was rendered on.
259func nginxPath(p string) string {
260 return strings.ReplaceAll(strings.ReplaceAll(p, "\\", "/"), "\"", "")
261}
262
263func validIPRule(s string) bool {
264 s = strings.TrimSpace(s)
265 if s == "" || len(s) > 64 {
266 return false
267 }
268 for _, r := range s {
269 switch {
270 case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F',
271 r == '.', r == ':', r == '/':
272 default:
273 return false
274 }
275 }
276 return true
277}
278
279// sortedRules keeps rendering deterministic in tests.
280func sortedRules(rules []WAFRule) []WAFRule {
281 out := append([]WAFRule{}, rules...)
282 sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
283 return out
284}