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

جواب «Step 2: Watch the Flows» چالش 5 از جلسه‌ی 16

سؤال

(سخت‌تر) قدم ۲: پیش از حلقه‌ی چاپ، FLOWS را به ازای جفت (src, dst) گروه کن (به ترتیب اولین دیده‌شدن) و برای هر جفت:
۱) اگر جمع بایت‌های رفته دست‌کم 100000000 بود، هشدار با زمان اولین جریان آن جفت: what برابر upload 2100.0 MB (round(total / 1000000, 1))، technique برابر T1048.
۲) اگر دست‌کم ۶ جریان داشت: فاصله‌ها را به ثانیه بگیر، mean = sum(gaps) / len(gaps) و اگر statistics.pstdev(gaps) / mean <= 0.1 بود، هشدار با زمان اولین جریان: what برابر beacon every 60.0 s (7 connections)، technique برابر T1071.
(user در هر دو "".) دو خط تازه‌ی خط زمانی:
08:07:00 192.168.10.23 -> 198.51.100.200 beacon every 60.0 s (7 connections) [T1071]
08:15:00 192.168.10.23 -> 203.0.113.99 upload 2100.0 MB [T1048]

راهنما

pairs.setdefault((src, dst), []).append((clock, sent)). برای هر key in pairs: جمع با یک حلقه؛ فاصله‌ها (to_time(flows[i][0]) - to_time(flows[i - 1][0])).total_seconds(). یادت باشد این کد باید بالای حلقه‌ی چاپ باشد.

یک جواب درست

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']}]")

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