بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 3: The Incident Report» چالش 6 از جلسه‌ی 16

سؤال

(سخت‌تر) قدم ۳: بعد از خط زمانی، گزارش حادثه را چاپ کن. روی خط زمانی مرتب‌شده بچرخ و جمع کن: IPهای بیرونی و درونی (از src و dst هر هشدار، بدون تکرار، به ترتیب اولین دیده‌شدن؛ درونی یعنی در یکی از شبکه‌های PRIVATE)، تکنیک‌ها (بدون تکرار)، و کاربرهای غیرخالی. شدت: high اگر T1110 یا T1048 در تکنیک‌ها بود، وگرنه medium اگر هشداری بود، وگرنه low. خط‌های گزارش:
INCIDENT REPORT
first: 08:02:05, last: 08:15:00, alerts: 5
external: 198.51.100.66, 198.51.100.200, 203.0.113.99
internal: 192.168.10.23
techniques: T1595, T1190, T1110, T1071, T1048
severity: high
action: block 198.51.100.66, 198.51.100.200, 203.0.113.99
action: isolate 192.168.10.23
action: reset password for admin
(برای هر کاربر یک خط reset password.)

راهنما

is_private(addr) با حلقه روی PRIVATE. timeline = sorted(alerts, key=by_time)، چهار فهرست خالی، و برای هر هشدار for addr in (a["src"], a["dst"]):. ", ".join(...) فهرست‌ها را با ویرگول می‌چسباند. زمان اول و آخر: timeline[0] و timeline[-1].

یک جواب درست

import ipaddress
import statistics
from datetime import datetime, timedelta

PRIVATE = [ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16")]
WEB_SERVER = "192.168.10.23"
IDS = [
    {"sid": 1000001, "msg": "LOCAL admin page probe", "contents": ["/admin"], "nocase": True, "technique": "T1595"},
    {"sid": 1000002, "msg": "LOCAL path traversal", "contents": ["../"], "nocase": False, "technique": "T1190"},
]
WEB = [
    ("08:01:10", "198.51.100.66", "GET /index.html HTTP/1.1"),
    ("08:02:05", "198.51.100.66", "GET /Admin/ HTTP/1.1"),
    ("08:02:40", "198.51.100.66", "GET /../../etc/passwd HTTP/1.1"),
    ("08:30:00", "192.0.2.44", "GET /products HTTP/1.1"),
]
AUTH = [
    ("07:50:00", "192.168.10.5", "sara", "success"),
    ("08:05:01", "198.51.100.66", "admin", "failure"),
    ("08:05:20", "198.51.100.66", "admin", "failure"),
    ("08:05:41", "198.51.100.66", "root", "failure"),
    ("08:06:02", "198.51.100.66", "admin", "failure"),
    ("08:06:30", "198.51.100.66", "admin", "success"),
    ("09:00:00", "192.0.2.44", "guest", "failure"),
]
FLOWS = [
    ("08:07:00", "192.168.10.23", "198.51.100.200", 310),
    ("08:08:00", "192.168.10.23", "198.51.100.200", 305),
    ("08:09:01", "192.168.10.23", "198.51.100.200", 312),
    ("08:10:00", "192.168.10.23", "198.51.100.200", 309),
    ("08:11:00", "192.168.10.23", "198.51.100.200", 306),
    ("08:12:01", "192.168.10.23", "198.51.100.200", 311),
    ("08:13:00", "192.168.10.23", "198.51.100.200", 308),
    ("08:15:00", "192.168.10.23", "203.0.113.99", 2100000000),
    ("08:20:00", "192.168.10.5", "198.51.100.20", 5000),
    ("08:21:30", "192.168.10.5", "198.51.100.20", 4000),
    ("08:40:00", "192.168.10.5", "198.51.100.20", 7000),
    ("08:41:10", "192.168.10.5", "198.51.100.20", 3000),
    ("08:44:00", "192.168.10.7", "198.51.100.53", 900),
    ("09:10:00", "192.168.10.5", "198.51.100.20", 6000),
    ("09:30:00", "192.168.10.5", "198.51.100.20", 2000),
]

def to_time(text):
    return datetime.strptime(text, "%H:%M:%S")

def ids_match(rule, text):
    if rule["nocase"]:
        text = text.lower()
    for needle in rule["contents"]:
        if rule["nocase"]:
            needle = needle.lower()
        if needle not in text:
            return False
    return True

def by_time(alert):
    return to_time(alert["time"])

alerts = []
for clock, src, request in WEB:
    for rule in IDS:
        if ids_match(rule, request):
            alerts.append({"time": clock, "src": src, "dst": WEB_SERVER, "user": "",
                           "what": f"IDS sid:{rule['sid']} {rule['msg']}", "technique": rule["technique"]})

fails = {}
def auth_time(e):
    return to_time(e[0])

for clock, ip, user, outcome in sorted(AUTH, key=auth_time):
    if outcome == "failure":
        fails.setdefault(ip, []).append(to_time(clock))
    else:
        count = 0
        for f in fails.get(ip, []):
            if to_time(clock) - f <= timedelta(minutes=10):
                count += 1
        if count >= 3:
            alerts.append({"time": clock, "src": ip, "dst": WEB_SERVER, "user": user,
                           "what": f"brute-force success for {user} ({count} failures)", "technique": "T1110"})
pairs = {}
for clock, src, dst, sent in FLOWS:
    pairs.setdefault((src, dst), []).append((clock, sent))
for key in pairs:
    src, dst = key
    flows = pairs[key]
    total = 0
    for clock, sent in flows:
        total += sent
    if total >= 100000000:
        alerts.append({"time": flows[0][0], "src": src, "dst": dst, "user": "",
                       "what": f"upload {round(total / 1000000, 1)} MB", "technique": "T1048"})
    if len(flows) >= 6:
        gaps = []
        for i in range(1, len(flows)):
            gaps.append((to_time(flows[i][0]) - to_time(flows[i - 1][0])).total_seconds())
        mean = sum(gaps) / len(gaps)
        if statistics.pstdev(gaps) / mean <= 0.1:
            alerts.append({"time": flows[0][0], "src": src, "dst": dst, "user": "",
                           "what": f"beacon every {round(mean, 1)} s ({len(flows)} connections)", "technique": "T1071"})
for a in sorted(alerts, key=by_time):
    print(f"{a['time']} {a['src']} -> {a['dst']} {a['what']} [{a['technique']}]")
def is_private(addr):
    for net in PRIVATE:
        if ipaddress.ip_address(addr) in net:
            return True
    return False

timeline = sorted(alerts, key=by_time)
external = []
internal = []
techniques = []
users = []
for a in timeline:
    for addr in (a["src"], a["dst"]):
        if is_private(addr):
            if addr not in internal:
                internal.append(addr)
        elif addr not in external:
            external.append(addr)
    if a["technique"] not in techniques:
        techniques.append(a["technique"])
    if a["user"] and a["user"] not in users:
        users.append(a["user"])
if "T1110" in techniques or "T1048" in techniques:
    severity = "high"
elif timeline:
    severity = "medium"
else:
    severity = "low"
print("INCIDENT REPORT")
print(f"first: {timeline[0]['time']}, last: {timeline[-1]['time']}, alerts: {len(timeline)}")
print("external:", ", ".join(external))
print("internal:", ", ".join(internal))
print("techniques:", ", ".join(techniques))
print("severity:", severity)
print("action: block " + ", ".join(external))
print("action: isolate " + ", ".join(internal))
for user in users:
    print("action: reset password for " + user)

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن