-
Notifications
You must be signed in to change notification settings - Fork 19
/
webstor.py
executable file
·1652 lines (1503 loc) · 69.2 KB
/
webstor.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# WebStor
#
# Author:
# Ross Geerlings <rjgeer at umich.edu>, <ross at seekerdlp.com>
#
# Special thanks to:
# Brandon Bailey <Twitter: @ge0stigm4> (Co-designer of original concept)
# Bob Harold (Guidance on DNS)
# Neamen Negash <nnegash at umich.edu> (Installer)
# afreudenreich (Multiple bug fixes and enhancements)
#
# WebStor uses Wappalyzer's technologies database for pre-populated, name-
# indexed technology lookups against WebStor's stored responses. Wappalyzer
# (https://github.com/AliasIO/wappalyzer) is licensed under the terms of the
# MIT licence.
#
#
#
# WebStor is licensed under the terms of the MIT license, reproduced below.
#
# ==========================================================================
# The MIT License
# Copyright (c) 2020-2021 The University of Michigan Board of Regents.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation fime-les (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
#
import os
import dns.query
import dns.tsigkeyring
import dns.update
import dns.zone
import sys
import datetime
import requests
from bs4 import BeautifulSoup
import mysql.connector
from multiprocessing.dummy import Pool as ThreadPool
import time
import argparse
import subprocess
import ipaddress
import re
import js_regex
import logging
import urllib3
import urllib.parse
import random
import traceback
import json
import socket
from gevent import Timeout
from gevent import monkey
orig_connect = urllib3.connection.HTTPConnection.connect
parser = argparse.ArgumentParser()
parser.add_argument("--ADD-HTTP-PORT", "-a", dest="HttpPortToAdd", default=None, help="Add a custom HTTP port.")
parser.add_argument("--CLEAR-HTTP", "-aC", dest="ClearHttpPorts", default=False, action="store_true", \
help="Clear any custom HTTP ports and revert to default of 80.")
parser.add_argument("--ADD-HTTPS-PORT", "-b", dest="HttpsPortToAdd", default=None, help="Add a custom HTTPS port.")
parser.add_argument("--CLEAR-HTTPS", "-bC", dest="ClearHttpsPorts", default=False, action="store_true", \
help="Clear any custom HTTPS ports and revert to default of 443.")
parser.add_argument("--ADD-CUSTOM-FINGERPRINT", "-c", dest="Fingerprint", default=None, \
help="Add a custom fingerprint in the form <Name>,<RegEx>.")
parser.add_argument("--DELETE-CUSTOM-FINGERPRINT", "-cD", dest="FingerprintNameToDelete", default=None, \
help="Delete a custom fingerprint by name.")
parser.add_argument("--IMPORT-CUSTOM-FINGERPRINT", "-cI", dest="ImportFingerprintFile", default=None, \
help="Import a custom fingerprint file with the path specified.")
parser.add_argument("--CLEAR-CUSTOM-FINGERPRINTS", "-cC", dest="ClearFingerprints", default=False, action="store_true", \
help="Clears all custom fingerprints stored in DB.")
parser.add_argument("--SHOW-CONFIG", "-g", dest="ShowConfigBrief", default=False, action="store_true", \
help="Show current WebStor configuration (brief).")
parser.add_argument("--SHOW-CONFIG-FULL", "-gF", dest="ShowConfigFull", default=False, action="store_true", \
help="Show current WebStor configuration (full).")
parser.add_argument("--RUN-MASSCAN", "-m", dest='ForceScan', default=False, action='store_true', \
help="Runs a new port scan with Masscan on all configured TCP ports for HTTP and HTTPS, " \
"against all configured ranges and any IP addresses from DNS records that are outside those ranges.")
parser.add_argument("--SET-MASSCAN-RANGES", "-mR", dest="SetScanRanges", default=None, \
help="Scan range or ranges, replaces existing ranges in DB, comma " \
"separated, such as: -s 10.10.0.0/16,10.13.0.0/16,192.168.1.0/24")
parser.add_argument("--ADD-RANGE", "-mA", dest="RangeToAdd", default=None, help="Add scan range.")
parser.add_argument("--DELETE-RANGE", "-mD", dest="RangeToDelete", default=None, help="Delete scan range.")
parser.add_argument("--IMPORT-MASSCAN-RANGES", "-mI", dest="ImportScanRanges", default=None, \
help="Import scan ranges (CIDR blocks) from a specified file.")
parser.add_argument("--ADD-PATH", "-p", dest="PathToAdd", default=None, help="Add paths for which to request " \
"and store responses besides '/'.")
parser.add_argument("--DELETE-PATH", "-pD", dest="PathToDelete", default=None, help="Delete paths for which to " \
"request and store responses besides '/'.")
parser.add_argument("--CLEAR-PATHS", "-pC", dest="ClearPaths", default=False, action="store_true", \
help="Clear any custom URL request paths and revert to default of '/'.")
parser.add_argument("--REFRESH-RESPONSES", "-r", dest="RefreshResponses", default=False, action="store_true", \
help="Refresh URL responses in DB.")
parser.add_argument("--RESPONSES-ADD-FOR-PATH", "-rP", dest="ResponsesAddForPath", default=None, \
help="Add URL responses for a one-time path in with the current responses in the DB.")
parser.add_argument("--SEARCH-PATTERN", "-sP", dest="SearchPattern", default=None, \
help="Search for string or regular expression in WebStor database.")
parser.add_argument("--SEARCH-CUSTOM-FINGERPRINT", "-sC", dest="SearchFingerprint", default=None, \
help="Search for technology by name of user-provided custom fingerprint.")
parser.add_argument("--SEARCH-WAPPALYZER", "-sW", dest="SearchWappalyzer", default=None, \
help="Search for technology by name (from Wappalyzer Tech DB) in WebStor DB.")
parser.add_argument("--NO-TSIG-KEY", "-tN", dest="UseTSIG", default=True, action="store_false", \
help="Do not use DNSSec TSIG key stored in database or a file, even if present.")
parser.add_argument("--TSIG-KEY-IMPORT", "-tI", dest="ImportTSIGFile", default=None, \
help="Import a specified TSIG key file into the database")
parser.add_argument("--TSIG-KEY-REPLACE", "-tR", dest="ReplacementTSIGFile", default=None, \
help="Replace a TSIG key in the database with a specified file")
parser.add_argument("--DELETE-TSIG", "-dT", dest="TSIGToDelete", default=None, \
help="Delete a TSIG key from the database by name.")
parser.add_argument("--USE-TSIG-FILE-ONLY", "-tF", dest="UseTSIGFileOnly", default=None, \
help="Only use tsig file specified (full path), do not use TSIGs stored in the DB. " \
"Applies to all domains, limiting WebStor to one TSIG for zone transfers in the current execution.")
parser.add_argument("--DOWNLOAD-NEW-WAPPALYZER", '-w', dest="DLWap", default=False, action="store_true", \
help="Download a new Wappalyzer fingerprints file directly from GitHub. Overwrites existing " \
"Wappalyzer fingerprint data.")
parser.add_argument("--LIST-WAPPALYZER-TECH-NAMES", "-wL", dest="ListWappalyzer", default=False, action="store_true", \
help="List the names of all Wappalyzer technologies in the database.")
parser.add_argument("--ZONE-XFER", "-z", dest='PerformZoneXfer', default=False, action='store_true', \
help="Forces a new zone transfer using all domains, servers, and associated TSIG keys in DB")
parser.add_argument("--ADD-DOMAIN", "-zA", dest="DomainDetails", default=None, \
help="Add a domain in the form <Domain name>,<Server>,<TSIG Key Name>.")
parser.add_argument("--DELETE-DOMAIN", "-zD", dest="DomainToDelete", default=None, \
help="Delete a DNS domain from the database by name.")
parser.add_argument("--IMPORT-ZONE-FILE", "-zI", dest="ImportZoneFile", default=None, \
help="Add domains for zone transfers from a file.")
parser.add_argument("--CLEAR-DOMAINS", "-zC", dest="ClearDomains", default=False, action="store_true", \
help="Clears all DNS domains stored in DB.")
parser.add_argument("--LIST-DOMAINS", "-zL", dest="ListDomains", default=False, action="store_true", \
help="Lists all DNS domains stored in DB.")
parser.add_argument("--LIST-OUTSIDE", "-e", dest="ListOutside", default=False, action="store_true", \
help="Prints a list of all names and IPs from our zone transfers that are outside defined net ranges.")
parser.add_argument("--SQL-CREDS", "-q", dest="SQLCredsFile", default=None, \
help="Use SQL credentials in file at specified path.")
args = parser.parse_args()
sMySQLhost="localhost"
sMySQLuser="root"
sMySQLpw=""
if args.SQLCredsFile != None:
if os.path.exists(args.SQLCredsFile):
try:
MySQLcredFile = open(args.SQLCredsFile, 'r')
lMySQLlines = MySQLcredFile.readlines()
sMySQLhost = lMySQLlines[0].rstrip()
sMySQLuser = lMySQLlines[1].rstrip()
sMySQLpw = lMySQLlines[2].rstrip()
mysqlconn = mysql.connector.connect(host=sMySQLhost, user=sMySQLuser, password=sMySQLpw)
except Exception as e:
print("Error reading MySQL credential file or connecting to database. Falling back to default credentials." \
" Error was: %s\n" % e)
sMySQLhost="localhost"
sMySQLuser="root"
sMySQLpw=""
try:
mysqlconn = mysql.connector.connect(host=sMySQLhost, user=sMySQLuser, password=sMySQLpw)
except Exception as e:
print("Failed after falling back to default credentials. Exiting. Error was: %s\n\n" \
% e)
exit(1)
else:
print("Specified MySQL credential file does not exist. Exiting.")
exit(1)
else:
try:
mysqlconn = mysql.connector.connect(host=sMySQLhost, user=sMySQLuser, password=sMySQLpw)
except Exception as e:
print("Failed connecting with MySQL default credentials. Exiting. Error was: %s\n\n" \
"Do you have MariaDB 10.0.5 or newer installed?" % e)
exit(1)
cursor = mysqlconn.cursor()
def create_database():
#Create the database if it's not already there
cursor.execute("CREATE DATABASE IF NOT EXISTS webstor")
#Default latin character set won't work with characters in some responses
cursor.execute("ALTER DATABASE webstor CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
cursor.execute("USE webstor")
#tsig keys
cursor.execute("CREATE TABLE IF NOT EXISTS tsig (name VARCHAR(80), algorithm VARCHAR(80), secret VARCHAR(256), " \
"PRIMARY KEY (name))")
cursor.execute("INSERT IGNORE INTO tsig (name, algorithm, secret) VALUES ('none', 'none', 'none')")
#Ranges specified by user
cursor.execute("CREATE TABLE IF NOT EXISTS target_ranges (cidr VARCHAR(18), PRIMARY KEY (cidr))")
#Domains specified by user
cursor.execute("CREATE TABLE IF NOT EXISTS domains (domain VARCHAR(80), server VARCHAR(80), keyname VARCHAR(80), " \
"PRIMARY KEY (domain))")
#DNS hosts identified that were outside the target ranges specified by user. These IPs also need to be covered by Masscan
cursor.execute("CREATE TABLE IF NOT EXISTS dns_hosts (fqdn VARCHAR(80),ip VARCHAR(15), PRIMARY KEY (fqdn,ip))")
#Paths for which to store responses. Default is '/'
cursor.execute("CREATE TABLE IF NOT EXISTS paths (path VARCHAR(80), PRIMARY KEY (path))")
cursor.execute("INSERT IGNORE INTO paths (path) VALUES ('/')")
#Ports and types. Default 80/HTTP and 443/HTTPS
cursor.execute("CREATE TABLE IF NOT EXISTS masscan_ports (type VARCHAR(15), port INT, PRIMARY KEY (type,port))")
cursor.execute("INSERT IGNORE INTO masscan_ports (type,port) VALUES ('http',80)")
cursor.execute("INSERT IGNORE INTO masscan_ports (type,port) VALUES ('https',443)")
#Open IP/port combos found by Masscan
cursor.execute("CREATE TABLE IF NOT EXISTS masscan_results (ip VARCHAR(15), port INT, PRIMARY KEY (ip,port))")
#Stored responses
cursor.execute("CREATE TABLE IF NOT EXISTS responses (host VARCHAR(160), port INT, path VARCHAR(80), " \
"response LONGTEXT, PRIMARY KEY (host,port))")
#Imported Wappalyzer technologies database lets us query by technology name against stored responses
cursor.execute("CREATE TABLE IF NOT EXISTS wapp_technologies (name VARCHAR(80), details VARCHAR(4096), " \
"PRIMARY KEY (name))")
#Custom fingerprints defined by user. Lets us query by name for a custom regex within responses
cursor.execute("CREATE TABLE IF NOT EXISTS custom_fingerprints (name VARCHAR(80), regex VARCHAR(4096), " \
"PRIMARY KEY (name))")
#Config values defined by user
cursor.execute("CREATE TABLE IF NOT EXISTS config (setting VARCHAR(20), value VARCHAR(80), PRIMARY KEY (setting))")
mysqlconn.commit()
return
def add_fingerprint(sFingerprint):
print("Attempting to add custom fingerprint")
try:
lFingerprint = sFingerprint.split(',', 1)
except:
print("Unable to parse provided fingerprint. Must be in the form [Name],[Regex]. Provided value was: %s" % \
sFingerprint)
return
print('Importing custom fingerprint with name: "%s" and value: %s' % (lFingerprint[0], lFingerprint[1]))
sSQL_InsertCF = """INSERT INTO custom_fingerprints (name, regex) VALUES (%s,%s)"""
try:
cursor.execute(sSQL_InsertCF, (lFingerprint[0],lFingerprint[1]) )
mysqlconn.commit()
except Exception as e:
print("Error inserting values into database: %s", e)
return
print("Successfully inserted fingerprint into database.")
show_config("brief")
return
def import_fingerprints(sFileName):
print("Importing custom fingerprints from file: %s" % sFileName)
sSQL_InsertCF = """INSERT INTO custom_fingerprints (name, regex) VALUES (%s,%s)"""
fFingerprintFile = open(sFileName, 'r')
lFingerprintLines = fFingerprintFile.readlines()
for sFingerprint in lFingerprintLines:
try:
lFingerprint = sFingerprint.split(',', 1)
except:
print("File appears to be invalid. Unable to parse provided fingerprint. " \
"Must be in the form [Name],[Regex]. Provided value was: %s" % sFingerprint)
return
print("Inserting fingerprint: %s." % sFingerprint)
try:
cursor.execute(sSQL_InsertCF, (lFingerprint[0],lFingerprint[1].rstrip()) )
mysqlconn.commit()
except Exception as e:
print("Error inserting fingerprint values into database: %s", e)
return
print("Successfully imported fingerprint(s) into database.")
show_config("brief")
return
def delete_fingerprint(sFingerprintName):
print("Deleting custom fingerprints.")
sSQL_DeleteCF = """DELETE FROM custom_fingerprints where name = %s"""
try:
cursor.execute(sSQL_DeleteCF, (sFingerprintName,) )
mysqlconn.commit()
print("Fingerprint successfully deleted.")
except Exception as e:
print("Exception encountered while deleting custom fingerprint from database: %s", e)
return
show_config("brief")
return
def clear_fingerprints():
print("Clearing custom fingerprints.")
try:
cursor.execute("DROP TABLE IF EXISTS custom_fingerprints")
cursor.execute("CREATE TABLE IF NOT EXISTS custom_fingerprints (name VARCHAR(80), regex VARCHAR(4096), " \
"PRIMARY KEY (name))")
print("Custom fingerprints successfully cleared.")
except Exception as e:
print("Exception encountered while clearing custom fingerprints from database: %s", e)
return
show_config("brief")
return
def list_fingerprints():
print("Custom fingerprints in WebStor database:\n========================================")
try:
cursor.execute("SELECT name,regex from custom_fingerprints")
lCF = cursor.fetchall()
except Exception as e:
print("Exception encountered while retrieving custom fingerprints from database: %s", e)
return
for Fingerprint in lCF:
print("Name: %s\nRegex: %s\n------------------------------------------------------------" % Fingerprint)
return
def perform_masscan():
lIntRanges = [] #Will be used to store tuples of int representations of net and mask for each range, better performance
lExtraAddresses = []
print("Performing Masscan.")
cursor.execute("DROP TABLE IF EXISTS masscan_results") #IP and port
cursor.execute("CREATE TABLE IF NOT EXISTS masscan_results (ip VARCHAR(15), port INT, PRIMARY KEY (ip,port))") #IP, port
#In addition to the ranges provided, we will scan IPs that came up in our zone transfer that are outside the ranges
#For many organizations, this will be useful as it will look at cloud hosts
sSQL_SelectIP = "SELECT distinct ip from dns_hosts"
try:
cursor.execute(sSQL_SelectIP)
lIPs = cursor.fetchall()
except Exception as e:
print("Exception encountered while retrieving DNS hosts from database: %s", e)
return
sSQL_SelectRanges = "SELECT cidr from target_ranges"
try:
cursor.execute(sSQL_SelectRanges)
lRanges = cursor.fetchall()
except Exception as e:
print("Exception encountered while retrieving CIDR ranges from database: %s", e)
return
print("Retrieved %s IP records from zone transfer(s) and %s target ranges." % (len(lIPs),len(lRanges)))
print("Checking for DNS records outside of ranges to add to scan...")
lOriginalRanges = [] #Clean,just string,no tuple
for tCIDRblock in lRanges:
lOriginalRanges.append(tCIDRblock[0])
ip_net = ipaddress.ip_network(tCIDRblock[0])
iNetw = int(ip_net.network_address)
iMask = int(ip_net.netmask)
lIntRanges.append((iNetw,iMask))
for address in lIPs:
iAddress = int(ipaddress.ip_address(address[0]))
bInRange = False
for tIntRange in lIntRanges:
bInRange = (iAddress & tIntRange[1]) == tIntRange[0]
if bInRange == True:
break
if bInRange == False:
lExtraAddresses.append(address[0])
lExtraAddresses = list(set(lExtraAddresses)) #Only Unique
print("Total addresses outside ranges added: %s" % len(lExtraAddresses))
lAllTargets = lOriginalRanges + lExtraAddresses
sAllTargets = ",".join(lAllTargets)
sSQL_SelectPorts = "SELECT DISTINCT port FROM masscan_ports"
try:
cursor.execute(sSQL_SelectPorts)
lPortTuples = cursor.fetchall()
except Exception as e:
print("Exception encountered while retrieving ports from database: %s", e)
return
lPorts = []
for tPorts in lPortTuples:
lPorts.append(str(tPorts[0]))
sPorts = ",".join(lPorts)
if len(sAllTargets) > 130000:
print("WARNING:\n" \
"The length of the target list appears to exceed the maximum threshold. This usually occurs when an " \
"organization's network ranges (CIDR blocks) have not all been provided to WebStor. WebStor will now " \
"attempt to replace all individual RFC1918 private addresses from DNS which share a /24 CIDR block " \
"with only that block.") \
#Combine all private addresses with common /24 CIDR blocks into those blocks, eliminating the original.
lModifiedExtraAddresses = []
dModifiedExtraAddresses = {}
for sAddr in lExtraAddresses:
if ipaddress.ip_address(sAddr).is_private:
sFirstThreeOctets = sAddr.split('.')
sThisCIDR = '.'.join(sFirstThreeOctets[:3]) + ".0/24"
if sThisCIDR in dModifiedExtraAddresses.keys():
dModifiedExtraAddresses[sThisCIDR].append(sAddr)
else:
dModifiedExtraAddresses[sThisCIDR] = [sAddr]
else:
lModifiedExtraAddresses.append(sAddr)
for sCIDR in dModifiedExtraAddresses:
if len(dModifiedExtraAddresses[sCIDR]) == 1:
lModifiedExtraAddresses.append(dModifiedExtraAddresses[sCIDR][0])
else:
lModifiedExtraAddresses.append(sCIDR)
lAllTargets = lOriginalRanges + lModifiedExtraAddresses
sAllTargets = ",".join(lAllTargets)
if len(sAllTargets) > 130000:
print("WARNING:\n" \
"After simplifying private IP address into their shared /24 CIDR blocks, the list of targets is still " \
"over the maximum threshold. WebStor will proceed, scanning only the first 6800 specified targets.")
lAllTargets = lAllTargets[:6800]
else:
print("SUCCESS:\n" \
"After simplifying private IP address into their shared /24 CIDR blocks, the list of targets is under " \
"the maxumum threshold. Proceeding with Masscan...")
if not os.path.exists('/usr/bin/masscan'):
print("Could not find /usr/bin/masscan. Is Masscan installed?")
exit(1)
MasscanOut = subprocess.Popen(['/usr/bin/sudo', '/usr/bin/masscan', '-p'+sPorts, sAllTargets, '--rate=10000'], stdout=subprocess.PIPE, \
stderr=subprocess.STDOUT)
stdout,stderr = MasscanOut.communicate()
lMasscanLines = stdout.decode("ascii").splitlines()
sPrefixA = "Discovered open port "
sPrefixB = "tcp on "
for sLine in lMasscanLines:
if sLine.startswith(sPrefixA):
sCurrent = sLine[len(sPrefixA):]
aCurrent = sCurrent.split("/")
if aCurrent[0].isdigit():
if int(aCurrent[0]) > 1 and int(aCurrent[0]) < 65536:
if (aCurrent[1].startswith(sPrefixB)):
if is_valid_ipv4(aCurrent[1][len(sPrefixB):]):
sSQL_InsertMSR = """INSERT IGNORE INTO masscan_results (ip, port) VALUES (%s,%s)"""
cursor.execute(sSQL_InsertMSR, (aCurrent[1][len(sPrefixB):],aCurrent[0]) )
mysqlconn.commit()
print("Masscan results have been inserted into WebStor database.")
return
def show_config(sDetail):
sDashes = "--------------------------------------------------------------------------------"
sEquals = "================================================================================"
print("\n\n")
print(sEquals)
print("CURRENT WEBSTOR CONFIG")
print(sEquals)
try:
#Domains (for zone transfers) and count
sSQL_Select = "SELECT domain from domains"
cursor.execute(sSQL_Select)
lDomains = cursor.fetchall()
sDomains = ', '.join([ str(r[0]) for r in lDomains ])
print("\nDomains:")
print(sDashes)
if len(lDomains) > 10 and sDetail == "brief":
sDomains = ', '.join([ str(r[0]) for r in lDomains[:10] ])
sDomains += "... (to see full list of configured domains, run WebStor with the -gF switch)."
else:
sDomains = ', '.join([ str(r[0]) for r in lDomains ])
print(sDomains)
print(sDashes)
print("%s total domains configured." % len(lDomains))
#Target ranges and count
sSQL_Select = "SELECT * from target_ranges"
cursor.execute(sSQL_Select)
lRanges = cursor.fetchall()
if len(lRanges) > 10 and sDetail == "brief":
sRanges = ', '.join([ str(r[0]) for r in lRanges[:10] ])
sRanges += "... (to see full list of configured ranges, run WebStor with the -gF switch)."
else:
sRanges = ', '.join([ str(r[0]) for r in lRanges ])
print("\n\nScan ranges:")
print(sDashes)
print(sRanges)
print(sDashes)
print("%s total scan ranges configured." % len(lRanges))
#Fingerprints, name and regex, and count
print("\n\nCustom fingerprints:")
print(sDashes)
sSQL_Select = "SELECT name,regex from custom_fingerprints"
cursor.execute(sSQL_Select)
lCustom = cursor.fetchall()
for Fingerprint in lCustom:
print("Name: %-20s Regex: %s" % Fingerprint)
print(sDashes)
print("%s custom fingerprints in database." % len(lCustom))
#Paths and count
print("\n\nPaths against which HTTP and HTTPS request are performed:")
sSQL_Select = "SELECT path from paths"
cursor.execute(sSQL_Select)
lPaths = cursor.fetchall()
print(sDashes)
for path in lPaths:
print(path[0])
print(sDashes)
sSQL_Select = "SELECT COUNT(*) from paths"
cursor.execute(sSQL_Select)
lPath = cursor.fetchall()
print("%s total path(s) in database." % str(lPath[0][0]))
#TSIGs and count
print("\n\nNames of TSIG keys in database:")
sSQL_Select = "SELECT name from tsig where name not like 'none'"
cursor.execute(sSQL_Select)
lTSIGs = cursor.fetchall()
sTsigNames = ', '.join([ str(r[0]) for r in lTSIGs ])
sTSIGs = ', '.join([ str(r[0]) for r in lTSIGs ])
print(sDashes)
print(sTSIGs)
print(sDashes)
sSQL_Select = "SELECT COUNT(*) from tsig where name not like 'none'"
cursor.execute(sSQL_Select)
lTSIG = cursor.fetchall()
print("%s total TSIG key(s) in database." % str(lTSIG[0][0]))
#HTTP ports, HTTPS ports, Present count of Wappalyzer technologies, and number of stored responses
sSQL_Select = "SELECT port from masscan_ports where type='http'"
cursor.execute(sSQL_Select)
sHttp = ', '.join([ str(r[0]) for r in cursor.fetchall() ])
print("\n\nHTTP ports: %s" % sHttp)
sSQL_Select = "SELECT port from masscan_ports where type='https'"
cursor.execute(sSQL_Select)
sHttps = ', '.join([ str(r[0]) for r in cursor.fetchall() ])
print("HTTPS ports: %s" % sHttps)
sSQL_Select = "SELECT COUNT(*) from wapp_technologies"
cursor.execute(sSQL_Select)
lWapp = cursor.fetchall()
print("Number of Wappalyzer technologies in database: %s" % str(lWapp[0][0]))
sSQL_Select = "SELECT COUNT(*) from responses"
cursor.execute(sSQL_Select)
lResp = cursor.fetchall()
print("Number of responses in database: %s" % str(lResp[0][0]))
except Exception as e:
print("\nException encountered while retrieving configuration settings from database: %s", e)
return
print(sEquals)
print("\n\n")
return
def add_http_port(sPort):
if not sPort.isdigit():
print("Port value is not an integer.")
return
if int(sPort) < 1 or int(sPort) > 65535:
print("Port is outside valid range.")
return
sInsertPort = """INSERT IGNORE INTO masscan_ports (type,port) VALUES (%s,%s)"""
print("Attempting to add HTTP port: %s." % sPort)
try:
cursor.execute(sInsertPort, ('http',int(sPort)) )
mysqlconn.commit()
except Exception as e:
print("Exception encountered inserting ports into database: %s", e)
return
print("Successfully added HTTP port to database.")
show_config("brief")
return
def clear_http_ports():
print("Attempting to clear HTTP Ports.")
try:
cursor.execute("DELETE FROM masscan_ports WHERE type='http'")
cursor.execute("INSERT IGNORE INTO masscan_ports (type,port) VALUES ('http',80)")
mysqlconn.commit()
except Exception as e:
print("Exception encountered clearing HTTP ports from database: %s", e)
return
show_config("brief")
return
def add_https_port(sPort):
if not sPort.isdigit():
print("Port value is not an integer.")
return
if int(sPort) < 1 or int(sPort) > 65535:
print("Port is outside valid range.")
return
sInsertPort = """INSERT IGNORE INTO masscan_ports (type,port) VALUES (%s,%s)"""
print("Attempting to add HTTPS port: %s." % sPort)
try:
cursor.execute(sInsertPort, ('https',int(sPort)) )
mysqlconn.commit()
except Exception as e:
print("Exception encountered inserting ports into database: %s", e)
return
print("Successfully added HTTPS port to database.")
show_config("brief")
return
def clear_https_ports():
print("Attempting to clear HTTPS Ports.")
try:
cursor.execute("DELETE FROM masscan_ports WHERE type='https'")
cursor.execute("INSERT IGNORE INTO masscan_ports (type,port) VALUES ('https',443)")
mysqlconn.commit()
except Exception as e:
print("Exception encountered clearing HTTPS ports from database: %s", e)
return
show_config("brief")
return
def add_path(sPath):
print("Attempting to add path: %s" % sPath)
if not sPath.startswith("/") and not sPath.startswith("?"):
print("Any request path should start with '/' or '?'. Not adding.")
return
sPath = sPath.replace("'","''")
sInsertPath = """INSERT IGNORE INTO paths (path) VALUES (%s)"""
try:
cursor.execute(sInsertPath, (sPath,) )
mysqlconn.commit()
except Exception as e:
print("Error inserting path value into database: %s", e)
show_config("brief")
return
def delete_path(sPathToRemove):
print("Attempting to remove path: %s" % sPathToRemove)
sDeletePath = """DELETE FROM paths WHERE path = %s"""
try:
cursor.execute(sDeletePath, (sPathToRemove,) )
mysqlconn.commit()
except Exception as e:
print("Error deleting path value from database: %s", e)
return
show_config("brief")
return
def clear_paths():
print("Attempting to clear paths.")
try:
cursor.execute("DELETE FROM paths")
cursor.execute("INSERT IGNORE INTO paths (path) VALUES ('/')")
mysqlconn.commit()
except Exception as e:
print("Error clearing path values from database: %s", e)
return
show_config("brief")
return
def patch_connect(self):
orig_connect(self)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1),
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3),
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5),
return
def refresh_responses(sPathToAdd):
print ("Refreshing responses for targets from most recent Masscan.")
#Get the list of requests we need to make. Start with Masscan responses
try:
sSQL_Select_dnsh = "SELECT * from dns_hosts"
cursor.execute(sSQL_Select_dnsh)
lDNSh = cursor.fetchall()
except Exception as e:
print("Error retrieving DNS host values from database: %s", e)
return
#Dictionary for faster, easier lookup
dDNSh = {}
for tDNSh in lDNSh:
if tDNSh[1] not in dDNSh:
dDNSh[tDNSh[1]] = [tDNSh[0]]
else:
dDNSh[tDNSh[1]].append(tDNSh[0])
print("Name table completed with one or more names mapped to %s IPs." % len(dDNSh))
sSQL_Select_ports = "SELECT * from masscan_ports"
try:
cursor.execute(sSQL_Select_ports)
except Exception as e:
print("Error retrieving ports from database: %s", e)
return
lPorts = []
lPorts = cursor.fetchall()
dPorts = {}
for tPort in lPorts:
dPorts[tPort[1]] = tPort[0]
if sPathToAdd != None:
tPathToAdd = (sPathToAdd,)
lPaths = [tPathToAdd]
else:
sSQL_Select_Paths = "SELECT * from paths"
try:
cursor.execute(sSQL_Select_Paths)
except Exception as e:
print("Error retrieving paths from database: %s", e)
return
lPaths = cursor.fetchall()
lRequests = []
sSQL_Select_mr = "SELECT * from masscan_results"
try:
cursor.execute(sSQL_Select_mr)
except Exception as e:
print("Error retrieving Masscan results from database: %s", e)
return
lMR = cursor.fetchall() #[0] is IP, [1] is port
iTotalRequests = 0
iTotalExceptions = 0
iTotalInsertions = 0
for tMSresult in lMR:
for tPath in lPaths:
sRequest = dPorts[tMSresult[1]]+"://"+tMSresult[0].rstrip()
if (tMSresult[1] != 80) and (tMSresult[1] != 443):
sRequest += ":" + str(tMSresult[1])
sRequest += tPath[0]
lRequests.append((sRequest,tMSresult[0].rstrip(),tMSresult[1],tPath[0]))
iTotalRequests +=1
try:
for sHostname in dDNSh[tMSresult[0].rstrip()]:
sRequest = dPorts[tMSresult[1]]+"://"+sHostname
if (tMSresult[1] != 80) and (tMSresult[1] != 443):
sRequest += ":" + str(tMSresult[1])
sRequest += tPath[0]
lRequests.append((sRequest,sHostname,tMSresult[1],tPath[0]))
iTotalRequests +=1
except KeyError:
continue
if sPathToAdd == None:
try:
cursor.execute("DROP TABLE IF EXISTS responses")
cursor.execute("CREATE TABLE IF NOT EXISTS responses (host VARCHAR(160), port INT, path VARCHAR(80), " \
"response LONGTEXT, PRIMARY KEY (host,port))")
except Exception as e:
print("Error dropping and recreating responses table: %s", e)
return
print("Using threadpool for %s requests (this may take some time) ..." % iTotalRequests)
random.shuffle(lRequests)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
urllib3.connection.HTTPConnection.connect = patch_connect
sSQL_InsertResponse = """INSERT INTO responses (host,port,path,response) VALUES (%s,%s,%s,%s)"""
start_time = time.time()
pool = ThreadPool(128)
lResults = pool.map(url_request, lRequests)
lResults= list(filter(None, lResults))
iCumulativeSize = 0
try:
cursor.execute("SET GLOBAL max_allowed_packet=2048000000")
mysqlconn.commit()
except Exception as e:
print("Error resetting max packet size: %s", e)
return
print("Beginning database insertions.")
for tResult in lResults:
if tResult != None:
try:
cursor.execute(sSQL_InsertResponse, tResult)
iTotalInsertions += 1
except Exception as e:
iTotalExceptions += 1
logging.debug("Problem inserting response record beginning with %s,%s,%s,%s: " % \
(tResult[0], tResult[1], tResult[2], tResult[3][:128], e) )
logging.debug(traceback.format_exc())
iCumulativeSize += len(str(tResult))
if iTotalInsertions % 10 == 0:
try:
mysqlconn.commit()
except Exception as e:
print("Error committing response insertions to database: %s", e)
return
iCumulativeSize = 0
try:
mysqlconn.commit()
except Exception as e:
print("Error committing response insertions to database: %s", e)
return
pool.close()
pool.join()
print("%s exceptions encountered during database insertions." % iTotalExceptions)
print("%s total insertions made in %s seconds." % (iTotalInsertions,format(time.time() - start_time,'.2f')))
return
def set_scan_ranges(sScanRanges):
print("Attempting to set scan ranges to: %s" % sScanRanges)
sInsertRange = """INSERT IGNORE INTO target_ranges (cidr) VALUES (%s)"""
lScanRanges = sScanRanges.split(',')
for sCIDRblock in lScanRanges:
print(sCIDRblock)
lCIDRblock = sCIDRblock.split('/')
if lCIDRblock[1].isdigit():
if (len(lCIDRblock)==2) and (is_valid_ipv4(lCIDRblock[0])) and (int(lCIDRblock[1])>7 and int(lCIDRblock[1])<33):
print("Inserting CIDR block: %s." % sCIDRblock.rstrip() )
try:
cursor.execute(sInsertRange, (sCIDRblock.rstrip(),) )
mysqlconn.commit()
except Exception as e:
print("Error inserting scan ranges into database: %s", e)
return
else:
print(len(lCIDRblock))
print(is_valid_ipv4(lCIDRblock[0]))
print(int(lCIDRblock[1]))
print("Invalid CIDR block: %s. Exiting." % sCIDRblock)
exit(1)
else:
print("Invalid bit mask for CIDR block: %s. Exiting." % sCIDRblock)
exit(1)
print("Successfully inserted scan ranges into database.")
return
def import_scan_ranges(sFileName):
print("Attempting to import scan ranges from file: %s" % sFileName)
sInsertRange = """INSERT IGNORE INTO target_ranges (cidr) VALUES (%s)"""
lScanRangeLines = []
try:
fScanRangeFile = open(sFileName, 'r')
lScanRangeLines = fScanRangeFile.readlines()
except Exception as e:
print("Error opening file for scan range import: %s", e)
return
for sCIDRblock in lScanRangeLines:
lCIDRblock = sCIDRblock.split('/')
if (len(lCIDRblock) == 2) and (is_valid_ipv4(lCIDRblock[0])) and (int(lCIDRblock[1])>7 and int(lCIDRblock[1])<33):
print("Inserting CIDR block: %s." % sCIDRblock.rstrip())
try:
cursor.execute(sInsertRange, (sCIDRblock.rstrip(),))
mysqlconn.commit()
except Exception as e:
print("Error inserting scan ranges into database: %s", e)
return
else:
print("Skipping invalid CIDR block in file: %s" % sCIDRblock )
print("Successfully imported scan ranges into database.")
return
def add_scan_range(sRangeToAdd):
print("Attempting to add scan range: %s" % sRangeToAdd)
sInsertRange = """INSERT IGNORE INTO target_ranges (cidr) VALUES (%s)"""
lCIDRblock = sRangeToAdd.split('/')
if (len(lCIDRblock) == 2) and (is_valid_ipv4(lCIDRblock[0])) and (int(lCIDRblock[1])>7 and int(lCIDRblock[1])<33):
try:
cursor.execute(sInsertRange, (sRangeToAdd.rstrip(),))
mysqlconn.commit()
print("Successfully added scan range into database.")
except Exception as e:
print("Error inserting scan ranges into database: %s", e)
else:
print("Not adding invalid CIDR block: %s" % sRangeToAdd )
return
def delete_scan_range(sRangeToRemove):
print("Attempting to delete scan range: %s" % sRangeToRemove)
sql_delete_range = """DELETE FROM target_ranges WHERE cidr = %s"""
try:
cursor.execute(sql_delete_range, (sRangeToRemove,) )
mysqlconn.commit()
except Exception as e:
print("Error deleting range: %s" % e)
return
print("Successfully deleted range.")
show_config("brief")
return
def import_tsig(sFileName):
print("Attempting to import TSIG file: %s" % sFileName)
#Key name, algorithm, secret
sDomain = input("Enter a domain(s) to associate with this TSIG, comma separate if more than one: ")
sDomain = sDomain.replace(" ", "")
aDomains = sDomain.split(",")
sServer = input("Enter a DNS server IP address to associate with domain(s) and TSIG: ")
if not is_valid_ipv4(sServer):
print("DNS server must be given as a valid IPv4 IP address. Exiting.")
exit(1)
print("Those values are %s %s" % (aDomains, sServer))
try:
TSIGFile = open(sFileName, 'r')
aTSIGLines = TSIGFile.readlines()
for aTSIGLine in aTSIGLines:
if aTSIGLine.startswith("key"):
sKey = aTSIGLine.split()[1]
print(sKey)
elif aTSIGLine.lstrip().startswith("algorithm"):
sAlgorithm = aTSIGLine.split('"')[1]
print(sAlgorithm)
elif aTSIGLine.lstrip().startswith("secret"):
sSecret = aTSIGLine.split('"')[1]
print("*****")
except Exception as e:
print(f"Error importing TSIG from file: {e}")
return
if not (sKey and sAlgorithm and sSecret):
print("TSIG key information missing")
return
sInsertTsig = """INSERT INTO tsig (name, algorithm, secret) VALUES (%s,%s,%s)"""
try:
cursor.execute(sInsertTsig, (sKey,sAlgorithm,sSecret) )
mysqlconn.commit()
except Exception as e:
print("Error inserting scan ranges into database: %s", e)
return
#loop through each domain that was provided...
sInsertDomain = """INSERT INTO domains (domain, server, keyname) VALUES (%s,%s,%s)"""
try:
for sDomain in aDomains:
tDomainInsert = (sDomain,sServer,sKey)
cursor.execute(sInsertDomain, tDomainInsert)
mysqlconn.commit()
except Exception as e:
print("Error inserting scan ranges into database: %s", e)
return
print("Successfully inserted TSIG into database.")
show_config("brief")
return
def replace_tsig(sFileName):
#Key name, algorithm, secret
print("Attempting to import TSIG file, overwriting any previous key with same name: %s" % sFileName)
try:
TSIGFile = open(sFileName, 'r')
aTSIGLines = TSIGFile.readlines()
except Exception as e:
print("Error opening TSIG file: %s", e)
return
if aTSIGLines[0].startswith("key"):
sKey = aTSIGLines[0].split()[1]
else:
print("Invalid key name in TSIG file")
return
if aTSIGLines[1].find("algorithm"):
sAlgorithm = aTSIGLines[1].split('"')[1]
else:
print("Invalid algorithm in TSIG file")
return
if aTSIGLines[2].find("secret"):
sSecret = aTSIGLines[2].split('"')[1]
else:
print("Invalid secret in TSIG file")
return
sql_insert="INSERT INTO tsig (name,algorithm,secret) VALUES (%s,%s,%s) ON DUPLICATE KEY UPDATE algorithm=%s, secret=%s"
tTsigInsert = (sKey,sAlgorithm,sSecret,sAlgorithm,sSecret)
logging.debug(tTsigInsert)
try:
cursor.execute(sql_insert, tTsigInsert)
mysqlconn.commit()
except Exception as e:
print("Error replacing TSIG file: %s", e)
return
print("Successfully replaced TSIG.")
show_config("brief")
return
def delete_tsig(sTSIGToRemove):
print("Attempting to remove domains using TSIG named: %s" % sTSIGToRemove)
try:
sql_delete_domain = """DELETE FROM domains WHERE keyname = '%s')"""
cursor.execute(sql_delete_domain, (sTSIGToRemove,) )
mysqlconn.commit()
except Exception as e:
print("Error deleting domains associated with this key: %s" % e)
return
print("Attempting to remove TSIG Key: %s" % sTSIGToRemove)
try:
sql_delete_tsig = """DELETE FROM tsig WHERE name = '%s')"""
cursor.execute(sql_delete_tsig, (sTSIGToRemove,) )
mysqlconn.commit()
except Exception as e:
print("Error deleting TSIG key from database: %s" % e)
return
print("Successfully deleted TSIG.")
show_config("brief")
return