-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathportScanner.py
657 lines (552 loc) · 23.3 KB
/
portScanner.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
"""
portScanner is a tool for scanning whole network or any number of hosts in a network
to find open ports and vulnerable services running on the machine.
For example : the network format can be 192.168.31.0/24 (whole network),
192.168.31.10-25(some hosts in the network), or a single host like 192.168.31.5
or 192.168.31.5/32
"""
# ----------------------------------------------------------------------------#
# Imports
# ----------------------------------------------------------------------------#
import argparse
import nmap
import json
import ipaddress
from colorama import Style, Fore
import datetime
from sqlalchemy import and_, exists
from src.ftp_login import FTP_login
from src.ssh_login import SSH_login
from src.telnet_login import Telnet_login
from src.rfunctions import *
from models import *
import configparser
from multiprocessing import Pool
from functools import partial
import os
__author__ = "tinyb0y"
__email__ = Fore.RED + "[email protected]"
# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#
basedir = os.path.abspath(os.path.dirname(__file__)) + '/'
config = configparser.ConfigParser()
config.read(basedir + 'app.cfg')
engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=False)
Session = sessionmaker(bind=engine)
Session.configure(bind=engine)
session = Session()
attackVectorList = dict()
# ----------------------------------------------------------------------------#
ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
END = '\033[0m'
additional_options = ' ' + config['DEFAULT']['options']
inModule = False
allModules = []
modules = []
cores = int(config['DEFAULT']['cores'])
header = """
_____ _ _ ___
|_ _(_)_ __ _ _| |__ / _ \ _ _
| | | | '_ \| | | | '_ \| | | | | | |
| | | | | | | |_| | |_) | |_| | |_| |
|_| |_|_| |_|\__, |_.__/ \___/ \__, |
|___/ |___/
""" + "\t\t" + __email__
# -----------------------------------------------------#
def loadConfig():
with open('Options.conf') as f:
data = json.load(f)
return data
def loadModules():
data = loadConfig()
for item in data:
allModules.append([item['option'], item['help']])
modules.append(item['option'])
def helpPrint(name, desc, usage):
print("\t" + Fore.YELLOW + name + Fore.GREEN + ": " + Fore.BLUE + desc + Fore.GREEN + " - '" + usage + "'" + END)
def commands():
print(Fore.GREEN + "\n[I] Available commands:\n" + END)
helpPrint("MODULES", "List all modules", "modules")
helpPrint("USE", "Use a module", "use module_name")
helpPrint("OPTIONS", "Show a module's options", "options")
helpPrint("SET", "Set an option", "set option_name option_value")
helpPrint("RUN", "Run the selected module", "run")
helpPrint("FULL SCAN", "Scan the whole network", "fullscan")
helpPrint("BACK", "Go back to menu", "back")
helpPrint("EXIT", "Shut down portScanner", "exit")
print()
def checkCommandAvailable(module):
if module in modules:
return True
else:
return False
def logFileCreation():
script_path = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(script_path + "/logs"):
os.makedirs(script_path + "/logs")
dt = datetime.now()
dt = str(dt).replace(" ", "_")
dt = str(dt).replace(":", "-")
fileName = script_path + "/logs/tinyb0y-ScanReport" + dt + ".log"
file = open(fileName, 'w')
file.write("Scan Report using Tinyb0y PortScanner " + str(dt))
file.close()
return fileName
def writeScanEvents(fileName, eventScan):
file = open(fileName, "a")
# print("*"*50)
# print("Writing to FIlename", fileName)
# print(eventScan)
# print("*" * 50)
file.write(eventScan)
file.close()
def getModuleOptions(module):
commands_for_current_module = []
data = loadConfig()
if inModule:
for item in data:
if item['option'] == module:
for key in item['commands'].keys():
if '->' in item['commands'][key]:
value = item['commands'][key].split('->')[1].strip()
description = item['commands'][key].split('->')[0]
else:
value = ''
description = item['commands'][key]
commands_for_current_module.append([key, description, value])
return commands_for_current_module
def getOptionValue(option):
for item in moduleOptions:
if item[0] == option:
return item[2]
def createIPList(network):
net4 = ipaddress.ip_network(network)
ipList = []
for x in net4.hosts():
ipList.append(str(x))
return ipList
def createIPListRange(networkRange):
end = int(networkRange.split('-')[1])
ipaddressSplit = networkRange.split('-')[0].split('.')
start = int(ipaddressSplit[3])
IPList = []
for num in range(start, end):
IPList.append(ipaddressSplit[0] + '.' + ipaddressSplit[1] + '.' + ipaddressSplit[2] + '.' + str(num))
return IPList
def getIPlist(ipvar):
if '/' in ipvar:
if len(ipvar.split('/')) > 1:
return createIPList(ipvar)
else:
print(Fore.RED + "[!] Invalid IP subnet")
elif '-' in ipvar:
if len(ipvar.split('-')) > 1:
return createIPListRange(ipvar)
else:
print(Fore.RED + "[!] Invalid IP Range")
elif ',' in ipvar:
if len(ipvar.split(',')) > 1:
return list(filter(None, ipvar.split(',')))
else:
return [ipvar]
# ----------------------------------------------------------------------------#
# BruteForce Modules
# ----------------------------------------------------------------------------#
bruteforce_modules = [
('ftp_login', (Controller, FTP_login)),
('ssh_login', (Controller, SSH_login)),
('telnet_login', (Controller, Telnet_login))
]
available = dict(bruteforce_modules)
ssh = [22, 2222]
telnet = [23]
ftp = [21]
def bruteforce():
for ip in attackVectorList.keys():
for port in attackVectorList[ip]:
modulename = ''
if port in ssh:
modulename = 'ssh_login'
ignoremseg = 'ignore:mesg=Authentication failed.'
FILE0 = basedir + getOptionValue('userFile')
FILE1 = basedir + getOptionValue('passFile')
elif port in telnet:
modulename = 'telnet_login'
ignoremseg1 = 'ignore:egrep="Login incorrect."'
ignoremseg2 = 'ignore:fgrep="Password:"'
FILE0 = basedir + getOptionValue('userFile')
FILE1 = basedir + getOptionValue('passFile')
elif port in ftp:
modulename = 'ftp_login'
ignoremseg = 'ignore:mesg=Login incorrect.'
FILE0 = basedir + getOptionValue('userFile')
FILE1 = basedir + getOptionValue('passFile')
else:
pass
if modulename != '':
print(
Fore.RED + "[!] Brute Force Attack Going On " + Style.RESET_ALL + Fore.YELLOW + ip + Style.RESET_ALL + Fore.RED,
"with modulename", Style.RESET_ALL, Fore.GREEN, modulename, END)
ctrl, module = available[modulename]
user = 'FILE0\n'
passwd = 'FILE1'
if getOptionValue('verbose') == 'true':
if modulename == 'telnet_login':
powder = ctrl(module,
[modulename, 'host=' + ip, 'inputs=FILE0\nFILE1', '0=' + FILE0, '1=' + FILE1,
'persistent=0', 'prompt_re="Username:|Password:"', '-x', ignoremseg1, '-x',
ignoremseg2, '-l', 'logs/'])
elif modulename == 'ftp_login':
powder = ctrl(module,
[modulename, 'host=' + ip, 'user=' + user, 'password=' + passwd, '0=' + FILE0,
'1=' + FILE1, '-x', ignoremseg,
'-l', 'logs/'])
elif modulename == 'ssh_login':
powder = ctrl(module,
[modulename, 'host=' + ip, 'user=' + user, 'password=' + passwd, '0=' + FILE0,
'1=' + FILE1, '-x', ignoremseg,
'-l', 'logs/'])
else:
print("[-] No Module to bruteforce")
else:
powder = ctrl(module,
[modulename, 'host=' + ip, 'user=' + user, 'password=' + passwd, '0=' + FILE0,
'1=' + FILE1, '-x', ignoremseg])
powder.fire()
# ----------------------------------------------------------------------------#
# Scanning
# ----------------------------------------------------------------------------#
# def scan(IP, options):
# fileName = logFileCreation()
# IPList = getIPlist(IP)
# for ip in IPList:
# if 'p' in options:
# nm = nmap.PortScanner()
# nm.scan(ip, arguments=options + additional_options)
# # print(nm.command_line())
# else:
# nm = nmap.PortScanner()
# nm.scan(ip, options, arguments=additional_options)
# # print(nm.command_line())
# try:
# if nm[ip].all_protocols():
# PrintOnScreen(ip, nm, fileName)
# else:
# print(nm[ip].all_protocols())
# except:
# pass
# if getOptionValue('bruteforce') == 'true' or getOptionValue('bruteforce') == 'True':
# bruteforce()
#
# print("Logs are saved in " + fileName)
def checkToPrint(nm, host):
for proto in nm[host].all_protocols():
ports = list(nm[host][proto].keys())
for port in ports:
# print(nm[host][proto])
if nm[host][proto][port]['state'] == "open":
return True
return False
def scanMulti(ip, args):
options = args[0]
fileName = args[1]
if 'p' in options:
nm = nmap.PortScanner()
nm.scan(ip, arguments=options + additional_options)
# print(nm.command_line())
else:
nm = nmap.PortScanner()
nm.scan(ip, options, arguments=additional_options)
# print(nm.command_line())
try:
if checkToPrint(nm, ip):
PrintOnScreen(ip, nm, fileName)
else:
pass
# print(nm[ip].all_protocols())
except:
writeScanEvents(fileName, ip)
def scan(IP, options):
fileName = logFileCreation()
IPList = getIPlist(IP)
pool = Pool(processes=cores)
args = [options, fileName]
pool.map(partial(scanMulti, args=args), IPList)
if getOptionValue('bruteforce') == 'true' or getOptionValue('bruteforce') == 'True':
bruteforce()
print("Logs are saved in " + fileName)
print()
def scan_from_file(options):
fileName = logFileCreation()
IPListFromFile = getListfromFile(getOptionValue('filename'))
for IP in IPListFromFile:
IPList = getIPlist(IP)
pool = Pool(processes=cores)
args = [options, fileName]
pool.map(partial(scanMulti, args=args), IPList)
# for ip in IPList:
# # print(ip)
# if 'p' in options:
# nm = nmap.PortScanner()
# nm.scan(ip, arguments=options + additional_options)
# else:
# nm = nmap.PortScanner()
# nm.scan(ip, options, arguments=additional_options)
# try:
# if nm[ip].all_protocols():
# PrintOnScreen(ip, nm, fileName)
# except:
# pass
if getOptionValue('bruteforce') == 'true' or getOptionValue('bruteforce') == 'True':
bruteforce()
print("Logs are saved in " + fileName)
print()
def getListfromFile(filename):
iplist = open(filename).read().split()
return iplist
def insertRecord(ip, service, port):
if session.query(exists().where(and_(Scan.port == port, Scan.ip == ip))).scalar():
row = session.query(Scan).filter(and_(Scan.port == port, Scan.ip == ip)).first()
row.port = port
row.service = service
row.ip = ip
row.updated = datetime.now()
session.commit()
else:
scanRecord = Scan(ip=ip, service=service, port=port, updated=datetime.now())
session.add(scanRecord)
session.commit()
def PrintOnScreen(host, nm, fileName):
if getOptionValue('verbose') == 'true':
finalStr = '\n'
finalStr += '-' * 50 + '\n'
finalStr += "| " + Fore.GREEN + str(host) + " |" + '\n'
finalStr += '-' * 50 + '\n'
hostname = Fore.YELLOW + "-unknown-" + '\n'
if nm[host].hostname() != "":
hostname = nm[host].hostname()
finalStr += " " * (
(len(host) + 4)) + "|_ " + Fore.GREEN + Style.DIM + "Hostname" + Style.RESET_ALL + " : %s" % (
hostname) + '\n'
if nm[host].all_protocols():
finalStr += " " * (len(host) + 4) + "|_ " + Fore.GREEN + Style.DIM + "Ports" + Style.RESET_ALL + '\n'
for proto in nm[host].all_protocols():
ports = list(nm[host][proto].keys())
ports.sort()
finalStr += " " * ((len(
host) + 4)) + "|" + '\t' + "[" + Fore.GREEN + Style.DIM + "+" + Style.RESET_ALL + '] Protocol : %s' % proto + '\n'
finalStr += " " * (len(host) + 4) + "|" + '\t\tPort\t\tState\t\tServiceVersion' + '\n'
finalStr += " " * (len(host) + 4) + "|" + '\t\t====\t\t=====\t\t==============' + '\n'
for port in ports:
if nm[host][proto][port]['state'] == "open":
if host not in attackVectorList:
attackVectorList[host] = [port]
else:
attackVectorList[host].append(port)
VersionString = nm[host][proto][port]['product'] + " " + nm[host][proto][port][
'version'] + " ExtraInfo: " + nm[host][proto][port]['extrainfo'] + " " + \
nm[host][proto][port][
'cpe']
finalStr += " " * (len(host) + 4) + "|" + '\t\t%s\t\t%s\t\t%s' % (
port, nm[host][proto][port]['state'], VersionString) + '\n'
insertRecord(host, VersionString, port)
else:
finalStr += " " * ((len(
host) + 4)) + "|_ " + Fore.GREEN + Style.DIM + "Ports" + Style.RESET_ALL + " : %s" % (
(Fore.YELLOW + "-none-")) + '\n'
finalStr += " " * (
(len(host) + 4)) + "|_ " + Fore.GREEN + Style.DIM + "OS fingerprinting" + Style.RESET_ALL + '\n'
if 'osclass' in nm[host]:
for osclass in nm[host]['osclass']:
finalStr += '\t\t' + "[" + Fore.GREEN + Style.DIM + "+" + Style.RESET_ALL + "] Type : {0}".format(
osclass['type']) + '\n'
finalStr += '\t\t Vendor : {0}'.format(osclass['vendor']) + '\n'
finalStr += '\t\t OS-Family : {0}'.format(osclass['osfamily']) + '\n'
finalStr += '\t\t OS-Gen : {0}'.format(osclass['osgen']) + '\n'
finalStr += '\t\t Accuracy : {0}%'.format(osclass['accuracy']) + '\n'
elif 'osmatch' in nm[host]:
for osmatch in nm[host]['osmatch']:
finalStr += '\t\t' + "[" + Fore.GREEN + Style.DIM + "+" + Style.RESET_ALL + "] Name : {0} (accuracy {1}%)".format(
osmatch['name'], osmatch['accuracy']) + '\n'
elif 'fingerprint' in nm[host]:
finalStr += '\t\t* Fingerprint : {0}'.format(nm[host]['fingerprint']) + '\n'
print(finalStr)
finalStr = ansi_escape.sub('', finalStr)
writeScanEvents(fileName, finalStr)
return True
def commandHandler(command):
command = str(command)
global inModule
global currentModule
global moduleOptions
global currentModuleFile
# HELP
# commands
if command == "help":
commands()
if command == "use":
print(Fore.RED + "[!] Usage: 'use " + Fore.YELLOW + "module_name" + Fore.RED + "'" + END)
# USE
elif command.startswith("use "):
command = command.replace("use ", "")
if checkCommandAvailable(command):
inModule = True
currentModule = command
moduleOptions = getModuleOptions(currentModule)
else:
print(Fore.RED + "[!] Module '" + Fore.YELLOW + command + Fore.RED + "' not found." + END)
# OPTIONS
elif command == "options":
if inModule:
print(Fore.GREEN + "\n Options for module '" + Fore.YELLOW + currentModule + Fore.GREEN + "':" + END)
for option in moduleOptions:
if option[2] == "":
print("\t" + Fore.YELLOW + option[0] + Fore.GREEN + " - " + Fore.BLUE + option[
1] + Fore.GREEN + " ==> " + Fore.RED + "[NOT SET]" + END)
else:
print("\t" + Fore.YELLOW + option[0] + Fore.GREEN + " - " + Fore.BLUE + option[
1] + Fore.GREEN + " ==> '" + Fore.YELLOW +
option[2] + Fore.GREEN + "'" + END)
print()
else:
print(Fore.RED + "[!] No module selected." + END)
# SET
elif command.startswith("set "):
if inModule:
command = command.replace("set ", "")
command = command.split()
error = False
try:
test = command[0]
test = command[1]
except:
print(Fore.RED + "[!] Usage: 'set " + Fore.YELLOW + "option_name option_value" + Fore.RED + "'" + END)
error = True
if not error:
inOptions = False
for option in moduleOptions:
if option[0] == command[0]:
inOptions = True
option[2] = command[1]
print(Fore.YELLOW + option[0] + Fore.GREEN + " ==> '" + Fore.YELLOW + command[
1] + Fore.GREEN + "'" + END)
if not inOptions:
print(Fore.RED + "[!] Option '" + Fore.YELLOW + command[0] + Fore.RED + "' not found." + END)
else:
print(Fore.RED + "[!] No module selected." + END)
elif command == "set":
print(Fore.RED + "[!] Usage: 'set " + Fore.YELLOW + "option_name option_value" + Fore.RED + "'" + END)
elif command == "run":
if inModule:
ipFileName = getOptionValue('filename')
if ipFileName == '':
if currentModule == 'fullscan':
IP = getOptionValue('network')
args = '-Pn -p-'
if IP != '':
scan(IP, args)
else:
print(Fore.RED + "[!]" + " set network " + END)
else:
IP = getOptionValue('network') # pull network element
args = getOptionValue('port') # pull port element
if IP != '':
scan(IP, args)
else:
print(Fore.RED + "[!] " + "set network " + END)
else:
if currentModule == 'fullscan':
args = '-Pn -p-'
scan_from_file(args)
else:
args = getOptionValue('port') # pull port element
scan_from_file(args)
else:
print(Fore.RED + "[!] No module selected." + END)
# BACK
elif command == "back":
if inModule:
inModule = False
currentModule = ""
moduleOptions = []
# EXIT
elif command == "exit":
print(Fore.GREEN + "[I] Shutting down..." + END)
print()
raise SystemExit
# MODULES
elif command == "modules":
print(Fore.GREEN + "\nAvailable modules:" + END)
for module in allModules:
print(Fore.YELLOW + "\t" + module[0] + Fore.GREEN + " - " + Fore.BLUE + module[1] + END)
print()
# CLEAR
elif command == "clear" or command == "cls":
os.system("clear||cls")
print(Fore.RED + header + END)
print()
# DEBUG
elif command == "debug":
try:
print("inModule: " + str(inModule))
print(currentModule)
print(moduleOptions)
print()
except:
pass
elif command == "":
pass
else:
print(Fore.RED + "[!] Unknown command: '" + Fore.YELLOW + command + Fore.RED
+ "'. Type '" + Fore.YELLOW + "help" + Fore.RED + "' for all available commands." + END)
def NonInteractiveMode(module,network, port, verbose):
commandHandler("use "+ module)
commandHandler("set network " + network)
if port is not None:
commandHandler("set port " + port)
commandHandler("run")
print()
# ----------------------------------------------------------------------------#
# Launch.
# ----------------------------------------------------------------------------#
if __name__ == "__main__":
loadModules()
multiprocessing.freeze_support()
parser = argparse.ArgumentParser(description="portScanner", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--interactive','-i', help="1 for Interactive Mode, 0 for Commandline", default=1)
parser.add_argument('--module','-m', help="Module name to scan -> " + " ".join([m for m in modules]), default='fullscan')
parser.add_argument('--network','-n', help="Network to scan")
parser.add_argument('--port','-p', help="Port to scan", default=None)
parser.add_argument('--verbose','-v', help="Verbose Level", default=True)
parser.add_argument('--filename', '-f', help="Absolute Path of the filename", default=True)
parser.add_argument('--bruteforce', '-b', help="Brute Attack", default=False)
parser.add_argument("--test", action='store_true')
args, leftovers = parser.parse_known_args()
if args.interactive == '0':
# print(args.module)
# print(args.network)
# print(args.verbose)
NonInteractiveMode(args.module,args.network,args.port,args.verbose)
else:
# os.system("python app.py ")
if args.test:
print("Test build detected. Exiting...")
exit()
print(Fore.GREEN + header + END + Style.RESET_ALL)
while True:
if inModule:
inputHeader = Fore.BLUE + "tinyb0y" + Fore.RED + "/" + currentModule + Fore.BLUE + " $> " + END
else:
inputHeader = Fore.BLUE + "tinyb0y $> " + END
try:
commandHandler(input(inputHeader))
except KeyboardInterrupt:
print(Fore.GREEN + "\n[I] Shutting down..." + END)
raise SystemExit
except Exception as e:
print()
print(Fore.Red + str(e) + END)
print(Fore.RED + "\n[!] portScanner crashed...\n[!] Debug info: \n")
print("\n" + END)
exit()