Download source/five_desks/tasks/security.py from rca-umb/five-desks: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/rca-umb/five-desks/resolve/main/source/five_desks/tasks/security.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks/source/five_desks/tasks/security.py
-
curl -L -o security.py https://huggingface.co/datasets/rca-umb/five-desks/resolve/main/source/five_desks/tasks/security.py
11.1 kB
| """Security desk: SSH brute-force triage and first-match firewall rules.""" | |
| import ipaddress | |
| import random | |
| from ..grading import Part | |
| from .base import Instance, csv_text | |
| USERS = ["alice", "bob", "carol", "dave", "erin", "frank", "deploy", "backup"] | |
| PROBE_USERS = ["root", "admin", "test", "oracle", "ubuntu", "postgres", "git"] | |
| def _ext_ip(rng): | |
| net = rng.choice(["203.0.113", "198.51.100", "192.0.2", "100.64.7", "45.83.12"]) | |
| return f"{net}.{rng.randrange(2, 254)}" | |
| def _int_ip(rng): | |
| return f"10.{rng.randrange(0, 4)}.{rng.randrange(0, 255)}.{rng.randrange(2, 254)}" | |
| def _fmt(seconds): | |
| return f"{seconds // 3600:02d}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}" | |
| def auth_log(rng: random.Random, level: int, task_id: str) -> Instance: | |
| while True: | |
| inst = _auth_once(rng, level, task_id) | |
| if inst is not None: | |
| return inst | |
| def _auth_once(rng, level, task_id): | |
| threshold = {1: 5, 2: 5, 3: rng.choice([4, 5, 6])}[level] | |
| window_min = {1: 10, 2: 10, 3: rng.choice([5, 10, 15])}[level] | |
| host = rng.choice(["web01", "bastion", "db-02", "gw1"]) | |
| events = [] # (seconds, kind, user, ip) | |
| start = rng.randrange(1 * 3600, 20 * 3600) | |
| def failures(ip, count, t0, spacing, users): | |
| t = t0 | |
| for _ in range(count): | |
| user = rng.choice(users) | |
| kind = "invalid" if user in PROBE_USERS and rng.random() < 0.6 else "fail" | |
| events.append((t, kind, user, ip)) | |
| t += rng.randrange(*spacing) | |
| return t | |
| used_ips = set() | |
| def fresh(maker): | |
| while True: | |
| ip = maker(rng) | |
| if ip not in used_ips: | |
| used_ips.add(ip) | |
| return ip | |
| # The real compromise. | |
| attacker = fresh(_ext_ip) | |
| victim = rng.choice(USERS) | |
| t_attack = start + rng.randrange(600, 5400) | |
| n_fail = threshold + rng.randrange(0, 4) | |
| burst = max(5, (window_min * 60 - 30) // (n_fail + 1)) | |
| t = failures(attacker, n_fail, t_attack, (5, burst), PROBE_USERS + [victim]) | |
| success_t = t + rng.randrange(3, 20) | |
| if success_t - t_attack >= window_min * 60: | |
| return None | |
| events.append((success_t, "accept", victim, attacker)) | |
| # Benign logins from inside the network. | |
| for _ in range({1: 4, 2: 5, 3: 6}[level]): | |
| user = rng.choice(USERS) | |
| ip = fresh(_int_ip) | |
| t0 = start + rng.randrange(0, 7200) | |
| if rng.random() < 0.4: | |
| events.append((t0, "fail", user, ip)) | |
| t0 += rng.randrange(5, 40) | |
| events.append((t0, "accept", user, ip)) | |
| allowlist = [] | |
| if level >= 2: | |
| # Noisy IP that never gets in. | |
| failures(fresh(_ext_ip), threshold + 3, start + rng.randrange(0, 6000), (2, 30), PROBE_USERS) | |
| # A real user who mistypes a few times, below the threshold, from outside. | |
| ip = fresh(_ext_ip) | |
| user = rng.choice([u for u in USERS if u != victim]) | |
| t = failures(ip, threshold - 1, start + rng.randrange(0, 6000), (8, 40), [user]) | |
| events.append((t + 10, "accept", user, ip)) | |
| if level == 3: | |
| # An allowlisted scanner that fails a lot and then succeeds. | |
| scanner = fresh(_ext_ip) | |
| allowlist.append(scanner) | |
| t = failures(scanner, threshold + 2, start + rng.randrange(0, 6000), (2, 20), PROBE_USERS) | |
| events.append((t + 5, "accept", "backup", scanner)) | |
| # A slow guesser: enough failures in total, but spread over more than the window. | |
| slow = fresh(_ext_ip) | |
| t0 = start + rng.randrange(0, 4000) | |
| gap = window_min * 60 // (threshold - 2) + 20 | |
| t = t0 | |
| for _ in range(threshold + 1): | |
| events.append((t, "fail", rng.choice(USERS), slow)) | |
| t += gap | |
| events.append((t, "accept", rng.choice(USERS), slow)) | |
| events.sort() | |
| # Verify the ground truth by brute force over the final log. | |
| allowed = set(allowlist) | |
| hits = [] | |
| for when, kind, user, ip in events: | |
| if kind != "accept" or ip in allowed: | |
| continue | |
| recent = [e for e in events if e[3] == ip and e[1] in ("fail", "invalid") | |
| and when - window_min * 60 <= e[0] < when] | |
| if len(recent) >= threshold: | |
| hits.append((when, user, ip)) | |
| if len(hits) != 1 or hits[0][2] != attacker: | |
| return None | |
| if len({e[0] for e in events}) != len(events): | |
| return None | |
| lines = [] | |
| for when, kind, user, ip in events: | |
| if kind == "accept": | |
| msg = f"Accepted password for {user} from {ip}" | |
| elif kind == "invalid": | |
| msg = f"Failed password for invalid user {user} from {ip}" | |
| else: | |
| msg = f"Failed password for {user} from {ip}" | |
| lines.append(f"{_fmt(when)} {host} sshd: {msg}") | |
| files = {"auth.log": "\n".join(lines) + "\n"} | |
| rules = ["# Triage rule", | |
| f"- A compromise is an 'Accepted' login from an IP that had at least {threshold} failed attempts " | |
| f"(any user, including invalid users) from that same IP in the {window_min} minutes before the accepted login."] | |
| if level == 3: | |
| files["allowlist.txt"] = "\n".join(allowlist) + "\n" | |
| rules.append("- IPs in allowlist.txt are internal scanners: never report them.") | |
| rules.append("- Exactly one compromise is present.") | |
| files["triage_rule.md"] = "\n".join(rules) + "\n" | |
| question = "Find the compromise in auth.log: report (1) the source IP, (2) the account that was logged into, and (3) the time of the accepted login." | |
| parts = [Part("ip", "text", attacker, '"<ip>"'), | |
| Part("user", "text", victim, '"<user>"'), | |
| Part("time", "text", _fmt(success_t), '"HH:MM:SS"')] | |
| return Instance(task_id, "cybersecurity", question, files, parts, max_steps=10) | |
| # ---------------------------------------------------------------- firewall | |
| def _net_pool(rng, level): | |
| prefixes = {1: [8, 16, 24], 2: [16, 24, 24, 28], 3: [12, 20, 22, 26, 27, 29]}[level] | |
| nets = [] | |
| for _ in range(6): | |
| plen = rng.choice(prefixes) | |
| base = ipaddress.ip_address(rng.choice([ | |
| f"10.{rng.randrange(256)}.{rng.randrange(256)}.{rng.randrange(256)}", | |
| f"172.{rng.randrange(16, 32)}.{rng.randrange(256)}.{rng.randrange(256)}", | |
| f"192.168.{rng.randrange(256)}.{rng.randrange(256)}", | |
| ])) | |
| nets.append(ipaddress.ip_network(f"{base}/{plen}", strict=False)) | |
| return nets | |
| def _port_spec(rng, level): | |
| roll = rng.random() | |
| if roll < 0.25: | |
| return "any" | |
| if level >= 2 and roll < 0.5: | |
| lo = rng.choice([1000, 2000, 3000, 8000, 5000]) | |
| return f"{lo}-{lo + rng.choice([99, 499, 999])}" | |
| return str(rng.choice([22, 53, 80, 123, 443, 3306, 5432, 8080])) | |
| def _port_matches(spec, port): | |
| if spec == "any": | |
| return True | |
| if "-" in spec: | |
| lo, hi = map(int, spec.split("-")) | |
| return lo <= port <= hi | |
| return int(spec) == port | |
| def _addr_matches(spec, addr): | |
| return spec == "any" or ipaddress.ip_address(addr) in ipaddress.ip_network(spec) | |
| def _sample_in(rng, net): | |
| return str(net.network_address + rng.randrange(net.num_addresses)) | |
| def _near_miss(rng, net): | |
| # An address just outside the network, which naive prefix reading may misjudge. | |
| side = rng.choice([-1, 1]) | |
| edge = net.network_address - 1 - rng.randrange(0, 3) if side < 0 else net.broadcast_address + 1 + rng.randrange(0, 3) | |
| return str(edge) | |
| def firewall(rng: random.Random, level: int, task_id: str) -> Instance: | |
| while True: | |
| inst = _firewall_once(rng, level, task_id) | |
| if inst is not None: | |
| return inst | |
| def _firewall_once(rng, level, task_id): | |
| n_rules = {1: 4, 2: 6, 3: 8}[level] | |
| n_packets = {1: 5, 2: 7, 3: 9}[level] | |
| protos = ["tcp", "udp"] + (["any"] if level == 3 else []) | |
| nets = _net_pool(rng, level) | |
| rules = [] | |
| for idx in range(n_rules): | |
| rules.append({ | |
| "num": (idx + 1) * 10, | |
| "action": rng.choice(["allow", "deny"]) if idx else "allow", | |
| "proto": rng.choice(protos), | |
| "src": rng.choice([str(n) for n in nets] + ["any"]), | |
| "dst": rng.choice([str(n) for n in nets]), | |
| "port": _port_spec(rng, level), | |
| }) | |
| def decide(pkt): | |
| for r in rules: | |
| if ((r["proto"] == "any" or r["proto"] == pkt["proto"]) and _addr_matches(r["src"], pkt["src"]) | |
| and _addr_matches(r["dst"], pkt["dst"]) and _port_matches(r["port"], pkt["port"])): | |
| return r["action"], str(r["num"]) | |
| return "deny", "default" | |
| packets = [] | |
| for i in range(n_packets): | |
| rule = rng.choice(rules) | |
| proto = rule["proto"] if rule["proto"] != "any" else rng.choice(["tcp", "udp"]) | |
| src_net = ipaddress.ip_network(rule["src"]) if rule["src"] != "any" else rng.choice(nets) | |
| dst_net = ipaddress.ip_network(rule["dst"]) | |
| src = _sample_in(rng, src_net) | |
| dst = _near_miss(rng, dst_net) if level >= 2 and rng.random() < 0.3 else _sample_in(rng, dst_net) | |
| spec = rule["port"] | |
| if spec == "any": | |
| port = rng.choice([22, 80, 443, 8443, 3389, 25]) | |
| elif "-" in spec: | |
| lo, hi = map(int, spec.split("-")) | |
| port = rng.choice([lo, hi, rng.randrange(lo, hi + 1), hi + 1]) | |
| else: | |
| port = int(spec) | |
| if rng.random() < 0.15: | |
| proto = "udp" if proto == "tcp" else "tcp" | |
| packets.append({"id": f"P{i + 1}", "proto": proto, "src": src, "dst": dst, "port": port}) | |
| verdicts = {p["id"]: decide(p) for p in packets} | |
| allowed = sorted((pid for pid, (act, _) in verdicts.items() if act == "allow"), key=lambda s: int(s[1:])) | |
| if not (1 <= len(allowed) <= n_packets - 1): | |
| return None | |
| deciders = {v[1] for v in verdicts.values()} | |
| if len(deciders) < 3: | |
| return None | |
| # Ask about a packet that is not decided by the first rule it superficially resembles. | |
| query = rng.choice([p["id"] for p in packets if verdicts[p["id"]][1] != "10"] or [packets[0]["id"]]) | |
| rule_lines = ["# Firewall policy (evaluated top to bottom; the first matching rule decides; no match = deny)"] | |
| for r in rules: | |
| rule_lines.append(f"rule {r['num']}: {r['action']} proto {r['proto']} from {r['src']} to {r['dst']} port {r['port']}") | |
| files = { | |
| "rules.txt": "\n".join(rule_lines) + "\n", | |
| "packets.csv": csv_text(["id", "proto", "src", "dst", "dst_port"], | |
| [[p["id"], p["proto"], p["src"], p["dst"], p["port"]] for p in packets]), | |
| } | |
| question = (f"Apply rules.txt to every packet in packets.csv. Report (1) the ids of all allowed packets and " | |
| f"(2) which rule decides packet {query} (its rule number, or \"default\" if no rule matches).") | |
| parts = [Part("allowed", "items", allowed, '["P1", ...]'), | |
| Part("deciding_rule", "rule", verdicts[query][1], '"<rule number or default>"')] | |
| return Instance(task_id, "cybersecurity", question, files, parts, max_steps=8) | |