-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDNSint.py
More file actions
1783 lines (1444 loc) · 72.1 KB
/
DNSint.py
File metadata and controls
1783 lines (1444 loc) · 72.1 KB
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
"""
DNSint v1.1 - DNS Intelligence Toolkit
A professional DNS reconnaissance and OSINT tool for comprehensive domain analysis
Created by wh0xac
"""
import argparse
import json
import socket
import sys
import re
import os
from pathlib import Path
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional, Set, Tuple
import dns.resolver
import dns.query
import dns.zone
import dns.exception
import dns.reversename
import dns.message
import dns.rdatatype
import requests
import whois as whois_lib
from ipwhois import IPWhois
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.tree import Tree
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.layout import Layout
from rich.syntax import Syntax
from rich import box
from rich.text import Text
from bs4 import BeautifulSoup
console = Console()
RECORD_TYPES = ["A", "AAAA", "CNAME", "MX", "TXT", "NS", "SOA", "SRV", "CAA", "NAPTR", "DNSKEY", "DS"]
PUBLIC_RESOLVERS = {
"Google": "8.8.8.8",
"Cloudflare": "1.1.1.1",
"Quad9": "9.9.9.9"
}
def get_desktop_path() -> Path:
"""Get the desktop directory path cross-platform (Windows/Mac/Linux)"""
home = Path.home()
if sys.platform == "win32":
desktop = home / "Desktop"
elif sys.platform == "darwin":
desktop = home / "Desktop"
else:
desktop = home / "Desktop"
if not desktop.exists():
desktop = home
if not desktop.exists():
desktop = home
return desktop
def print_banner():
"""Display the enhanced ASCII banner with version and creator"""
banner = """
[bold cyan] ▗▄▄▄ ▗▖ ▗▖ ▗▄▄▖ [/bold cyan]
[bold cyan] ▐▌ ▐▌▐▛▚▖▐▌▐▌ [/bold cyan]
[bold cyan] ▐▌ ▐▌▐▌ ▝▜▌ ▝▀▚▖ [/bold cyan]
[bold cyan] ▐▙▄▄▀ ▐▌ ▐▌▗▄▄▞▘ [/bold cyan][bold white]int[/bold white]
[bold cyan] ═══════════════════════════════ [/bold cyan]
[bold yellow] v1.1, by wh0xac [/bold yellow]
"""
console.print(banner)
def join_txt_chunks(txt_value: str) -> str:
"""Join multi-chunk TXT records (quoted strings) into a single string"""
parts = re.findall(r'"([^"]*)"', txt_value)
if parts:
return ''.join(parts)
return txt_value.strip('"')
def create_resolver(timeout: int = 5, dns_server: Optional[str] = None) -> dns.resolver.Resolver:
"""Create a DNS resolver with optional custom DNS server"""
resolver = dns.resolver.Resolver()
resolver.lifetime = timeout
if dns_server:
resolver.nameservers = [dns_server]
return resolver
def update_tool():
"""Update DNSint to the latest version from GitHub"""
console.print("\n[bold cyan]Checking for updates...[/bold cyan]\n")
try:
import subprocess
# Check if we're in a git repository
result = subprocess.run(
["git", "rev-parse", "--is-inside-work-tree"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
console.print("[red]Error:[/red] Not a git repository. Please clone from GitHub:")
console.print("[cyan]git clone https://github.com/who0xac/DNSint.git[/cyan]\n")
sys.exit(1)
# Fetch latest changes
console.print("[yellow]Fetching latest changes...[/yellow]")
subprocess.run(["git", "fetch", "origin"], check=True, timeout=30)
# Check if there are updates
result = subprocess.run(
["git", "rev-list", "HEAD...origin/main", "--count"],
capture_output=True,
text=True,
timeout=5
)
commits_behind = int(result.stdout.strip())
if commits_behind == 0:
console.print("[green]✓ You're already on the latest version![/green]\n")
sys.exit(0)
console.print(f"[yellow]Found {commits_behind} new commit(s)[/yellow]\n")
# Show what will be updated
console.print("[cyan]Latest changes:[/cyan]")
subprocess.run(
["git", "log", "HEAD..origin/main", "--oneline", "--no-decorate"],
timeout=5
)
console.print()
# Pull updates
console.print("[yellow]Updating DNSint...[/yellow]")
subprocess.run(["git", "pull", "origin", "main"], check=True, timeout=30)
console.print("\n[green]✓ DNSint updated successfully![/green]")
console.print("[dim]You may need to reinstall dependencies: pip install -r requirements.txt[/dim]\n")
sys.exit(0)
except subprocess.TimeoutExpired:
console.print("[red]Error:[/red] Update timed out. Please try again.\n")
sys.exit(1)
except subprocess.CalledProcessError as e:
console.print(f"[red]Error:[/red] Update failed: {e}\n")
sys.exit(1)
except Exception as e:
console.print(f"[red]Error:[/red] {e}\n")
sys.exit(1)
def get_parent_zone(domain: str) -> Optional[str]:
"""Get the parent zone for a domain (for DS record lookup)"""
parts = domain.split('.')
if len(parts) >= 2:
return '.'.join(parts[1:])
return None
def detect_technologies(domain: str, timeout: int, verbose: bool) -> Dict[str, Any]:
"""Detect web technologies, frameworks, CMS, and server information"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task("[cyan]Detecting web technologies and server info...", total=None)
tech_data = {
"web_server": None,
"frameworks": [],
"cms": None,
"analytics": [],
"cdn": None,
"hosting_provider": None,
"technologies": [],
"security_headers": {},
"ssl_info": {},
"checked": False,
"error": None
}
try:
protocols = ["https://", "http://"]
response = None
for protocol in protocols:
try:
url = f"{protocol}{domain}"
response = requests.get(url, timeout=timeout, allow_redirects=True,
headers={'User-Agent': 'DNSint/1.0 Security Scanner'})
tech_data["checked"] = True
break
except requests.exceptions.SSLError:
if protocol == "https://":
continue
except requests.exceptions.ConnectionError:
continue
except requests.exceptions.Timeout:
continue
if not response:
tech_data["error"] = "Could not connect to web server"
return tech_data
headers = response.headers
if 'Server' in headers:
tech_data["web_server"] = headers['Server']
tech_data["security_headers"] = {
"X-Frame-Options": headers.get("X-Frame-Options", "Not Set"),
"Content-Security-Policy": headers.get("Content-Security-Policy", "Not Set"),
"Strict-Transport-Security": headers.get("Strict-Transport-Security", "Not Set"),
"X-Content-Type-Options": headers.get("X-Content-Type-Options", "Not Set"),
"X-XSS-Protection": headers.get("X-XSS-Protection", "Not Set"),
"Referrer-Policy": headers.get("Referrer-Policy", "Not Set"),
"Permissions-Policy": headers.get("Permissions-Policy", "Not Set")
}
if 'X-Powered-By' in headers:
tech_data["technologies"].append(f"X-Powered-By: {headers['X-Powered-By']}")
if 'CF-Ray' in headers or 'cf-ray' in headers:
tech_data["cdn"] = "Cloudflare"
elif 'X-Amz-Cf-Id' in headers:
tech_data["cdn"] = "Amazon CloudFront"
elif 'X-CDN' in headers:
tech_data["cdn"] = headers['X-CDN']
soup = BeautifulSoup(response.text, 'html.parser')
meta_tags = soup.find_all('meta')
for meta in meta_tags:
if meta.get('name', '').lower() == 'generator':
content = meta.get('content', '')
if 'WordPress' in content:
tech_data["cms"] = f"WordPress ({content})"
elif 'Drupal' in content:
tech_data["cms"] = f"Drupal ({content})"
elif 'Joomla' in content:
tech_data["cms"] = f"Joomla ({content})"
else:
tech_data["cms"] = content
scripts = soup.find_all('script', src=True)
for script in scripts:
src = script.get('src', '')
if 'react' in src.lower():
if 'React' not in tech_data["frameworks"]:
tech_data["frameworks"].append("React")
elif 'vue' in src.lower():
if 'Vue.js' not in tech_data["frameworks"]:
tech_data["frameworks"].append("Vue.js")
elif 'angular' in src.lower():
if 'Angular' not in tech_data["frameworks"]:
tech_data["frameworks"].append("Angular")
elif 'jquery' in src.lower():
if 'jQuery' not in tech_data["frameworks"]:
tech_data["frameworks"].append("jQuery")
elif 'bootstrap' in src.lower():
if 'Bootstrap' not in tech_data["frameworks"]:
tech_data["frameworks"].append("Bootstrap")
if 'google-analytics' in src or 'analytics.js' in src or 'gtag' in src:
if 'Google Analytics' not in tech_data["analytics"]:
tech_data["analytics"].append("Google Analytics")
elif 'googletagmanager' in src:
if 'Google Tag Manager' not in tech_data["analytics"]:
tech_data["analytics"].append("Google Tag Manager")
elif 'facebook.net' in src or 'fbevents.js' in src:
if 'Facebook Pixel' not in tech_data["analytics"]:
tech_data["analytics"].append("Facebook Pixel")
elif 'hotjar' in src:
if 'Hotjar' not in tech_data["analytics"]:
tech_data["analytics"].append("Hotjar")
page_content = response.text.lower()
if 'wp-content' in page_content or 'wp-includes' in page_content:
if not tech_data["cms"] or 'WordPress' not in tech_data["cms"]:
tech_data["cms"] = "WordPress"
elif '/sites/default/' in page_content or 'drupal' in page_content:
if not tech_data["cms"]:
tech_data["cms"] = "Drupal"
elif 'shopify' in page_content:
if not tech_data["cms"]:
tech_data["cms"] = "Shopify"
elif 'wix.com' in page_content:
tech_data["hosting_provider"] = "Wix"
elif 'squarespace' in page_content:
tech_data["hosting_provider"] = "Squarespace"
if response.url:
tech_data["ssl_info"]["protocol_used"] = "HTTPS" if response.url.startswith("https") else "HTTP"
except Exception as e:
tech_data["error"] = f"Error detecting technologies: {str(e)}"
return tech_data
def display_technology_info(tech_data: Dict[str, Any], quiet: bool):
"""Display detected technologies and server information"""
if quiet or not tech_data.get("checked"):
return
if tech_data.get("error"):
console.print(f"\n[yellow]⚠ Technology Detection: {tech_data['error']}[/yellow]\n")
return
tree = Tree("[bold cyan]🔧 Technology Stack & Server Analysis[/bold cyan]", guide_style="cyan")
if tech_data.get("web_server"):
server_branch = tree.add("[bold]Web Server[/bold]")
server_branch.add(f"[green]{tech_data['web_server']}[/green]")
if tech_data.get("cms"):
cms_branch = tree.add("[bold]Content Management System (CMS)[/bold]")
cms_branch.add(f"[green]{tech_data['cms']}[/green]")
if tech_data.get("frameworks"):
framework_branch = tree.add(f"[bold]Frameworks & Libraries ({len(tech_data['frameworks'])})[/bold]")
for framework in tech_data["frameworks"]:
framework_branch.add(f"[cyan]• {framework}[/cyan]")
if tech_data.get("analytics"):
analytics_branch = tree.add(f"[bold]Analytics & Tracking ({len(tech_data['analytics'])})[/bold]")
for analytic in tech_data["analytics"]:
analytics_branch.add(f"[yellow]• {analytic}[/yellow]")
if tech_data.get("cdn"):
cdn_branch = tree.add("[bold]Content Delivery Network (CDN)[/bold]")
cdn_branch.add(f"[magenta]{tech_data['cdn']}[/magenta]")
if tech_data.get("hosting_provider"):
hosting_branch = tree.add("[bold]Hosting Provider[/bold]")
hosting_branch.add(f"[blue]{tech_data['hosting_provider']}[/blue]")
if tech_data.get("technologies"):
tech_branch = tree.add("[bold]Additional Technologies[/bold]")
for tech in tech_data["technologies"]:
tech_branch.add(f"[dim]• {tech}[/dim]")
security_headers = tech_data.get("security_headers", {})
if security_headers:
sec_branch = tree.add("[bold]HTTP Security Headers[/bold]")
for header, value in security_headers.items():
if value == "Not Set":
sec_branch.add(f"[red]✗ {header}: {value}[/red]")
else:
short_value = value[:50] + "..." if len(value) > 50 else value
sec_branch.add(f"[green]✓ {header}: {short_value}[/green]")
if tech_data.get("ssl_info", {}).get("protocol_used"):
ssl_branch = tree.add("[bold]Protocol[/bold]")
protocol = tech_data["ssl_info"]["protocol_used"]
if protocol == "HTTPS":
ssl_branch.add(f"[green]✓ {protocol}[/green]")
else:
ssl_branch.add(f"[red]✗ {protocol} (Not Secure)[/red]")
console.print()
console.print(Panel(tree, border_style="cyan", box=box.ROUNDED))
console.print()
def display_dns_records_table(records: Dict[str, List[Any]], quiet: bool):
"""Display DNS records in a beautiful table"""
if quiet:
return
table = Table(
title="[bold cyan]DNS Records Discovery[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("Type", style="cyan bold", width=10)
table.add_column("Value", style="white", max_width=50)
table.add_column("TTL", style="yellow", width=8)
table.add_column("Extra", style="green", width=20)
total_records = 0
for rtype in RECORD_TYPES:
record_list = records.get(rtype, [])
if record_list:
for idx, record in enumerate(record_list):
total_records += 1
value = record.get("value", "")
ttl = str(record.get("ttl", "N/A"))
extra = ""
if rtype == "MX" and "priority" in record:
extra = f"Priority: {record['priority']}"
elif rtype == "SRV":
extra = f"P:{record.get('priority')} W:{record.get('weight')} Port:{record.get('port')}"
type_display = rtype if idx == 0 else ""
if len(value) > 50:
value = value[:47] + "..."
table.add_row(type_display, value, ttl, extra)
if len(record_list) > 1:
table.add_row("", "", "", "", end_section=True)
if total_records == 0:
table.add_row("[dim]No records found[/dim]", "", "", "")
console.print()
console.print(table)
console.print(f"[dim]Total: {total_records} DNS records found[/dim]\n")
def display_ptr_table(ptr_results: Dict[str, List[str]], quiet: bool):
"""Display PTR lookups in a beautiful table"""
if quiet or not ptr_results:
return
table = Table(
title="[bold cyan]Reverse PTR Lookups[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("IP Address", style="cyan bold", width=20)
table.add_column("PTR Record", style="white")
table.add_column("Status", style="green", width=12)
for ip, ptrs in sorted(ptr_results.items()):
if ptrs:
status = "[green]✓ Found[/green]"
ptr_display = ", ".join(ptrs)
else:
status = "[dim]○ None[/dim]"
ptr_display = "[dim]No PTR record[/dim]"
table.add_row(ip, ptr_display, status)
console.print(table)
console.print()
def display_axfr_results(axfr_results: Dict[str, Any], quiet: bool):
"""Display AXFR results in a beautiful table"""
if quiet or not axfr_results:
return
table = Table(
title="[bold cyan]Zone Transfer (AXFR) Security Test[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("Nameserver", style="cyan bold", width=30)
table.add_column("IP Addresses", style="white", width=20)
table.add_column("AXFR Status", style="white", width=20)
table.add_column("Risk", style="white", width=15)
for ns, data in sorted(axfr_results.items()):
ips = ", ".join(data.get("ips", []))
if data.get("axfr_allowed"):
status = "[red bold]✗ ALLOWED[/red bold]"
risk = "[red]CRITICAL[/red]"
else:
status = "[green]✓ Denied[/green]"
risk = "[green]Secure[/green]"
zone_count = len(data.get("zone_records", []))
if zone_count > 0:
status += f"\n[red]({zone_count} records exposed)[/red]"
table.add_row(ns, ips, status, risk)
console.print(table)
console.print()
def display_email_security(email_sec: Dict[str, Any], quiet: bool):
"""Display email security analysis in beautiful panels"""
if quiet:
return
tree = Tree("[bold cyan]📧 Email Security Analysis[/bold cyan]", guide_style="cyan")
spf_branch = tree.add("[bold]SPF (Sender Policy Framework)[/bold]")
if email_sec["spf"]["present"]:
spf_branch.add(f"[green]✓ SPF Record Found[/green]")
spf_record = email_sec['spf']['record']
if len(spf_record) > 80:
spf_record = spf_record[:80] + "..."
spf_branch.add(f"[dim]Record:[/dim] {spf_record}")
spf_branch.add(f"[yellow]DNS Lookups:[/yellow] {email_sec['spf']['total_lookups']} (limit: 10)")
if email_sec['spf']['includes']:
includes_tree = spf_branch.add(f"[cyan]Includes ({len(email_sec['spf']['includes'])}):[/cyan]")
for inc in email_sec['spf']['includes'][:5]:
includes_tree.add(f"• {inc}")
if email_sec['spf']['issues']:
issues_tree = spf_branch.add("[yellow]⚠ Issues:[/yellow]")
for issue in email_sec['spf']['issues']:
issues_tree.add(f"[yellow]• {issue}[/yellow]")
else:
spf_branch.add("[red]✗ No SPF Record Found[/red]")
dmarc_branch = tree.add("[bold]DMARC (Domain-based Message Authentication)[/bold]")
if email_sec["dmarc"]["present"]:
policy = email_sec["dmarc"]["policy"]
if policy == "reject":
policy_color = "green"
elif policy == "quarantine":
policy_color = "yellow"
else:
policy_color = "red"
dmarc_branch.add(f"[green]✓ DMARC Record Found[/green]")
dmarc_branch.add(f"[{policy_color}]Policy: {policy}[/{policy_color}]")
if email_sec['dmarc']['issues']:
issues_tree = dmarc_branch.add("[yellow]⚠ Issues:[/yellow]")
for issue in email_sec['dmarc']['issues']:
issues_tree.add(f"[yellow]• {issue}[/yellow]")
else:
dmarc_branch.add("[red]✗ No DMARC Record Found[/red]")
dkim_branch = tree.add("[bold]DKIM (DomainKeys Identified Mail)[/bold]")
if email_sec["dkim"]["selectors_found"]:
dkim_branch.add(f"[green]✓ DKIM Selectors Found: {len(email_sec['dkim']['selectors_found'])}[/green]")
for selector in email_sec['dkim']['selectors_found']:
dkim_branch.add(f"[cyan]• {selector}[/cyan]")
else:
dkim_branch.add("[dim]○ No common DKIM selectors detected[/dim]")
console.print()
console.print(Panel(tree, border_style="cyan", box=box.ROUNDED))
console.print()
def display_whois_info(whois_data: Dict[str, Any], quiet: bool):
"""Display enhanced WHOIS information in a beautiful panel"""
if quiet:
return
table = Table(
title="[bold cyan]WHOIS Registration Information[/bold cyan]",
box=box.ROUNDED,
show_header=False,
border_style="cyan"
)
table.add_column("Field", style="cyan bold", width=25)
table.add_column("Value", style="white")
table.add_row("Domain Name", whois_data.get("domain_name") or "[dim]Unknown[/dim]")
table.add_row("Registrar", whois_data.get("registrar") or "[dim]Unknown[/dim]")
if whois_data.get("registrant_org"):
org = whois_data["registrant_org"]
if isinstance(org, list):
org = org[0] if org else "Unknown"
table.add_row("Registrant Organization", str(org))
if whois_data.get("registrant_country"):
country = whois_data["registrant_country"]
if isinstance(country, list):
country = country[0] if country else "Unknown"
table.add_row("Registrant Country", str(country))
table.add_row("Created", whois_data.get("creation_date") or "[dim]Unknown[/dim]")
table.add_row("Updated", whois_data.get("updated_date") or "[dim]Unknown[/dim]")
expiry = whois_data.get("expiration_date") or "[dim]Unknown[/dim]"
days = whois_data.get("days_until_expiry")
if days is not None:
if days < 30:
expiry += f" [red]({days} days left!)[/red]"
elif days < 90:
expiry += f" [yellow]({days} days left)[/yellow]"
else:
expiry += f" [green]({days} days left)[/green]"
table.add_row("Expires", expiry)
privacy = "[yellow]Yes[/yellow]" if whois_data.get("privacy") else "[green]No[/green]"
table.add_row("Privacy Protection", privacy)
if whois_data.get("status"):
status_list = whois_data["status"][:3]
table.add_row("Status", ", ".join(status_list))
if whois_data.get("admin_email"):
table.add_row("Admin Email", whois_data["admin_email"])
if whois_data.get("tech_email"):
table.add_row("Tech Email", whois_data["tech_email"])
if whois_data.get("name_servers"):
ns_list = whois_data["name_servers"][:5]
table.add_row("Name Servers", ", ".join(ns_list))
if len(whois_data["name_servers"]) > 5:
table.add_row("", f"[dim]... and {len(whois_data['name_servers']) - 5} more[/dim]")
console.print(table)
console.print()
def display_nameserver_analysis(ns_info: Dict[str, Any], quiet: bool):
"""Display nameserver analysis in beautiful format"""
if quiet:
return
table = Table(
title="[bold cyan]Nameserver Infrastructure Analysis[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("Nameserver", style="cyan bold", width=30)
table.add_column("IP Address", style="white", width=18)
table.add_column("SOA Serial", style="yellow", width=12)
table.add_column("ASN", style="green", width=12)
table.add_column("Country", style="blue", width=8)
for ns_host, ns_data in ns_info["nameservers"].items():
ips = ns_data.get("ips", [])
ip_display = ips[0] if ips else "[dim]N/A[/dim]"
soa_serial = str(ns_data.get("soa_serial", "N/A"))
asn = f"AS{ns_data.get('asn')}" if ns_data.get('asn') else "[dim]N/A[/dim]"
country = ns_data.get("country") or "[dim]--[/dim]"
table.add_row(ns_host, ip_display, soa_serial, asn, country)
console.print(table)
info_panel = ""
dnssec = ns_info["dnssec"]
if dnssec["enabled"]:
info_panel += f"[green]✓ DNSSEC Enabled[/green]\n"
info_panel += f" • DNSKEY records: {dnssec['dnskey_count']}\n"
info_panel += f" • DS records at parent: {'Yes' if dnssec['has_ds'] else 'No (chain incomplete!)'}\n"
else:
info_panel += "[yellow]⚠ DNSSEC Not Enabled[/yellow]\n"
if ns_info["issues"]:
info_panel += "\n[yellow]⚠ Infrastructure Issues:[/yellow]\n"
for issue in ns_info["issues"]:
info_panel += f" • {issue}\n"
console.print(Panel(info_panel.strip(), border_style="yellow" if ns_info["issues"] else "green", box=box.ROUNDED))
console.print()
def display_propagation(propagation: Dict[str, Any], quiet: bool):
"""Display DNS propagation status"""
if quiet:
return
table = Table(
title="[bold cyan]DNS Propagation Check[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("Resolver", style="cyan bold", width=15)
table.add_column("Method", style="magenta", width=10)
table.add_column("A Records", style="green", width=20)
table.add_column("MX Records", style="yellow", width=12)
table.add_column("Status", style="white", width=12)
for resolver_name, data in propagation.items():
method = data.get("method", "UDP")
method_color = "cyan" if method == "UDP" else "magenta"
a_records = ", ".join(data.get("A", [])) if data.get("A") else "[dim]None[/dim]"
mx_count = len(data.get("MX", []))
mx_display = f"{mx_count} record(s)" if mx_count > 0 else "[dim]None[/dim]"
if data["status"] == "success":
status = "[green]✓ Online[/green]"
else:
status = "[red]✗ Failed[/red]"
table.add_row(resolver_name, f"[{method_color}]{method}[/{method_color}]", a_records, mx_display, status)
console.print(table)
console.print()
def display_security_audit(security: Dict[str, Any], quiet: bool):
"""Display security audit results"""
if quiet:
return
tree = Tree("[bold red]🔒 Security Audit Results[/bold red]", guide_style="red")
if security["critical"]:
critical_branch = tree.add(f"[bold red]Critical Issues ({len(security['critical'])})[/bold red]")
for issue in security["critical"]:
critical_branch.add(f"[red]✗ {issue}[/red]")
if security["warnings"]:
warning_branch = tree.add(f"[bold yellow]Warnings ({len(security['warnings'])})[/bold yellow]")
for warning in security["warnings"]:
warning_branch.add(f"[yellow]⚠ {warning}[/yellow]")
if security["info"]:
info_branch = tree.add(f"[bold blue]Informational ({len(security['info'])})[/bold blue]")
for info in security["info"][:5]:
info_branch.add(f"[blue]ℹ {info}[/blue]")
if not security["critical"] and not security["warnings"]:
tree.add("[green]✓ No security issues detected[/green]")
console.print()
console.print(Panel(tree, border_style="red" if security["critical"] else "yellow" if security["warnings"] else "green", box=box.DOUBLE))
console.print()
def display_osint_results(osint: Dict[str, Any], quiet: bool):
"""Display OSINT enrichment results"""
if quiet:
return
ct_data = osint.get("cert_transparency", {})
if not ct_data.get("checked"):
return
domains = ct_data.get("domains", [])
if domains:
table = Table(
title=f"[bold cyan]🔍 OSINT - Certificate Transparency Logs ({len(domains)} domains)[/bold cyan]",
box=box.ROUNDED,
show_header=True,
header_style="bold magenta",
border_style="cyan"
)
table.add_column("#", style="dim", width=5)
table.add_column("Related Domain", style="cyan")
table.add_column("Type", style="yellow", width=15)
for idx, domain in enumerate(domains[:15], 1):
if domain.startswith("*."):
domain_type = "[yellow]Wildcard[/yellow]"
elif domain.count('.') > 2:
domain_type = "[cyan]Subdomain[/cyan]"
else:
domain_type = "[green]Domain[/green]"
table.add_row(str(idx), domain, domain_type)
console.print(table)
if len(domains) > 15:
console.print(f"[dim]... and {len(domains) - 15} more domains (see JSON export for full list)[/dim]")
console.print()
def get_dns_records(domain: str, timeout: int, verbose: bool, dns_server: Optional[str] = None) -> Dict[str, List[Any]]:
"""Query all major DNS record types"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task("[cyan]Querying DNS records...", total=None)
resolver = create_resolver(timeout, dns_server)
records = {}
for rtype in RECORD_TYPES:
try:
answers = resolver.resolve(domain, rtype, lifetime=timeout)
record_list = []
for rdata in answers:
record_info = {
"value": rdata.to_text(),
"ttl": answers.rrset.ttl if answers.rrset else None
}
if rtype == "MX":
parts = rdata.to_text().split()
if len(parts) >= 2:
record_info["priority"] = parts[0]
record_info["value"] = parts[1]
if rtype == "SRV":
parts = rdata.to_text().split()
if len(parts) >= 4:
record_info["priority"] = parts[0]
record_info["weight"] = parts[1]
record_info["port"] = parts[2]
record_info["value"] = parts[3]
record_list.append(record_info)
records[rtype] = record_list
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.resolver.NoNameservers, dns.exception.Timeout):
records[rtype] = []
except Exception:
records[rtype] = []
return records
def reverse_ptr_lookups(records: Dict, timeout: int, verbose: bool, dns_server: Optional[str] = None) -> Dict[str, List[str]]:
"""Perform reverse PTR lookups for discovered IPs"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task("[cyan]Performing reverse PTR lookups...", total=None)
resolver = create_resolver(timeout, dns_server)
ptr_results = {}
ip_list = []
for rtype in ["A", "AAAA"]:
for record in records.get(rtype, []):
ip = record.get("value", "").split()[0]
if ip:
ip_list.append(ip)
for record in records.get("MX", []):
mx_host = record.get("value", "").rstrip('.')
if mx_host:
try:
mx_ips = socket.gethostbyname_ex(mx_host)[2]
ip_list.extend(mx_ips)
except Exception:
pass
for ip in set(ip_list):
try:
rev_name = dns.reversename.from_address(ip)
answers = resolver.resolve(rev_name, "PTR", lifetime=timeout)
ptr_results[ip] = [rdata.to_text() for rdata in answers]
except Exception:
ptr_results[ip] = []
return ptr_results
def attempt_axfr(domain: str, records: Dict, timeout: int, verbose: bool, dns_server: Optional[str] = None) -> Dict[str, Any]:
"""Attempt AXFR zone transfers on nameservers"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task("[cyan]Testing zone transfers (AXFR)...", total=None)
axfr_results = {}
ns_list = records.get("NS", [])
ns_hosts = []
for ns_record in ns_list:
ns_host = ns_record.get("value", "").rstrip('.')
if ns_host:
ns_hosts.append(ns_host)
for ns in sorted(set(ns_hosts)):
try:
ns_ips = socket.gethostbyname_ex(ns)[2]
except Exception:
ns_ips = []
axfr_results[ns] = {
"ips": ns_ips,
"axfr_allowed": False,
"zone_records": [],
"record_count": 0
}
for ip in ns_ips:
try:
z = dns.query.xfr(ip, domain, timeout=timeout)
zone = dns.zone.from_xfr(z)
if zone:
axfr_results[ns]["axfr_allowed"] = True
zone_names = [str(name) for name in zone.nodes.keys()]
axfr_results[ns]["zone_records"] = zone_names[:10]
axfr_results[ns]["record_count"] = len(zone_names)
break
except Exception:
pass
return axfr_results
def count_spf_lookups(spf_record: str, domain: str, timeout: int, depth: int = 0, max_depth: int = 5, seen: Set[str] = None) -> Tuple[int, Set[str]]:
"""Recursively count DNS lookups in SPF record"""
if seen is None:
seen = set()
if depth > max_depth:
return 0, seen
if spf_record in seen:
return 0, seen
seen.add(spf_record)
lookup_count = 0
mechanisms = re.findall(r'(?<!\S)(?:[-~+?])?(a(?!ll)\b|mx\b|ptr\b|exists\b)(?::([^\s]+))?', spf_record, re.IGNORECASE)
lookup_count += len(mechanisms)
includes = re.findall(r'include:([^\s]+)', spf_record, re.IGNORECASE)
for include_domain in includes:
lookup_count += 1
if depth < max_depth:
try:
resolver = dns.resolver.Resolver()
resolver.lifetime = timeout
answers = resolver.resolve(include_domain, "TXT", lifetime=timeout)
for rdata in answers:
txt = join_txt_chunks(rdata.to_text())
if "v=spf1" in txt.lower():
nested_count, seen = count_spf_lookups(txt, include_domain, timeout, depth + 1, max_depth, seen)
lookup_count += nested_count
break
except Exception:
pass
return lookup_count, seen
def email_security_analysis(domain: str, records: Dict, timeout: int, verbose: bool, dns_server: Optional[str] = None) -> Dict[str, Any]:
"""Analyze SPF, DMARC, and DKIM configurations"""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True
) as progress:
task = progress.add_task("[cyan]Analyzing email security (SPF/DMARC/DKIM)...", total=None)
email_sec = {
"spf": {"present": False, "record": None, "total_lookups": 0, "includes": [], "issues": []},
"dmarc": {"present": False, "record": None, "policy": None, "issues": []},
"dkim": {"selectors_found": []}
}
txt_records = records.get("TXT", [])
for record in txt_records:
value = join_txt_chunks(record.get("value", ""))
if "v=spf1" in value.lower():
email_sec["spf"]["present"] = True
email_sec["spf"]["record"] = value
includes = re.findall(r'include:([^\s]+)', value, re.IGNORECASE)
email_sec["spf"]["includes"] = includes
total_lookups, _ = count_spf_lookups(value, domain, timeout)
email_sec["spf"]["total_lookups"] = total_lookups
if total_lookups > 10:
email_sec["spf"]["issues"].append(f"Too many DNS lookups ({total_lookups}/10) - may cause SPF failures")
if "~all" in value:
pass
elif "-all" in value:
pass