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

جواب «Step 2: Drop What Must Die» چالش 5 از جلسه‌ی 8

سؤال

(سخت‌تر) قدم ۲: پیش از مسیریابی هر بسته دو بررسی بکن، به همین ترتیب:
۱) اگر از wan0 آمده و is_private(src) درست است: 5 drop: spoofed source 192.168.1.99 on wan0.
۲) اگر ttl <= 1: 4 drop: ttl expired, ICMP time exceeded to 10.20.5.9.
بسته‌ی دورانداخته‌شده دیگر خط مسیر ندارد (continue). بقیه مثل قدم ۱. خط‌های ۴ و ۵ خروجی:
4 drop: ttl expired, ICMP time exceeded to 10.20.5.9
5 drop: spoofed source 192.168.1.99 on wan0

راهنما

داخل حلقه، بعد از n += 1: if p["in"] == "wan0" and is_private(p["src"]): چاپ و continue؛ بعد if p["ttl"] <= 1: چاپ و continue.

یک جواب درست

import ipaddress

PUBLIC_IP = "203.0.113.5"
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")]
ROUTES = [
    ("192.168.1.0/24", "connected", "lan0"),
    ("10.20.0.0/16", "10.255.0.2", "eth1"),
    ("10.20.30.0/24", "10.255.0.3", "eth2"),
    ("203.0.113.5/32", "local", "self"),
    ("0.0.0.0/0", "203.0.113.1", "wan0"),
]
PACKETS = [
    {"in": "lan0", "src": "192.168.1.10", "sport": 51000, "dst": "10.20.30.7", "dport": 443, "ttl": 64},
    {"in": "lan0", "src": "192.168.1.10", "sport": 51001, "dst": "10.20.5.9", "dport": 22, "ttl": 64},
    {"in": "lan0", "src": "192.168.1.23", "sport": 51000, "dst": "198.51.100.20", "dport": 443, "ttl": 128},
    {"in": "eth1", "src": "10.20.5.9", "sport": 22, "dst": "192.168.1.10", "dport": 51001, "ttl": 1},
    {"in": "wan0", "src": "192.168.1.99", "sport": 4444, "dst": "192.168.1.10", "dport": 445, "ttl": 50},
    {"in": "lan0", "src": "192.168.1.10", "sport": 51002, "dst": "203.0.113.80", "dport": 80, "ttl": 64},
    {"in": "wan0", "src": "198.51.100.20", "sport": 443, "dst": "203.0.113.5", "dport": 40000, "ttl": 55},
    {"in": "wan0", "src": "198.51.100.66", "sport": 5555, "dst": "203.0.113.5", "dport": 40009, "ttl": 49},
]

def is_private(addr):
    ip = ipaddress.ip_address(addr)
    for net in PRIVATE:
        if ip in net:
            return True
    return False

def lookup(dst):
    ip = ipaddress.ip_address(dst)
    best = None
    for prefix, hop, iface in ROUTES:
        net = ipaddress.ip_network(prefix)
        if ip in net and (best is None or net.prefixlen > best[0].prefixlen):
            best = (net, hop, iface)
    return best

n = 0
for p in PACKETS:
    n += 1
    if p["in"] == "wan0" and is_private(p["src"]):
        print(f"{n} drop: spoofed source {p['src']} on wan0")
        continue
    if p["ttl"] <= 1:
        print(f"{n} drop: ttl expired, ICMP time exceeded to {p['src']}")
        continue
    net, hop, iface = lookup(p["dst"])
    print(f"{n} {p['src']} -> {p['dst']} via {hop} ({iface}) ttl {p['ttl'] - 1}")

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