log-anomaly-context-lr / src /features.py
DaveyD347's picture
Add context-aware log anomaly detector
a56b6dd verified
Raw History Blame Contribute Delete
18.2 kB
"""Parse raw log lines and turn a log stream into per-line features.
This file is the single source of truth for the feature pipeline. `space/features.js` is a line-by-line port,
and `tests/parity.mjs` checks the two agree on every test-split event.
A stream is a time-ordered sequence of raw lines (one incident session in the dataset, or whatever a user pastes
into the demo). `StreamFeaturizer` reads it left to right and keeps a little state per entity (source IP, access
key, DNS client, host), so each line's features use only that line and the lines *before* it. That makes the model
usable on a live feed, and it is what lets it separate an attacker's `uname -a` from an admin's.
Two kinds of features come out for each line:
* tokens: sparse, binary, mostly from the line itself (`src=web`, `ua=sqlmap`, `ev=AttachUserPolicy`, ...)
* numeric: dense context features in [0, 1] (prior 404s from this IP, is this a new IP for this access key, ...)
"""
from __future__ import annotations
import json
import math
import re
# --------------------------------------------------------------------------------------------------------------
# Parsing
# --------------------------------------------------------------------------------------------------------------
RE_APACHE = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) [^"]*" (\d{3}) (\d+|-) "([^"]*)" "([^"]*)"')
RE_SYSLOG = re.compile(r"^[A-Z][a-z]{2} +\d+ [\d:]{8} (\S+) ([\w\-]+)(?:\[\d+\])?: (.*)$")
RE_AUDIT = re.compile(r"^type=EXECVE msg=audit\(([\d.]+):\d+\): argc=(\d+) (.*?) uid=(\d+) auid=\d+ exe=\"([^\"]*)\"(?: host=(\S+))?")
RE_ARG = re.compile(r'a\d+="((?:[^"\\]|\\.)*)"')
RE_DNS = re.compile(r"^(\S+ [\d:.]+) queries: info: client @\S+ ([\d.]+)#\d+ \(([^)]*)\): query: (\S+) IN (\S+)")
RE_IPV4 = re.compile(r"\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b")
RE_URL_IP = re.compile(r"\b(?:https?|ftp)://\d{1,3}(?:\.\d{1,3}){3}")
RE_SQLI = re.compile(r"(%27|')|\bunion\b|\bselect\b|\bsleep\(|waitfor|information_schema|\bor\b.{0,6}=|"
r"order%20by|order by|--|0x[0-9a-f]+|\band\b%20\d|\band \d", re.I)
TOOL_UAS = ["sqlmap", "nikto", "gobuster", "zgrab", "nuclei", "masscan", "dirbuster", "wfuzz", "hydra",
"python-requests", "curl", "okhttp", "go-http-client", "wget", "kali", "boto3", "aws-cli/1"]
SENSITIVE_FILES = ["/etc/shadow", "/etc/passwd", "/etc/sudoers", "/root/.ssh", "/.aws/credentials", "id_rsa"]
SCRIPT_EXT = (".php", ".jsp", ".asp", ".aspx", ".cgi", ".sh", ".pl")
SECRET_PATHS = (".env", ".git", ".aws", ".ds_store", ".bak", ".sql", ".zip", "phpmyadmin", "server-status",
"actuator", "debug", "swagger", "xmlrpc", "console", "wp-login", "phpunit", "cgi-bin")
def is_private(ip: str | None) -> bool:
if not ip:
return False
m = RE_IPV4.fullmatch(ip)
if not m:
return False
a, b = int(m.group(1)), int(m.group(2))
return a == 10 or a == 127 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168)
def parse_line(line: str) -> dict:
"""Return a dict with at least `src` (web/ssh/exec/cloud/dns/unknown)."""
line = line.rstrip("\r\n")
s = line.lstrip()
if s.startswith("{"):
try:
rec = json.loads(s)
except ValueError:
rec = None
if isinstance(rec, dict) and "eventName" in rec:
ui = rec.get("userIdentity") or {}
params = rec.get("requestParameters") or {}
return {"src": "cloud", "ip": rec.get("sourceIPAddress"), "event": str(rec.get("eventName", "")),
"service": str(rec.get("eventSource", "")).split(".")[0], "ua": str(rec.get("userAgent", "")),
"key": ui.get("accessKeyId"), "user": ui.get("userName"),
"error": rec.get("errorCode"), "read_only": bool(rec.get("readOnly")),
"params": json.dumps(params, sort_keys=True) if params else ""}
m = RE_APACHE.match(s)
if m:
path = m.group(4)
return {"src": "web", "ip": m.group(1), "method": m.group(3), "path": path.split("?")[0],
"query": path.split("?", 1)[1] if "?" in path else "", "status": int(m.group(5)),
"size": 0 if m.group(6) == "-" else int(m.group(6)), "ua": m.group(8)}
m = RE_AUDIT.match(s)
if m:
argv = [a.replace('\\"', '"') for a in RE_ARG.findall(m.group(3))]
return {"src": "exec", "uid": int(m.group(4)), "argv": argv, "exe": m.group(5), "host": m.group(6) or ""}
m = RE_DNS.match(s)
if m:
return {"src": "dns", "ip": m.group(2), "qname": m.group(4).lower().rstrip("."), "qtype": m.group(5).upper()}
m = RE_SYSLOG.match(s)
if m:
host, prog, msg = m.group(1), m.group(2), m.group(3)
out = {"src": "ssh", "host": host, "prog": prog, "msg": msg, "kind": "other", "user": None, "ip": None}
if prog == "sshd":
for pat, kind in ((r"^Failed password for (?:invalid user )?(\S+) from (\S+)", "failed_password"),
(r"^Invalid user (\S*) from (\S+)", "invalid_user"),
(r"^Accepted password for (\S+) from (\S+)", "accepted_password"),
(r"^Accepted publickey for (\S+) from (\S+)", "accepted_publickey"),
(r"^Accepted keyboard-interactive/pam for (\S+) from (\S+)", "accepted_password")):
mm = re.match(pat, msg)
if mm:
out.update(kind=kind, user=mm.group(1), ip=mm.group(2))
break
else:
mm = re.search(r"session (opened|closed) for user ([^\s(]+)", msg)
if mm:
out.update(kind="session_" + ("open" if mm.group(1) == "opened" else "close"), user=mm.group(2))
elif "Connection closed" in msg or "Disconnected" in msg:
out["kind"] = "disconnect"
elif prog == "sudo":
mm = re.match(r"^\s*(\S+) : .*COMMAND=(.*)$", msg)
out.update(kind="sudo", user=mm.group(1) if mm else None, command=mm.group(2) if mm else "")
return out
return {"src": "unknown"}
def entropy(s: str) -> float:
if not s:
return 0.0
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
n = len(s)
return -sum(c / n * math.log2(c / n) for c in counts.values())
def base_domain(qname: str) -> str:
parts = qname.split(".")
return ".".join(parts[-2:]) if len(parts) >= 2 else qname
def ua_tool(ua: str) -> str | None:
u = ua.lower()
for t in TOOL_UAS:
if t in u:
return t
return None
def ua_family(ua: str) -> str:
t = ua_tool(ua)
if t:
return t
u = ua.lower()
for fam in ("bot", "iphone", "android", "firefox", "chrome", "safari", "terraform", "console.amazonaws",
"aws-sdk-go", "aws-cli/2", "mozilla"):
if fam in u:
return fam
return "other"
def lg(x: float, cap: float) -> float:
"""log-scaled count in [0, 1]: 0 -> 0, cap -> 1."""
return min(1.0, math.log1p(max(0.0, x)) / math.log1p(cap))
# --------------------------------------------------------------------------------------------------------------
# Stream featurizer
# --------------------------------------------------------------------------------------------------------------
NUMERIC = [
# web
"web_ip_prior_req", "web_ip_prior_404", "web_ip_prior_4xx_share", "web_ip_prior_login_fail",
"web_ip_prior_sqli", "web_stream_login_posts", "web_stream_login_ips", "web_stream_login_fail_share",
"web_login_ua_share", "web_sqli_score", "web_big_response", "web_ip_prior_tool_ua",
# ssh
"ssh_ip_prior_fail", "ssh_ip_prior_users", "ssh_login_after_fail", "ssh_user_compromised", "ssh_stream_fail",
# exec
"exec_after_suspicious_login", "exec_after_webshell", "exec_url_raw_ip", "exec_sensitive_file", "exec_hidden_tmp",
"exec_dev_tcp", "exec_crontab_write",
# cloud
"cloud_key_new_ip", "cloud_key_new_ua", "cloud_key_prior_events", "cloud_ip_prior_events", "cloud_admin_policy",
"cloud_error", "cloud_ip_external", "cloud_key_prior_errors_from_ip",
# dns
"dns_max_label", "dns_entropy", "dns_num_labels", "dns_digit_share", "dns_client_domain_prior",
"dns_domain_prior_unique", "dns_rare_qtype",
# generic
"ip_external",
]
NUMERIC_INDEX = {n: i for i, n in enumerate(NUMERIC)}
class StreamFeaturizer:
def __init__(self):
self.web_ip = {} # ip -> {"req", "n404", "n4xx", "login_fail", "sqli", "tool"}
self.login_posts = 0
self.login_fail = 0
self.login_ips = set()
self.login_ua = {}
self.ssh_ip = {} # ip -> {"fail", "users": set}
self.ssh_stream_fail = 0
self.compromised_users = set()
self.last_login_suspicious = {} # host -> bool
self.any_suspicious_login = False
self.webshell_seen = False
self.cloud_key = {} # key -> {"ips": set, "uas": set, "n"}
self.cloud_ip = {} # ip -> n
self.cloud_key_ip_err = {} # (key, ip) -> errors
self.dns_cd = {} # (client, base) -> n
self.dns_dom = {} # base -> set(sub labels)
def step(self, line: str):
"""Featurize one line and update the stream state. Returns (parsed, tokens, numeric list)."""
p = parse_line(line)
src = p["src"]
tok = ["src=" + src]
x = [0.0] * len(NUMERIC)
def setf(name, v):
x[NUMERIC_INDEX[name]] = float(v)
ip = p.get("ip")
if ip and RE_IPV4.fullmatch(ip):
setf("ip_external", 0.0 if is_private(ip) else 1.0)
if src == "web":
st = self.web_ip.setdefault(ip, {"req": 0, "n404": 0, "n4xx": 0, "login_fail": 0, "sqli": 0, "tool": 0})
path, q, status, ua = p["path"].lower(), p["query"], p["status"], p["ua"]
tool = ua_tool(ua)
tok += ["m=" + p["method"], "st=" + str(status), "stc=" + str(status // 100) + "xx",
"ua=" + ua_family(ua)]
segs = [s for s in path.split("/") if s]
for s in segs[:4]:
s2 = re.sub(r"\d+", "0", s)
tok.append("seg=" + s2[:40])
ext = re.search(r"\.[a-z0-9]{1,5}$", path)
if ext:
tok.append("ext=" + ext.group(0))
if any(path.endswith(e) for e in SCRIPT_EXT) and p["method"] == "POST":
tok.append("post_script")
if any(k in path for k in SECRET_PATHS):
tok.append("secret_path")
if q:
for k in re.findall(r"(?:^|&)([A-Za-z_]+)=", q)[:4]:
tok.append("qk=" + k.lower())
dq = q.replace("+", " ")
sqli = len(RE_SQLI.findall(dq))
is_login = "login" in path or "signin" in path or "auth" in path
if is_login:
tok.append("login_path")
cmd = re.search(r"(?:^|&)(cmd|exec|command|c)=", q)
if cmd and any(path.endswith(e) for e in SCRIPT_EXT):
tok.append("webshell_cmd")
prior = st["req"]
setf("web_ip_prior_req", lg(prior, 200))
setf("web_ip_prior_404", lg(st["n404"], 20))
setf("web_ip_prior_4xx_share", st["n4xx"] / prior if prior else 0.0)
setf("web_ip_prior_login_fail", lg(st["login_fail"], 10))
setf("web_ip_prior_sqli", lg(st["sqli"], 10))
setf("web_ip_prior_tool_ua", 1.0 if st["tool"] else 0.0)
setf("web_sqli_score", min(1.0, sqli / 4))
setf("web_big_response", 1.0 if p["size"] > 30000 and q else 0.0)
if is_login and p["method"] == "POST":
self.login_posts += 1
self.login_ips.add(ip)
fam = ua_family(ua)
self.login_ua[fam] = self.login_ua.get(fam, 0) + 1
if status >= 400:
self.login_fail += 1
setf("web_stream_login_posts", lg(self.login_posts, 100))
setf("web_stream_login_ips", lg(len(self.login_ips), 20))
setf("web_stream_login_fail_share", self.login_fail / self.login_posts)
setf("web_login_ua_share", self.login_ua[fam] / self.login_posts * lg(self.login_posts, 100))
# update
st["req"] += 1
st["n404"] += status == 404
st["n4xx"] += 400 <= status < 500
st["login_fail"] += is_login and status in (401, 403)
st["sqli"] += sqli >= 2
st["tool"] = st["tool"] or bool(tool)
if "webshell_cmd" in tok:
self.webshell_seen = True
elif src == "ssh":
kind = p["kind"]
tok += ["ssh=" + kind, "prog=" + p["prog"]]
user = p.get("user")
if user in ("root", "admin", "test", "guest", "oracle", "postgres", "ftpuser", "pi", "ubuntu", "ec2-user",
"user", "support", "jenkins", "hadoop", "git", "deploy", "backup"):
tok.append("ssh_generic_user")
host = p.get("host", "")
if ip:
st = self.ssh_ip.setdefault(ip, {"fail": 0, "users": set()})
setf("ssh_ip_prior_fail", lg(st["fail"], 50))
setf("ssh_ip_prior_users", lg(len(st["users"]), 15))
if kind.startswith("accepted"):
suspicious = (st["fail"] >= 3) or (kind == "accepted_password" and not is_private(ip))
setf("ssh_login_after_fail", lg(st["fail"], 50))
self.last_login_suspicious[host] = suspicious
if suspicious:
self.compromised_users.add(user)
self.any_suspicious_login = True
if kind in ("failed_password", "invalid_user"):
st["fail"] += 1
st["users"].add(user)
self.ssh_stream_fail += 1
setf("ssh_stream_fail", lg(self.ssh_stream_fail, 100))
if user and user in self.compromised_users:
setf("ssh_user_compromised", 1.0)
if kind == "sudo":
cmd = (p.get("command") or "").split(" ")[0].split("/")[-1]
tok.append("sudo=" + cmd[:30])
elif src == "exec":
argv = p["argv"] or [""]
a0 = argv[0].split("/")[-1]
joined = " ".join(argv)
tok += ["exe=" + a0[:30], "uid=" + ("www" if p["uid"] == 33 else "root" if p["uid"] == 0 else "user")]
if len(argv) > 1 and argv[1].startswith("-"):
tok.append("flag=" + a0[:20] + argv[1][:6])
host = p.get("host", "")
setf("exec_after_suspicious_login",
1.0 if self.last_login_suspicious.get(host, self.any_suspicious_login) else 0.0)
setf("exec_after_webshell", 1.0 if self.webshell_seen else 0.0)
setf("exec_url_raw_ip", 1.0 if RE_URL_IP.search(joined) else 0.0)
setf("exec_sensitive_file", 1.0 if any(f in joined for f in SENSITIVE_FILES) else 0.0)
setf("exec_hidden_tmp", 1.0 if re.search(r"(/tmp|/dev/shm|/var/tmp)/\.", joined) else 0.0)
setf("exec_dev_tcp", 1.0 if "/dev/tcp/" in joined or re.search(r"\bnc\b.*-e\b", joined) else 0.0)
setf("exec_crontab_write", 1.0 if "crontab -" in joined and "echo" in joined else 0.0)
elif src == "cloud":
key, ua, ev = p.get("key") or "", p["ua"], p["event"]
tok += ["ev=" + ev, "svc=" + p["service"], "ua=" + ua_family(ua),
"ro=" + ("1" if p["read_only"] else "0")]
if p["error"]:
tok.append("err=" + str(p["error"]))
st = self.cloud_key.setdefault(key, {"ips": set(), "uas": set(), "n": 0})
if st["n"]:
setf("cloud_key_new_ip", 0.0 if ip in st["ips"] else 1.0)
setf("cloud_key_new_ua", 0.0 if ua in st["uas"] else 1.0)
setf("cloud_key_prior_events", lg(st["n"], 50))
setf("cloud_ip_prior_events", lg(self.cloud_ip.get(ip, 0), 50))
setf("cloud_admin_policy", 1.0 if "AdministratorAccess" in p["params"] else 0.0)
setf("cloud_error", 1.0 if p["error"] else 0.0)
setf("cloud_ip_external", 0.0 if is_private(ip) else 1.0)
setf("cloud_key_prior_errors_from_ip", lg(self.cloud_key_ip_err.get((key, ip), 0), 5))
# a key that has only ever been used from one place and suddenly shows up somewhere new
# stays suspicious for the rest of the stream, so remember the *first* IP/UA only
if not st["n"]:
st["ips"].add(ip)
st["uas"].add(ua)
st["n"] += 1
self.cloud_ip[ip] = self.cloud_ip.get(ip, 0) + 1
if p["error"]:
self.cloud_key_ip_err[(key, ip)] = self.cloud_key_ip_err.get((key, ip), 0) + 1
elif src == "dns":
q, qt = p["qname"], p["qtype"]
labels = q.split(".")
base = base_domain(q)
sub = ".".join(labels[:-2])
longest = max(labels, key=len) if labels else ""
# no TLD token: the dataset puts every attacker domain under the reserved .test TLD, which a model
# would happily learn as "malicious" and which says nothing about real traffic
tok += ["qt=" + qt]
setf("dns_max_label", min(1.0, len(longest) / 63))
setf("dns_entropy", min(1.0, entropy(sub) / 5.0))
setf("dns_num_labels", min(1.0, (len(labels) - 2) / 4))
setf("dns_digit_share", sum(c.isdigit() for c in sub) / len(sub) if sub else 0.0)
ck = (ip, base)
setf("dns_client_domain_prior", lg(self.dns_cd.get(ck, 0), 100))
subs = self.dns_dom.setdefault(base, set())
setf("dns_domain_prior_unique", lg(len(subs), 100))
setf("dns_rare_qtype", 1.0 if qt in ("TXT", "NULL", "CNAME", "ANY") else 0.0)
self.dns_cd[ck] = self.dns_cd.get(ck, 0) + 1
subs.add(sub)
return p, tok, x
def featurize_stream(lines):
f = StreamFeaturizer()
return [f.step(l) for l in lines]