Files
urutau/internal/core/classify.go
T

195 lines
6.1 KiB
Go

package core
import (
"net/url"
"regexp"
"strings"
)
// decode percent-decodes s up to twice (double encoding is a common evasion).
func decode(s string) string {
for i := 0; i < 2; i++ {
d, err := url.QueryUnescape(s)
if err != nil || d == s {
break
}
s = d
}
return s
}
// Class is the verdict on one web request.
type Class struct {
Cat Category
// Soft: a scanner/exploit probe the server answered with 2xx/3xx. It may be
// a false positive (SPA fallback, documentation page), so it weighs little.
Soft bool
// Strong: a high confidence exploit attempt that was refused (4xx/5xx).
Strong bool
// Weak: only a weak exploit marker (cmd=, |sh, eval(...)) matched. The runner
// promotes it to an exploit when the User-Agent is an attack tool.
Weak bool
}
var strongMarkers = []string{
"../", "..\\", "..;/", "%2e%2e", "/etc/passwd", "/etc/shadow", "/proc/self",
"${jndi:", "<script", "union select", "union+select", "base64_decode", ";wget",
"php://", "/bin/sh", "/bin/bash",
}
var weakMarkers = []string{"cmd=", "|sh", "eval("}
var shellRe = regexp.MustCompile(`/shell(?:$|[/._?-])`)
func hasAny(markers []string, texts ...string) bool {
for _, m := range markers {
for _, t := range texts {
if strings.Contains(t, m) {
return true
}
}
}
return false
}
func isBrute(method, path string, status int) bool {
if strings.Contains(path, "/xmlrpc.php") {
return true
}
if method == "POST" && strings.HasSuffix(path, "/wp-login.php") {
// 200 means the login form came back: wrong password. 302 is a success.
return status == 200 || status == 401 || status == 403
}
return method == "POST" && status == 401
}
// segment reports whether name appears in path as a whole path segment prefix
// (followed by the end, "/", "." or "?"), so "/.git" matches "/.git/config"
// but not "/.github/x".
func segment(path, name string) bool {
for from := 0; ; {
i := strings.Index(path[from:], name)
if i < 0 {
return false
}
end := from + i + len(name)
if end == len(path) || path[end] == '/' || path[end] == '.' || path[end] == '?' {
return true
}
from = from + i + 1
}
}
// always sensitive, whatever the answer
var sensitive = []string{"/.env", "/.git", "/.gitignore", "/.gitconfig", "/.git-credentials", "/.git-rewrite", "/.aws", "/.ssh", "/.svn", "/.hg", "/.vscode", "/.htaccess", "/.htpasswd", "/.ds_store", "/id_rsa"}
var sensitiveSub = []string{"wp-config", "phpmyadmin", "/server-status", "/vendor/phpunit", "/cgi-bin/", "/wp-admin/install.php",
"/boaform/", "/pma/", "/adminer", "/telescope/requests", "/_profiler"}
var backupExts = []string{".sql", ".bak", ".old", ".orig", ".swp", ".zip", ".tar.gz", ".tgz", ".7z", ".rar", ".tar", ".gz"}
// refused: only suspicious when the answer is 403/404, because the same paths
// are legitimate on many sites when they exist (SPA config, actuator health,
// documentation about phpinfo, downloadable archives).
func refusedProbe(path string) bool {
if path == "/config.json" || strings.HasSuffix(path, "/config.json") || segment(path, "/actuator") || strings.Contains(path, "phpinfo.php") ||
strings.HasSuffix(path, "/phpinfo") {
return true
}
for _, e := range backupExts {
if strings.HasSuffix(path, e) {
return true
}
}
return false
}
var forgeGitea = map[string]bool{"src": true, "raw": true, "blame": true, "commits": true, "commit": true, "media": true, "history": true}
var forgeRef = map[string]bool{"branch": true, "commit": true, "tag": true}
var forgeGeneric = map[string]bool{"blob": true, "tree": true, "raw": true, "blame": true, "commits": true}
// ForgeBrowse reports whether the (decoded, lowercase, query-less) path is a
// code forge page that shows repository content: Gitea/Forgejo
// /{owner}/{repo}/(src|raw|blame|commits|commit|media|history)/(branch|commit|tag)/<ref>/<file>,
// GitHub style /{owner}/{repo}/(blob|tree|raw|blame|commits)/<ref>/<file> and
// GitLab style /{group}/{project}/-/(blob|tree|raw|blame|commits)/<ref>/<file>.
// A file named ".env" inside a repository is content, not a probe of the host.
// It needs an owner and a repo that are not dot names, so "/.env", "/.git/config"
// or "/app/.env" are never forge paths. Traversal markers are checked before.
func ForgeBrowse(path string) bool {
if len(path) == 0 || path[0] != '/' {
return false
}
seg := strings.Split(path[1:], "/")
if len(seg) < 4 || seg[0] == "" || seg[1] == "" || seg[0][0] == '.' || seg[1][0] == '.' {
return false
}
for i := 2; i+3 < len(seg); i++ { // GitLab: /group/project/-/blob/<ref>/<file>
if seg[i] == "-" && forgeGeneric[seg[i+1]] && seg[i+2] != "" && seg[i+3] != "" {
return true
}
}
if seg[2] != "" && seg[3] != "" && len(seg) >= 5 && seg[4] != "" {
if forgeGitea[seg[2]] && forgeRef[seg[3]] {
return true // Gitea: /owner/repo/src/commit/<sha>/<file>
}
if forgeGeneric[seg[2]] {
return true // GitHub: /owner/repo/blob/<ref>/<file>
}
}
return false
}
func isScanner(path string, status int) bool {
if ForgeBrowse(path) {
return false
}
for _, m := range sensitive {
if segment(path, m) {
return true
}
}
for _, m := range sensitiveSub {
if strings.Contains(path, m) {
return true
}
}
if status == 403 || status == 404 {
if refusedProbe(path) || strings.Contains(path, "/wp-content/plugins/") && status == 404 {
return true
}
}
return false
}
// Classify classifies one web request.
func Classify(method, rawPath string, status int) Class {
raw := strings.ToLower(rawPath)
dec := decode(raw)
method = strings.ToUpper(method)
refused := status >= 400
if hasAny(strongMarkers, raw, dec) || shellRe.MatchString(dec) {
return Class{Cat: Exploit, Soft: !refused, Strong: refused}
}
path := dec
if i := strings.IndexAny(path, "?#"); i >= 0 {
path = path[:i]
}
if isBrute(method, path, status) {
return Class{Cat: BruteForce}
}
if isScanner(path, status) {
return Class{Cat: Scanner, Soft: !refused}
}
c := Class{Cat: OK}
if status >= 400 && status < 500 {
c.Cat = NotFound
}
c.Weak = hasAny(weakMarkers, raw, dec)
return c
}
// ClassifyHTTP returns only the category of Classify.
func ClassifyHTTP(method, rawPath string, status int) Category {
return Classify(method, rawPath, status).Cat
}