-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3250 lines (2753 loc) · 131 KB
/
main.py
File metadata and controls
3250 lines (2753 loc) · 131 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
"""
╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ ███████╗██╗ ██╗ █████╗ ██████╗ ██████╗ ██╗ ██╗ ║
║ ██╔════╝██║ ██║██╔══██╗██╔══██╗██╔═══██╗██║ ██║ ║
║ ███████╗███████║███████║██║ ██║██║ ██║██║ █╗ ██║ ║
║ ╚════██║██╔══██║██╔══██║██║ ██║██║ ██║██║███╗██║ ║
║ ███████║██║ ██║██║ ██║██████╔╝╚██████╔╝╚███╔███╔╝ ║
║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚══╝╚══╝ ║
║ ║
║ ██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗ ║
║ ██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗ ║
║ ███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝ ║
║ ██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗ ║
║ ██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║ ║
║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ║
║ ║
║ Dark Web Threat Intelligence Platform ║
║ Version: 0.1.0 ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝
ShadowHunter - Unified CLI Entry Point
Author: Fevra
Version: 0.1.0
Comprehensive dark web intelligence platform with:
- Credential monitoring (Telegram, Tor, Pastebin)
- Google dorking reconnaissance
- Web crawling and data extraction
- OSINT lookup (email, phone, username, domain)
- Neo4j threat intelligence graph
- Real-time alerting and reporting
"""
import asyncio
import os
import sys
import json
from pathlib import Path
from datetime import datetime
from typing import Optional, List
import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.syntax import Syntax
from rich.markdown import Markdown
# Import ShadowHunter modules
from shadowhunter_logger import get_logger, LogLevel, configure_logging
from shadowhunter_dorking import DorkingEngine, DorkCategory, SimulatedSearchProvider
from shadowhunter_crawler import ShadowCrawler, OnionLinkMapper
from shadowhunter_osint import OSINTEngine
from shadowhunter_core import ShadowHunter as CoreMonitor
from shadowhunter_tor import DarkWebIntelligencePlatform
from shadowhunter_telegram import TelegramIntelligencePlatform
# Import new consolidated modules
from shadowhunter_alerts import (
AlertManager,
AlertConfig,
Alert,
AlertPriority,
AlertChannel,
create_alert_manager,
create_credential_leak_alert,
)
from shadowhunter_scheduler import (
SchedulerEngine,
SchedulerDatabase,
SiteMonitor,
MonitoredSite,
MonitorStatus,
CheckInterval,
)
from shadowhunter_verify import (
VanguardVerify,
ContentType,
AuthenticityLevel,
ThreatIndicator,
)
# Import stealer log parser module
from shadowhunter.parsers import (
StealerParserFactory,
StealerLogPipeline,
PipelineConfig,
StealerFamily,
)
# Import IOC enrichment module
from shadowhunter.intelligence import (
EnrichmentEngine,
IOCExtractor,
IOCType,
ThreatLevel,
)
# Import session validator module
from shadowhunter.validators import (
SessionValidatorEngine,
ValidatorConfig,
Platform,
SessionStatus,
RiskLevel,
)
# Import data leak monitor module
from shadowhunter.monitors import (
DataLeakMonitor,
MonitorConfig as LeakMonitorConfig,
LeakSource,
LeakSeverity,
SecretType,
)
# Import attack surface scanner module
from shadowhunter.scanner import (
AttackSurfaceScanner,
ScanConfig,
ScanResult,
AssetType,
RiskLevel as SurfaceRiskLevel,
)
# Import blockchain forensics module
from shadowhunter.blockchain import (
BlockchainForensicsEngine,
Chain,
WalletProfile,
WalletType,
RiskLevel as BlockchainRiskLevel,
detect_chain,
)
# Import ingestion pipeline (MVP: I2P, STIX, Neo4j; analytics)
from shadowhunter.ingestion import IngestionOrchestrator
from shadowhunter.database import GraphStore
from config import get_config
# Phase 3: Multi-Agent Hunter System
try:
from shadowhunter.hunters import (
PasteHunter,
CryptoHunter,
AttributionHunter,
AgenticProfiler,
DACOAnalyst,
IdentityHunter,
EntropyMonitor,
PipelineDefender,
SupplyChainHunter,
AIThreatHunter,
InsiderThreatHunter,
SyntheticIDHunter,
PhysicalSecHunter,
ExploitMarketHunter,
SocialMediaHunter,
GitHubHunter,
APTHunter,
ThreatScoringEngine,
)
from shadowhunter.orchestration import (
Orchestrator,
EscapeHatchRegistry,
EnhancedOrchestrator,
EnhancedEscapeHatchRegistry,
)
from shadowhunter.nl_to_cypher.schema_context import load_schema
from shadowhunter.nl_to_cypher.translator import LLMNLToCypherTranslator
PHASE3_AVAILABLE = True
except ImportError as e:
PHASE3_AVAILABLE = False
PasteHunter = CryptoHunter = AttributionHunter = AgenticProfiler = None
DACOAnalyst = IdentityHunter = EntropyMonitor = PipelineDefender = None
SupplyChainHunter = AIThreatHunter = InsiderThreatHunter = None
SyntheticIDHunter = PhysicalSecHunter = ExploitMarketHunter = None
SocialMediaHunter = GitHubHunter = APTHunter = ThreatScoringEngine = None
Orchestrator = EscapeHatchRegistry = None
load_schema = LLMNLToCypherTranslator = None
# Initialize console and logger
console = Console()
logger = get_logger("CLI", log_level=LogLevel.INFO)
# Version from single source (shadowhunter._version)
try:
from shadowhunter._version import __version__ as VERSION
except ImportError:
VERSION = "0.1.0"
AUTHOR = "Fevra"
# ============================================================================
# BANNER & UTILITIES
# ============================================================================
def print_banner():
"""Print the ShadowHunter banner."""
banner = """
[bold blue]███████╗██╗ ██╗ █████╗ ██████╗ ██████╗ ██╗ ██╗[/bold blue]
[bold blue]██╔════╝██║ ██║██╔══██╗██╔══██╗██╔═══██╗██║ ██║[/bold blue]
[bold cyan]███████╗███████║███████║██║ ██║██║ ██║██║ █╗ ██║[/bold cyan]
[bold cyan]╚════██║██╔══██║██╔══██║██║ ██║██║ ██║██║███╗██║[/bold cyan]
[bold magenta]███████║██║ ██║██║ ██║██████╔╝╚██████╔╝╚███╔███╔╝[/bold magenta]
[bold magenta]╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚══╝╚══╝ [/bold magenta]
[bold yellow]██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗ [/bold yellow]
[bold yellow]██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗[/bold yellow]
[bold green]███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝[/bold green]
[bold green]██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗[/bold green]
[bold red]██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║[/bold red]
[bold red]╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝[/bold red]
"""
console.print(banner)
console.print(
Panel.fit(
"[bold white]Dark Web Threat Intelligence Platform[/bold white]\n"
f"[dim]Version {VERSION} | By {AUTHOR}[/dim]",
border_style="blue"
)
)
console.print()
def print_status(message: str, status: str = "info"):
"""Print status message with icon."""
icons = {
"info": "[blue]ℹ[/blue]",
"success": "[green]✓[/green]",
"warning": "[yellow]⚠[/yellow]",
"error": "[red]✗[/red]",
"running": "[cyan]⟳[/cyan]"
}
icon = icons.get(status, icons["info"])
console.print(f" {icon} {message}")
# ============================================================================
# CLI GROUP
# ============================================================================
@click.group()
@click.version_option(VERSION, prog_name="ShadowHunter")
@click.option('--debug', is_flag=True, help='Enable debug logging')
@click.pass_context
def cli(ctx, debug):
"""
ShadowHunter - Dark Web Threat Intelligence Platform
A comprehensive toolkit for cybersecurity professionals to monitor
dark web threats, analyze credentials, and gather OSINT intelligence.
\b
Modules:
• scan - Credential and threat monitoring
• parse - Parse stealer logs (RedLine, Vidar, Lumma)
• enrich - IOC extraction and threat intel enrichment
• validate - Session cookie validation (Google, Microsoft)
• leaks - Data leak detection (GitHub, paste sites)
• surface - Attack surface scanning and discovery
• blockchain - Cryptocurrency forensics and tracing
• dork - Google dorking reconnaissance
• crawl - Web crawling and data extraction
• osint - Email, phone, username, domain lookup
• verify - AI content integrity verification
• schedule - Dark web site monitoring scheduler
• alerts - Multi-channel alerting (Telegram, Discord, Slack)
• monitor - Continuous threat monitoring
• ingest - Ingestion pipeline (I2P/Telegram -> STIX -> Neo4j)
• hunters - Multi-agent hunter system (synthesis report, Neo4j)
• search - Dark web search (LLM refine → Tor → scrape → summary; multi-model)
• api - Start the REST API server
\b
Examples:
shadowhunter scan --domain example.com
shadowhunter parse ./stealer_logs/ -c 20
shadowhunter validate parsed.json --allowed yourcompany.com
shadowhunter leaks -k "mycompany" -d mycompany.com
shadowhunter enrich 1.2.3.4 --virustotal YOUR_KEY
shadowhunter dork target.com --category credentials
shadowhunter osint email test@example.com
"""
ctx.ensure_object(dict)
# Configure logging
log_level = LogLevel.DEBUG if debug else LogLevel.INFO
configure_logging(log_level=log_level)
ctx.obj['debug'] = debug
# ============================================================================
# SCAN COMMAND
# ============================================================================
@cli.command()
@click.option('--domain', '-d', multiple=True, help='Domain(s) to monitor')
@click.option('--email', '-e', multiple=True, help='Email(s) to check')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.option('--format', '-f', type=click.Choice(['json', 'table']), default='table')
@click.pass_context
def scan(ctx, domain, email, output, format):
"""
Scan for credential leaks and threats.
\b
Examples:
shadowhunter scan --domain acmecorp.com
shadowhunter scan --email admin@example.com
shadowhunter scan -d example.com -d company.com -o results.json
"""
print_banner()
if not domain and not email:
console.print("[yellow]Please provide at least one domain or email to scan.[/yellow]")
console.print("\nExample: [cyan]shadowhunter scan --domain example.com[/cyan]")
return
console.print(Panel.fit(
f"[bold]Credential Scan[/bold]\n"
f"Domains: {', '.join(domain) if domain else 'None'}\n"
f"Emails: {', '.join(email) if email else 'None'}",
title="🔍 Scan Configuration",
border_style="blue"
))
# Run scan
async def run_scan():
monitor = CoreMonitor()
# Add domains to watchlist
for d in domain:
monitor.domain_monitor.add_domain(d)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[cyan]Running credential scan...", total=None)
results = await monitor.run_scan()
progress.update(task, completed=True)
return results
results = asyncio.run(run_scan())
# Display results
console.print()
print_status(f"Scan completed", "success")
# Create results table
table = Table(title="Scan Results", show_header=True, header_style="bold cyan")
table.add_column("Source", style="dim")
table.add_column("Type", style="dim")
table.add_column("Count")
table.add_column("Status")
for source, data in results.items():
count = len(data) if isinstance(data, list) else 1
status = "[green]✓[/green]" if count > 0 else "[dim]-[/dim]"
table.add_row(source, "credentials", str(count), status)
console.print(table)
# Export if requested
if output:
with open(output, 'w') as f:
json.dump(results, f, indent=2, default=str)
print_status(f"Results exported to {output}", "success")
# ============================================================================
# DORK COMMAND
# ============================================================================
@cli.command()
@click.argument('domain')
@click.option('--category', '-c',
type=click.Choice([c.value for c in DorkCategory]),
help='Specific category to scan')
@click.option('--severity', '-s',
type=click.Choice(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']),
multiple=True,
help='Filter by severity')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.option('--format', '-f',
type=click.Choice(['json', 'markdown', 'csv']),
default='json')
@click.pass_context
def dork(ctx, domain, category, severity, output, format):
"""
Google dorking reconnaissance.
Discover exposed files, credentials, and sensitive data using
advanced search queries.
\b
Categories:
credentials, sensitive_files, database, subdomain,
api_keys, documents, admin_panels, paste_sites,
cloud_storage, source_code
\b
Examples:
shadowhunter dork example.com
shadowhunter dork target.com -c credentials -c database
shadowhunter dork company.com -s CRITICAL -s HIGH -o report.json
"""
print_banner()
console.print(Panel.fit(
f"[bold]Google Dorking Scan[/bold]\n"
f"Target: {domain}\n"
f"Category: {category or 'All'}\n"
f"Severity Filter: {', '.join(severity) if severity else 'All'}",
title="🔍 Dork Configuration",
border_style="yellow"
))
async def run_dork():
engine = DorkingEngine(
search_provider=SimulatedSearchProvider(),
rate_limit_delay=0.2
)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[yellow]Running Google dorks...", total=None)
categories = [DorkCategory(category)] if category else None
severity_filter = list(severity) if severity else None
report = await engine.scan_domain(
domain,
categories=categories,
severity_filter=severity_filter
)
progress.update(task, completed=True)
return report, engine
report, engine = asyncio.run(run_dork())
# Display results
console.print()
# Summary table
table = Table(title="Dorking Results", show_header=True, header_style="bold yellow")
table.add_column("Metric", style="dim")
table.add_column("Value")
table.add_row("Total Findings", str(report.total_results))
table.add_row("[red]Critical[/red]", str(report.critical_count))
table.add_row("[orange1]High[/orange1]", str(report.high_count))
table.add_row("Categories Scanned", str(len(report.categories_scanned)))
console.print(table)
# Show findings
if report.results:
console.print("\n[bold]Top Findings:[/bold]")
for result in report.results[:5]:
severity_color = {
"CRITICAL": "red",
"HIGH": "orange1",
"MEDIUM": "yellow",
"LOW": "blue"
}.get(result.dork.severity, "white")
console.print(
f" [{severity_color}]●[/{severity_color}] "
f"[{severity_color}]{result.dork.severity}[/{severity_color}] | "
f"{result.dork.description}"
)
console.print(f" [dim]{result.url}[/dim]")
# Export
if output:
engine.export_report(report, Path(output), format)
print_status(f"Report exported to {output}", "success")
# ============================================================================
# CRAWL COMMAND
# ============================================================================
@cli.command()
@click.argument('url')
@click.option('--depth', '-d', default=2, help='Maximum crawl depth')
@click.option('--max-pages', '-p', default=50, help='Maximum pages to crawl')
@click.option('--concurrent', '-c', default=5, help='Concurrent requests')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.option('--format', '-f',
type=click.Choice(['json', 'markdown']),
default='json')
@click.pass_context
def crawl(ctx, url, depth, max_pages, concurrent, output, format):
"""
Web crawling and data extraction.
Crawl websites to discover emails, API endpoints, secrets,
and other sensitive information.
\b
Examples:
shadowhunter crawl https://example.com
shadowhunter crawl https://target.com -d 3 -p 100
shadowhunter crawl https://company.com -o report.json
"""
print_banner()
console.print(Panel.fit(
f"[bold]Web Crawler[/bold]\n"
f"Target: {url}\n"
f"Depth: {depth}\n"
f"Max Pages: {max_pages}\n"
f"Concurrent: {concurrent}",
title="🕷️ Crawl Configuration",
border_style="cyan"
))
async def run_crawl():
crawler = ShadowCrawler(
max_depth=depth,
max_pages=max_pages,
max_concurrent=concurrent,
delay=0.3
)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[cyan]Crawling website...", total=None)
report = await crawler.crawl(url)
progress.update(task, completed=True)
return report, crawler
report, crawler = asyncio.run(run_crawl())
# Display results
console.print()
# Summary table
table = Table(title="Crawl Results", show_header=True, header_style="bold cyan")
table.add_column("Metric", style="dim")
table.add_column("Value")
table.add_row("Pages Crawled", str(report.pages_crawled))
table.add_row("Pages Failed", str(report.pages_failed))
table.add_row("Total URLs", str(len(report.all_urls)))
table.add_row("Emails Found", str(len(report.emails)))
table.add_row("API Endpoints", str(len(report.api_endpoints)))
table.add_row("Secrets Found", str(len(report.secrets)))
table.add_row("Subdomains", str(len(report.subdomains)))
console.print(table)
# Show findings
if report.emails:
console.print("\n[bold]Emails Found:[/bold]")
for email in list(report.emails)[:5]:
console.print(f" [green]●[/green] {email}")
if report.secrets:
console.print("\n[bold red]⚠ Secrets Detected:[/bold red]")
for secret in report.secrets[:5]:
console.print(f" [red]●[/red] {secret['type']}: {secret['value']}")
# Export
if output:
crawler.export_report(report, Path(output), format)
print_status(f"Report exported to {output}", "success")
# ============================================================================
# OSINT COMMAND GROUP
# ============================================================================
@cli.group()
@click.pass_context
def osint(ctx):
"""
OSINT lookup capabilities.
Investigate emails, phone numbers, usernames, and domains.
\b
Commands:
email - Email address investigation
phone - Phone number lookup
username - Username enumeration
domain - Domain reconnaissance
"""
pass
@osint.command()
@click.argument('email')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.pass_context
def email(ctx, email, output):
"""
Investigate email address.
Check for breaches, validate domain, detect disposable emails.
Example: shadowhunter osint email test@example.com
"""
print_banner()
console.print(Panel.fit(
f"[bold]Email Investigation[/bold]\n"
f"Target: {email}",
title="📧 OSINT",
border_style="green"
))
async def run():
engine = OSINTEngine()
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console
) as progress:
task = progress.add_task("[green]Investigating email...", total=None)
result = await engine.investigate_email(email)
progress.update(task, completed=True)
return result
result = asyncio.run(run())
# Display results
console.print()
table = Table(title="Email Intelligence", show_header=True, header_style="bold green")
table.add_column("Property", style="dim")
table.add_column("Value")
table.add_row("Email", result.email)
table.add_row("Valid Format", "✓" if result.valid_format else "✗")
table.add_row("Disposable", "[red]Yes[/red]" if result.disposable else "[green]No[/green]")
table.add_row("Domain Exists", "✓" if result.domain_exists else "✗")
table.add_row("MX Records", str(len(result.mx_records)))
table.add_row("Breaches Found", str(len(result.breaches)))
table.add_row("Risk Level", f"[{'red' if result.risk_level.value in ['CRITICAL', 'HIGH'] else 'yellow'}]{result.risk_level.value}[/]")
console.print(table)
if result.risk_factors:
console.print("\n[bold]Risk Factors:[/bold]")
for factor in result.risk_factors:
console.print(f" [yellow]⚠[/yellow] {factor}")
if output:
with open(output, 'w') as f:
json.dump(result.to_dict(), f, indent=2)
print_status(f"Report exported to {output}", "success")
@osint.command()
@click.argument('number')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.pass_context
def phone(ctx, number, output):
"""
Investigate phone number.
Identify carrier, location, and line type.
Example: shadowhunter osint phone +1-555-123-4567
"""
print_banner()
async def run():
engine = OSINTEngine()
return await engine.investigate_phone(number)
result = asyncio.run(run())
table = Table(title="Phone Intelligence", show_header=True, header_style="bold green")
table.add_column("Property", style="dim")
table.add_column("Value")
table.add_row("Number", result.number)
table.add_row("Valid", "✓" if result.valid else "✗")
table.add_row("Country", result.country_name or "Unknown")
table.add_row("Carrier", result.carrier or "Unknown")
table.add_row("Line Type", result.line_type or "Unknown")
console.print(table)
@osint.command()
@click.argument('username')
@click.option('--platform', '-p', multiple=True, help='Specific platforms to check')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.pass_context
def username(ctx, username, platform, output):
"""
Enumerate username across platforms.
Search for username on social media and other platforms.
Example: shadowhunter osint username johndoe
"""
print_banner()
async def run():
engine = OSINTEngine()
platforms = list(platform) if platform else None
return await engine.investigate_username(username, platforms)
result = asyncio.run(run())
console.print(f"\n[bold]Username Enumeration: {username}[/bold]\n")
if result.found_platforms:
table = Table(title="Profiles Found", show_header=True, header_style="bold green")
table.add_column("Platform")
table.add_column("URL")
for profile in result.found_platforms:
table.add_row(profile['platform'], profile['url'])
console.print(table)
else:
console.print("[yellow]No profiles found on checked platforms.[/yellow]")
@osint.command()
@click.argument('domain')
@click.option('--output', '-o', type=click.Path(), help='Output file path')
@click.pass_context
def domain(ctx, domain, output):
"""
Domain reconnaissance.
WHOIS lookup, DNS enumeration, subdomain discovery.
Example: shadowhunter osint domain example.com
"""
print_banner()
async def run():
engine = OSINTEngine()
return await engine.investigate_domain(domain)
result = asyncio.run(run())
table = Table(title="Domain Intelligence", show_header=True, header_style="bold green")
table.add_column("Property", style="dim")
table.add_column("Value")
table.add_row("Domain", result.domain)
table.add_row("Registered", "✓" if result.registered else "✗")
table.add_row("Registrar", result.registrar or "Unknown")
table.add_row("Created", result.creation_date or "Unknown")
table.add_row("Expires", result.expiration_date or "Unknown")
table.add_row("A Records", str(len(result.a_records)))
table.add_row("MX Records", str(len(result.mx_records)))
table.add_row("Subdomains", str(len(result.subdomains)))
console.print(table)
if result.subdomains:
console.print("\n[bold]Subdomains Found:[/bold]")
for sub in result.subdomains[:10]:
console.print(f" [cyan]●[/cyan] {sub}")
# ============================================================================
# MONITOR COMMAND
# ============================================================================
@cli.command()
@click.option('--domain', '-d', multiple=True, required=True, help='Domain(s) to monitor')
@click.option('--interval', '-i', default=300, help='Scan interval in seconds')
@click.option('--telegram', is_flag=True, help='Enable Telegram monitoring')
@click.option('--tor', is_flag=True, help='Enable Tor/dark web monitoring')
@click.pass_context
def monitor(ctx, domain, interval, telegram, tor):
"""
Continuous threat monitoring.
Run continuous monitoring for specified domains across
multiple intelligence sources.
\b
Examples:
shadowhunter monitor -d example.com -d company.com
shadowhunter monitor -d target.com --telegram --tor
shadowhunter monitor -d corp.com -i 600
"""
print_banner()
console.print(Panel.fit(
f"[bold]Continuous Monitoring[/bold]\n"
f"Domains: {', '.join(domain)}\n"
f"Interval: {interval} seconds\n"
f"Telegram: {'Enabled' if telegram else 'Disabled'}\n"
f"Tor/Dark Web: {'Enabled' if tor else 'Disabled'}",
title="🔄 Monitor Configuration",
border_style="magenta"
))
console.print("\n[yellow]Press Ctrl+C to stop monitoring[/yellow]\n")
async def run_monitor():
monitor_instance = CoreMonitor()
# Add domains
for d in domain:
monitor_instance.domain_monitor.add_domain(d)
scan_count = 0
try:
while True:
scan_count += 1
console.print(f"[cyan]Scan #{scan_count}[/cyan] - {datetime.now().strftime('%H:%M:%S')}")
results = await monitor_instance.run_scan()
# Check for alerts
total_findings = sum(
len(v) if isinstance(v, list) else 0
for v in results.values()
)
if total_findings > 0:
console.print(f" [red]⚠ {total_findings} findings detected![/red]")
else:
console.print(f" [green]✓ No new threats[/green]")
await asyncio.sleep(interval)
except KeyboardInterrupt:
console.print("\n[yellow]Monitoring stopped.[/yellow]")
try:
asyncio.run(run_monitor())
except KeyboardInterrupt:
pass
# ============================================================================
# API COMMAND
# ============================================================================
# ============================================================================
# INGEST COMMAND (MVP Ingestion Pipeline: I2P/Telegram -> STIX -> Neo4j)
# ============================================================================
@cli.command()
@click.option('--destinations', '-d', multiple=True, help='I2P/Telegram destinations to fetch (e.g. host.i2p)')
@click.option('--source-type', '-s', default='i2p', type=click.Choice(['i2p', 'telegram']), help='Source type')
@click.option('--neo4j-uri', default=None, help='Neo4j bolt URI (default from config)')
@click.option('--neo4j-user', default=None, help='Neo4j user (default from config)')
@click.option('--neo4j-password', default=None, help='Neo4j password (default from config)')
@click.pass_context
def ingest(ctx, destinations, source_type, neo4j_uri, neo4j_user, neo4j_password):
"""
Run the ingestion pipeline: fetch from I2P/Telegram -> FaP filter -> STIX -> Neo4j.
Fetches raw content from decentralized sources, filters adversarial FaP,
transforms to STIX 2.1 (ObservedData, Indicator), and persists to Neo4j.
\b
Examples:
shadowhunter ingest -d market.i2p -d news.eepsite.i2p
shadowhunter ingest -d market.i2p --source-type i2p --neo4j-uri bolt://localhost:7687
"""
print_banner()
if not destinations:
console.print("[yellow]No destinations given. Use -d/--destinations (e.g. -d market.i2p)[/yellow]")
return
config = get_config()
uri = neo4j_uri or config.database.neo4j_uri
user = neo4j_user or config.database.neo4j_user
password = neo4j_password or config.database.neo4j_password
graph_store = GraphStore(uri=uri, user=user, password=password)
orchestrator = IngestionOrchestrator(graph_store=graph_store)
with console.status("[bold blue]Running ingestion pipeline...[/bold blue]", spinner="dots"):
result = orchestrator.run_sync(list(destinations), source_type=source_type)
table = Table(title="Ingestion Result")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Destinations fetched", str(result.destinations_fetched))
table.add_row("Passed FaP filter", str(result.contents_passed_fap))
table.add_row("Rejected (FaP)", str(result.contents_rejected_fap))
table.add_row("ObservedData written", str(result.observed_data_written))
table.add_row("Indicators written", str(result.indicators_written))
table.add_row("Errors", str(len(result.errors)))
console.print(table)
if result.errors:
for err in result.errors[:5]:
console.print(f" [red]✗[/red] {err}")
if len(result.errors) > 5:
console.print(f" [dim]... and {len(result.errors) - 5} more[/dim]")
else:
print_status("Ingestion completed.", "success")
# ============================================================================
# PHASE 3: MULTI-AGENT HUNTER SYSTEM
# ============================================================================
@cli.command()
@click.option('--neo4j-uri', default=None, help='Neo4j bolt URI (default from config)')
@click.option('--neo4j-user', default=None, help='Neo4j user (default from config)')
@click.option('--neo4j-password', default=None, help='Neo4j password (default from config)')
@click.option('--events-file', type=click.Path(exists=True), default=None, help='JSON file with event_stream (list of {source, raw_content, stix_objects, timestamp, metadata})')
@click.option('--enhanced', is_flag=True, help='Use enhanced orchestrator (IntelligentEventRouter, ResourcePool, CircuitBreaker, EnhancedEscapeHatchRegistry)')
@click.option('--output', '-o', type=click.Path(), default=None, help='Write synthesis report to file (.md or .json); default filename if dir given')
@click.option('--model', '-m', default=None, help='LLM model for synthesis/NL (e.g. gpt-4, claude-3-sonnet); optional, uses config if not set')
@click.option('--hunters', '-H', default=None, help='Comma-separated subset of hunters to run (e.g. PasteHunter,CryptoHunter,ThreatScoringEngine); default: all')
@click.pass_context
def hunters(ctx, neo4j_uri, neo4j_user, neo4j_password, events_file, enhanced, output, model, hunters):
"""
Run Multi-Agent Hunter System: fan out events to all registered hunters,
process escape hatches, de-duplicate, write high-confidence to Neo4j, synthesize report.
Use --enhanced for priority routing, resource pools, circuit breakers, and condition-based escape hatches.
Use --hunters to run only a subset of hunters (e.g. PasteHunter,CryptoHunter).
"""
if not PHASE3_AVAILABLE:
console.print("[red]Hunters not available (missing dependencies).[/red]")
return
print_banner()
config = get_config()
uri = neo4j_uri or getattr(config.database, 'neo4j_uri', 'bolt://localhost:7687')
user = neo4j_user or getattr(config.database, 'neo4j_user', 'neo4j')
password = neo4j_password or getattr(config.database, 'neo4j_password', 'password')
try:
from neo4j import GraphDatabase
db_driver = GraphDatabase.driver(uri, auth=(user, password))
db_driver.verify_connectivity()
except Exception as e:
console.print(f"[red]Neo4j connection failed: {e}[/red]")
return
hunter_config = getattr(config, 'hunters', None) or {}
config_by_hunter = {
'paste_hunter': hunter_config.get('paste_hunter', {}),
'crypto_hunter': hunter_config.get('crypto_hunter', {}),
'attribution_hunter': hunter_config.get('attribution_hunter', {}),
'agentic_profiler': hunter_config.get('agentic_profiler', {}),
'daco_analyst': hunter_config.get('daco_analyst', {}),
'identity_hunter': hunter_config.get('identity_hunter', {}),
'entropy_monitor': hunter_config.get('entropy_monitor', {}),
'pipeline_defender': hunter_config.get('pipeline_defender', {}),
'supply_chain_hunter': hunter_config.get('supply_chain_hunter', {}),
'ai_threat_hunter': hunter_config.get('ai_threat_hunter', {}),
'insider_threat_hunter': hunter_config.get('insider_threat_hunter', {}),
'synthetic_id_hunter': hunter_config.get('synthetic_id_hunter', {}),
'physical_sec_hunter': hunter_config.get('physical_sec_hunter', {}),
'exploit_market_hunter': hunter_config.get('exploit_market_hunter', {}),
'social_media_hunter': hunter_config.get('social_media_hunter', {}),
'github_hunter': hunter_config.get('github_hunter', {}),
'apt_hunter': hunter_config.get('apt_hunter', {}),
'threat_scoring_engine': hunter_config.get('threat_scoring', hunter_config.get('threat_scoring_engine', {})),
}
session = db_driver.session()
all_hunters_list = [
PasteHunter(session, config_by_hunter['paste_hunter']),
CryptoHunter(session, config_by_hunter['crypto_hunter']),
AttributionHunter(session, config_by_hunter['attribution_hunter']),
AgenticProfiler(session, config_by_hunter['agentic_profiler']),
DACOAnalyst(session, config_by_hunter['daco_analyst']),
IdentityHunter(session, config_by_hunter['identity_hunter']),
EntropyMonitor(session, config_by_hunter['entropy_monitor']),
PipelineDefender(session, config_by_hunter['pipeline_defender']),
SupplyChainHunter(session, config_by_hunter['supply_chain_hunter']),
AIThreatHunter(session, config_by_hunter['ai_threat_hunter']),
InsiderThreatHunter(session, config_by_hunter['insider_threat_hunter']),
SyntheticIDHunter(session, config_by_hunter['synthetic_id_hunter']),
PhysicalSecHunter(session, config_by_hunter['physical_sec_hunter']),
ExploitMarketHunter(session, config_by_hunter['exploit_market_hunter']),
SocialMediaHunter(session, config_by_hunter['social_media_hunter']),
GitHubHunter(session, config_by_hunter['github_hunter']),
APTHunter(session, config_by_hunter['apt_hunter']),
ThreatScoringEngine(session, config_by_hunter['threat_scoring_engine']),
]
if hunters:
allowed = {n.strip() for n in hunters.split(',') if n.strip()}