// Package wafengine implements the request level detection used by the // reverse proxy gateway. It is deliberately dependency free (standard library // only) so it can be unit tested without nginx, SQLite or a network. // // The design follows the layered approach used by SafeLine/雷池: // // 1. decode the input several times (URL, HTML entity, unicode escape, SQL // comments) so obfuscated payloads are compared after normalisation; // 2. run independent detectors per attack class; // 3. score every hit and block only when the strongest hit (plus a small // bonus for corroborating hits) reaches the configured threshold. // // Scoring keeps false positives low: a lone "onclick=" or "order by" is // logged but not blocked, while "union ... select" or "= 10) always blocks on its own. const DefaultThreshold = 8 // MaxBodyScan limits how much of a request body is inspected. Larger bodies // are streamed by the gateway after a cheap literal pre-scan. const MaxBodyScan = 256 << 10 // Request is the subset of an HTTP request the engine needs. type Request struct { Method string Path string RawQuery string ContentType string RemoteIP string Header map[string][]string Cookies map[string]string Body []byte } // Hit is one detector match. type Hit struct { Module string `json:"module"` Rule string `json:"rule"` Score int `json:"score"` Location string `json:"location"` Evidence string `json:"evidence"` } // Result is the verdict for one request. type Result struct { Score int `json:"score"` Hits []Hit `json:"hits"` Blocked bool `json:"blocked"` } // CustomRule mirrors the operator rules stored in waf_rules so the gateway can // enforce them even for parts of the request nginx cannot see (body). type CustomRule struct { Name string MatchOn string // uri | ua | referer | method Op string // contains | prefix | regex Pattern string Enabled bool } // Config is the runtime policy snapshot. type Config struct { Strict bool Threshold int Whitelist []string Custom []CustomRule } func (c Config) threshold() int { t := c.Threshold if t <= 0 { t = DefaultThreshold } if c.Strict && t > 4 { t = 4 } return t } type target struct { location string value string } // Inspect evaluates one request. func Inspect(req *Request, cfg Config) Result { if req == nil { return Result{} } if trustedIP(req.RemoteIP, cfg.Whitelist) { return Result{} } var hits []Hit seen := map[string]bool{} add := func(h Hit) { if h.Score <= 0 { return } key := h.Module + "|" + h.Rule if seen[key] { return } seen[key] = true if len(h.Evidence) > 180 { h.Evidence = h.Evidence[:180] } hits = append(hits, h) } for _, t := range requestTargets(req) { scanTarget(t, add) } for _, t := range bodyTargets(req) { scanTarget(t, add) } scanCustom(req, cfg.Custom, add) if len(hits) == 0 { return Result{} } best := 0 modules := map[string]bool{} for _, h := range hits { if h.Score > best { best = h.Score } modules[h.Module] = true } bonus := len(modules) - 1 if bonus > 3 { bonus = 3 } score := best + bonus return Result{Score: score, Hits: hits, Blocked: score >= cfg.threshold()} } func requestTargets(req *Request) []target { out := []target{ {"path", req.Path}, {"query", req.RawQuery}, {"method", req.Method}, } addHeader := func(name string) { for _, v := range req.Header[name] { if strings.TrimSpace(v) != "" { out = append(out, target{"header:" + strings.ToLower(name), v}) } } } addHeader("User-Agent") addHeader("Referer") addHeader("X-Forwarded-For") addHeader("X-Real-IP") addHeader("Content-Type") for name, values := range req.Header { // Cookies are attacker controlled; the rest of the headers mostly are // not, so only a few interesting ones are inspected above. if strings.EqualFold(name, "Cookie") { for _, v := range values { out = append(out, target{"header:cookie", v}) } } } for name, value := range req.Cookies { out = append(out, target{"cookie:" + name, value}) } if values, err := url.ParseQuery(req.RawQuery); err == nil { for name, list := range values { for _, value := range list { out = append(out, target{"query:" + name, value}) } } } return out } func bodyTargets(req *Request) []target { body := req.Body if len(body) == 0 { return nil } truncated := false if len(body) > MaxBodyScan { body = body[:MaxBodyScan] truncated = true } mediaType, params, _ := mime.ParseMediaType(req.ContentType) var out []target add := func(location, value string) { if strings.TrimSpace(value) != "" { out = append(out, target{location, value}) } } switch { case mediaType == "application/x-www-form-urlencoded": if values, err := url.ParseQuery(string(body)); err == nil { for k, list := range values { add("body:"+k, k) for _, v := range list { add("body:"+k, v) } } } case strings.HasPrefix(mediaType, "multipart/"): out = append(out, multipartTargets(body, params["boundary"])...) case mediaType == "application/json" || strings.HasSuffix(mediaType, "+json"): add("body:json", string(body)) // JSON may encode the payload as \u003c etc; decodeUnicode is part of // the variant pipeline, so the raw text is enough here. if truncated { add("body:json-tail", string(req.Body[len(req.Body)-min(len(req.Body), 32<<10):])) } default: add("body", string(body)) } return out } func multipartTargets(body []byte, boundary string) []target { if boundary == "" { return []target{{"body:multipart", string(body)}} } reader := multipart.NewReader(bytes.NewReader(body), boundary) var out []target for i := 0; i < 64; i++ { part, err := reader.NextPart() if err != nil { break } name := part.FormName() filename := part.FileName() if filename != "" { out = append(out, target{"upload:filename", filename}) head := make([]byte, 4096) n, _ := part.Read(head) if n > 0 { out = append(out, target{"upload:content", string(head[:n])}) } _ = part.Close() continue } buf := make([]byte, 64<<10) n, _ := part.Read(buf) if n > 0 { out = append(out, target{"body:" + name, string(buf[:n])}) } _ = part.Close() } return out } // scanTarget runs every detector over the decoded variants of one value. func scanTarget(t target, add func(Hit)) { // Uploaded file bodies are only checked for embedded server-side code. // Running the full rule set over them flags legitimate source/archive // uploads (the README of this very repository contains backticks). if strings.HasPrefix(t.location, "upload:content") { if m := rePHPTag.FindString(t.value); m != "" { add(Hit{Module: "upload", Rule: "embedded_code", Score: 10, Location: t.location, Evidence: m}) } return } for _, v := range variants(t.value) { if v == "" { continue } detectSQLi(v, t.location, add) detectXSS(v, t.location, add) detectRCE(v, t.location, add) detectLFI(v, t.location, add) detectPHP(v, t.location, add) detectJava(v, t.location, add) detectXXE(v, t.location, add) detectSSTI(v, t.location, add) detectProtocol(v, t.location, add) } lower := strings.ToLower(t.value) detectScanner(lower, t.location, add) detectUpload(t, add) } func scanCustom(req *Request, rules []CustomRule, add func(Hit)) { for _, rule := range rules { if !rule.Enabled || rule.Pattern == "" { continue } var values []string switch rule.MatchOn { case "uri": values = []string{req.Path, req.RawQuery} case "ua": values = req.Header["User-Agent"] case "referer": values = req.Header["Referer"] case "method": values = []string{req.Method} default: continue } for _, value := range values { if matchCustom(rule, value) { add(Hit{Module: "custom", Rule: rule.Name, Score: 10, Location: rule.MatchOn, Evidence: value}) break } } } } func matchCustom(rule CustomRule, value string) bool { switch rule.Op { case "prefix": return strings.HasPrefix(strings.ToLower(value), strings.ToLower(rule.Pattern)) case "regex": re, err := regexp.Compile("(?i)" + rule.Pattern) return err == nil && re.MatchString(value) default: return strings.Contains(strings.ToLower(value), strings.ToLower(rule.Pattern)) } } // --- decoding / normalisation --------------------------------------------- var ( reUnicodeEscape = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`) rePercentU = regexp.MustCompile(`(?i)%u([0-9a-f]{4})`) reSQLBlock = regexp.MustCompile(`(?s)/\*.*?\*/`) reSQLDash = regexp.MustCompile(`(?m)--[^\n]*`) reSpaces = regexp.MustCompile(`\s+`) ) // variants returns the representations a detector should look at. The list is // bounded so a malicious input cannot force unbounded decoding work. func variants(s string) []string { if len(s) > 1<<20 { s = s[:1<<20] } out := make([]string, 0, 10) seen := map[string]bool{} add := func(v string) { if v == "" || seen[v] || len(out) >= 10 { return } seen[v] = true out = append(out, v) } add(s) cur := s for i := 0; i < 3; i++ { next, err := url.QueryUnescape(cur) if err != nil || next == cur { break } add(next) cur = next } s = cur add(htmlUnescape(s)) add(decodeUnicode(s)) add(decodePercentU(s)) add(unescapeJSON(s)) base := append([]string(nil), out...) for _, v := range base { add(strings.ToLower(v)) } for _, v := range base { add(stripSQLComments(v)) } for _, v := range append([]string(nil), out...) { if strings.Contains(v, " ") || strings.Contains(v, "\t") { add(reSpaces.ReplaceAllString(v, " ")) } } return out } func htmlUnescape(s string) string { // net/html is avoided on purpose: it live-parses and can be slow on // garbage. A small replacement table covers the payloads that matter. replacer := strings.NewReplacer( "<", "<", ">", ">", """, `"`, "'", "'", "'", "'", "<", "<", ">", ">", "&", "&", ) return replacer.Replace(s) } func decodeUnicode(s string) string { if !strings.Contains(s, `\u`) { return s } return reUnicodeEscape.ReplaceAllStringFunc(s, func(m string) string { n, err := strconv.ParseUint(m[2:], 16, 32) if err != nil || n == 0 { return m } return string(rune(n)) }) } // unescapeJSON turns the escaped quotes of a JSON string into their literal // form so SQL/XSS rules see the payload the application will decode. func unescapeJSON(s string) string { if !strings.Contains(s, `\"`) && !strings.Contains(s, `\/`) { return s } return strings.NewReplacer(`\"`, `"`, `\/`, `/`, `\\`, `\`).Replace(s) } func decodePercentU(s string) string { if !strings.Contains(strings.ToLower(s), "%u") { return s } return rePercentU.ReplaceAllStringFunc(s, func(m string) string { n, err := strconv.ParseUint(m[2:], 16, 32) if err != nil || n == 0 { return m } return string(rune(n)) }) } func stripSQLComments(s string) string { if !strings.Contains(s, "/*") && !strings.Contains(s, "--") { return s } s = reSQLBlock.ReplaceAllString(s, "") s = reSQLDash.ReplaceAllString(s, " ") return s } // --- SQL injection --------------------------------------------------------- var ( reUnionSelect = regexp.MustCompile(`(?i)\bunion\b\s+(?:all\s+)?\bselect\b`) reSQLTime = regexp.MustCompile(`(?i)\b(?:sleep|benchmark|pg_sleep|waitfor\s+delay|dbms_lock\.sleep|dbms_pipe\.receive_message)\s*\(`) reSQLMeta = regexp.MustCompile(`(?i)\b(?:information_schema|sysobjects|syscolumns|mysql\.user|pg_catalog|all_tables|sqlite_master)\b`) reSQLFile = regexp.MustCompile(`(?i)\b(?:load_file|into\s+(?:out|dump)file|xp_cmdshell|sp_executesql|openrowset)\b`) reSQLStacked = regexp.MustCompile(`(?i);\s*(?:select|insert|update|delete|drop|alter|create|truncate|exec|execute|call|declare)\b`) reSQLQuoteCmt = regexp.MustCompile(`(?i)['"]\s*(?:--|#|/\*)`) reSQLBoolNum = regexp.MustCompile(`(?i)\b(?:or|and)\b\s+\d{1,6}\s*=\s*\d{1,6}\b`) reSQLBoolStr = regexp.MustCompile(`(?i)\b(?:or|and)\b\s+['"][^'"]{0,40}['"]\s*=\s*['"][^'"]{0,40}['"]`) reSQLQuoteOr = regexp.MustCompile(`(?i)['"]\s*(?:or|and)\b\s*['"]?[0-9a-z_]{1,30}['"]?\s*=\s*['"]?[0-9a-z_]{1,30}['"]?`) reSQLHex = regexp.MustCompile(`(?i)\b0x[0-9a-f]{8,}\b`) reSQLFunc = regexp.MustCompile(`(?i)\b(?:extractvalue|updatexml|group_concat|concat_ws|char|ascii|substr|mid|length|database|version|user)\s*\(`) reSQLOrder = regexp.MustCompile(`(?i)\b(?:order|group)\s+by\s+\d{1,4}\b`) reSQLComment = regexp.MustCompile(`(?i)(?:/\*!?\d*|#\s*$|--\s)`) ) func detectSQLi(v, loc string, add func(Hit)) { rules := []struct { id string re *regexp.Regexp scr int cond func(string) bool }{ {"union_select", reUnionSelect, 10, nil}, {"time_based", reSQLTime, 12, nil}, {"metadata", reSQLMeta, 9, nil}, {"file_access", reSQLFile, 12, nil}, {"stacked_query", reSQLStacked, 10, nil}, {"quote_comment", reSQLQuoteCmt, 9, nil}, {"tautology_numeric", reSQLBoolNum, 8, nil}, {"tautology_string", reSQLBoolStr, 9, nil}, {"tautology_quoted", reSQLQuoteOr, 9, nil}, {"hex_literal", reSQLHex, 4, nil}, {"function_probe", reSQLFunc, 5, func(s string) bool { return strings.Contains(s, "select") || strings.Contains(s, "from") || strings.Contains(s, "'") || strings.Contains(s, `"`) }}, {"order_by", reSQLOrder, 4, nil}, {"comment", reSQLComment, 4, nil}, } for _, r := range rules { m := r.re.FindString(v) if m == "" { continue } if r.cond != nil && !r.cond(strings.ToLower(v)) { continue } add(Hit{Module: "sqli", Rule: r.id, Score: r.scr, Location: loc, Evidence: m}) } } // --- XSS ------------------------------------------------------------------- var ( reXSSScript = regexp.MustCompile(`(?i)<\s*script\b`) reXSSUri = regexp.MustCompile(`(?i)\b(?:javascript|vbscript)\s*:`) reXSSData = regexp.MustCompile(`(?i)data\s*:\s*text/html`) 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*=`) reXSSCombined = regexp.MustCompile(`(?i)<\s*(?:svg|img|body|iframe|details|marquee|object|embed|video|audio)[^>]{0,120}\bon\w+\s*=`) reXSSTag = regexp.MustCompile(`(?i)<\s*(?:iframe|object|embed|svg|link|style|meta|base)\b`) reXSSDOM = regexp.MustCompile(`(?i)\b(?:document\.(?:cookie|domain|write)|window\.(?:location|name)|eval|alert|prompt|confirm)\s*\(`) reXSSExpr = regexp.MustCompile(`(?i)\bexpression\s*\(`) reXSSImg = regexp.MustCompile(`(?i)<\s*img\b`) ) func detectXSS(v, loc string, add func(Hit)) { if m := reXSSScript.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "script_tag", Score: 10, Location: loc, Evidence: m}) } if m := reXSSCombined.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "handler_in_tag", Score: 10, Location: loc, Evidence: m}) } if m := reXSSUri.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "js_uri", Score: 8, Location: loc, Evidence: m}) } if m := reXSSData.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "data_uri", Score: 8, Location: loc, Evidence: m}) } if m := reXSSHandler.FindString(v); m != "" { score := 6 if strings.Contains(v, "<") { score = 8 } add(Hit{Module: "xss", Rule: "event_handler", Score: score, Location: loc, Evidence: m}) } if m := reXSSTag.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "dangerous_tag", Score: 7, Location: loc, Evidence: m}) } if m := reXSSImg.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "img_tag", Score: 4, Location: loc, Evidence: m}) } if m := reXSSDOM.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "dom_sink", Score: 6, Location: loc, Evidence: m}) } if m := reXSSExpr.FindString(v); m != "" { add(Hit{Module: "xss", Rule: "css_expression", Score: 7, Location: loc, Evidence: m}) } } // --- command / code injection --------------------------------------------- var ( 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`) reSubshell = regexp.MustCompile(`\$\([^)]{1,200}\)`) reBacktick = regexp.MustCompile("`[^`]{1,200}`") rePipeExec = regexp.MustCompile(`(?i)\|\|\s*(?:curl|wget|bash|sh|nc|ncat|python|perl)\b`) reLog4j = regexp.MustCompile(`(?i)\$\{jndi:(?:ldap|rmi|dns|http|https|iiop|corba)`) reNcExec = regexp.MustCompile(`(?i)(?:^|\s)(?:nc|ncat|netcat)\s+-[a-z]*e\s`) rePwshEnc = regexp.MustCompile(`(?i)powershell(?:\.exe)?\s+(?:-\w+\s+)*-enc(?:odedcommand)?\b`) ) func detectRCE(v, loc string, add func(Hit)) { if m := reLog4j.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "log4j_jndi", Score: 12, Location: loc, Evidence: m}) } if m := reShellMeta.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "shell_meta", Score: 9, Location: loc, Evidence: m}) } if m := rePipeExec.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "pipe_exec", Score: 10, Location: loc, Evidence: m}) } if m := reSubshell.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "subshell", Score: 7, Location: loc, Evidence: m}) } if m := reBacktick.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "backtick", Score: 7, Location: loc, Evidence: m}) } if m := reNcExec.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "reverse_shell", Score: 10, Location: loc, Evidence: m}) } if m := rePwshEnc.FindString(v); m != "" { add(Hit{Module: "rce", Rule: "powershell_encoded", Score: 10, Location: loc, Evidence: m}) } } // --- path traversal / file inclusion -------------------------------------- var ( reTraversal = regexp.MustCompile(`(?:\.\./){2,}|(?:\.\.\\){2,}`) reSensitive = regexp.MustCompile(`(?i)(?:^|/)(?:etc/passwd|etc/shadow|proc/self/environ|windows/win\.ini|boot\.ini|\.ssh/id_rsa)`) reWrapper = regexp.MustCompile(`(?i)\b(?:php|file|gopher|dict|expect|zip|phar|data)://`) ) func detectLFI(v, loc string, add func(Hit)) { if m := reTraversal.FindString(v); m != "" { add(Hit{Module: "lfi", Rule: "traversal", Score: 10, Location: loc, Evidence: m}) } if m := reSensitive.FindString(v); m != "" { add(Hit{Module: "lfi", Rule: "sensitive_file", Score: 10, Location: loc, Evidence: m}) } if m := reWrapper.FindString(v); m != "" { add(Hit{Module: "lfi", Rule: "stream_wrapper", Score: 8, Location: loc, Evidence: m}) } } // --- language specific code injection ------------------------------------- var ( rePHPTag = regexp.MustCompile(`(?i)<\?php|<%\s`) rePHPFunc = regexp.MustCompile(`(?i)\b(?:eval|assert|system|exec|shell_exec|passthru|popen|proc_open|pcntl_exec|create_function)\s*\(`) rePHPObfus = regexp.MustCompile(`(?i)\b(?:base64_decode|gzinflate|str_rot13|str_rot13|gzuncompress)\s*\(`) reJavaRT = regexp.MustCompile(`(?i)java\.lang\.(?:runtime|processbuilder)|getruntime\s*\(\s*\)\s*\.\s*exec`) reJavaSer = regexp.MustCompile(`rO0AB`) reXXEDoctyp = regexp.MustCompile(`(?is)]{0,500}\[[\s\S]{0,1000}`) reSSTINew = regexp.MustCompile(`(?i)\$\{[^}]*\?new\s*\(`) reSSTISmarty = regexp.MustCompile(`(?i)\{(?:if|foreach|php)\s`) ) func detectSSTI(v, loc string, add func(Hit)) { if m := reSSTINew.FindString(v); m != "" { add(Hit{Module: "ssti", Rule: "freemarker_new", Score: 10, Location: loc, Evidence: m}) return } if m := reSSTIErb.FindString(v); m != "" { add(Hit{Module: "ssti", Rule: "erb_expression", Score: 8, Location: loc, Evidence: m}) } if m := reSSTIJinja.FindString(v); m != "" { add(Hit{Module: "ssti", Rule: "jinja_expression", Score: 8, Location: loc, Evidence: m}) } if m := reSSTIEL.FindString(v); m != "" { add(Hit{Module: "ssti", Rule: "el_expression", Score: 4, Location: loc, Evidence: m}) } if m := reSSTISmarty.FindString(v); m != "" { add(Hit{Module: "ssti", Rule: "template_tag", Score: 4, Location: loc, Evidence: m}) } } // --- protocol / SSRF / CRLF ------------------------------------------------ var ( 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\])`) reSSRFMeta = regexp.MustCompile(`(?i)169\.254\.169\.254|metadata\.google\.internal|metadata\.azure\.com`) reCRLF = regexp.MustCompile(`(?i)(?:%0d%0a|%0a%0d|%0d|%0a)`) ) func detectProtocol(v, loc string, add func(Hit)) { if m := reCRLF.FindString(v); m != "" { add(Hit{Module: "crlf", Rule: "header_injection", Score: 7, Location: loc, Evidence: m}) } name := "" switch { case strings.HasPrefix(loc, "body:"): name = strings.ToLower(strings.TrimPrefix(loc, "body:")) case strings.HasPrefix(loc, "query:"): name = strings.ToLower(strings.TrimPrefix(loc, "query:")) default: return } switch name { case "url", "uri", "link", "src", "source", "dest", "destination", "target", "redirect", "redirect_uri", "callback", "webhook", "proxy", "fetch", "image", "host", "domain", "next", "return", "continue": default: return } if m := reSSRFLocal.FindString(v); m != "" { add(Hit{Module: "ssrf", Rule: "internal_target", Score: 10, Location: loc, Evidence: m}) } if m := reSSRFMeta.FindString(v); m != "" { add(Hit{Module: "ssrf", Rule: "cloud_metadata", Score: 12, Location: loc, Evidence: m}) } } // --- scanner / sensitive paths / uploads ---------------------------------- var ( 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)`) 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)`) reUpExt = regexp.MustCompile(`(?i)\.(?:php\d?|phtml|phar|jsp|jspx|asp|aspx|ashx|asmx|cgi|pl|py|sh|exe|dll)(?:$|[.;\s])`) reDblEx = regexp.MustCompile(`(?i)\.(?:jpg|jpeg|png|gif|txt|pdf|doc|docx|zip)\.(?:php\d?|jsp|asp|aspx|exe|sh)$`) ) func detectScanner(lower, loc string, add func(Hit)) { if strings.HasPrefix(loc, "header:user-agent") { if m := reBadUA.FindString(lower); m != "" { add(Hit{Module: "scanner", Rule: "bad_ua", Score: 12, Location: loc, Evidence: m}) } } if strings.HasPrefix(loc, "path") || strings.HasPrefix(loc, "query") { if m := reProbe.FindString(lower); m != "" { add(Hit{Module: "scanner", Rule: "probe_path", Score: 8, Location: loc, Evidence: m}) } } } func detectUpload(t target, add func(Hit)) { if strings.HasPrefix(t.location, "upload:filename") { if m := reDblEx.FindString(t.value); m != "" { add(Hit{Module: "upload", Rule: "double_extension", Score: 10, Location: t.location, Evidence: m}) } else if m := reUpExt.FindString(t.value); m != "" { add(Hit{Module: "upload", Rule: "executable_extension", Score: 10, Location: t.location, Evidence: m}) } if strings.ContainsRune(t.value, 0) { add(Hit{Module: "upload", Rule: "null_byte", Score: 9, Location: t.location, Evidence: "NUL"}) } } } // --- helpers --------------------------------------------------------------- func trustedIP(ip string, list []string) bool { if ip == "" || len(list) == 0 { return false } parsed := net.ParseIP(strings.TrimSpace(ip)) if parsed == nil { return false } for _, raw := range list { raw = strings.TrimSpace(raw) if raw == "" { continue } if strings.Contains(raw, "/") { if _, network, err := net.ParseCIDR(raw); err == nil && network.Contains(parsed) { return true } continue } if other := net.ParseIP(raw); other != nil && other.Equal(parsed) { return true } } return false } // DecodeJSON is a helper for callers that want the same unicode decoding the // engine uses (kept exported for tests and future rule editors). func DecodeJSON(raw []byte) any { var v any if err := json.Unmarshal(raw, &v); err != nil { return nil } return v }