-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshadowhunter_crawler.py
More file actions
1518 lines (1247 loc) · 51.3 KB
/
shadowhunter_crawler.py
File metadata and controls
1518 lines (1247 loc) · 51.3 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
"""
ShadowHunter - Dark Web Credential Intelligence Platform
Module: Async Web Crawler (Inspired by Photon)
Author: Fevra
Version: 0.1.0
High-performance async web crawler for:
- Deep link extraction and mapping
- JavaScript file analysis for secrets
- API endpoint discovery
- Email/credential harvesting
- Subdomain enumeration
- Metadata extraction
- Form detection and analysis
"""
import asyncio
import aiohttp
import re
import hashlib
from datetime import datetime, timezone
from typing import List, Dict, Set, Optional, Any, Tuple
from dataclasses import dataclass, field
from urllib.parse import urljoin, urlparse, parse_qs
from pathlib import Path
from collections import defaultdict
import json
from enum import Enum
# Import logger
try:
from shadowhunter_logger import get_logger, LogLevel
except ImportError:
import logging
def get_logger(name, **kwargs):
return logging.getLogger(name)
# Initialize module logger
logger = get_logger("Crawler", log_level=LogLevel.DEBUG)
# ============================================================================
# REGEX PATTERNS FOR EXTRACTION
# ============================================================================
class ExtractionPatterns:
"""Regex patterns for extracting various data types from web content."""
# URL patterns
URL = re.compile(
r'(?:href|src|action|data-url|data-src)=["\']([^"\']+)["\']',
re.IGNORECASE
)
JS_URL = re.compile(
r'(?:url\s*[:\(]|fetch\s*\(|XMLHttpRequest.*open\s*\([^,]+,)\s*["\']([^"\']+)["\']',
re.IGNORECASE
)
# Email patterns
EMAIL = re.compile(
r'[\w\.-]+@[\w\.-]+\.\w{2,}',
re.IGNORECASE
)
# Phone patterns (international formats)
PHONE = re.compile(
r'(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}|'
r'\+[0-9]{1,3}[-.\s]?[0-9]{4,14}',
re.IGNORECASE
)
# Social media handles
TWITTER = re.compile(r'(?:twitter\.com|x\.com)/([A-Za-z0-9_]{1,15})', re.IGNORECASE)
LINKEDIN = re.compile(r'linkedin\.com/(?:in|company)/([A-Za-z0-9_-]+)', re.IGNORECASE)
GITHUB = re.compile(r'github\.com/([A-Za-z0-9_-]+)', re.IGNORECASE)
# API endpoints
API_ENDPOINT = re.compile(
r'["\'](?:/api/|/v[0-9]+/|/rest/)([^"\']+)["\']',
re.IGNORECASE
)
# Secrets and keys
AWS_KEY = re.compile(r'(?:AKIA|A3T|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}')
AWS_SECRET = re.compile(r'["\'][A-Za-z0-9/+=]{40}["\']')
GOOGLE_API = re.compile(r'AIza[0-9A-Za-z_-]{35}')
GITHUB_TOKEN = re.compile(r'gh[pousr]_[A-Za-z0-9_]{36,}')
JWT_TOKEN = re.compile(r'eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*')
PRIVATE_KEY = re.compile(r'-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----')
GENERIC_SECRET = re.compile(
r'(?:password|passwd|secret|token|api_key|apikey|auth|credential)["\'\s]*[:=]\s*["\']([^"\']{8,})["\']',
re.IGNORECASE
)
# JavaScript files
JS_FILE = re.compile(r'["\']([^"\']*\.js(?:\?[^"\']*)?)["\']', re.IGNORECASE)
# Form fields
FORM = re.compile(r'<form[^>]*>(.*?)</form>', re.IGNORECASE | re.DOTALL)
INPUT = re.compile(
r'<input[^>]*(?:name|id)=["\']([^"\']+)["\'][^>]*>',
re.IGNORECASE
)
# Comments (may contain sensitive info)
HTML_COMMENT = re.compile(r'<!--(.*?)-->', re.DOTALL)
JS_COMMENT = re.compile(r'/\*[\s\S]*?\*/|//.*?(?:\n|$)')
# Subdomains from content
SUBDOMAIN = re.compile(r'[a-zA-Z0-9][-a-zA-Z0-9]*\.[a-zA-Z0-9][-a-zA-Z0-9.]+')
# ============================================================================
# DATA MODELS
# ============================================================================
class CrawlStatus(str, Enum):
"""Page crawl status."""
SUCCESS = "success"
FAILED = "failed"
TIMEOUT = "timeout"
BLOCKED = "blocked"
REDIRECT = "redirect"
@dataclass
class ExtractedData:
"""Data extracted from a single page."""
urls: List[str] = field(default_factory=list)
emails: List[str] = field(default_factory=list)
phones: List[str] = field(default_factory=list)
api_endpoints: List[str] = field(default_factory=list)
js_files: List[str] = field(default_factory=list)
forms: List[Dict[str, Any]] = field(default_factory=list)
secrets: List[Dict[str, str]] = field(default_factory=list)
social_profiles: List[Dict[str, str]] = field(default_factory=list)
comments: List[str] = field(default_factory=list)
subdomains: List[str] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
def merge(self, other: 'ExtractedData') -> 'ExtractedData':
"""Merge another ExtractedData into this one."""
self.urls.extend(other.urls)
self.emails.extend(other.emails)
self.phones.extend(other.phones)
self.api_endpoints.extend(other.api_endpoints)
self.js_files.extend(other.js_files)
self.forms.extend(other.forms)
self.secrets.extend(other.secrets)
self.social_profiles.extend(other.social_profiles)
self.comments.extend(other.comments)
self.subdomains.extend(other.subdomains)
return self
@dataclass
class CrawlResult:
"""Result from crawling a single URL."""
url: str
status: CrawlStatus
status_code: Optional[int] = None
content_type: Optional[str] = None
content_length: Optional[int] = None
response_time_ms: float = 0
extracted: ExtractedData = field(default_factory=ExtractedData)
error: Optional[str] = None
timestamp: str = ""
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now(timezone.utc).isoformat()
@dataclass
class CrawlReport:
"""Complete crawl report for a domain."""
domain: str
seed_url: str
started_at: str = ""
completed_at: str = ""
pages_crawled: int = 0
pages_failed: int = 0
# Aggregated data
all_urls: Set[str] = field(default_factory=set)
internal_urls: Set[str] = field(default_factory=set)
external_urls: Set[str] = field(default_factory=set)
emails: Set[str] = field(default_factory=set)
phones: Set[str] = field(default_factory=set)
api_endpoints: Set[str] = field(default_factory=set)
js_files: Set[str] = field(default_factory=set)
subdomains: Set[str] = field(default_factory=set)
secrets: List[Dict[str, str]] = field(default_factory=list)
social_profiles: List[Dict[str, str]] = field(default_factory=list)
forms: List[Dict[str, Any]] = field(default_factory=list)
# Page results
results: List[CrawlResult] = field(default_factory=list)
errors: List[str] = field(default_factory=list)
def __post_init__(self):
if not self.started_at:
self.started_at = datetime.now(timezone.utc).isoformat()
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"domain": self.domain,
"seed_url": self.seed_url,
"started_at": self.started_at,
"completed_at": self.completed_at,
"summary": {
"pages_crawled": self.pages_crawled,
"pages_failed": self.pages_failed,
"total_urls": len(self.all_urls),
"internal_urls": len(self.internal_urls),
"external_urls": len(self.external_urls),
"emails_found": len(self.emails),
"phones_found": len(self.phones),
"api_endpoints": len(self.api_endpoints),
"js_files": len(self.js_files),
"subdomains": len(self.subdomains),
"secrets_found": len(self.secrets),
"forms_found": len(self.forms)
},
"data": {
"emails": list(self.emails),
"phones": list(self.phones),
"api_endpoints": list(self.api_endpoints),
"js_files": list(self.js_files),
"subdomains": list(self.subdomains),
"secrets": self.secrets,
"social_profiles": self.social_profiles,
"forms": self.forms
},
"errors": self.errors
}
# ============================================================================
# DATA EXTRACTOR
# ============================================================================
class DataExtractor:
"""
Extracts various data types from HTML and JavaScript content.
Features:
- Email and phone extraction
- API endpoint discovery
- Secret detection (API keys, tokens)
- Form analysis
- Social media profile extraction
- Comment mining
"""
def __init__(self, base_url: str):
"""
Initialize extractor.
Args:
base_url: Base URL for resolving relative URLs
"""
self.base_url = base_url
self.parsed_base = urlparse(base_url)
self.domain = self.parsed_base.netloc
def extract_all(self, content: str, content_type: str = "text/html") -> ExtractedData:
"""
Extract all data from content.
Args:
content: Page content
content_type: MIME type of content
Returns:
ExtractedData with all findings
"""
data = ExtractedData()
# Extract URLs
data.urls = self._extract_urls(content)
# Extract emails
data.emails = self._extract_emails(content)
# Extract phones
data.phones = self._extract_phones(content)
# Extract API endpoints
data.api_endpoints = self._extract_api_endpoints(content)
# Extract JS files
data.js_files = self._extract_js_files(content)
# Extract forms
data.forms = self._extract_forms(content)
# Extract secrets
data.secrets = self._extract_secrets(content)
# Extract social profiles
data.social_profiles = self._extract_social_profiles(content)
# Extract comments
data.comments = self._extract_comments(content)
# Extract subdomains
data.subdomains = self._extract_subdomains(content)
return data
def _resolve_url(self, url: str) -> str:
"""Resolve relative URL to absolute."""
if url.startswith(('http://', 'https://', '//')):
if url.startswith('//'):
return f"{self.parsed_base.scheme}:{url}"
return url
return urljoin(self.base_url, url)
def _extract_urls(self, content: str) -> List[str]:
"""Extract all URLs from content."""
urls = set()
# HTML attributes
for match in ExtractionPatterns.URL.finditer(content):
url = match.group(1)
if url and not url.startswith(('#', 'javascript:', 'mailto:', 'tel:')):
urls.add(self._resolve_url(url))
# JavaScript URLs
for match in ExtractionPatterns.JS_URL.finditer(content):
url = match.group(1)
if url and url.startswith(('/', 'http')):
urls.add(self._resolve_url(url))
return list(urls)
def _extract_emails(self, content: str) -> List[str]:
"""Extract email addresses."""
emails = set()
for match in ExtractionPatterns.EMAIL.finditer(content):
email = match.group().lower()
# Filter out common false positives
if not any(fp in email for fp in ['example.com', 'test.com', '.png', '.jpg', '.gif']):
emails.add(email)
return list(emails)
def _extract_phones(self, content: str) -> List[str]:
"""Extract phone numbers."""
phones = set()
for match in ExtractionPatterns.PHONE.finditer(content):
phone = re.sub(r'[^\d+]', '', match.group())
if len(phone) >= 10:
phones.add(phone)
return list(phones)
def _extract_api_endpoints(self, content: str) -> List[str]:
"""Extract API endpoints."""
endpoints = set()
for match in ExtractionPatterns.API_ENDPOINT.finditer(content):
endpoint = match.group(1)
endpoints.add(endpoint)
return list(endpoints)
def _extract_js_files(self, content: str) -> List[str]:
"""Extract JavaScript file URLs."""
js_files = set()
for match in ExtractionPatterns.JS_FILE.finditer(content):
js_url = match.group(1)
if js_url:
js_files.add(self._resolve_url(js_url))
return list(js_files)
def _extract_forms(self, content: str) -> List[Dict[str, Any]]:
"""Extract and analyze HTML forms."""
forms = []
for form_match in ExtractionPatterns.FORM.finditer(content):
form_html = form_match.group(0)
# Extract action URL
action_match = re.search(r'action=["\']([^"\']+)["\']', form_html, re.I)
action = action_match.group(1) if action_match else ""
# Extract method
method_match = re.search(r'method=["\']([^"\']+)["\']', form_html, re.I)
method = method_match.group(1).upper() if method_match else "GET"
# Extract input fields
inputs = []
for input_match in ExtractionPatterns.INPUT.finditer(form_html):
inputs.append(input_match.group(1))
# Identify form type
form_type = "unknown"
if any(f in form_html.lower() for f in ['password', 'login', 'signin']):
form_type = "login"
elif any(f in form_html.lower() for f in ['search', 'query']):
form_type = "search"
elif any(f in form_html.lower() for f in ['email', 'subscribe', 'newsletter']):
form_type = "newsletter"
elif any(f in form_html.lower() for f in ['register', 'signup', 'create']):
form_type = "registration"
forms.append({
"action": self._resolve_url(action) if action else "",
"method": method,
"inputs": inputs,
"type": form_type
})
return forms
def _extract_secrets(self, content: str) -> List[Dict[str, str]]:
"""Extract potential secrets and API keys."""
secrets = []
# AWS keys
for match in ExtractionPatterns.AWS_KEY.finditer(content):
secrets.append({"type": "aws_access_key", "value": match.group()[:12] + "****"})
# Google API keys
for match in ExtractionPatterns.GOOGLE_API.finditer(content):
secrets.append({"type": "google_api_key", "value": match.group()[:12] + "****"})
# GitHub tokens
for match in ExtractionPatterns.GITHUB_TOKEN.finditer(content):
secrets.append({"type": "github_token", "value": match.group()[:12] + "****"})
# JWT tokens
for match in ExtractionPatterns.JWT_TOKEN.finditer(content):
secrets.append({"type": "jwt_token", "value": match.group()[:20] + "..."})
# Private keys
for match in ExtractionPatterns.PRIVATE_KEY.finditer(content):
secrets.append({"type": "private_key", "value": "PRIVATE KEY DETECTED"})
# Generic secrets
for match in ExtractionPatterns.GENERIC_SECRET.finditer(content):
value = match.group(1)
if len(value) >= 8:
secrets.append({"type": "generic_secret", "value": value[:8] + "****"})
return secrets
def _extract_social_profiles(self, content: str) -> List[Dict[str, str]]:
"""Extract social media profiles."""
profiles = []
for match in ExtractionPatterns.TWITTER.finditer(content):
profiles.append({"platform": "twitter", "handle": match.group(1)})
for match in ExtractionPatterns.LINKEDIN.finditer(content):
profiles.append({"platform": "linkedin", "handle": match.group(1)})
for match in ExtractionPatterns.GITHUB.finditer(content):
profiles.append({"platform": "github", "handle": match.group(1)})
return profiles
def _extract_comments(self, content: str) -> List[str]:
"""Extract HTML and JS comments that might contain sensitive info."""
comments = []
# HTML comments
for match in ExtractionPatterns.HTML_COMMENT.finditer(content):
comment = match.group(1).strip()
# Only keep comments with potentially interesting content
if any(kw in comment.lower() for kw in
['todo', 'fixme', 'bug', 'hack', 'password', 'secret',
'api', 'key', 'token', 'debug', 'test', 'admin']):
comments.append(comment[:200]) # Truncate long comments
return comments
def _extract_subdomains(self, content: str) -> List[str]:
"""Extract subdomains related to target domain."""
subdomains = set()
base_domain = self.domain.replace('www.', '')
for match in ExtractionPatterns.SUBDOMAIN.finditer(content):
potential = match.group().lower()
if base_domain in potential and potential != base_domain:
# Extract just the subdomain prefix
if potential.endswith(base_domain):
subdomains.add(potential)
return list(subdomains)
# ============================================================================
# ASYNC WEB CRAWLER
# ============================================================================
class ShadowCrawler:
"""
High-performance async web crawler for OSINT.
Features:
- Concurrent crawling with configurable limits
- Depth-limited exploration
- Duplicate URL detection
- Rate limiting and politeness
- JavaScript file analysis
- Comprehensive data extraction
Usage:
crawler = ShadowCrawler(max_depth=3, max_pages=100)
report = await crawler.crawl("https://example.com")
"""
# Default headers to appear as legitimate browser
DEFAULT_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
}
def __init__(
self,
max_depth: int = 3,
max_pages: int = 100,
max_concurrent: int = 10,
timeout: int = 30,
delay: float = 0.5,
headers: Optional[Dict[str, str]] = None,
exclude_patterns: Optional[List[str]] = None
):
"""
Initialize crawler.
Args:
max_depth: Maximum crawl depth from seed URL
max_pages: Maximum pages to crawl
max_concurrent: Maximum concurrent requests
timeout: Request timeout in seconds
delay: Delay between requests (politeness)
headers: Custom HTTP headers
exclude_patterns: URL patterns to exclude
"""
self.max_depth = max_depth
self.max_pages = max_pages
self.max_concurrent = max_concurrent
self.timeout = timeout
self.delay = delay
self.headers = headers or self.DEFAULT_HEADERS
self.exclude_patterns = exclude_patterns or [
r'\.(?:jpg|jpeg|png|gif|ico|css|woff|woff2|ttf|eot|svg)(?:\?|$)',
r'\?(?:utm_|ref=|share=|print=)',
r'(?:logout|signout|unsubscribe)',
]
# State
self.visited: Set[str] = set()
self.queue: asyncio.Queue = asyncio.Queue()
self.session: Optional[aiohttp.ClientSession] = None
self.semaphore: Optional[asyncio.Semaphore] = None
logger.info("ShadowCrawler initialized", {
"max_depth": max_depth,
"max_pages": max_pages,
"max_concurrent": max_concurrent
})
def _normalize_url(self, url: str) -> str:
"""Normalize URL for deduplication."""
parsed = urlparse(url)
# Remove fragments and trailing slashes
normalized = f"{parsed.scheme}://{parsed.netloc}{parsed.path.rstrip('/')}"
if parsed.query:
# Sort query parameters for consistency
params = sorted(parse_qs(parsed.query).items())
query = "&".join(f"{k}={v[0]}" for k, v in params if v)
if query:
normalized += f"?{query}"
return normalized
def _is_valid_url(self, url: str, base_domain: str) -> bool:
"""Check if URL should be crawled."""
try:
parsed = urlparse(url)
# Must be HTTP(S)
if parsed.scheme not in ('http', 'https'):
return False
# Must be same domain or subdomain
if not parsed.netloc.endswith(base_domain.replace('www.', '')):
return False
# Check exclude patterns
for pattern in self.exclude_patterns:
if re.search(pattern, url, re.I):
return False
return True
except Exception:
return False
async def _fetch_page(
self,
url: str,
depth: int
) -> CrawlResult:
"""
Fetch single page and extract data.
Args:
url: URL to fetch
depth: Current crawl depth
Returns:
CrawlResult with extracted data
"""
start_time = datetime.now()
try:
async with self.semaphore:
async with self.session.get(
url,
timeout=aiohttp.ClientTimeout(total=self.timeout),
allow_redirects=True
) as response:
# Calculate response time
response_time = (datetime.now() - start_time).total_seconds() * 1000
# Get content
content_type = response.headers.get('Content-Type', '')
# Only process HTML and JS content
if 'text/html' in content_type or 'javascript' in content_type:
content = await response.text()
content_length = len(content)
else:
content = ""
content_length = 0
# Extract data
extractor = DataExtractor(url)
extracted = extractor.extract_all(content, content_type)
logger.http(f"Crawled: {url}", {
"status": response.status,
"response_time_ms": round(response_time, 2),
"urls_found": len(extracted.urls),
"depth": depth
})
return CrawlResult(
url=url,
status=CrawlStatus.SUCCESS,
status_code=response.status,
content_type=content_type,
content_length=content_length,
response_time_ms=response_time,
extracted=extracted
)
except asyncio.TimeoutError:
logger.warn(f"Timeout: {url}")
return CrawlResult(
url=url,
status=CrawlStatus.TIMEOUT,
error="Request timeout"
)
except aiohttp.ClientError as e:
logger.warn(f"Client error: {url} - {e}")
return CrawlResult(
url=url,
status=CrawlStatus.FAILED,
error=str(e)
)
except Exception as e:
logger.error(f"Crawl error: {url} - {e}")
return CrawlResult(
url=url,
status=CrawlStatus.FAILED,
error=str(e)
)
async def _worker(
self,
report: CrawlReport,
base_domain: str
):
"""
Worker coroutine that processes URLs from queue.
Args:
report: Crawl report to populate
base_domain: Base domain for filtering
"""
while True:
try:
# Get next URL and depth from queue
url, depth = await asyncio.wait_for(
self.queue.get(),
timeout=5.0
)
# Skip if already visited or max pages reached
normalized_url = self._normalize_url(url)
if normalized_url in self.visited:
self.queue.task_done()
continue
if len(self.visited) >= self.max_pages:
self.queue.task_done()
continue
# Mark as visited
self.visited.add(normalized_url)
# Fetch and process page
result = await self._fetch_page(url, depth)
report.results.append(result)
if result.status == CrawlStatus.SUCCESS:
report.pages_crawled += 1
# Process extracted data
self._update_report(report, result, url, base_domain)
# Add discovered URLs to queue (if within depth limit)
if depth < self.max_depth:
for discovered_url in result.extracted.urls:
if self._is_valid_url(discovered_url, base_domain):
norm_discovered = self._normalize_url(discovered_url)
if norm_discovered not in self.visited:
await self.queue.put((discovered_url, depth + 1))
else:
report.pages_failed += 1
if result.error:
report.errors.append(f"{url}: {result.error}")
# Politeness delay
await asyncio.sleep(self.delay)
self.queue.task_done()
except asyncio.TimeoutError:
# Queue is empty
break
except Exception as e:
logger.error(f"Worker error: {e}")
break
def _update_report(
self,
report: CrawlReport,
result: CrawlResult,
url: str,
base_domain: str
):
"""Update report with extracted data."""
extracted = result.extracted
# Categorize URLs
for discovered_url in extracted.urls:
report.all_urls.add(discovered_url)
parsed = urlparse(discovered_url)
if base_domain in parsed.netloc:
report.internal_urls.add(discovered_url)
else:
report.external_urls.add(discovered_url)
# Aggregate other data
report.emails.update(extracted.emails)
report.phones.update(extracted.phones)
report.api_endpoints.update(extracted.api_endpoints)
report.js_files.update(extracted.js_files)
report.subdomains.update(extracted.subdomains)
report.secrets.extend(extracted.secrets)
report.social_profiles.extend(extracted.social_profiles)
report.forms.extend(extracted.forms)
async def crawl(self, seed_url: str) -> CrawlReport:
"""
Crawl website starting from seed URL.
Args:
seed_url: Starting URL to crawl
Returns:
Complete crawl report
"""
# Parse seed URL
parsed = urlparse(seed_url)
domain = parsed.netloc
base_domain = domain.replace('www.', '')
# Initialize report
report = CrawlReport(
domain=domain,
seed_url=seed_url
)
logger.scan_started("web_crawl", [seed_url])
logger.info(f"Starting crawl: {seed_url}", {
"max_depth": self.max_depth,
"max_pages": self.max_pages
})
start_time = datetime.now()
# Initialize state
self.visited = set()
self.queue = asyncio.Queue()
self.semaphore = asyncio.Semaphore(self.max_concurrent)
# Create session
connector = aiohttp.TCPConnector(limit=self.max_concurrent, ssl=False)
self.session = aiohttp.ClientSession(
headers=self.headers,
connector=connector
)
try:
# Seed the queue
await self.queue.put((seed_url, 0))
# Start workers
workers = [
asyncio.create_task(self._worker(report, base_domain))
for _ in range(self.max_concurrent)
]
# Wait for queue to empty
await self.queue.join()
# Cancel workers
for worker in workers:
worker.cancel()
finally:
await self.session.close()
# Finalize report
report.completed_at = datetime.now(timezone.utc).isoformat()
duration = (datetime.now() - start_time).total_seconds()
logger.scan_completed(
"web_crawl",
duration,
report.pages_crawled,
report.pages_failed
)
# Log findings summary
logger.info("Crawl completed", {
"pages_crawled": report.pages_crawled,
"urls_found": len(report.all_urls),
"emails_found": len(report.emails),
"secrets_found": len(report.secrets),
"duration_seconds": round(duration, 2)
})
# Alert on significant findings
if report.secrets:
logger.threat_detected(
threat_type="exposed_secrets",
severity="CRITICAL" if len(report.secrets) > 5 else "HIGH",
domain=domain,
source="Web Crawler",
details={
"secrets_count": len(report.secrets),
"secret_types": list(set(s['type'] for s in report.secrets))
}
)
return report
def export_report(
self,
report: CrawlReport,
output_path: Path,
format: str = "json"
):
"""
Export crawl report.
Args:
report: Crawl report to export
output_path: Output file path
format: Export format (json, markdown)
"""
output_path = Path(output_path)
if format == "json":
with open(output_path, 'w') as f:
json.dump(report.to_dict(), f, indent=2, default=str)
elif format == "markdown":
md = self._generate_markdown(report)
with open(output_path, 'w') as f:
f.write(md)
logger.info(f"Report exported: {output_path}", {"format": format})
def _generate_markdown(self, report: CrawlReport) -> str:
"""Generate markdown report."""
lines = [
f"# ShadowHunter Crawl Report",
f"",
f"**Target:** {report.domain}",
f"**Seed URL:** {report.seed_url}",
f"**Started:** {report.started_at}",
f"**Completed:** {report.completed_at}",
f"",
f"## Summary",
f"",
f"| Metric | Value |",
f"|--------|-------|",
f"| Pages Crawled | {report.pages_crawled} |",
f"| Pages Failed | {report.pages_failed} |",
f"| Total URLs | {len(report.all_urls)} |",
f"| Internal URLs | {len(report.internal_urls)} |",
f"| External URLs | {len(report.external_urls)} |",
f"| Emails Found | {len(report.emails)} |",
f"| API Endpoints | {len(report.api_endpoints)} |",
f"| Secrets Found | {len(report.secrets)} |",
f"",
]
# Emails
if report.emails:
lines.append("## Emails")
lines.append("")
for email in sorted(report.emails):
lines.append(f"- {email}")
lines.append("")
# Secrets
if report.secrets:
lines.append("## ⚠️ Secrets Detected")
lines.append("")
for secret in report.secrets:
lines.append(f"- **{secret['type']}**: `{secret['value']}`")
lines.append("")
# API Endpoints
if report.api_endpoints:
lines.append("## API Endpoints")
lines.append("")
for endpoint in sorted(report.api_endpoints):
lines.append(f"- `{endpoint}`")
lines.append("")
# Subdomains
if report.subdomains:
lines.append("## Subdomains")
lines.append("")
for subdomain in sorted(report.subdomains):
lines.append(f"- {subdomain}")
lines.append("")
return "\n".join(lines)
# ============================================================================
# ONION LINK MAPPER - Consolidated from Darkweb Monitor
# ============================================================================
@dataclass
class OnionLink:
"""
Represents a discovered .onion link.
Tracks where the link was found and its relationship
to other dark web sites for network mapping.
"""
url: str
domain: str
source_url: str # Where it was found
source_domain: str
anchor_text: Optional[str] = None
context: Optional[str] = None # Surrounding text
discovered_at: str = ""
verified: bool = False
def __post_init__(self):
if not self.discovered_at:
self.discovered_at = datetime.now(timezone.utc).isoformat()
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"url": self.url,
"domain": self.domain,