miaopanel
1// Package wafengine implements the request level detection used by the
2// reverse proxy gateway. It is deliberately dependency free (standard library
3// only) so it can be unit tested without nginx, SQLite or a network.
4//
5// The design follows the layered approach used by SafeLine/雷池:
6//
7// 1. decode the input several times (URL, HTML entity, unicode escape, SQL
8// comments) so obfuscated payloads are compared after normalisation;
9// 2. run independent detectors per attack class;
10// 3. score every hit and block only when the strongest hit (plus a small
11// bonus for corroborating hits) reaches the configured threshold.
12//
13// Scoring keeps false positives low: a lone "onclick=" or "order by" is
14// logged but not blocked, while "union ... select" or "<script" is fatal on
15// its own.
16package wafengine
17
18import (
19 "bytes"
20 "encoding/json"
21 "mime"
22 "mime/multipart"
23 "net"
24 "net/url"
25 "regexp"
26 "strconv"
27 "strings"
28)
29
30// DefaultThreshold is the score required to block in normal mode. Strict mode
31// halves it. A critical rule (score >= 10) always blocks on its own.
32const DefaultThreshold = 8
33
34// MaxBodyScan limits how much of a request body is inspected. Larger bodies
35// are streamed by the gateway after a cheap literal pre-scan.
36const MaxBodyScan = 256 << 10
37
38// Request is the subset of an HTTP request the engine needs.
39type Request struct {
40 Method string
41 Path string
42 RawQuery string
43 ContentType string
44 RemoteIP string
45 Header map[string][]string
46 Cookies map[string]string
47 Body []byte
48}
49
50// Hit is one detector match.
51type Hit struct {
52 Module string `json:"module"`
53 Rule string `json:"rule"`
54 Score int `json:"score"`
55 Location string `json:"location"`
56 Evidence string `json:"evidence"`
57}
58
59// Result is the verdict for one request.
60type Result struct {
61 Score int `json:"score"`
62 Hits []Hit `json:"hits"`
63 Blocked bool `json:"blocked"`
64}
65
66// CustomRule mirrors the operator rules stored in waf_rules so the gateway can
67// enforce them even for parts of the request nginx cannot see (body).
68type CustomRule struct {
69 Name string
70 MatchOn string // uri | ua | referer | method
71 Op string // contains | prefix | regex
72 Pattern string
73 Enabled bool
74}
75
76// Config is the runtime policy snapshot.
77type Config struct {
78 Strict bool
79 Threshold int
80 Whitelist []string
81 Custom []CustomRule
82}
83
84func (c Config) threshold() int {
85 t := c.Threshold
86 if t <= 0 {
87 t = DefaultThreshold
88 }
89 if c.Strict && t > 4 {
90 t = 4
91 }
92 return t
93}
94
95type target struct {
96 location string
97 value string
98}
99
100// Inspect evaluates one request.
101func Inspect(req *Request, cfg Config) Result {
102 if req == nil {
103 return Result{}
104 }
105 if trustedIP(req.RemoteIP, cfg.Whitelist) {
106 return Result{}
107 }
108
109 var hits []Hit
110 seen := map[string]bool{}
111 add := func(h Hit) {
112 if h.Score <= 0 {
113 return
114 }
115 key := h.Module + "|" + h.Rule
116 if seen[key] {
117 return
118 }
119 seen[key] = true
120 if len(h.Evidence) > 180 {
121 h.Evidence = h.Evidence[:180]
122 }
123 hits = append(hits, h)
124 }
125
126 for _, t := range requestTargets(req) {
127 scanTarget(t, add)
128 }
129 for _, t := range bodyTargets(req) {
130 scanTarget(t, add)
131 }
132 scanCustom(req, cfg.Custom, add)
133
134 if len(hits) == 0 {
135 return Result{}
136 }
137 best := 0
138 modules := map[string]bool{}
139 for _, h := range hits {
140 if h.Score > best {
141 best = h.Score
142 }
143 modules[h.Module] = true
144 }
145 bonus := len(modules) - 1
146 if bonus > 3 {
147 bonus = 3
148 }
149 score := best + bonus
150 return Result{Score: score, Hits: hits, Blocked: score >= cfg.threshold()}
151}
152
153func requestTargets(req *Request) []target {
154 out := []target{
155 {"path", req.Path},
156 {"query", req.RawQuery},
157 {"method", req.Method},
158 }
159 addHeader := func(name string) {
160 for _, v := range req.Header[name] {
161 if strings.TrimSpace(v) != "" {
162 out = append(out, target{"header:" + strings.ToLower(name), v})
163 }
164 }
165 }
166 addHeader("User-Agent")
167 addHeader("Referer")
168 addHeader("X-Forwarded-For")
169 addHeader("X-Real-IP")
170 addHeader("Content-Type")
171 for name, values := range req.Header {
172 // Cookies are attacker controlled; the rest of the headers mostly are
173 // not, so only a few interesting ones are inspected above.
174 if strings.EqualFold(name, "Cookie") {
175 for _, v := range values {
176 out = append(out, target{"header:cookie", v})
177 }
178 }
179 }
180 for name, value := range req.Cookies {
181 out = append(out, target{"cookie:" + name, value})
182 }
183 if values, err := url.ParseQuery(req.RawQuery); err == nil {
184 for name, list := range values {
185 for _, value := range list {
186 out = append(out, target{"query:" + name, value})
187 }
188 }
189 }
190 return out
191}
192
193func bodyTargets(req *Request) []target {
194 body := req.Body
195 if len(body) == 0 {
196 return nil
197 }
198 truncated := false
199 if len(body) > MaxBodyScan {
200 body = body[:MaxBodyScan]
201 truncated = true
202 }
203 mediaType, params, _ := mime.ParseMediaType(req.ContentType)
204 var out []target
205 add := func(location, value string) {
206 if strings.TrimSpace(value) != "" {
207 out = append(out, target{location, value})
208 }
209 }
210 switch {
211 case mediaType == "application/x-www-form-urlencoded":
212 if values, err := url.ParseQuery(string(body)); err == nil {
213 for k, list := range values {
214 add("body:"+k, k)
215 for _, v := range list {
216 add("body:"+k, v)
217 }
218 }
219 }
220 case strings.HasPrefix(mediaType, "multipart/"):
221 out = append(out, multipartTargets(body, params["boundary"])...)
222 case mediaType == "application/json" || strings.HasSuffix(mediaType, "+json"):
223 add("body:json", string(body))
224 // JSON may encode the payload as \u003c etc; decodeUnicode is part of
225 // the variant pipeline, so the raw text is enough here.
226 if truncated {
227 add("body:json-tail", string(req.Body[len(req.Body)-min(len(req.Body), 32<<10):]))
228 }
229 default:
230 add("body", string(body))
231 }
232 return out
233}
234
235func multipartTargets(body []byte, boundary string) []target {
236 if boundary == "" {
237 return []target{{"body:multipart", string(body)}}
238 }
239 reader := multipart.NewReader(bytes.NewReader(body), boundary)
240 var out []target
241 for i := 0; i < 64; i++ {
242 part, err := reader.NextPart()
243 if err != nil {
244 break
245 }
246 name := part.FormName()
247 filename := part.FileName()
248 if filename != "" {
249 out = append(out, target{"upload:filename", filename})
250 head := make([]byte, 4096)
251 n, _ := part.Read(head)
252 if n > 0 {
253 out = append(out, target{"upload:content", string(head[:n])})
254 }
255 _ = part.Close()
256 continue
257 }
258 buf := make([]byte, 64<<10)
259 n, _ := part.Read(buf)
260 if n > 0 {
261 out = append(out, target{"body:" + name, string(buf[:n])})
262 }
263 _ = part.Close()
264 }
265 return out
266}
267
268// scanTarget runs every detector over the decoded variants of one value.
269func scanTarget(t target, add func(Hit)) {
270 // Uploaded file bodies are only checked for embedded server-side code.
271 // Running the full rule set over them flags legitimate source/archive
272 // uploads (the README of this very repository contains backticks).
273 if strings.HasPrefix(t.location, "upload:content") {
274 if m := rePHPTag.FindString(t.value); m != "" {
275 add(Hit{Module: "upload", Rule: "embedded_code", Score: 10, Location: t.location, Evidence: m})
276 }
277 return
278 }
279 for _, v := range variants(t.value) {
280 if v == "" {
281 continue
282 }
283 detectSQLi(v, t.location, add)
284 detectXSS(v, t.location, add)
285 detectRCE(v, t.location, add)
286 detectLFI(v, t.location, add)
287 detectPHP(v, t.location, add)
288 detectJava(v, t.location, add)
289 detectXXE(v, t.location, add)
290 detectSSTI(v, t.location, add)
291 detectProtocol(v, t.location, add)
292 }
293 lower := strings.ToLower(t.value)
294 detectScanner(lower, t.location, add)
295 detectUpload(t, add)
296}
297
298func scanCustom(req *Request, rules []CustomRule, add func(Hit)) {
299 for _, rule := range rules {
300 if !rule.Enabled || rule.Pattern == "" {
301 continue
302 }
303 var values []string
304 switch rule.MatchOn {
305 case "uri":
306 values = []string{req.Path, req.RawQuery}
307 case "ua":
308 values = req.Header["User-Agent"]
309 case "referer":
310 values = req.Header["Referer"]
311 case "method":
312 values = []string{req.Method}
313 default:
314 continue
315 }
316 for _, value := range values {
317 if matchCustom(rule, value) {
318 add(Hit{Module: "custom", Rule: rule.Name, Score: 10,
319 Location: rule.MatchOn, Evidence: value})
320 break
321 }
322 }
323 }
324}
325
326func matchCustom(rule CustomRule, value string) bool {
327 switch rule.Op {
328 case "prefix":
329 return strings.HasPrefix(strings.ToLower(value), strings.ToLower(rule.Pattern))
330 case "regex":
331 re, err := regexp.Compile("(?i)" + rule.Pattern)
332 return err == nil && re.MatchString(value)
333 default:
334 return strings.Contains(strings.ToLower(value), strings.ToLower(rule.Pattern))
335 }
336}
337
338// --- decoding / normalisation ---------------------------------------------
339
340var (
341 reUnicodeEscape = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`)
342 rePercentU = regexp.MustCompile(`(?i)%u([0-9a-f]{4})`)
343 reSQLBlock = regexp.MustCompile(`(?s)/\*.*?\*/`)
344 reSQLDash = regexp.MustCompile(`(?m)--[^\n]*`)
345 reSpaces = regexp.MustCompile(`\s+`)
346)
347
348// variants returns the representations a detector should look at. The list is
349// bounded so a malicious input cannot force unbounded decoding work.
350func variants(s string) []string {
351 if len(s) > 1<<20 {
352 s = s[:1<<20]
353 }
354 out := make([]string, 0, 10)
355 seen := map[string]bool{}
356 add := func(v string) {
357 if v == "" || seen[v] || len(out) >= 10 {
358 return
359 }
360 seen[v] = true
361 out = append(out, v)
362 }
363
364 add(s)
365 cur := s
366 for i := 0; i < 3; i++ {
367 next, err := url.QueryUnescape(cur)
368 if err != nil || next == cur {
369 break
370 }
371 add(next)
372 cur = next
373 }
374 s = cur
375 add(htmlUnescape(s))
376 add(decodeUnicode(s))
377 add(decodePercentU(s))
378 add(unescapeJSON(s))
379 base := append([]string(nil), out...)
380 for _, v := range base {
381 add(strings.ToLower(v))
382 }
383 for _, v := range base {
384 add(stripSQLComments(v))
385 }
386 for _, v := range append([]string(nil), out...) {
387 if strings.Contains(v, " ") || strings.Contains(v, "\t") {
388 add(reSpaces.ReplaceAllString(v, " "))
389 }
390 }
391 return out
392}
393
394func htmlUnescape(s string) string {
395 // net/html is avoided on purpose: it live-parses and can be slow on
396 // garbage. A small replacement table covers the payloads that matter.
397 replacer := strings.NewReplacer(
398 "<", "<", ">", ">", """, `"`, "'", "'", "'", "'",
399 "<", "<", ">", ">", "&", "&",
400 )
401 return replacer.Replace(s)
402}
403
404func decodeUnicode(s string) string {
405 if !strings.Contains(s, `\u`) {
406 return s
407 }
408 return reUnicodeEscape.ReplaceAllStringFunc(s, func(m string) string {
409 n, err := strconv.ParseUint(m[2:], 16, 32)
410 if err != nil || n == 0 {
411 return m
412 }
413 return string(rune(n))
414 })
415}
416
417// unescapeJSON turns the escaped quotes of a JSON string into their literal
418// form so SQL/XSS rules see the payload the application will decode.
419func unescapeJSON(s string) string {
420 if !strings.Contains(s, `\"`) && !strings.Contains(s, `\/`) {
421 return s
422 }
423 return strings.NewReplacer(`\"`, `"`, `\/`, `/`, `\\`, `\`).Replace(s)
424}
425
426func decodePercentU(s string) string {
427 if !strings.Contains(strings.ToLower(s), "%u") {
428 return s
429 }
430 return rePercentU.ReplaceAllStringFunc(s, func(m string) string {
431 n, err := strconv.ParseUint(m[2:], 16, 32)
432 if err != nil || n == 0 {
433 return m
434 }
435 return string(rune(n))
436 })
437}
438
439func stripSQLComments(s string) string {
440 if !strings.Contains(s, "/*") && !strings.Contains(s, "--") {
441 return s
442 }
443 s = reSQLBlock.ReplaceAllString(s, "")
444 s = reSQLDash.ReplaceAllString(s, " ")
445 return s
446}
447
448// --- SQL injection ---------------------------------------------------------
449
450var (
451 reUnionSelect = regexp.MustCompile(`(?i)\bunion\b\s+(?:all\s+)?\bselect\b`)
452 reSQLTime = regexp.MustCompile(`(?i)\b(?:sleep|benchmark|pg_sleep|waitfor\s+delay|dbms_lock\.sleep|dbms_pipe\.receive_message)\s*\(`)
453 reSQLMeta = regexp.MustCompile(`(?i)\b(?:information_schema|sysobjects|syscolumns|mysql\.user|pg_catalog|all_tables|sqlite_master)\b`)
454 reSQLFile = regexp.MustCompile(`(?i)\b(?:load_file|into\s+(?:out|dump)file|xp_cmdshell|sp_executesql|openrowset)\b`)
455 reSQLStacked = regexp.MustCompile(`(?i);\s*(?:select|insert|update|delete|drop|alter|create|truncate|exec|execute|call|declare)\b`)
456 reSQLQuoteCmt = regexp.MustCompile(`(?i)['"]\s*(?:--|#|/\*)`)
457 reSQLBoolNum = regexp.MustCompile(`(?i)\b(?:or|and)\b\s+\d{1,6}\s*=\s*\d{1,6}\b`)
458 reSQLBoolStr = regexp.MustCompile(`(?i)\b(?:or|and)\b\s+['"][^'"]{0,40}['"]\s*=\s*['"][^'"]{0,40}['"]`)
459 reSQLQuoteOr = regexp.MustCompile(`(?i)['"]\s*(?:or|and)\b\s*['"]?[0-9a-z_]{1,30}['"]?\s*=\s*['"]?[0-9a-z_]{1,30}['"]?`)
460 reSQLHex = regexp.MustCompile(`(?i)\b0x[0-9a-f]{8,}\b`)
461 reSQLFunc = regexp.MustCompile(`(?i)\b(?:extractvalue|updatexml|group_concat|concat_ws|char|ascii|substr|mid|length|database|version|user)\s*\(`)
462 reSQLOrder = regexp.MustCompile(`(?i)\b(?:order|group)\s+by\s+\d{1,4}\b`)
463 reSQLComment = regexp.MustCompile(`(?i)(?:/\*!?\d*|#\s*$|--\s)`)
464)
465
466func detectSQLi(v, loc string, add func(Hit)) {
467 rules := []struct {
468 id string
469 re *regexp.Regexp
470 scr int
471 cond func(string) bool
472 }{
473 {"union_select", reUnionSelect, 10, nil},
474 {"time_based", reSQLTime, 12, nil},
475 {"metadata", reSQLMeta, 9, nil},
476 {"file_access", reSQLFile, 12, nil},
477 {"stacked_query", reSQLStacked, 10, nil},
478 {"quote_comment", reSQLQuoteCmt, 9, nil},
479 {"tautology_numeric", reSQLBoolNum, 8, nil},
480 {"tautology_string", reSQLBoolStr, 9, nil},
481 {"tautology_quoted", reSQLQuoteOr, 9, nil},
482 {"hex_literal", reSQLHex, 4, nil},
483 {"function_probe", reSQLFunc, 5, func(s string) bool {
484 return strings.Contains(s, "select") || strings.Contains(s, "from") ||
485 strings.Contains(s, "'") || strings.Contains(s, `"`)
486 }},
487 {"order_by", reSQLOrder, 4, nil},
488 {"comment", reSQLComment, 4, nil},
489 }
490 for _, r := range rules {
491 m := r.re.FindString(v)
492 if m == "" {
493 continue
494 }
495 if r.cond != nil && !r.cond(strings.ToLower(v)) {
496 continue
497 }
498 add(Hit{Module: "sqli", Rule: r.id, Score: r.scr, Location: loc, Evidence: m})
499 }
500}
501
502// --- XSS -------------------------------------------------------------------
503
504var (
505 reXSSScript = regexp.MustCompile(`(?i)<\s*script\b`)
506 reXSSUri = regexp.MustCompile(`(?i)\b(?:javascript|vbscript)\s*:`)
507 reXSSData = regexp.MustCompile(`(?i)data\s*:\s*text/html`)
508 reXSSHandler = regexp.MustCompile(`(?i)\bon(?:error|load|click|dblclick|mouse\w+|focus|blur|submit|change|input|key\w+|touch\w+|pointer\w+|drag\w+|animation\w+|transition\w+|toggle|wheel|scroll|contextmenu|copy|paste|cut|play|pause|ended|canplay|loaded\w+|abort|resize|select|invalid|search|show|before\w+)\s*=`)
509 reXSSCombined = regexp.MustCompile(`(?i)<\s*(?:svg|img|body|iframe|details|marquee|object|embed|video|audio)[^>]{0,120}\bon\w+\s*=`)
510 reXSSTag = regexp.MustCompile(`(?i)<\s*(?:iframe|object|embed|svg|link|style|meta|base)\b`)
511 reXSSDOM = regexp.MustCompile(`(?i)\b(?:document\.(?:cookie|domain|write)|window\.(?:location|name)|eval|alert|prompt|confirm)\s*\(`)
512 reXSSExpr = regexp.MustCompile(`(?i)\bexpression\s*\(`)
513 reXSSImg = regexp.MustCompile(`(?i)<\s*img\b`)
514)
515
516func detectXSS(v, loc string, add func(Hit)) {
517 if m := reXSSScript.FindString(v); m != "" {
518 add(Hit{Module: "xss", Rule: "script_tag", Score: 10, Location: loc, Evidence: m})
519 }
520 if m := reXSSCombined.FindString(v); m != "" {
521 add(Hit{Module: "xss", Rule: "handler_in_tag", Score: 10, Location: loc, Evidence: m})
522 }
523 if m := reXSSUri.FindString(v); m != "" {
524 add(Hit{Module: "xss", Rule: "js_uri", Score: 8, Location: loc, Evidence: m})
525 }
526 if m := reXSSData.FindString(v); m != "" {
527 add(Hit{Module: "xss", Rule: "data_uri", Score: 8, Location: loc, Evidence: m})
528 }
529 if m := reXSSHandler.FindString(v); m != "" {
530 score := 6
531 if strings.Contains(v, "<") {
532 score = 8
533 }
534 add(Hit{Module: "xss", Rule: "event_handler", Score: score, Location: loc, Evidence: m})
535 }
536 if m := reXSSTag.FindString(v); m != "" {
537 add(Hit{Module: "xss", Rule: "dangerous_tag", Score: 7, Location: loc, Evidence: m})
538 }
539 if m := reXSSImg.FindString(v); m != "" {
540 add(Hit{Module: "xss", Rule: "img_tag", Score: 4, Location: loc, Evidence: m})
541 }
542 if m := reXSSDOM.FindString(v); m != "" {
543 add(Hit{Module: "xss", Rule: "dom_sink", Score: 6, Location: loc, Evidence: m})
544 }
545 if m := reXSSExpr.FindString(v); m != "" {
546 add(Hit{Module: "xss", Rule: "css_expression", Score: 7, Location: loc, Evidence: m})
547 }
548}
549
550// --- command / code injection ---------------------------------------------
551
552var (
553 reShellMeta = regexp.MustCompile(`(?i)[;&|]\s*(?:cat|ls|id|whoami|uname|wget|curl|bash|sh|nc|ncat|python[0-9.]*|perl|ruby|powershell|pwsh|cmd|chmod|chown|rm|mv|cp|echo|touch|kill|ps)\b`)
554 reSubshell = regexp.MustCompile(`\$\([^)]{1,200}\)`)
555 reBacktick = regexp.MustCompile("`[^`]{1,200}`")
556 rePipeExec = regexp.MustCompile(`(?i)\|\|\s*(?:curl|wget|bash|sh|nc|ncat|python|perl)\b`)
557 reLog4j = regexp.MustCompile(`(?i)\$\{jndi:(?:ldap|rmi|dns|http|https|iiop|corba)`)
558 reNcExec = regexp.MustCompile(`(?i)(?:^|\s)(?:nc|ncat|netcat)\s+-[a-z]*e\s`)
559 rePwshEnc = regexp.MustCompile(`(?i)powershell(?:\.exe)?\s+(?:-\w+\s+)*-enc(?:odedcommand)?\b`)
560)
561
562func detectRCE(v, loc string, add func(Hit)) {
563 if m := reLog4j.FindString(v); m != "" {
564 add(Hit{Module: "rce", Rule: "log4j_jndi", Score: 12, Location: loc, Evidence: m})
565 }
566 if m := reShellMeta.FindString(v); m != "" {
567 add(Hit{Module: "rce", Rule: "shell_meta", Score: 9, Location: loc, Evidence: m})
568 }
569 if m := rePipeExec.FindString(v); m != "" {
570 add(Hit{Module: "rce", Rule: "pipe_exec", Score: 10, Location: loc, Evidence: m})
571 }
572 if m := reSubshell.FindString(v); m != "" {
573 add(Hit{Module: "rce", Rule: "subshell", Score: 7, Location: loc, Evidence: m})
574 }
575 if m := reBacktick.FindString(v); m != "" {
576 add(Hit{Module: "rce", Rule: "backtick", Score: 7, Location: loc, Evidence: m})
577 }
578 if m := reNcExec.FindString(v); m != "" {
579 add(Hit{Module: "rce", Rule: "reverse_shell", Score: 10, Location: loc, Evidence: m})
580 }
581 if m := rePwshEnc.FindString(v); m != "" {
582 add(Hit{Module: "rce", Rule: "powershell_encoded", Score: 10, Location: loc, Evidence: m})
583 }
584}
585
586// --- path traversal / file inclusion --------------------------------------
587
588var (
589 reTraversal = regexp.MustCompile(`(?:\.\./){2,}|(?:\.\.\\){2,}`)
590 reSensitive = regexp.MustCompile(`(?i)(?:^|/)(?:etc/passwd|etc/shadow|proc/self/environ|windows/win\.ini|boot\.ini|\.ssh/id_rsa)`)
591 reWrapper = regexp.MustCompile(`(?i)\b(?:php|file|gopher|dict|expect|zip|phar|data)://`)
592)
593
594func detectLFI(v, loc string, add func(Hit)) {
595 if m := reTraversal.FindString(v); m != "" {
596 add(Hit{Module: "lfi", Rule: "traversal", Score: 10, Location: loc, Evidence: m})
597 }
598 if m := reSensitive.FindString(v); m != "" {
599 add(Hit{Module: "lfi", Rule: "sensitive_file", Score: 10, Location: loc, Evidence: m})
600 }
601 if m := reWrapper.FindString(v); m != "" {
602 add(Hit{Module: "lfi", Rule: "stream_wrapper", Score: 8, Location: loc, Evidence: m})
603 }
604}
605
606// --- language specific code injection -------------------------------------
607
608var (
609 rePHPTag = regexp.MustCompile(`(?i)<\?php|<%\s`)
610 rePHPFunc = regexp.MustCompile(`(?i)\b(?:eval|assert|system|exec|shell_exec|passthru|popen|proc_open|pcntl_exec|create_function)\s*\(`)
611 rePHPObfus = regexp.MustCompile(`(?i)\b(?:base64_decode|gzinflate|str_rot13|str_rot13|gzuncompress)\s*\(`)
612 reJavaRT = regexp.MustCompile(`(?i)java\.lang\.(?:runtime|processbuilder)|getruntime\s*\(\s*\)\s*\.\s*exec`)
613 reJavaSer = regexp.MustCompile(`rO0AB`)
614 reXXEDoctyp = regexp.MustCompile(`(?is)<!doctype[^>]{0,500}\[[\s\S]{0,1000}<!entity`)
615 reXXEEntity = regexp.MustCompile(`(?i)<!entity\s+%?\s*\w+\s+system`)
616)
617
618func detectPHP(v, loc string, add func(Hit)) {
619 if m := rePHPTag.FindString(v); m != "" {
620 add(Hit{Module: "php", Rule: "php_tag", Score: 10, Location: loc, Evidence: m})
621 }
622 if m := rePHPFunc.FindString(v); m != "" {
623 add(Hit{Module: "php", Rule: "php_function", Score: 6, Location: loc, Evidence: m})
624 }
625 if m := rePHPObfus.FindString(v); m != "" {
626 add(Hit{Module: "php", Rule: "obfuscation", Score: 6, Location: loc, Evidence: m})
627 }
628}
629
630func detectJava(v, loc string, add func(Hit)) {
631 if m := reJavaRT.FindString(v); m != "" {
632 add(Hit{Module: "java", Rule: "runtime_exec", Score: 10, Location: loc, Evidence: m})
633 }
634 if m := reJavaSer.FindString(v); m != "" {
635 add(Hit{Module: "java", Rule: "serialized_object", Score: 8, Location: loc, Evidence: m})
636 }
637}
638
639func detectXXE(v, loc string, add func(Hit)) {
640 if m := reXXEDoctyp.FindString(v); m != "" {
641 add(Hit{Module: "xxe", Rule: "doctype_entity", Score: 10, Location: loc, Evidence: m})
642 }
643 if m := reXXEEntity.FindString(v); m != "" {
644 add(Hit{Module: "xxe", Rule: "external_entity", Score: 9, Location: loc, Evidence: m})
645 }
646}
647
648// --- server side template injection ---------------------------------------
649
650var (
651 reSSTIJinja = regexp.MustCompile(`\{\{[^}]{0,200}(?:\d+\s*[*+\-/]\s*['"]?\d+|__\w+__|[a-zA-Z_]\w*\s*\(|(?:config|self|request|cycler|joiner|namespace)\.)[^}]{0,200}\}\}`)
652 reSSTIEL = regexp.MustCompile(`\$\{[^}]{1,200}\}`)
653 reSSTIErb = regexp.MustCompile(`(?s)<%=[\s\S]{1,200}%>`)
654 reSSTINew = regexp.MustCompile(`(?i)\$\{[^}]*\?new\s*\(`)
655 reSSTISmarty = regexp.MustCompile(`(?i)\{(?:if|foreach|php)\s`)
656)
657
658func detectSSTI(v, loc string, add func(Hit)) {
659 if m := reSSTINew.FindString(v); m != "" {
660 add(Hit{Module: "ssti", Rule: "freemarker_new", Score: 10, Location: loc, Evidence: m})
661 return
662 }
663 if m := reSSTIErb.FindString(v); m != "" {
664 add(Hit{Module: "ssti", Rule: "erb_expression", Score: 8, Location: loc, Evidence: m})
665 }
666 if m := reSSTIJinja.FindString(v); m != "" {
667 add(Hit{Module: "ssti", Rule: "jinja_expression", Score: 8, Location: loc, Evidence: m})
668 }
669 if m := reSSTIEL.FindString(v); m != "" {
670 add(Hit{Module: "ssti", Rule: "el_expression", Score: 4, Location: loc, Evidence: m})
671 }
672 if m := reSSTISmarty.FindString(v); m != "" {
673 add(Hit{Module: "ssti", Rule: "template_tag", Score: 4, Location: loc, Evidence: m})
674 }
675}
676
677// --- protocol / SSRF / CRLF ------------------------------------------------
678
679var (
680 reSSRFLocal = regexp.MustCompile(`(?i)^(?:https?|file|gopher|dict|ftp)://(?:127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|localhost|0\.0\.0\.0|\[::1\])`)
681 reSSRFMeta = regexp.MustCompile(`(?i)169\.254\.169\.254|metadata\.google\.internal|metadata\.azure\.com`)
682 reCRLF = regexp.MustCompile(`(?i)(?:%0d%0a|%0a%0d|%0d|%0a)`)
683)
684
685func detectProtocol(v, loc string, add func(Hit)) {
686 if m := reCRLF.FindString(v); m != "" {
687 add(Hit{Module: "crlf", Rule: "header_injection", Score: 7, Location: loc, Evidence: m})
688 }
689 name := ""
690 switch {
691 case strings.HasPrefix(loc, "body:"):
692 name = strings.ToLower(strings.TrimPrefix(loc, "body:"))
693 case strings.HasPrefix(loc, "query:"):
694 name = strings.ToLower(strings.TrimPrefix(loc, "query:"))
695 default:
696 return
697 }
698 switch name {
699 case "url", "uri", "link", "src", "source", "dest", "destination", "target",
700 "redirect", "redirect_uri", "callback", "webhook", "proxy", "fetch",
701 "image", "host", "domain", "next", "return", "continue":
702 default:
703 return
704 }
705 if m := reSSRFLocal.FindString(v); m != "" {
706 add(Hit{Module: "ssrf", Rule: "internal_target", Score: 10, Location: loc, Evidence: m})
707 }
708 if m := reSSRFMeta.FindString(v); m != "" {
709 add(Hit{Module: "ssrf", Rule: "cloud_metadata", Score: 12, Location: loc, Evidence: m})
710 }
711}
712
713// --- scanner / sensitive paths / uploads ----------------------------------
714
715var (
716 reBadUA = regexp.MustCompile(`(?i)(?:sqlmap|nikto|nmap|masscan|acunetix|nessus|openvas|dirbuster|gobuster|wpscan|zgrab|arachni|whatweb|xray|fscan|nuclei|ffuf|feroxbuster|wfuzz|zaproxy|burp|shodan|censys|netsparker|appscan|acunetix)`)
717 reProbe = regexp.MustCompile(`(?i)(?:^|/)(?:\.git|\.svn|\.hg|\.env|wp-login\.php|xmlrpc\.php|phpmyadmin|adminer|actuator|manager/html|\.aws/credentials|config\.php\.bak|\.ds_store)`)
718 reUpExt = regexp.MustCompile(`(?i)\.(?:php\d?|phtml|phar|jsp|jspx|asp|aspx|ashx|asmx|cgi|pl|py|sh|exe|dll)(?:$|[.;\s])`)
719 reDblEx = regexp.MustCompile(`(?i)\.(?:jpg|jpeg|png|gif|txt|pdf|doc|docx|zip)\.(?:php\d?|jsp|asp|aspx|exe|sh)$`)
720)
721
722func detectScanner(lower, loc string, add func(Hit)) {
723 if strings.HasPrefix(loc, "header:user-agent") {
724 if m := reBadUA.FindString(lower); m != "" {
725 add(Hit{Module: "scanner", Rule: "bad_ua", Score: 12, Location: loc, Evidence: m})
726 }
727 }
728 if strings.HasPrefix(loc, "path") || strings.HasPrefix(loc, "query") {
729 if m := reProbe.FindString(lower); m != "" {
730 add(Hit{Module: "scanner", Rule: "probe_path", Score: 8, Location: loc, Evidence: m})
731 }
732 }
733}
734
735func detectUpload(t target, add func(Hit)) {
736 if strings.HasPrefix(t.location, "upload:filename") {
737 if m := reDblEx.FindString(t.value); m != "" {
738 add(Hit{Module: "upload", Rule: "double_extension", Score: 10, Location: t.location, Evidence: m})
739 } else if m := reUpExt.FindString(t.value); m != "" {
740 add(Hit{Module: "upload", Rule: "executable_extension", Score: 10, Location: t.location, Evidence: m})
741 }
742 if strings.ContainsRune(t.value, 0) {
743 add(Hit{Module: "upload", Rule: "null_byte", Score: 9, Location: t.location, Evidence: "NUL"})
744 }
745 }
746}
747
748// --- helpers ---------------------------------------------------------------
749
750func trustedIP(ip string, list []string) bool {
751 if ip == "" || len(list) == 0 {
752 return false
753 }
754 parsed := net.ParseIP(strings.TrimSpace(ip))
755 if parsed == nil {
756 return false
757 }
758 for _, raw := range list {
759 raw = strings.TrimSpace(raw)
760 if raw == "" {
761 continue
762 }
763 if strings.Contains(raw, "/") {
764 if _, network, err := net.ParseCIDR(raw); err == nil && network.Contains(parsed) {
765 return true
766 }
767 continue
768 }
769 if other := net.ParseIP(raw); other != nil && other.Equal(parsed) {
770 return true
771 }
772 }
773 return false
774}
775
776// DecodeJSON is a helper for callers that want the same unicode decoding the
777// engine uses (kept exported for tests and future rule editors).
778func DecodeJSON(raw []byte) any {
779 var v any
780 if err := json.Unmarshal(raw, &v); err != nil {
781 return nil
782 }
783 return v
784}