-
Notifications
You must be signed in to change notification settings - Fork 240
/
domain_analyzer.py
executable file
·2785 lines (2374 loc) · 129 KB
/
domain_analyzer.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 python
# Copyright (C) 2009 Sebastian Garcia, Veronica Valeros
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# MatesLab www.mateslab.com.ar
#
#
# Authors:
# Sebastian Garcia eldraco@gmail.com
# Veronica Valeros vero.valeros@gmail.com
#
# Thanks to Gustavo Sorondo iampuky@gmail.com for contributing the common hosts list code.
#
# Changelog
# 0.8.1
# - Small delete of few debug options
# 0.8
# - Added "-L --common-hosts-list" option to read the common hosts list from a text file.
# 0.7
# - Changed robtex web url.
# 0.6
# - Some minor bug fixes when dealing with host that do not have a host name or a PTR record.
# 0.5
# - Added an option to download files from the crawler to the output directory
# - Now crawler results are obtained ok
# - Old udp option was deleted
# - Adds http://www.robtex.com information for every domain and the domain searched!. In http://www.robtex.com/dns/<domain>.html we can find other domains that use THIS dns server. Useful if the NS has zone transfer!!!
# - Check first if what was given was a domain
# - More gtld subdomains added, like 'co', 'go' and 'ag'.
# - Some minor options name fix
# - If host has some pattern given by the user (like google) do not check it with nmap
# - Some dns are broken and gets into a loop! We do not follow them!
# - Now we randomly find X domain in internet and analyze them
# - Store every line in the output file, not just the summary
# - We avoid adding subdomains if we found a broken DNS server with recursive subdomains
# - Now we also print out in the output file what is going on during the analysis and we don't wait until we finish to print everything out.
# - Check SPF record, looking for ip addresses and hostnames
# - We store in the output file the new subdomains found and in the printout
# - Now xml stylesheet is used.
# - Nmap scripts results are parsed and used.
# - A LOT of aesthetical fixes!
# - We look for PTR records, and alert when hostname and PTR are different
# - Now every host found in sL is added to the Ip list
# - Print everything in colors! Including the critical ports as a warning!
# - Now we print the country of every IP!
# - Some minor bug fixes
# - Now netblocks are extracked well, and netblocks are checked only once.
# - Add printing the hostname when scanning ports
# - We developed a web crawler serching for web things. It is external.
# - We create a pdf report from the text file
# - We added subdomains automatic analysis. It can found recursive subdomains!
# - We added email searching for that domain in google sets and google
# 0.4
# - Fixed a bug that prevented this to work fine under Debian systems. (Something with False!="" exploting)
# - Now the directory is not created until we know some DNS servers exist
# - Now if the domain does not exists, we exit
# - We use zenmap to show the topology of the hosts.
# - A parameter not to store nmap output files on disk
# - We create an output directory with everything into it.
# - A parameter -z to only scan host in the zone transfer. This is now stored correctly.
# - some minor typo fixes
# 0.3
# - A parameter not to scan with nmap
# - A parameter to do everything only when ZT is successful
# 0.2 New filename without dash
# Fixed a bug that we try to store in disk without opening the file
# 0.1 feb 2 2011: Creation
#
# TODO
# - We still don't read every nmap results
# - OBTAIN THE CRAWLER RESULTS CORRECLTY!!!
# - Use threads to improve the performance.
# - Create a tar.gz with everything!
# - Add the last router in the traceroute to the analysis.
# - Compute and print statistics about the problems found sorted by country/domain
# - Be tor-friendly. Detect tor is being used and Use tor-resolve or something.
# - Detect and count DNS missconfigurations
# - Zenmap does not work fine with multiple subdomains, it keeps opening the main domain only
# - From inside a network with a web proxy, sometimes zone transfer does not work and every domain seems to have wilcards!. To identify this
# perhaps is useful to try to make a ZT froma known public domain. If it does not occur, then the internal network is filtering!
# - Have a --robin-hood option, which sends the pdf report to every email found in the domain, using domain MX host.
# - Check domains like with strange characters, like chineese
# - For every version, try to find vulnerabilities!!!!!
# - For every email, search owner information on every social site
# - Make nmap error do not appear in the output
# - Use xsltproc nmap.xml > nmap.html to create web pages with the information
# - Play an audio sound when we found errors!!
# -- Web --
# - Recognize login web pages
# - Run a very light nikto?
# - Make zenmap work in macos
#
# BUGS
# - Nmap ports are printed twice in the printout, and ports are not printed at all during the scan. BOTH IN THE OUTPUT FILE.
#
# standard imports
from subprocess import Popen
from subprocess import PIPE
from subprocess import call
from ansistrm import ColorizingStreamHandler, logging
import socket
import os, sys
import getopt
try:
import dns.resolver
except:
print("You need to install python-dnspython. apt-get install python-dnspython")
sys.exit(-1)
import dns.query
import dns.zone
import copy
import shlex
import time
from geoip import geolite2
####################
# Global Variables
# Debug
debug = 0
vernum = "0.8.3"
# domain_data{'IpsInfo'}
# {
# '1.1.1.1': [ {'HostName':'test.com'},
# {'Type':'NS'},
# {'IpCountry':'Peru'},
# {'PTR':'rev.name.pe'},
# {'SubDomain':'other.test.com'},
# {'HostUp': True},
# {'PortInfo':'text'}
# {'ScriptInfo':'text'}
# {'OSInfo':'Linux'}
# {'ZT': 23}
# {'DirIndex':}
# ]
# '2.2.2.2': [
# ]
# }
# domain_data{'DomainInfo'}
# {
# 'Email': 'test@test.com'
# 'Email': 'test2@test.com'
# }
# Main dictionary
domain_data={}
# First component is for Ip information
domain_data['IpsInfo']={}
# Second component is for Domain information
domain_data['DomainInfo']=[]
# By default check common hostnames
check_common_hosts_names=True
# Default is to scan only TCP ports
nmap_scantype="-O --reason --webxml --traceroute -sS -sV -sC -Pn -n -v -F"
# Default is to transfer the zone
zone_transfer=True
# Default is to scan the netblocks
net_block=True
# Output file
output_file=""
# Default is to scan nmap ports
nmap=1
output_directory=False
not_store_nmap=0
# Default is not to use zenmap
zenmap=0
# Default is not to look for emails using goog-mail.py
googmail=0
# Here we store every subdomain found
subdomains_found=[]
not_goog_mail=True
# By default we DO analyze subdomains recursively
not_subdomains=False
create_pdf=False
# by default do NOT go into robin hood mode. Should this be random???
robin_hood=False
webcrawl=True
common_hostnames=[]
# By default only scan 10 web pages
max_amount_to_crawl=50
# By default do not dominate the world
world_domination=False
# By default resolve country names
countrys=True
colors=True
# If ports found are in this list, then we do not print them as critical
normal_port_list=['21/','22/','25/','53/udp','80/','443/','110/','143/','993/','995/','465/']
check_spf=True
output_file_handler=False
amount_of_random_domains=False
ignore_host_pattern=False
robtex_domains=False
# Here we store the next ns servers to check with robetx
ns_servers_to_robtex={}
domains_still_to_analyze=[]
download_files=False
all_robtex=False
# By default we don't use common hostname list
use_common_list = False
common_list_path = ""
# zenmap command
zenmap_command = 'zenmap'
# End of global variables
###########################
# Print version information
def version():
print("+----------------------------------------------------------------------+")
print("| "+ sys.argv[0] + " Version "+ vernum +" |")
print("| This program is free software; you can redistribute it and/or modify |")
print("| it under the terms of the GNU General Public License as published by |")
print("| the Free Software Foundation; either version 2 of the License, or |")
print("| (at your option) any later version. |")
print("| |")
print("| Author: Garcia Sebastian, eldraco@gmail.com |")
print("| Author: Veronica Valeros, vero.valeros@gmail.com |")
print("| www.mateslab.com.ar - Argentina |")
print("+----------------------------------------------------------------------+")
print()
# Print help information and exit:
def usage():
# print("+----------------------------------------------------------------------+")
# print("| "+ sys.argv[0] + " Version "+ vernum +" |")
# print("| This program is free software; you can redistribute it and/or modify |")
# print("| it under the terms of the GNU General Public License as published by |")
# print("| the Free Software Foundation; either version 2 of the License, or |")
# print("| (at your option) any later version. |")
# print("| |")
# print("| Author: Garcia Sebastian, eldraco@gmail.com |")
# print("| Author: Veronica Valeros, vero.valeros@gmail.com |")
# print("| www.mateslab.com.ar - Argentina |")
# print("+----------------------------------------------------------------------+")
print("\nusage: %s -d <domain> <options>" % sys.argv[0])
print("options:")
print(" -h, --help Show this help message and exit.")
print(" -V, --version Output version information and exit.")
print(" -D, --debug Debug.")
print(" -d, --domain Domain to analyze.")
print(" -L <list>, --common-hosts-list <list> Relative path to txt file containing common hostnames. One name per line.")
print(" -j, --not-common-hosts-names Do not check common host names. Quicker but you will lose hosts.")
print(" -t, --not-zone-transfer Do not attempt to transfer the zone.")
print(" -n, --not-net-block Do not attempt to -sL each IP netblock.")
print(" -o, --store-output Store everything in a directory named as the domain. Nmap output files and the summary are stored inside.")
print(" -a, --not-scan-or-active Do not use nmap to scan ports nor to search for active hosts.")
print(" -p, --not-store-nmap Do not store any nmap output files in the directory <output-directory>/nmap.")
print(" -e, --zenmap Move xml nmap files to a directory and open zenmap with the topology of the whole group. Your user should have access to the DISPLAY variable.")
print(" -g, --not-goog-mail Do not use goog-mail.py (embebed) to look for emails for each domain")
print(" -s, --not-subdomains Do not analyze sub-domains recursively. You will lose subdomain internal information.")
print(" -f, --create-pdf Create a pdf file with all the information.")
print(" -l, --world-domination Scan every gov,mil,org and net domains of every country on the world. Interesting if you don't use -s")
print(" -r, --robin-hood Send the pdf report to every email found using domains the MX servers found. Good girl.")
print(" -w, --not-webcrawl Do not web crawl every web site (in every port) we found looking for public web mis-configurations (Directory listing, etc.).")
print(" -m, --max-amount-to-crawl If you crawl, do it up to this amount of links for each web site. Defaults to 50.")
print(" -F, --download-files If you crawl, download every file to disk.")
print(" -c, --not-countrys Do not resolve the country name for every IP and hostname.")
print(" -C, --not-colors Do not use colored output.")
print(" -q, --not-spf Do not check SPF records.")
print(" -k, --random-domains Find this amount of domains from google and analyze them. For base domain use -d")
print(" -v, --ignore-host-pattern When using nmap to find active hosts and to port scan, ignore hosts which names match this pattern. Separete them with commas.")
print(" -x, --nmap-scantype Nmap parameters to port scan. Defaults to: '-O --reason --webxml --traceroute -sS -sV -sC -PN -n -v -F' .")
print(" -b, --robtex-domains If we found a DNS server with zone transfer activated, search other UNrelated domains using that DNS server with robtex and analyze them too.")
print(" -B, --all-robtex Like -b, but also if no Zone Transfer was found. Useful to analyze all the domains in one corporative DNS server. Includes also -b.")
print("Press CTRL-C at any time to stop only the current step.")
print()
sys.exit(1)
def get_NS_records(domain):
"""
This function takes the domain and ask for the nameservers information
"""
global debug
global domain_data
global check_common_hosts_names
global zone_transfer
global net_block
global output_file
global output_directory
global not_store_nmap
global subdomains_found
global not_subdomains
global output_file_handler
global countrys
hosttype={}
reverseDNS={}
hostname={}
ip_registry=[]
#
# Here we obtain the NS servers for the domain
#
try:
print('\tChecking NameServers using system default resolver...')
if output_file!="":
output_file_handler.writelines('\tChecking NameServers using system default resolver...\n')
# Get the list of name servers IPs
ns_servers = dns.resolver.resolve(domain, 'NS')
if debug:
logging.debug('\t\t> There are {0} nameservers'.format(len(ns_servers)))
for rdata in ns_servers:
if debug:
logging.debug('\t\t> Looking for {0} IP address'.format(rdata.to_text()))
# We search for the IP of each NSs
ip_list = dns.resolver.resolve(rdata.to_text()[:-1], 'A')
# For each IP we store its information
for ip in ip_list:
ip_registry=[]
if debug:
logging.debug('\t\t> NS IP: {0}'.format(ip.to_text()))
try:
# If already exists this IP in the registry
# We search for this IP in the main dict
ip_registry=domain_data['IpsInfo'][ip.to_text()]
# Here we store the hostname in a dictionary. The index is 'HostName'
hostname['HostName']=rdata.to_text()[:-1]
ip_registry.append(hostname)
# Here we store the type of register in a dictionary. The index is 'Type'
hosttype['Type']='NS'
ip_registry.append(hosttype)
# Do we have the country of this ip?
has_country=False
for dicts in ip_registry:
if dicts.__contains__('IpCountry'):
has_country=True
if not has_country and countrys:
# We don't have this country
if debug:
logging.debug('\t\t> No country yet')
ipcountry={}
try:
country=geolite2.lookup(ip.to_text()).country
except AttributeError:
country='Not found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
logging.debug('\t\t> Country: {0}'.format(country))
ipcountry['IpCountry']=country
# Obtain Ip's reverse DNS name if we don't have it
has_ptr=False
for dicts in ip_registry:
if dicts.__contains__('PTR'):
has_ptr=True
if not has_ptr:
# Obtain Ip's reverse DNS name
reverse_name=check_PTR_record(ip.to_text())
if reverse_name != "":
reverseDNS['PTR']=reverse_name
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip.to_text()]=a
printout(domain,ip.to_text(),0)
except KeyError:
# If this is a new IP
ip_registry=[]
ipcountry={}
# Do we have the country of this ip?
if countrys:
try:
country=geolite2.lookup(ip.to_text()).country
except AttributeError:
country='Not found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
ipcountry['IpCountry']=country
# Here we store the hostname in a dictionary. The index is 'HostName'
hostname['HostName']=rdata.to_text()[:-1]
ip_registry.append(hostname)
# Here we store the type of register in a dictionary. The index is 'Type'
hosttype['Type']='NS'
ip_registry.append(hosttype)
# Obtain Ip's reverse DNS name
reverse_name=check_PTR_record(ip.to_text())
if reverse_name != "":
reverseDNS['PTR']=reverse_name
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip.to_text()]=a
printout(domain,ip.to_text(),0)
except Exception as inst:
logging.warning('\t\tError in get_NS_records()')
logging.warning(inst)
if output_file!="":
output_file_handler.writelines('\t\tError in get_NS_records()\n')
return -1
except KeyboardInterrupt:
try:
# CTRL-C pretty handling.
print("Keyboard Interruption!. Skiping the NS search step. Press CTRL-C again to exit.")
time.sleep(1)
return (2)
except KeyboardInterrupt:
sys.exit(1)
def get_MX_records(domain):
"""
This function takes the domain and ask for mailservers information
"""
global debug
global domain_data
global check_common_hosts_names
global zone_transfer
global net_block
global output_file
global output_directory
global not_store_nmap
global subdomains_found
global not_subdomains
global output_file_handler
global countrys
hosttype={}
reverseDNS={}
hostname={}
ip_registry=[]
#
# Here we obtain the MX servers for the domain
#
print('\n\tChecking MailServers using system default resolver...')
if output_file!="":
output_file_handler.writelines('\n\tChecking MailServers using system default resolver...\n')
try:
mail_servers = dns.resolver.resolve(domain, 'MX')
for rdata in mail_servers:
# We search for the IP of each NSs
ip_list = dns.resolver.resolve(rdata.exchange.to_text()[:-1], 'A')
# For each IP we store its information
for ip in ip_list:
ip_registry=[]
try:
# If already exists this IP in the registry
# We search for this IP in the main dict
ip_registry=domain_data['IpsInfo'][ip.to_text()]
# Here we store the hostname in a dictionary. The index is 'HostName'
hostname['HostName']=rdata.exchange.to_text()[:-1]
ip_registry.append(hostname)
# Here we store the type of register in a dictionary. The index is 'Type'
hosttype['Type']='MX'
ip_registry.append(hosttype)
# Do we have the country of this ip?
has_country=False
for dicts in ip_registry:
if dicts.__contains__('IpCountry'):
has_country=True
if not has_country and countrys:
# We don't have this country
if debug:
logging.debug('\t\t> No country yet')
ipcountry={}
try:
country=geolite2.lookup(ip.to_text()).country
except AttributeError:
country='Not Found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
logging.debug('\t\t> Country: {0}'.format(country))
# Obtain Ip's reverse DNS name if we don't have it
has_ptr=False
for dicts in ip_registry:
if dicts.__contains__('PTR'):
has_ptr=True
if not has_ptr:
# Obtain Ip's reverse DNS name
reverse_name=check_PTR_record(ip.to_text())
if reverse_name != "":
reverseDNS['PTR']=reverse_name
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip.to_text()]=a
printout(domain,ip.to_text(),0)
except KeyError:
# If this is a new IP
ip_registry=[]
ipcountry={}
if countrys:
# Do we have the country of this ip?
try:
country=geolite2.lookup(ip.to_text()).country
except AttributeError:
country='Not Found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
if debug:
logging.debug('\t\t> Country: {0}'.format(country))
# Here we store the hostname in a dictionary. The index is 'HostName'
hostname['HostName']=rdata.exchange.to_text()[:-1]
ip_registry.append(hostname)
# Here we store the type of register in a dictionary. The index is 'Type'
hosttype['Type']='MX'
ip_registry.append(hosttype)
# Obtain Ip's reverse DNS name
reverse_name=check_PTR_record(ip.to_text())
if reverse_name != "":
reverseDNS['PTR']=reverse_name
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip.to_text()]=a
printout(domain,ip.to_text(),0)
except :
logging.warning('\t\tWARNING!! There are no MX records for this domain')
if output_file!="":
output_file_handler.writelines('\t\tWARNING!! There are no MX records for this domain\n')
return -1
def dns_request(domain):
"""
This function takes the domain and ask for several related dns information
"""
global debug
global domain_data
global check_common_hosts_names
global use_common_list
global common_list_path
global zone_transfer
global net_block
global output_file
global output_directory
global not_store_nmap
global subdomains_found
global not_subdomains
global common_hostnames
global output_file_handler
global countrys
try:
hosttype={}
reverseDNS={}
hostname={}
ip_registry=[]
if check_common_hosts_names==False:
common_hostnames=[]
elif use_common_list == True:
common_hostnames=[]
external_dns_file_name = os.path.join(os.getcwd(), common_list_path)
ins = open ( external_dns_file_name , "r" )
for line in ins:
common_hostnames.append( line.rstrip() )
else:
common_hostnames=['www','ftp','vnc','fw','mail' ,'dba' ,'db' ,'mssql' ,'sql' ,'ib','secure','oracle' ,'ora' ,'oraweb' ,'sybase' ,'gw' ,'log' ,'logs' ,'logserver' ,'backup' ,'windows' ,'win' ,'nt' ,'ntserver' ,'win2k' ,'mswin' ,'msnt' ,'posnt' ,'server' ,'test' ,'firewall' ,'cp' ,'cpfw1' ,'cpfw1ng' ,'fw' ,'fw1' ,'raptor' ,'drag' ,'dragon' ,'pix' ,'ciscopix' ,'nameserver' ,'dns' ,'ns' ,'ns1' ,'ns2' ,'mx' ,'webmail' ,'mailhost' ,'smtp' ,'owa' ,'pop' ,'notes' ,'proxy' ,'squid' ,'imap' ,'www1' ,'www2' ,'www3' ,'corp' ,'corpmail' ,'print' ,'printer' ,'search' ,'telnet' ,'tftp' ,'web' ,'bgp' ,'citrix' ,'pcanywhere' ,'ts' ,'terminalserver' ,'tserv' ,'tserver' ,'keyserver' ,'pgp' ,'samba' ,'linux' ,'redhat' ,'caldera' ,'openlinux' ,'conectiva' ,'corel' ,'corelinux' ,'debian' ,'mandrake' ,'linuxppc' ,'bastille' ,'stampede' ,'suse' ,'trinux' ,'trustix' ,'turbolinux' ,'turbo' ,'tux' ,'slack' ,'slackware' ,'bsd' ,'daemon' ,'darby' ,'beasty' ,'beastie' ,'openbsd' ,'netbsd' ,'freebsd' ,'obsd' ,'fbsd' ,'nbsd' ,'solaris' ,'sun' ,'sun1' ,'sun2' ,'sun3' ,'aix' ,'tru64' ,'hp-ux' ,'hp' ,'lynx' ,'lynxos' ,'macosx' ,'osx' ,'minix' ,'next' ,'nextstep' ,'qnx' ,'rt' ,'sco' ,'xenix' ,'sunos' ,'ultrix' ,'unixware' ,'multics' ,'zeus' ,'apollo' ,'hercules' ,'venus' ,'pendragon' ,'guinnevere' ,'lancellot' ,'percival' ,'prometheus' ,'ssh' ,'time' ,'nicname' ,'tacacs' ,'domain' ,'whois' ,'bootps' ,'bootpc' ,'gopher' ,'http' ,'kerberos' ,'hostname' ,'pop2' ,'pop3' ,'nntp' ,'ntp' ,'irc' ,'imap3' ,'ldap' ,'https' ,'nntps' ,'ldaps' ,'webster' ,'imaps' ,'ircs' ,'pop3s' ,'login' ,'router' ,'netnews' ,'ica' ,'radius' ,'hsrp' ,'mysql' ,'amanda' ,'pgpkeyserver' ,'quake' ,'kerberos_master' ,'passwd_server' ,'smtps' ,'swat' ,'support' ,'afbackup' ,'postgres' ,'fax' ,'hylafax' ,'tircproxy' ,'webcache' ,'tproxy' ,'jetdirect' ,'kamanda' ,'fido','old']
#
# Here we obtain the NS servers for the domain
#
get_NS_records(domain)
#
# Here we obtain the MX servers for the domain
#
get_MX_records(domain)
#
# Here we check if wildcard is activated
#
try:
wildcard_detect = dns.resolver.resolve('asdf80a98vrnwe9ufrcsajd90awe8ridsjkd.'+domain, 'A')
logging.warning('\t\tWARNING!! This domain has wildcards activated for hostnames resolution. We are checking "www" anyway, but perhaps it doesn\'t exists!')
if output_file!="":
output_file_handler.writelines('\t\tWARNING!! This domain has wildcards activated for hostnames resolution. We are checking "www" anyway, but perhaps it doesn\'t exists!\n')
# If wildcard is activated we don't check common hostnames except for www, it is too common not to be there!
common_hostnames=['www']
except:
# If wildcard is not activated we check every hostname
pass
#
# Here we check the zone transfer for each NS
#
if zone_transfer:
print('\n\tChecking the zone transfer for each NS... (if this takes more than 10 seconds, just hit CTRL-C and it will continue. Bug in the libs)')
if output_file!="":
output_file_handler.writelines('\n\tChecking the zone transfer for each NS... (if this takes more than 10 seconds, just hit CTRL-C and it will continue. Bug in the libs)\n')
try:
name_servers_list=[]
for ip in domain_data['IpsInfo']:
for dicts in domain_data['IpsInfo'][ip]:
if dicts.__contains__('Type'):
if dicts['Type']=='NS':
name_servers_list.append(ip)
if debug:
logging.debug('\t\t> Name server list: {0} '.format(name_servers_list))
# For each nameserver we check the zone transfer
for ip in name_servers_list:
try:
zone_transfer_data = dns.zone.from_xfr(dns.query.xfr(ip, domain,timeout=-1))
logging.critical('\t\tZone transfer successful on name server {0} ({1} hosts)'.format(ip, len(list(zone_transfer_data.items()))))
if output_file!="":
output_file_handler.writelines('\t\tZone transfer successful on name server {0} ({1} hosts)\n'.format(ip, len(list(zone_transfer_data.items()))))
# We should store this information in OS info or something...
ip_registry=[]
hosttype={}
try:
# If already exists this IP in the registry store it. ip is an IP. NS should
# be always stored!
ip_registry=domain_data['IpsInfo'][ip]
hosttype['ZT']=len(zone_transfer_data.items())
ip_registry.append(hosttype)
if debug:
logging.debug('\t\t> Storing ZT data for {0} : {1} hostnames: {2}'.format(ip,len(list(zone_transfer_data.items())), zone_transfer_data.keys()))
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip]=a
except:
if debug:
logging.warning('\t> WARNING! NS should be already stored in memory, and this one is not: {0}'.format(ip))
# If we found a zone transfer, we should not use the common_hostnames. It is enough with the zone! Thanks to Agustin Gugliotta
common_hostnames = []
for host in zone_transfer_data:
#if not(host in common_hostnames) and not('@' in host.to_text())and not ( '*' in host.to_text()):
common_hostnames.append(host.to_text())
except:
print(f'\t\tNo zone transfer found on nameserver {ip}')
if output_file!="":
output_file_handler.writelines('\t\tNo zone transfer found on nameserver {0}\n'.format(ip))
except KeyboardInterrupt:
try:
# CTRL-C pretty handling.
print("Keyboard Interruption!. Skiping the zone transfer step. Press CTRL-C again to exit.")
time.sleep(1)
return (2)
except KeyboardInterrupt:
sys.exit(1)
except:
logging.warning('\t\tZone error?')
pass
#
# Here we look for SPF record to obtain new IP address
#
check_SPF_record(domain)
#
# Here we check the A records of the hosts names, included de most common ones.
# This function is called BEFORE the nmap sL scan, so that we can include every netblock in the sL scan.
#
check_A_records(domain,'most common')
#
# Here we obtain the host names for each IP of every netblock using sL
#
if net_block:
print('\n\tChecking with nmap the reverse DNS hostnames of every <ip>/24 netblock using system default resolver...')
if output_file!="":
output_file_handler.writelines('\n\tChecking with nmap the reverse DNS hostnames of every <ip>/24 netblock using system default resolver...\n')
try:
# We already check the common hostnames, this is just for the ones found by nmap sL
common_hostnames2=copy.deepcopy(common_hostnames)
common_hostnames=[]
# We remember which netblock we did resolve...
netblocks_checked=[]
# For each ip, nmap sL it
for ip in domain_data['IpsInfo']:
# Obtain the net block
# from 1.2.3.4 -> ['1','2','3']
temp_ip_net_block=ip.split('.')[:-1]
# from ['1','2','3'] -> 1.2.3.0
temp_ip_net_block.append('0')
temp=""
for i in temp_ip_net_block:
temp=temp+'.'+i
ip_net_block=temp[1:]
# do not check twice the same netblock!
if ip_net_block not in netblocks_checked:
if output_directory==False or not_store_nmap == 1:
nmap_command_temp='nmap -sL -v '+ip_net_block+'/24'
else:
try:
os.mkdir(output_directory+'/nmap')
except OSError:
pass
nmap_command_temp='nmap -sL -v '+ip_net_block+'/24 -oA '+output_directory+'/nmap/'+ip_net_block+'.sL'
print(f'\t\tChecking netblock {ip_net_block}')
if output_file!="":
output_file_handler.writelines('\t\tChecking netblock {0}\n'.format(ip_net_block))
nmap_command=shlex.split(nmap_command_temp)
nmap_result_pipes =Popen(nmap_command, stdout=PIPE, stderr=PIPE).communicate()
nmap_result_raw = nmap_result_pipes[0]
nmap_result_raw_stderr = nmap_result_pipes[1]
if b'You requested a scan type which requires root privileges.' in nmap_result_raw_stderr:
print('\t\tNmap seems to need root for better results')
#print(f'\t\t{nmap_result_raw_stderr}')
nmap_result = nmap_result_raw.split('\n')
netblocks_checked.append(ip_net_block)
else:
if debug:
logging.debug('\t\t> Netblock {0} already resolved'.format(ip_net_block))
# Analyzing results
found=False
for i in nmap_result:
i = i.decode()
if i.find(domain)!=-1:
net_hostname=i.split('for ')[1].split(' (')[0].split('.')[0]
ip=i.split('(')[1].split(')')[0]
# We should add here the reverse DNS name of the host and the IP to de list!!!
if not(net_hostname in common_hostnames2):
common_hostnames.append(net_hostname)
common_hostnames2.append(net_hostname)
if debug:
logging.debug('\t\t\tNew host name {0} found in IP {1}'.format(net_hostname,ip))
found=True
# Add this IP to the main dictionary, with its PTR record found
try:
# If already exists this IP in the registry
# We search for this IP in the main dict
ip_registry=domain_data['IpsInfo'][ip]
if debug:
logging.debug('\t\t\t\tThe IP {1} was not new, adding {0} as PTR if it not there.'.format(net_hostname,ip))
# Do we have the country of this ip?
has_country=False
for dicts in ip_registry:
if dicts.__contains__('IpCountry'):
has_country=True
if not has_country and countrys:
# We don't have this country
if debug:
logging.debug('\t\t> No country yet')
ipcountry={}
try:
country=geolite2.lookup(ip.to_text()).country
except AttributeError:
country='Not Found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
logging.debug('\t\t> Country: {0}'.format(country))
# Obtain Ip's reverse DNS name if we don't have it
has_ptr=False
for dicts in ip_registry:
if dicts.__contains__('PTR'):
has_ptr=True
if not has_ptr:
# Obtain Ip's reverse DNS name
reverse_name=check_PTR_record(ip)
if reverse_name != "":
reverseDNS['PTR']=net_hostname+'.'+domain
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip]=a
printout(domain,ip,0)
except KeyError:
# If this is a new IP
ip_registry=[]
ipcountry={}
if debug:
logging.debug('\t\t\t\tThe IP {1} was new, adding it, the country and {0} as PTR.'.format(net_hostname,ip))
if countrys:
# Do we have the country of this ip?
try:
country=geolite2.lookup(ip).country
except AttributeError:
country='Not Found'
ipcountry['IpCountry']=country
ip_registry.append(ipcountry)
# Here we store the hostname in a dictionary. The index is 'HostName'
reverseDNS['PTR']=net_hostname+'.'+domain
ip_registry.append(reverseDNS)
# We store it in the main dictionary
a=[]
a=copy.deepcopy(ip_registry)
domain_data['IpsInfo'][ip]=a
printout(domain,ip,0)
#
# Here we check the A records of the hosts names found with nmap sL only. This function is called AFTER the nmap sL
# scan, so that we can include every netblock in the sL scan.
#
# Before this, we should check that the host names found by sL does not repeat with the NS or MX!!
if found:
check_A_records(domain,'sL')
except KeyboardInterrupt:
try:
# CTRL-C pretty handling.
print("Keyboard Interruption!. Skiping the netblock resolution step. Press CTRL-C again to exit.")
time.sleep(1)
return (2)
except KeyboardInterrupt:
sys.exit(1)
except:
pass
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to printed directly
x, y = inst # __getitem__ allows args to be unpacked directly
print('x =', x)
print('y =', y)
def check_PTR_record(ip):
"""
This function takes one ip and ask for the dns PTR record information or reverse DNS hostname, and latter adds it to the main dictionary
"""
global debug
global domain_data
try:
if debug:
logging.debug('\t\t> Checking {0} ip reverse DNS hostname'.format(ip))
"""
temp_ip = ip.split('.')
temp_ip.reverse()
reverse_ip=""
for i in temp_ip:
reverse_ip = reverse_ip + i +'.'
reverse_ip = reverse_ip + 'in-addr.arpa'
"""
reverse_name = dns.reversename.from_address(ip).to_text()[:-1]
return reverse_name
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to printed directly
x, y = inst # __getitem__ allows args to be unpacked directly
print('x =', x)
print('y =', y)
return ""
def check_SPF_record(domain):
"""
This function looks for SPF record information in the domain and adds the hosts found to the main dictionary
"""
global debug
global domain_data
global common_hostnames
global check_spf
global output_file
global output_file_handler
reverseDNS={}