-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootIP-Finder.py
More file actions
1418 lines (1181 loc) · 52.6 KB
/
RootIP-Finder.py
File metadata and controls
1418 lines (1181 loc) · 52.6 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
"""
IP Discovery - Advanced IP Discovery Tool for Security Research
LEGAL & ETHICAL NOTICE:
This tool is designed for authorized security testing, defensive security research,
vulnerability assessment, and network reconnaissance ONLY. Users MUST have explicit
permission to scan and enumerate infrastructure for any target domain or organization.
Unauthorized scanning may violate computer fraud laws, terms of service, and regulations
such as the CFAA (USA), Computer Misuse Act (UK), and similar laws worldwide.
By using this tool, you agree that you have proper authorization and will comply with
all applicable laws and regulations. The authors assume no liability for misuse.
Copyright (c) 2025 - For defensive security research only.
"""
import asyncio
import json
import csv
import os
import sys
import logging
import argparse
import hashlib
import time
from pathlib import Path
from typing import List, Dict, Set, Optional, Any, Tuple
from datetime import datetime, timedelta
from ipaddress import ip_address, ip_network, IPv4Address, IPv6Address
from urllib.parse import quote, urlencode
import re
import aiohttp
import dns.resolver
import dns.reversename
from dotenv import load_dotenv
import yaml
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from tqdm.asyncio import tqdm_asyncio
# ============================================================================
# Configuration & Constants
# ============================================================================
VERSION = "1.0.0"
TOOL_NAME = "IP Finder"
def print_banner():
"""Print the tool banner with ASCII art."""
# ANSI color codes
RED = '\033[91m'
GREEN = '\033[92m'
RESET = '\033[0m'
banner = f"""{RED}
██████╗ ██████╗ ██████╗ ██╗ ██╗
██╔════╝ ██╔══██╗██╔═══██╗██║ ██║
███████╗ ██████╔╝██║ ██║██║ █╗ ██║
╚════██║ ██╔══██╗██║ ██║██║███╗██║
███████║ ██████╔╝╚██████╔╝╚███╔███╔╝
╚══════╝ ╚═════╝ ╚═════╝ ╚══╝╚══╝{RESET}
"""
print(banner)
print(f"\t\t\t{GREEN}R00tIP v{VERSION}{RESET}")
print(f"\t\t\t{GREEN}Developed by Sidharth Bahuguna{RESET}")
print()
USER_AGENT = f"IPFinder/{VERSION} (Defensive Security Research Tool)"
CACHE_DIR = Path(".cache")
LOG_FILE = "ip_finder.log"
DEFAULT_CONCURRENCY = 10
HTTP_TIMEOUT = 30
DNS_TIMEOUT = 5
CACHE_TTL_HOURS = 24
# API endpoints and configurations
API_CONFIGS = {
"crt_sh": "https://crt.sh/?q={query}&output=json",
"censys_search": "https://search.censys.io/api/v2/hosts/search",
"shodan_host": "https://api.shodan.io/shodan/host/{ip}",
"shodan_search": "https://api.shodan.io/shodan/host/search",
"zoomeye_search": "https://api.zoomeye.org/v2/search",
"virustotal_domain": "https://www.virustotal.com/api/v3/domains/{domain}",
"virustotal_resolutions": "https://www.virustotal.com/api/v3/domains/{domain}/resolutions",
"fofa_search": "https://fofa.info/api/v1/search/all",
"binaryedge_domain": "https://api.binaryedge.io/v2/query/domains/subdomain/{domain}",
"securitytrails_domain": "https://api.securitytrails.com/v1/domain/{domain}",
"bgp_he_net": "https://bgp.he.net/net/{prefix}",
"cymru_whois": "whois.cymru.com",
}
# ============================================================================
# Setup & Utilities
# ============================================================================
def setup_logging(verbose: bool = False, quiet: bool = False) -> logging.Logger:
"""Configure logging with file and console handlers."""
log_level = logging.DEBUG if verbose else (logging.WARNING if quiet else logging.INFO)
# Create logger
logger = logging.getLogger("ip_finder")
logger.setLevel(logging.DEBUG if verbose else logging.INFO)
logger.handlers.clear()
# File handler - only in verbose/debug mode
if verbose:
fh = logging.FileHandler(LOG_FILE, mode='a', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))
logger.addHandler(fh)
# Console handler - respects verbosity
if not quiet:
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(log_level)
ch.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(ch)
return logger
def load_config(config_path: Optional[str] = None) -> Dict[str, str]:
"""Load API keys from environment variables or config file."""
# Load .env file if present
load_dotenv()
config = {}
# Load from environment variables (preferred)
env_keys = [
"SHODAN_API_KEY",
"CENSYS_API_TOKEN",
"VT_API_KEY",
"ZOOMEYE_API_KEY",
"FOFA_EMAIL",
"FOFA_KEY",
"BINARYEDGE_API_KEY",
"SECURITYTRAILS_API_KEY",
"MAXMIND_LICENSE_KEY",
]
for key in env_keys:
value = os.environ.get(key)
if value:
config[key] = value
# Load from YAML config if provided
if config_path and Path(config_path).exists():
with open(config_path, 'r') as f:
yaml_config = yaml.safe_load(f) or {}
config.update(yaml_config)
return config
def get_cache_path(cache_key: str) -> Path:
"""Generate cache file path from key."""
CACHE_DIR.mkdir(exist_ok=True)
hash_key = hashlib.sha256(cache_key.encode()).hexdigest()
return CACHE_DIR / f"{hash_key}.json"
def get_cached(cache_key: str, ttl_hours: int = CACHE_TTL_HOURS) -> Optional[Any]:
"""Retrieve cached data if not expired."""
cache_path = get_cache_path(cache_key)
if not cache_path.exists():
return None
try:
with open(cache_path, 'r') as f:
cached = json.load(f)
cached_time = datetime.fromisoformat(cached['timestamp'])
if datetime.now() - cached_time < timedelta(hours=ttl_hours):
return cached['data']
except (json.JSONDecodeError, KeyError, ValueError):
pass
return None
def set_cache(cache_key: str, data: Any) -> None:
"""Store data in cache with timestamp."""
cache_path = get_cache_path(cache_key)
try:
with open(cache_path, 'w') as f:
json.dump({
'timestamp': datetime.now().isoformat(),
'data': data
}, f)
except Exception as e:
logging.getLogger("ip_finder").debug(f"Cache write failed: {e}")
def is_valid_ip(ip_str: str) -> bool:
"""Check if string is a valid IPv4 or IPv6 address."""
try:
ip_address(ip_str)
return True
except ValueError:
return False
def is_private_ip(ip_str: str) -> bool:
"""Check if IP is in private/reserved ranges."""
try:
ip = ip_address(ip_str)
return ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
except ValueError:
return True
def is_cdn_ip(ip_str: str) -> Tuple[bool, Optional[str]]:
"""
Check if IP belongs to known CDN networks.
Returns (is_cdn, cdn_name) tuple.
"""
try:
ip = ip_address(ip_str)
# Cloudflare IP ranges (IPv4 and IPv6)
cloudflare_ranges = [
# IPv4
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22",
"103.31.4.0/22", "141.101.64.0/18", "108.162.192.0/18",
"190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22",
"198.41.128.0/17", "162.158.0.0/15", "104.16.0.0/13",
"104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
# IPv6
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32",
"2405:b500::/32", "2405:8100::/32", "2a06:98c0::/29", "2c0f:f248::/32"
]
# Cloudflare check
for range_str in cloudflare_ranges:
if ip in ip_network(range_str):
return True, "Cloudflare"
# Akamai IP ranges (common ones)
akamai_ranges = [
"23.0.0.0/12", "23.32.0.0/11", "23.64.0.0/14", "23.72.0.0/13",
"104.64.0.0/10", "184.24.0.0/13", "184.50.0.0/15", "2.16.0.0/13"
]
for range_str in akamai_ranges:
if ip in ip_network(range_str):
return True, "Akamai"
# Fastly IP ranges
fastly_ranges = [
"23.235.32.0/20", "43.249.72.0/22", "103.244.50.0/24",
"103.245.222.0/23", "103.245.224.0/24", "104.156.80.0/20",
"151.101.0.0/16", "157.52.64.0/18", "167.82.0.0/17",
"172.111.64.0/18", "185.31.16.0/22", "199.27.72.0/21",
"199.232.0.0/16"
]
for range_str in fastly_ranges:
if ip in ip_network(range_str):
return True, "Fastly"
# Amazon CloudFront (sample ranges)
cloudfront_ranges = [
"13.32.0.0/15", "13.35.0.0/16", "13.224.0.0/14",
"13.249.0.0/16", "18.64.0.0/14", "52.46.0.0/18",
"52.84.0.0/15", "52.222.128.0/17", "54.182.0.0/16",
"54.192.0.0/16", "54.230.0.0/16", "54.239.128.0/18",
"99.84.0.0/16", "130.176.0.0/16", "204.246.164.0/22",
"204.246.168.0/22", "205.251.192.0/19", "143.204.0.0/16"
]
for range_str in cloudfront_ranges:
if ip in ip_network(range_str):
return True, "CloudFront"
# Google Cloud CDN (sample ranges)
google_cdn_ranges = [
"34.64.0.0/10", "34.128.0.0/10", "35.190.0.0/16",
"35.191.0.0/16", "35.201.0.0/16", "35.220.0.0/16",
"130.211.0.0/22"
]
for range_str in google_cdn_ranges:
if ip in ip_network(range_str):
return True, "Google Cloud CDN"
# Microsoft Azure CDN (sample ranges)
azure_cdn_ranges = [
"13.64.0.0/11", "13.104.0.0/14", "20.33.0.0/16",
"20.34.0.0/15", "20.36.0.0/14", "20.40.0.0/13",
"20.48.0.0/12", "20.135.0.0/16", "20.150.0.0/15"
]
for range_str in azure_cdn_ranges:
if ip in ip_network(range_str):
return True, "Azure CDN"
return False, None
except ValueError:
return False, None
# ============================================================================
# HTTP Client with Rate Limiting & Retries
# ============================================================================
class RateLimitedClient:
"""Async HTTP client with rate limiting, caching, and retry logic."""
def __init__(self, max_concurrency: int = DEFAULT_CONCURRENCY, logger: Optional[logging.Logger] = None):
self.semaphore = asyncio.Semaphore(max_concurrency)
self.session: Optional[aiohttp.ClientSession] = None
self.logger = logger or logging.getLogger("ip_finder")
async def __aenter__(self):
timeout = aiohttp.ClientTimeout(total=HTTP_TIMEOUT)
self.session = aiohttp.ClientSession(
timeout=timeout,
headers={"User-Agent": USER_AGENT}
)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self.session:
await self.session.close()
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((aiohttp.ClientError, asyncio.TimeoutError))
)
async def get(self, url: str, headers: Optional[Dict] = None,
cache_key: Optional[str] = None, params: Optional[Dict] = None) -> Optional[Dict]:
"""Perform GET request with caching and retry."""
# Check cache first
if cache_key:
cached_data = get_cached(cache_key)
if cached_data is not None:
self.logger.debug(f"Cache hit: {cache_key}")
return cached_data
async with self.semaphore:
try:
self.logger.debug(f"GET {url}")
async with self.session.get(url, headers=headers, params=params, ssl=False) as response:
if response.status == 200:
data = await response.json()
if cache_key:
set_cache(cache_key, data)
return data
elif response.status == 429:
self.logger.warning(f"Rate limited on {url}, waiting...")
await asyncio.sleep(5)
raise aiohttp.ClientError("Rate limited")
elif response.status in [401, 403]:
self.logger.warning(f"Auth failed for {url}: {response.status}")
return None
else:
self.logger.debug(f"HTTP {response.status} for {url}")
return None
except asyncio.TimeoutError:
self.logger.debug(f"Timeout for {url}")
raise
except aiohttp.ClientError as e:
self.logger.debug(f"HTTP error for {url}: {e}")
raise
except Exception as e:
self.logger.debug(f"Unexpected error for {url}: {e}")
return None
async def post(self, url: str, headers: Optional[Dict] = None,
json_data: Optional[Dict] = None, data: Optional[Dict] = None) -> Optional[Dict]:
"""Perform POST request with retry."""
async with self.semaphore:
try:
self.logger.debug(f"POST {url}")
async with self.session.post(url, headers=headers, json=json_data, data=data, ssl=False) as response:
if response.status == 200:
return await response.json()
elif response.status == 429:
self.logger.warning(f"Rate limited on {url}, waiting...")
await asyncio.sleep(5)
return None
elif response.status in [401, 403]:
self.logger.warning(f"Auth failed for {url}: {response.status}")
return None
else:
self.logger.debug(f"HTTP {response.status} for {url}")
return None
except Exception as e:
self.logger.debug(f"POST error for {url}: {e}")
return None
# ============================================================================
# IP Result Data Structure
# ============================================================================
class IPResult:
"""Container for discovered IP address with metadata."""
def __init__(self, ip: str, source: str):
self.ip = ip
self.sources: Set[str] = {source}
self.first_seen = datetime.now().isoformat()
self.asn: Optional[str] = None
self.netblock: Optional[str] = None
self.country: Optional[str] = None
self.ptr: Optional[str] = None
self.ports: List[int] = []
self.notes: str = ""
self.is_cdn: bool = False
self.cdn_name: Optional[str] = None
def merge(self, other: 'IPResult') -> None:
"""Merge another IPResult into this one."""
self.sources.update(other.sources)
if other.asn and not self.asn:
self.asn = other.asn
if other.netblock and not self.netblock:
self.netblock = other.netblock
if other.country and not self.country:
self.country = other.country
if other.ptr and not self.ptr:
self.ptr = other.ptr
if other.ports:
self.ports.extend(other.ports)
if other.notes:
self.notes = self.notes + "; " + other.notes if self.notes else other.notes
if other.is_cdn:
self.is_cdn = True
self.cdn_name = other.cdn_name
def to_dict(self) -> Dict:
"""Convert to dictionary for JSON serialization."""
return {
"ip": self.ip,
"sources": sorted(list(self.sources)),
"first_seen": self.first_seen,
"asn": self.asn,
"netblock": self.netblock,
"country": self.country,
"ptr": self.ptr,
"ports": sorted(list(set(self.ports))) if self.ports else [],
"notes": self.notes,
"is_cdn": self.is_cdn,
"cdn_name": self.cdn_name
}
# ============================================================================
# Data Source Collectors
# ============================================================================
class IPCollector:
"""Base class for IP address collectors."""
def __init__(self, client: RateLimitedClient, config: Dict[str, str], logger: logging.Logger):
self.client = client
self.config = config
self.logger = logger
self.name = self.__class__.__name__.replace("Collector", "")
def is_configured(self) -> bool:
"""Check if this collector has required API keys."""
return True
async def collect(self, target: str) -> List[IPResult]:
"""Collect IPs for target. Override in subclasses."""
raise NotImplementedError
class CrtShCollector(IPCollector):
"""Certificate Transparency log collector via crt.sh."""
async def collect(self, target: str) -> List[IPResult]:
results = []
try:
url = API_CONFIGS["crt_sh"].format(query=quote(f"%.{target}"))
cache_key = f"crt_sh:{target}"
data = await self.client.get(url, cache_key=cache_key)
if not data:
return results
# Extract unique domain names from certificates
domains = set()
for cert in data:
name_value = cert.get("name_value", "")
for domain in name_value.split("\n"):
domain = domain.strip().lower()
if domain and not domain.startswith("*"):
domains.add(domain)
# Resolve each domain to IPs
self.logger.info(f"crt.sh found {len(domains)} unique domains, resolving...")
for domain in list(domains)[:100]: # Limit to avoid overload
ips = await self._resolve_domain(domain)
for ip in ips:
results.append(IPResult(ip, "crt.sh"))
except Exception as e:
self.logger.debug(f"crt.sh error: {e}")
return results
async def _resolve_domain(self, domain: str) -> List[str]:
"""Resolve domain to IP addresses."""
ips = []
try:
resolver = dns.resolver.Resolver()
resolver.timeout = DNS_TIMEOUT
resolver.lifetime = DNS_TIMEOUT
for qtype in ['A', 'AAAA']:
try:
answers = await asyncio.to_thread(resolver.resolve, domain, qtype)
for rdata in answers:
ips.append(str(rdata))
except Exception:
pass
except Exception:
pass
return ips
class CensysCollector(IPCollector):
"""Censys search API collector."""
def is_configured(self) -> bool:
return "CENSYS_API_TOKEN" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
api_token = self.config["CENSYS_API_TOKEN"]
query = f"services.tls.certificates.leaf_data.subject.common_name: {target}"
url = API_CONFIGS["censys_search"]
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {api_token}"
}
params = {"q": query, "per_page": 100}
# Note: Censys uses Bearer token authentication
cache_key = f"censys:{target}"
async with self.client.semaphore:
try:
async with self.client.session.get(
url,
headers=headers,
params=params,
ssl=False
) as response:
if response.status == 200:
data = await response.json()
hits = data.get("result", {}).get("hits", [])
for hit in hits:
ip = hit.get("ip")
if ip and is_valid_ip(ip):
result = IPResult(ip, "censys")
result.asn = hit.get("autonomous_system", {}).get("asn")
result.country = hit.get("location", {}).get("country")
services = hit.get("services", [])
result.ports = [s.get("port") for s in services if s.get("port")]
results.append(result)
elif response.status in [401, 403]:
self.logger.warning(f"Censys auth failed - check your Personal Access Token")
else:
self.logger.debug(f"Censys returned status {response.status}")
except Exception as e:
self.logger.debug(f"Censys request error: {e}")
except Exception as e:
self.logger.debug(f"Censys error: {e}")
return results
class ShodanCollector(IPCollector):
"""Shodan search API collector."""
def is_configured(self) -> bool:
return "SHODAN_API_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
api_key = self.config["SHODAN_API_KEY"]
url = API_CONFIGS["shodan_search"]
params = {"key": api_key, "query": f"hostname:{target}"}
cache_key = f"shodan:{target}"
data = await self.client.get(url, params=params, cache_key=cache_key)
if not data:
return results
matches = data.get("matches", [])
for match in matches:
ip = match.get("ip_str")
if ip and is_valid_ip(ip):
result = IPResult(ip, "shodan")
result.asn = match.get("asn")
result.country = match.get("location", {}).get("country_code")
result.ports = [match.get("port")] if match.get("port") else []
hostnames = match.get("hostnames", [])
if hostnames:
result.ptr = hostnames[0]
results.append(result)
except Exception as e:
self.logger.debug(f"Shodan error: {e}")
return results
class ZoomEyeCollector(IPCollector):
"""ZoomEye search API collector."""
def is_configured(self) -> bool:
return "ZOOMEYE_API_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
import base64
api_key = self.config["ZOOMEYE_API_KEY"]
url = API_CONFIGS["zoomeye_search"]
headers = {
"API-KEY": api_key,
"Content-Type": "application/json"
}
# ZoomEye API v2 requires base64-encoded query in qbase64 parameter
query = f"hostname:{target}"
qbase64 = base64.b64encode(query.encode('utf-8')).decode('utf-8')
json_data = {
"qbase64": qbase64,
"page": 1,
"pagesize": 20
}
cache_key = f"zoomeye:{target}"
# Check cache first
cached_data = get_cached(cache_key)
if cached_data is not None:
data = cached_data
else:
data = await self.client.post(url, headers=headers, json_data=json_data)
if data:
set_cache(cache_key, data)
if not data:
return results
# Parse response - ZoomEye v2 returns data in 'data' field
matches = data.get("data", [])
for match in matches:
ip = match.get("ip")
if ip and is_valid_ip(ip):
result = IPResult(ip, "zoomeye")
# Parse port information
portinfo = match.get("portinfo", {})
if portinfo and portinfo.get("port"):
result.ports = [portinfo.get("port")]
results.append(result)
except Exception as e:
self.logger.debug(f"ZoomEye error: {e}")
return results
class VirusTotalCollector(IPCollector):
"""VirusTotal domain and passive DNS collector."""
def is_configured(self) -> bool:
return "VT_API_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
api_key = self.config["VT_API_KEY"]
headers = {"x-apikey": api_key}
# Get domain resolutions (passive DNS)
url = API_CONFIGS["virustotal_resolutions"].format(domain=target)
cache_key = f"vt_resolutions:{target}"
data = await self.client.get(url, headers=headers, cache_key=cache_key)
if data and "data" in data:
for resolution in data["data"]:
ip = resolution.get("attributes", {}).get("ip_address")
if ip and is_valid_ip(ip):
result = IPResult(ip, "virustotal")
result.notes = "Passive DNS resolution"
results.append(result)
except Exception as e:
self.logger.debug(f"VirusTotal error: {e}")
return results
class FOFACollector(IPCollector):
"""FOFA search API collector."""
def is_configured(self) -> bool:
return "FOFA_EMAIL" in self.config and "FOFA_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
import base64
email = self.config["FOFA_EMAIL"]
key = self.config["FOFA_KEY"]
query = f'domain="{target}"'
encoded_query = base64.b64encode(query.encode()).decode()
url = API_CONFIGS["fofa_search"]
params = {
"email": email,
"key": key,
"qbase64": encoded_query,
"size": 100,
"fields": "ip,port,country"
}
cache_key = f"fofa:{target}"
data = await self.client.get(url, params=params, cache_key=cache_key)
if not data or "results" not in data:
return results
for result_row in data["results"]:
if result_row and len(result_row) >= 1:
ip = result_row[0]
if ip and is_valid_ip(ip):
result = IPResult(ip, "fofa")
if len(result_row) >= 2:
result.ports = [int(result_row[1])] if result_row[1] else []
if len(result_row) >= 3:
result.country = result_row[2]
results.append(result)
except Exception as e:
self.logger.debug(f"FOFA error: {e}")
return results
class BinaryEdgeCollector(IPCollector):
"""BinaryEdge subdomain and host discovery collector."""
def is_configured(self) -> bool:
return "BINARYEDGE_API_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
api_key = self.config["BINARYEDGE_API_KEY"]
headers = {"X-Key": api_key}
url = API_CONFIGS["binaryedge_domain"].format(domain=target)
cache_key = f"binaryedge:{target}"
data = await self.client.get(url, headers=headers, cache_key=cache_key)
if not data:
return results
# BinaryEdge returns subdomains; we need to resolve them
subdomains = data.get("events", [])
for subdomain in subdomains[:50]: # Limit
ips = await self._resolve_domain(subdomain)
for ip in ips:
results.append(IPResult(ip, "binaryedge"))
except Exception as e:
self.logger.debug(f"BinaryEdge error: {e}")
return results
async def _resolve_domain(self, domain: str) -> List[str]:
"""Resolve domain to IPs."""
ips = []
try:
resolver = dns.resolver.Resolver()
resolver.timeout = DNS_TIMEOUT
resolver.lifetime = DNS_TIMEOUT
for qtype in ['A', 'AAAA']:
try:
answers = await asyncio.to_thread(resolver.resolve, domain, qtype)
for rdata in answers:
ips.append(str(rdata))
except Exception:
pass
except Exception:
pass
return ips
class SecurityTrailsCollector(IPCollector):
"""SecurityTrails passive DNS and domain collector."""
def is_configured(self) -> bool:
return "SECURITYTRAILS_API_KEY" in self.config
async def collect(self, target: str) -> List[IPResult]:
results = []
if not self.is_configured():
return results
try:
api_key = self.config["SECURITYTRAILS_API_KEY"]
headers = {"APIKEY": api_key}
url = API_CONFIGS["securitytrails_domain"].format(domain=target)
cache_key = f"securitytrails:{target}"
data = await self.client.get(url, headers=headers, cache_key=cache_key)
if not data:
return results
# Get current IPs
current_dns = data.get("current_dns", {})
a_records = current_dns.get("a", {}).get("values", [])
aaaa_records = current_dns.get("aaaa", {}).get("values", [])
for record in a_records + aaaa_records:
ip = record.get("ip")
if ip and is_valid_ip(ip):
results.append(IPResult(ip, "securitytrails"))
except Exception as e:
self.logger.debug(f"SecurityTrails error: {e}")
return results
class DNSCollector(IPCollector):
"""Local DNS resolution collector (A, AAAA, MX, NS, CNAME)."""
def is_configured(self) -> bool:
return True # Always available
async def collect(self, target: str) -> List[IPResult]:
results = []
try:
resolver = dns.resolver.Resolver()
resolver.timeout = DNS_TIMEOUT
resolver.lifetime = DNS_TIMEOUT
# Direct A/AAAA records
for qtype in ['A', 'AAAA']:
try:
answers = await asyncio.to_thread(resolver.resolve, target, qtype)
for rdata in answers:
ip = str(rdata)
result = IPResult(ip, "dns")
result.notes = f"{qtype} record"
results.append(result)
except Exception:
pass
# MX records
try:
mx_answers = await asyncio.to_thread(resolver.resolve, target, 'MX')
for rdata in mx_answers:
mx_host = str(rdata.exchange).rstrip('.')
for qtype in ['A', 'AAAA']:
try:
answers = await asyncio.to_thread(resolver.resolve, mx_host, qtype)
for ip_rdata in answers:
ip = str(ip_rdata)
result = IPResult(ip, "dns")
result.notes = f"MX record for {mx_host}"
results.append(result)
except Exception:
pass
except Exception:
pass
# NS records
try:
ns_answers = await asyncio.to_thread(resolver.resolve, target, 'NS')
for rdata in ns_answers:
ns_host = str(rdata).rstrip('.')
for qtype in ['A', 'AAAA']:
try:
answers = await asyncio.to_thread(resolver.resolve, ns_host, qtype)
for ip_rdata in answers:
ip = str(ip_rdata)
result = IPResult(ip, "dns")
result.notes = f"NS record for {ns_host}"
results.append(result)
except Exception:
pass
except Exception:
pass
except Exception as e:
self.logger.debug(f"DNS error: {e}")
return results
class PTRCollector(IPCollector):
"""Reverse DNS (PTR) lookup collector."""
def is_configured(self) -> bool:
return True # Always available
async def collect_for_ip(self, ip: str) -> Optional[str]:
"""Perform reverse DNS lookup for single IP."""
try:
resolver = dns.resolver.Resolver()
resolver.timeout = DNS_TIMEOUT
resolver.lifetime = DNS_TIMEOUT
rev_name = dns.reversename.from_address(ip)
answers = await asyncio.to_thread(resolver.resolve, rev_name, 'PTR')
if answers:
return str(answers[0]).rstrip('.')
except Exception:
pass
return None
async def collect(self, target: str) -> List[IPResult]:
"""Not used directly - used to enrich existing IPs."""
return []
class ASNCollector(IPCollector):
"""Team Cymru IP to ASN collector."""
def is_configured(self) -> bool:
return True # Public service
async def collect_for_ip(self, ip: str) -> Tuple[Optional[str], Optional[str]]:
"""Query Team Cymru for ASN and netblock."""
try:
resolver = dns.resolver.Resolver()
resolver.timeout = DNS_TIMEOUT
resolver.lifetime = DNS_TIMEOUT
# Construct origin query for Team Cymru
ip_obj = ip_address(ip)
if isinstance(ip_obj, IPv4Address):
parts = ip.split('.')
origin_query = f"{parts[3]}.{parts[2]}.{parts[1]}.{parts[0]}.origin.asn.cymru.com"
else:
# IPv6 support
rev = dns.reversename.from_address(ip)
origin_query = str(rev).replace('.ip6.arpa.', '.origin6.asn.cymru.com.')
answers = await asyncio.to_thread(resolver.resolve, origin_query, 'TXT')
if answers:
# Parse response: "ASN | IP Prefix | CC | Registry | Allocated"
txt = str(answers[0]).strip('"')
parts = [p.strip() for p in txt.split('|')]
if len(parts) >= 2:
asn = f"AS{parts[0]}"
netblock = parts[1]
return asn, netblock
except Exception:
pass
return None, None
async def collect(self, target: str) -> List[IPResult]:
"""Not used directly - used to enrich existing IPs."""
return []
class BGPHECollector(IPCollector):
"""BGP.he.net scraper (optional, behind flag)."""
def is_configured(self) -> bool:
return True # Public service, but scraping
async def collect(self, target: str) -> List[IPResult]:
"""
TODO: Implement BGP.he.net scraping for netblock enumeration.
This should be behind --enable-scrape flag.
Implementation notes:
1. Query bgp.he.net for ASN associated with target
2. Scrape netblocks announced by that ASN
3. Optionally enumerate IPs in small netblocks
4. Respect robots.txt and add delays between requests
"""
results = []
# Placeholder - user should enable with --enable-scrape
return results
# ============================================================================
# Main IP Finder Engine