ajinkyamulay's picture
v5: difficulty levels, 27B calibration notes
5f867e3 verified
Raw History Blame Contribute Delete
17.2 kB
"""Cybersecurity: log forensics, config deobfuscation, firewall rule evaluation."""
import base64
import hashlib
import ipaddress
import json
import zlib
from ..grading import TaskInstance, exact, norm, parts_score, token_set
USERS = ["root", "admin", "deploy", "backup", "git", "ubuntu", "oracle", "postgres", "jenkins", "svc_ci"]
def _ip(rng):
return f"{rng.choice([45, 61, 91, 103, 141, 185, 193, 203])}.{rng.randint(0, 255)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}"
def ssh_bruteforce(rng, level=1) -> TaskInstance:
if level >= 2:
return _ssh_subnet(rng)
threshold = rng.randint(5, 10)
window = rng.choice([10, 15, 30])
events = [] # (second, ip, user, ok)
def burst(ip, start, count, users):
t = start
for _ in range(count):
t += rng.randint(2, 40)
events.append((t, ip, rng.choice(users), False))
return t
attacker, victim = _ip(rng), rng.choice(USERS)
t = burst(attacker, rng.randint(3600, 60000), threshold + rng.randint(0, 6), [victim, "root", "admin"])
events.append((t + rng.randint(5, 50), attacker, victim, True))
for _ in range(rng.randint(2, 4)): # noisy scanners that never get in
burst(_ip(rng), rng.randint(0, 80000), rng.randint(threshold, threshold + 20), USERS)
slow = _ip(rng) # many failures but spread out, then a success
t = rng.randint(0, 20000)
for _ in range(threshold + 2):
t += window * 60 // (threshold - 2) + rng.randint(30, 300)
events.append((t, slow, "deploy", False))
events.append((t + 60, slow, "deploy", True))
for _ in range(rng.randint(8, 20)): # legitimate logins with an occasional typo
ip, user = f"10.0.{rng.randint(0, 9)}.{rng.randint(2, 250)}", rng.choice(USERS[2:])
t = rng.randint(60, 86000)
if rng.random() < 0.4:
events.append((t - 20, ip, user, False))
events.append((t, ip, user, True))
events.sort()
lines = []
for sec, ip, user, ok in events:
sec %= 86400
stamp = f"Oct 7 {sec // 3600:02d}:{sec % 3600 // 60:02d}:{sec % 60:02d}"
pid = rng.randint(1000, 65000)
if ok:
lines.append(f"{stamp} bastion sshd[{pid}]: Accepted password for {user} from {ip} port {rng.randint(30000, 65000)} ssh2")
else:
lines.append(f"{stamp} bastion sshd[{pid}]: Failed password for {'invalid user ' if rng.random() < 0.3 else ''}{user} from {ip} port {rng.randint(30000, 65000)} ssh2")
rule = (f"INCIDENT RULE: an IP is a confirmed compromise when it has at least {threshold} failed "
f"password attempts within any {window}-minute window and then an accepted login.\n")
return TaskInstance(
instruction=("auth.log is one day of sshd logs; incident_rule.txt defines a confirmed "
"compromise. Answer the attacking IP and the account it logged in as, "
"ip,username. Each part is worth 0.5."),
files={"auth.log": "\n".join(lines) + "\n", "incident_rule.txt": rule},
grade=lambda a: parts_score(a, [exact(attacker), exact(victim)]),
oracle=f"{attacker},{victim}",
wrong=[f"{slow},deploy"],
)
TLDS = ["example", "invalid", "test"]
def decode_config(rng, level=1) -> TaskInstance:
if level >= 2:
return _decode_layered(rng)
def host():
return "".join(rng.choice("bcdfghjklmnpqrstvwxz") + rng.choice("aeiou") for _ in range(rng.randint(3, 5))) \
+ "." + rng.choice(["cdn", "api", "sync", "edge"]) + "." + rng.choice(TLDS)
primary, fallback = host(), host()
key = bytes(rng.randint(1, 255) for _ in range(rng.randint(4, 9)))
offset = rng.randint(1, 7)
reverse = rng.random() < 0.5
def encode(obj):
raw = json.dumps(obj).encode()
if reverse:
raw = raw[::-1]
out = bytes(b ^ key[(i + offset) % len(key)] for i, b in enumerate(raw))
return base64.b64encode(out).decode()
cfg = {"c2": f"https://{primary}/{rng.choice(['beacon', 'gate', 'poll'])}", "sleep": rng.randint(10, 300),
"jitter": rng.randint(5, 40)}
fb = {"c2": f"https://{fallback}/{rng.choice(['beacon', 'gate'])}", "sleep": rng.randint(10, 300)}
source = f'''"""Sample recovered from a lab honeypot (defanged: nothing here runs on import)."""
import base64
import json
KEY = bytes({list(key)})
OFFSET = {offset}
PRIMARY = "{encode(cfg)}"
FALLBACK = "{encode(fb)}"
def unpack(blob):
data = base64.b64decode(blob)
plain = bytes(b ^ KEY[(i + OFFSET) % len(KEY)] for i, b in enumerate(data))
{"plain = plain[::-1]" if reverse else "pass"}
return json.loads(plain)
'''
return TaskInstance(
instruction=("loader.py holds two encoded configs. Which hostname does the PRIMARY config "
"contact? Answer the hostname only, without scheme or path."),
files={"loader.py": source},
grade=lambda a: float(norm(a).removeprefix("https://").split("/")[0] == primary),
oracle=primary,
wrong=[fallback],
)
def firewall_rules(rng, level=1) -> TaskInstance:
if level >= 2:
return _firewall_chains(rng)
rules = []
nets = ["10.0.0.0/8", "10.1.0.0/16", "10.1.2.0/24", "192.168.0.0/16", "172.16.0.0/12",
"203.0.113.0/24", "198.51.100.0/24", "0.0.0.0/0"]
ports = [(22, 22), (80, 80), (443, 443), (5432, 5432), (8000, 8999), (1, 1023), (3389, 3389), (1, 65535)]
for i in range(rng.randint(7, 11)):
lo, hi = rng.choice(ports)
rules.append({"id": f"R{10 * (i + 1)}", "action": rng.choice(["allow", "deny"]),
"proto": rng.choice(["tcp", "tcp", "udp", "any"]), "src": rng.choice(nets),
"ports": (lo, hi)})
def verdict(ip, proto, port):
for r in rules:
if (r["proto"] in ("any", proto) and ipaddress.ip_address(ip) in ipaddress.ip_network(r["src"])
and r["ports"][0] <= port <= r["ports"][1]):
return r["action"]
return "deny"
conns, allowed = [], set()
for i in range(rng.randint(15, 25)):
net = ipaddress.ip_network(rng.choice(nets[:-1] + ["8.8.0.0/16"]))
ip = str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 70000)))
proto = rng.choice(["tcp", "tcp", "udp"])
lo, hi = rng.choice(ports)
port = rng.randint(lo, min(hi, lo + 200))
cid = f"c{i + 1:02d}"
conns.append([cid, ip, proto, port])
if verdict(ip, proto, port) == "allow":
allowed.add(cid)
denied = sorted({c[0] for c in conns} - allowed)
if len(allowed) < 2 or len(denied) < 2:
return firewall_rules(rng)
text = ["# id action proto src_cidr dst_ports (evaluated top to bottom; first match wins)"]
text += [f"{r['id']} {r['action']} {r['proto']} {r['src']} {r['ports'][0]}-{r['ports'][1]}" for r in rules]
text.append("# no rule matched -> deny")
oracle = ",".join(sorted(allowed)) or "none"
target = token_set(oracle)
return TaskInstance(
instruction=("Evaluate each connection in connections.csv against rules.txt. Answer the ids "
"of all allowed connections, comma-separated ascending (e.g. c02,c07), or none."),
files={"rules.txt": "\n".join(text) + "\n",
"connections.csv": "id,src_ip,proto,dst_port\n" + "\n".join(",".join(map(str, c)) for c in conns) + "\n"},
grade=lambda a: float(token_set(a) == target),
oracle=oracle,
wrong=[",".join(sorted(allowed)[1:]), ",".join(sorted(allowed | {denied[0]}))],
)
def _syslog(sec, host, msg):
return f"Oct {7 + sec // 86400} {sec % 86400 // 3600:02d}:{sec % 3600 // 60:02d}:{sec % 60:02d} {host} {msg}"
def _ssh_subnet(rng) -> TaskInstance:
"""Failures spread over several IPs of one /24; logs split across a rotated file."""
threshold = rng.randint(8, 14)
window = rng.choice([10, 15, 20])
net = f"{rng.choice([45, 91, 141, 185, 193])}.{rng.randint(0, 255)}.{rng.randint(0, 255)}"
victim = rng.choice(USERS)
events = []
t = rng.randint(30000, 70000)
ips = [f"{net}.{h}" for h in rng.sample(range(2, 250), rng.randint(3, 5))]
for _ in range(threshold + rng.randint(0, 4)):
t += rng.randint(5, max(6, window * 60 // (threshold + 4)))
events.append((t, rng.choice(ips), rng.choice([victim, "root", "admin"]), False))
winner = rng.choice(ips)
events.append((t + rng.randint(10, 60), winner, victim, True))
for _ in range(rng.randint(2, 4)): # single noisy scanners that never get in
ip, t2 = _ip(rng), rng.randint(0, 80000)
for _ in range(rng.randint(threshold, threshold + 15)):
t2 += rng.randint(2, 30)
events.append((t2, ip, rng.choice(USERS), False))
other = f"{rng.choice([61, 103, 203])}.{rng.randint(0, 255)}.{rng.randint(0, 255)}" # slow subnet, gets in
t3 = rng.randint(0, 20000)
for _ in range(threshold + 3):
t3 += window * 60 // max(1, threshold - 3) + rng.randint(30, 200)
events.append((t3, f"{other}.{rng.randint(2, 250)}", "deploy", False))
events.append((t3 + 30, f"{other}.{rng.randint(2, 250)}", "deploy", True))
for _ in range(rng.randint(10, 25)): # legitimate internal logins
ip, user, t4 = f"10.0.{rng.randint(0, 9)}.{rng.randint(2, 250)}", rng.choice(USERS[2:]), rng.randint(60, 86000)
if rng.random() < 0.4:
events.append((t4 - 20, ip, user, False))
events.append((t4, ip, user, True))
events.sort()
lines = []
for sec, ip, user, ok in events:
pid = rng.randint(1000, 65000)
verb = f"Accepted password for {user}" if ok else f"Failed password for {'invalid user ' if rng.random() < 0.3 else ''}{user}"
lines.append(_syslog(sec, "bastion", f"sshd[{pid}]: {verb} from {ip} port {rng.randint(30000, 65000)} ssh2"))
burst_mid = sorted(e[0] for e in events if e[1].startswith(net + "."))
cut_time = burst_mid[len(burst_mid) // 2]
older = [ln for (sec, *_r), ln in zip(events, lines) if sec < cut_time]
newer = [ln for (sec, *_r), ln in zip(events, lines) if sec >= cut_time]
rule = (f"INCIDENT RULE: failures are counted per /24 network (the first three octets). A network is "
f"a confirmed compromise when it has at least {threshold} failed password attempts within "
f"any {window}-minute window and then an accepted login from any address in it. Logs rotate: "
"auth.log.1 holds the older lines.\n")
return TaskInstance(
instruction=("auth.log.1 and auth.log are one day of sshd logs; incident_rule.txt defines a "
"confirmed compromise. Answer the compromised network as a.b.c.0/24, the exact address "
"that logged in, and the account, network,ip,username. Each part counts equally."),
files={"auth.log.1": "\n".join(older) + "\n", "auth.log": "\n".join(newer) + "\n",
"incident_rule.txt": rule},
grade=lambda a: parts_score(a, [exact(f"{net}.0/24"), exact(winner), exact(victim)]),
oracle=f"{net}.0/24,{winner},{victim}",
wrong=[f"{other}.0/24,{winner},deploy"],
)
def _decode_layered(rng) -> TaskInstance:
"""base64 -> rotating XOR keyed by sha256(passphrase) -> zlib; the active profile is in a config file."""
def host():
return "".join(rng.choice("bcdfghjklmnpqrstvwxz") + rng.choice("aeiou") for _ in range(rng.randint(3, 5))) \
+ "." + rng.choice(["cdn", "api", "sync", "edge"]) + "." + rng.choice(TLDS)
names = rng.sample(["alpha", "beta", "gamma", "delta"], 3)
hosts = {n: host() for n in names}
active = rng.choice(names)
passphrase = "".join(rng.choice("abcdefghijkmnpqrstuvwxyz23456789") for _ in range(12))
key = hashlib.sha256(passphrase.encode()).digest()[: rng.randint(6, 12)]
def encode(obj):
raw = zlib.compress(json.dumps(obj).encode())
return base64.b64encode(bytes(b ^ key[i % len(key)] for i, b in enumerate(raw))).decode()
blobs = {n: encode({"c2": f"https://{hosts[n]}/{rng.choice(['beacon', 'gate', 'poll'])}",
"sleep": rng.randint(10, 300)}) for n in names}
source = f'''"""Sample recovered from a lab honeypot (defanged: nothing here runs on import)."""
import base64
import configparser
import hashlib
import json
import zlib
PROFILES = {json.dumps(blobs, indent=4)}
def _key(cfg):
phrase = cfg["loader"]["passphrase"]
return hashlib.sha256(phrase.encode()).digest()[: int(cfg["loader"]["key_len"])]
def unpack(blob, key):
data = base64.b64decode(blob)
return json.loads(zlib.decompress(bytes(b ^ key[i % len(key)] for i, b in enumerate(data))))
def active(path="loader.ini"):
cfg = configparser.ConfigParser()
cfg.read(path)
return unpack(PROFILES[cfg["loader"]["profile"]], _key(cfg))
'''
ini = (f"[loader]\n; profile selects one entry of PROFILES\nprofile = {active}\n"
f"passphrase = {passphrase}\nkey_len = {len(key)}\n")
return TaskInstance(
instruction=("loader.py and loader.ini come from a recovered sample. Which hostname does the "
"profile selected in loader.ini contact? Answer the hostname only, without scheme or path."),
files={"loader.py": source, "loader.ini": ini},
grade=lambda a: float(norm(a).removeprefix("https://").split("/")[0] == hosts[active]),
oracle=hosts[active],
wrong=[hosts[n] for n in names if n != active],
)
def _firewall_chains(rng) -> TaskInstance:
"""First-match rules with user chains (jump/return) and a default policy."""
nets = ["10.0.0.0/8", "10.1.0.0/16", "10.1.2.0/24", "192.168.0.0/16", "172.16.0.0/12",
"203.0.113.0/24", "198.51.100.0/24", "0.0.0.0/0"]
ports = [(22, 22), (80, 80), (443, 443), (5432, 5432), (8000, 8999), (1, 1023), (3389, 3389), (1, 65535)]
def rule(i, actions):
lo, hi = rng.choice(ports)
return {"id": f"R{i}", "action": rng.choice(actions), "proto": rng.choice(["tcp", "tcp", "udp", "any"]),
"src": rng.choice(nets), "ports": (lo, hi)}
chains = {"MGMT": [rule(100 + i, ["allow", "deny", "return"]) for i in range(rng.randint(3, 5))],
"WEB": [rule(200 + i, ["allow", "deny", "return"]) for i in range(rng.randint(3, 5))]}
main = [rule(10 * (i + 1), ["allow", "deny", "jump MGMT", "jump WEB"]) for i in range(rng.randint(6, 9))]
policy = rng.choice(["deny", "allow"])
def matches(r, ip, proto, port):
return (r["proto"] in ("any", proto) and ipaddress.ip_address(ip) in ipaddress.ip_network(r["src"])
and r["ports"][0] <= port <= r["ports"][1])
def run(chain, ip, proto, port):
for r in chain:
if not matches(r, ip, proto, port):
continue
if r["action"] in ("allow", "deny"):
return r["action"]
if r["action"] == "return":
return None
verdict = run(chains[r["action"].split()[1]], ip, proto, port)
if verdict:
return verdict
return None
conns, allowed = [], set()
for i in range(rng.randint(18, 28)):
net = ipaddress.ip_network(rng.choice(nets[:-1] + ["8.8.0.0/16"]))
ip = str(net.network_address + rng.randint(1, min(net.num_addresses - 2, 70000)))
proto = rng.choice(["tcp", "tcp", "udp"])
lo, hi = rng.choice(ports)
port = rng.randint(lo, min(hi, lo + 200))
cid = f"c{i + 1:02d}"
conns.append([cid, ip, proto, port])
if (run(main, ip, proto, port) or policy) == "allow":
allowed.add(cid)
denied = sorted({c[0] for c in conns} - allowed)
if len(allowed) < 2 or len(denied) < 2:
return _firewall_chains(rng)
def fmt(r):
return f"{r['id']} {r['action'].replace(' ', ':')} {r['proto']} {r['src']} {r['ports'][0]}-{r['ports'][1]}"
text = ["# chain INPUT (evaluated top to bottom; first matching allow/deny decides)"]
text += [fmt(r) for r in main]
text.append(f"# INPUT default policy: {policy}")
for name, chain in chains.items():
text.append(f"# chain {name}: jump:{name} evaluates it; return or reaching its end goes back to the rule after the jump")
text += [fmt(r) for r in chain]
oracle = ",".join(sorted(allowed))
target = token_set(oracle)
return TaskInstance(
instruction=("Evaluate each connection in connections.csv against rules.txt (chains, jumps and "
"the default policy). Answer the ids of all allowed connections, comma-separated "
"ascending (e.g. c02,c07)."),
files={"rules.txt": "\n".join(text) + "\n",
"connections.csv": "id,src_ip,proto,dst_port\n" + "\n".join(",".join(map(str, c)) for c in conns) + "\n"},
grade=lambda a: float(token_set(a) == target),
oracle=oracle,
wrong=[",".join(sorted(allowed)[1:]), ",".join(sorted(allowed | {denied[0]}))],
)
TASKS = {
"sec-ssh-bruteforce": ssh_bruteforce,
"sec-decode-config": decode_config,
"sec-firewall-rules": firewall_rules,
}