-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_ip_osint.py
More file actions
1510 lines (1320 loc) · 53.4 KB
/
Copy pathc_ip_osint.py
File metadata and controls
1510 lines (1320 loc) · 53.4 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
'''
(Clear Web) IP Address OSINT Tool
For authorized research and investigative purposes only.
You can get in trouble for scanning IPs you don't own / aren't authorized to scan.
Assume the owner of any IP you scan has logging in place and will know that you scanned it.
Please don't break any laws.
'''
import sys
import json
import socket
import ipaddress
import requests
import concurrent.futures
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Any
# AbuseIPDB has a free API tier for checking IP reputation and abuse reports.
# Sign up at: https://www.abuseipdb.com/register
ABUSEIPDB_API_KEY: str = '' # Paste the key here.
# If left blank the scan will still work, but abuse report data won't be available.
# Shodan offers a paid API tier for checking open ports and service banners.
# There is a free tier but it won't allow API access to this endpoint.
# Sign up at: https://account.shodan.io/register
# Paste your key below.
SHODAN_API_KEY: str = ''
# If left blank the tool will fall back to a direct TCP port probe instead.
# It is not the end of the world to leave this blank
# ANSI styling
R = '\033[91m'
G = '\033[92m'
Y = '\033[93m'
B = '\033[94m'
M = '\033[95m'
C = '\033[96m'
W = '\033[97m'
DIM = '\033[2m'
BOLD = '\033[1m'
RESET = '\033[0m'
BANNER = f'''
{B}{BOLD}
██╗██████╗ ██████╗ ███████╗██╗███╗ ██╗████████╗
██║██╔══██╗ ██╔═══██╗██╔════╝██║████╗ ██║╚══██╔══╝
██║██████╔╝ ██║ ██║███████╗██║██╔██╗ ██║ ██║
██║██╔═══╝ ██║ ██║╚════██║██║██║╚██╗██║ ██║
██║██║ ╚██████╔╝███████║██║██║ ╚████║ ██║
╚═╝╚═╝ ╚═════╝ ╚══════╝╚═╝╚═╝ ╚═══╝ ╚═╝
{RESET}{DIM}IP Address OSINT Tool | Authorized research use only{RESET}
'''
DIVIDER = f'{DIM}{"─" * 62}{RESET}'
# Common ports to probe with their service names
COMMON_PORTS: dict[int, str] = {
21: 'FTP',
22: 'SSH',
23: 'Telnet',
25: 'SMTP',
53: 'DNS',
80: 'HTTP',
110: 'POP3',
143: 'IMAP',
443: 'HTTPS',
445: 'SMB',
465: 'SMTPS',
587: 'SMTP (Submission)',
993: 'IMAPS',
995: 'POP3S',
1433: 'MSSQL',
3306: 'MySQL',
3389: 'RDP',
5432: 'PostgreSQL',
5900: 'VNC',
6379: 'Redis',
8080: 'HTTP-Alt',
8443: 'HTTPS-Alt',
9200: 'Elasticsearch',
27017: 'MongoDB',
}
PORT_TIMEOUT = 1.5 # seconds per port probe
PORT_WORKERS = 50 # concurrent (sort of) threads for port scanning
# Known datacenter/hosting ASN name fragments
DATACENTER_ASN_KEYWORDS: set[str] = {
# Cloud providers
'amazon', 'aws', 'google', 'microsoft', 'azure', 'googlecloud',
# Hosting / VPS
'digitalocean', 'linode', 'akamai', 'vultr', 'hetzner', 'ovh',
'leaseweb', 'rackspace', 'softlayer', 'choopa', 'as-choopa',
'frantech', 'quadranet', 'psychz', 'singlehop', 'nocix',
'colocation', 'colo', 'hosting', 'datacenter', 'data center',
'server', 'cloud', 'vps', 'dedicated',
# CDN
'cloudflare', 'fastly', 'incapsula', 'cdn',
# VPN providers (ASN-registered ones)
'mullvad', 'nordvpn', 'expressvpn', 'privateinternetaccess',
'pia ', 'ipvanish', 'purevpn', 'hidemyass',
# Tor-adjacent
'torservers', 'emerald onion',
}
RESIDENTIAL_ASN_KEYWORDS: set[str] = {
'comcast', 'xfinity', 'at&t', 'verizon', 'spectrum', 'cox',
'charter', 'centurylink', 'lumen', 'frontier', 'optimum',
'cablevision', 'mediacom', 'windstream', 'consolidated',
'british telecom', 'bt ', 'sky ', 'virgin media', 'talk talk',
'deutsche telekom', 'vodafone', 'orange', 'sfr', 'bouygues',
'telecom italia', 'telefonica', 'swisscom', 'proximus',
'bell canada', 'rogers', 'telus', 'shaw',
'isp', 'broadband', 'cable', 'dsl', 'fiber', 'fibre',
'residential', 'dynamic',
}
# Display helpers
def print_section(title: str) -> None:
print(f'\n{B}{BOLD}[ {title} ]{RESET}')
print(DIVIDER)
def print_field(label: str, value: str, color: str = W) -> None:
print(f' {DIM}{label:<30}{RESET}{color}{value}{RESET}')
# Dataclasses
@dataclass
class LocalInfo:
'''Network interface data for private/loopback IPs.'''
interfaces: list[dict[str, str]] # Like [{name, ip, mac}]
hostname: str
@dataclass
class GeoInfo:
ip: str
city: str
region: str
country: str
country_code: str
latitude: str
longitude: str
timezone: str
org: str
asn: str
asn_name: str
@dataclass
class RipeStatInfo:
prefix: str
announced: bool
rir: str
allocation_status: str
asn: str
asn_name: str
asn_country: str
asn_description: str
abuse_contacts: list[str]
bgp_peers: list[str]
@dataclass
class AsnDetail:
routing_history: list[str] # prefixes seen advertised historically returns list
first_seen: str
last_seen: str
upstream_peers: list[str]
downstream_peers: list[str]
neighbour_count_left: int
neighbour_count_right: int
@dataclass
class HostingClassification:
category: str # 'Datacenter / Cloud', 'Residential ISP', 'Mobile', 'Unknown'
confidence: str # 'High', 'Medium', 'Low'
signals: list[str]
@dataclass
class PassiveDnsEntry:
rrtype: str
rrname: str
rdata: str
last_seen: str
@dataclass
class DnsChainResult:
resource: str
forward_nodes: dict[str, list[str]]
reverse_nodes: dict[str, list[str]]
authoritative_nameservers: list[str]
nameservers: list[str]
@dataclass
class DomainDiscovery:
domains: list[str]
source_map: dict[str, list[str]]
probed: list[dict[str, str]]
@dataclass
class PortResult:
port: int
service: str
open: bool
banner: str
@dataclass
class ShodanInfo:
open_ports: list[int]
port_details: list[dict[str, str]]
isp: str
org: str
hostnames: list[str]
domains: list[str]
os: str
tags: list[str]
last_update: str
@dataclass
class AbuseInfo:
is_public: bool
abuse_confidence_score: int
country_code: str
isp: str
domain: str
usage_type: str
total_reports: int
num_distinct_users: int
last_reported_at: str
is_whitelisted: bool
@dataclass
class PingResult:
packets_sent: int
packets_received: int
packet_loss_pct: float
rtt_min_ms: float
rtt_avg_ms: float
rtt_max_ms: float
rtt_mdev_ms: float # Jitter
raw_output: str
error: str
@dataclass
class IpReport:
target: str
scan_time: str
ip_version: int
is_private: bool
is_loopback: bool
rdns: str
geo: GeoInfo | None
ripe: RipeStatInfo | None
asn_detail: AsnDetail | None
passive_dns: list[PassiveDnsEntry]
dns_chain: DnsChainResult | None
domain_discovery: DomainDiscovery | None
ports: list[PortResult]
hosting_class: HostingClassification | None
is_tor: bool
shodan: ShodanInfo | None
abuse: AbuseInfo | None
ping: PingResult | None
# IP classification and input
def classify_ip(ip_str: str) -> tuple[ipaddress.IPv4Address | ipaddress.IPv6Address, bool, bool]:
'''Parse and classify an IP. Returns (addr_obj, is_private, is_loopback).'''
addr = ipaddress.ip_address(ip_str)
return addr, addr.is_private, addr.is_loopback
def get_ip_input() -> str:
'''Prompt the user for an IP address.'''
print(f'\n{Y}Enter target IP address:{RESET}')
raw = input(f'{C}> IP Address (IPv4 or IPv6): {RESET}').strip()
return raw
def reverse_dns(ip: str) -> str:
'''Attempt reverse DNS lookup. Returns hostname or "N/A".'''
try:
return socket.gethostbyaddr(ip)[0]
except Exception:
return 'N/A'
# Local interface info (for private IPs)
def get_local_info() -> LocalInfo:
'''
Collect local network interface information without external dependencies.
Uses /proc/net/if_inet6 and /proc/net/fib_trie on Linux;
fall back to socket.getaddrinfo on other platforms.
'''
hostname = socket.gethostname()
interfaces: list[dict[str, str]] = []
# Try to use the netifaces library for best coverage
try:
import netifaces # type: ignore
for iface in netifaces.interfaces():
addrs = netifaces.ifaddresses(iface)
ipv4_list = addrs.get(netifaces.AF_INET, [])
mac_list = addrs.get(netifaces.AF_LINK, [])
mac = mac_list[0].get('addr', 'N/A') if mac_list else 'N/A'
if ipv4_list:
for entry in ipv4_list:
interfaces.append({
'name': iface,
'ip': entry.get('addr', 'N/A'),
'mask': entry.get('netmask', 'N/A'),
'mac': mac,
})
else:
interfaces.append({'name': iface, 'ip': 'N/A', 'mask': 'N/A', 'mac': mac})
return LocalInfo(interfaces=interfaces, hostname=hostname)
except ImportError:
pass
# Fallback use socket to get at least the primary outbound IP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
primary_ip = s.getsockname()[0]
s.close()
except Exception:
primary_ip = '127.0.0.1'
interfaces.append({
'name': 'primary',
'ip': primary_ip,
'mask': 'N/A',
'mac': 'N/A (install netifaces for full detail)',
})
return LocalInfo(interfaces=interfaces, hostname=hostname)
# Geo (ipapi.co no key required)
def fetch_geo(ip: str) -> GeoInfo | None:
'''
Fetch geolocation and ASN data from ipapi.co.
Free tier: 1000 req/day, no key required.
Docs: https://ipapi.co/api/
'''
url = f'https://ipapi.co/{ip}/json/'
try:
response = requests.get(url, timeout=8, headers={'User-Agent': 'ip-osint-tool/1.0'})
response.raise_for_status()
d = response.json()
except Exception as e:
print(f'\n {R}ipapi.co request failed: {e}{RESET}')
return None
if d.get('error'):
print(f'\n {R}ipapi.co error: {d.get("reason", "Unknown")}{RESET}')
return None
def s(key: str) -> str:
val = d.get(key)
return str(val) if val is not None else 'N/A'
return GeoInfo(
ip=s('ip'),
city=s('city'),
region=s('region'),
country=s('country_name'),
country_code=s('country_code'),
latitude=s('latitude'),
longitude=s('longitude'),
timezone=s('timezone'),
org=s('org'),
asn=s('asn'),
asn_name=s('org'),
)
# RIPEstat no key whoop
# Docs: https://stat.ripe.net/docs/02.data-api/
def _ripe_get(endpoint: str, params: dict[str, str]) -> dict[str, Any] | None: # Any Any Any
'''Helper: GET a RIPEstat data endpoint, return parsed JSON or None.'''
url = f'https://stat.ripe.net/data/{endpoint}/data.json'
try:
r = requests.get(url, params=params, timeout=10,
headers={'User-Agent': 'ip-osint-tool/1.0'})
r.raise_for_status()
return r.json()
except Exception as e:
print(f'\n {R}RIPEstat [{endpoint}] failed: {e}{RESET}')
return None
def fetch_ripestat(ip: str) -> RipeStatInfo | None:
'''
Query RIPEstat for prefix, ASN, abuse contact, and routing data.
Combines: prefix-overview, whois, abuse-contact-finder, routing-history.
Keyless.
'''
result = RipeStatInfo(
prefix='N/A',
announced=False,
rir='N/A',
allocation_status='N/A',
asn='N/A',
asn_name='N/A',
asn_country='N/A',
asn_description='N/A',
abuse_contacts=[],
bgp_peers=[],
)
# Prefix overview — gets BGP prefix + announcement status
data = _ripe_get('prefix-overview', {'resource': ip})
if data and data.get('status') == 'ok':
d = data.get('data', {})
result.announced = d.get('announced', False)
result.prefix = d.get('resource', 'N/A')
asns = d.get('asns', []) # type ?????
if asns:
result.asn = str(asns[0].get('asn', 'N/A'))
result.asn_name = asns[0].get('holder', 'N/A')
block = d.get('block', {})
result.rir = block.get('registry', 'N/A').upper()
result.allocation_status = block.get('name', 'N/A')
# Abuse contact finder
data = _ripe_get('abuse-contact-finder', {'resource': ip})
if data and data.get('status') == 'ok':
contacts = data.get('data', {}).get('abuse_contacts', [])
result.abuse_contacts = [str(c) for c in contacts if c]
# Network-info for extra ASN / country context
data = _ripe_get('network-info', {'resource': ip})
if data and data.get('status') == 'ok':
d = data.get('data', {})
if result.prefix == 'N/A':
result.prefix = d.get('prefix', 'N/A')
asns = d.get('asns', [])
if asns and result.asn == 'N/A':
result.asn = str(asns[0])
# BGP peers (routing neighbours) via bgp-state
data = _ripe_get('bgp-state', {'resource': result.prefix if result.prefix != 'N/A' else ip})
if data and data.get('status') == 'ok':
routes = data.get('data', {}).get('bgp_state', [])
peers: list[str] = []
for route in routes[:10]: # cap at 10
path = route.get('path', []) # This could be increased
if path:
peers.append(f"AS{path[-1]} (via path: {' → '.join(str(a) for a in path[-3:])})")
result.bgp_peers = peers
return result
def fetch_asn_detail(asn: str) -> AsnDetail | None:
'''
Query RIPEstat for ASN routing history and BGP neighbours.
Requires a valid ASN string (digits only, no AS prefix).
'''
if not asn or asn == 'N/A':
return None
resource = f'AS{asn}'
routing_history: list[str] = []
first_seen = 'N/A'
last_seen = 'N/A'
data = _ripe_get('routing-history', {'resource': resource})
if data and data.get('status') == 'ok':
routes = data.get('data', {}).get('by_origin', [])
for origin in routes:
prefixes = origin.get('prefixes', [])
for p in prefixes[:20]: # cap per origin
prefix_str = p.get('prefix', '')
timelines = p.get('timelines', [])
if timelines:
t_start = timelines[0].get('starttime', '')
t_end = timelines[-1].get('endtime', '')
if t_start and first_seen == 'N/A':
first_seen = t_start
if t_end:
last_seen = t_end
routing_history.append(f'{prefix_str} (active: {t_start[:10]} → {t_end[:10]})')
else:
routing_history.append(prefix_str)
upstream_peers: list[str] = []
downstream_peers: list[str] = []
neighbour_count_left = 0
neighbour_count_right = 0
data = _ripe_get('asn-neighbours', {'resource': resource})
if data and data.get('status') == 'ok':
d = data.get('data', {})
counts = d.get('neighbour_counts', {})
neighbour_count_left = int(counts.get('left', 0))
neighbour_count_right = int(counts.get('right', 0))
neighbours = d.get('neighbours', [])
for n in neighbours[:15]:
direction = n.get('type', '')
entry = (
f"AS{n.get('asn')} "
f"(power: {n.get('power')}, "
f"v4 peers: {n.get('v4_peers')}, "
f"v6 peers: {n.get('v6_peers')})"
)
if direction == 'left':
upstream_peers.append(entry)
else:
downstream_peers.append(entry)
return AsnDetail(
routing_history=routing_history[:30],
first_seen=first_seen,
last_seen=last_seen,
upstream_peers=upstream_peers,
downstream_peers=downstream_peers,
neighbour_count_left=neighbour_count_left,
neighbour_count_right=neighbour_count_right,
)
# Passive DNS (RIPEstat)
# Returns records as a string not dict
def fetch_passive_dns(ip: str) -> list[PassiveDnsEntry]:
data = _ripe_get('reverse-dns-ip', {'resource': ip})
entries: list[PassiveDnsEntry] = []
if not data or data.get('status') != 'ok':
return entries
records: list[str] = data.get('data', {}).get('result') or [] # lies its a list of strings
for hostname in records:
entries.append(PassiveDnsEntry(
rrtype='PTR',
rrname=hostname,
rdata=ip,
last_seen='N/A',
))
return entries[:30]
# If IP recursive chain is much less wide
def fetch_dns_chain(hostname: str) -> DnsChainResult | None:
'''
Fetch recursive DNS forward/reverse chain from RIPEstat.
Input should be a hostname, not an IP.
'''
if not hostname or hostname == 'N/A':
return None
data = _ripe_get('dns-chain', {'resource': hostname})
if not data or data.get('status') != 'ok':
return None
d = data.get('data', {})
return DnsChainResult(
resource=d.get('resource', hostname),
forward_nodes=d.get('forward_nodes', {}),
reverse_nodes=d.get('reverse_nodes', {}),
authoritative_nameservers=d.get('authoritative_nameservers', []),
nameservers=d.get('nameservers', []),
)
def check_tor_exit(ip: str) -> bool:
'''Check if IP is a known Tor exit node via torproject.org bulk exit list.'''
url = 'https://check.torproject.org/torbulkexitlist'
try:
r = requests.get(url, timeout=8, headers={'User-Agent': 'ip-osint-tool/1.0'})
r.raise_for_status()
exit_nodes = {line.strip() for line in r.text.splitlines() if line.strip()}
return ip in exit_nodes
except Exception as e:
print(f'\n {R}Tor exit check failed: {e}{RESET}')
return False
def classify_hosting(asn_name: str, org: str, prefix: str) -> HostingClassification:
'''
Classify IP as datacenter/cloud/VPN vs residential based on ASN name,
org string, and prefix size. No other calls required.
'''
signals: list[str] = []
dc_score = 0
res_score = 0
combined = f'{asn_name} {org}'.lower()
for keyword in DATACENTER_ASN_KEYWORDS:
if keyword in combined:
dc_score += 1
signals.append(f'ASN/org matches datacenter keyword: "{keyword}"')
break # one match is enough to flag it
for keyword in RESIDENTIAL_ASN_KEYWORDS:
if keyword in combined:
res_score += 1
signals.append(f'ASN/org matches residential ISP keyword: "{keyword}"')
break
# Mobile detection
mobile_keywords = {'mobile', 'cellular', 'wireless', 't-mobile', 'sprint', 'ee ', 'three ', 'o2 '}
if any(k in combined for k in mobile_keywords):
signals.append('ASN/org suggests mobile carrier')
return HostingClassification(category='Mobile Carrier', confidence='Medium', signals=signals)
# Prefix size signal — /24 or smaller = likely datacenter allocation
# Residential blocks tend to be larger (/8 to /16 at ISP level)
if prefix and prefix != 'N/A':
try:
net = ipaddress.ip_network(prefix, strict=False)
prefix_len = net.prefixlen
if prefix_len >= 24:
dc_score += 1
signals.append(f'Prefix /{prefix_len} is a small block, typical of datacenter allocation')
elif prefix_len <= 16:
res_score += 1
signals.append(f'Prefix /{prefix_len} is a large block, typical of ISP allocation')
except ValueError:
pass
if dc_score > res_score:
confidence = 'High' if dc_score >= 2 else 'Medium'
return HostingClassification(category='Datacenter / Cloud / Hosting', confidence=confidence, signals=signals)
elif res_score > dc_score:
confidence = 'High' if res_score >= 2 else 'Medium'
return HostingClassification(category='Residential ISP', confidence=confidence, signals=signals)
else:
return HostingClassification(category='Unknown', confidence='Low', signals=signals or ['No matching signals found'])
# Hackertarget reverse ip
# Docs: https://hackertarget.com/reverse-ip-lookup/
def fetch_hackertarget_reverseip(ip: str) -> list[str]:
'''
Free reverse-IP lookup via HackerTarget.
No API key needed. ~100 req/day free tier.
Return a list of domain names hosted on the IP.
'''
url = f'https://api.hackertarget.com/reverseiplookup/?q={ip}'
try:
r = requests.get(url, timeout=10, headers={'User-Agent': 'ip-osint-tool/1.0'})
r.raise_for_status()
text = r.text.strip()
except Exception as e:
print(f'\n {R}HackerTarget request failed: {e}{RESET}')
return []
# API returns "No records found" or "error" on failure
if 'no records' in text.lower() or 'error' in text.lower() or not text:
return []
return [line.strip() for line in text.splitlines() if line.strip()]
# TLS certificate SAN extraction
def fetch_tls_san_domains(ip: str, port: int = 443, timeout: float = 5.0) -> list[str]:
'''
Connect to the IP on port 443, retrieve TLS certificate,
and extract all Subject Alternative Names (SANs).
Uses stdlib ssl only.
Returns a list of domain names from the cert's SAN field.
'''
import ssl
import socket as _socket
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE # Just want the cert data, not to verify it
domains: list[str] = []
try:
with _socket.create_connection((ip, port), timeout=timeout) as raw_sock:
with ctx.wrap_socket(raw_sock, server_hostname=ip) as tls_sock:
cert: dict[str, Any] | None = tls_sock.getpeercert()
if cert is None:
return []
# subjectAltName is a tuple of (type, value) pairs like ('DNS', 'example.com')
sans: list[tuple[str, str]] = list(cert.get('subjectAltName', []))
for kind, value in sans:
kind_str: str = str(kind)
value_str: str = str(value)
if kind_str == 'DNS':
# removeprefix only strips the literal '*.' prefix unlike lstrip
# which would strip any leading '*' or '.' characters individually
clean: str = value_str.removeprefix('*.').strip()
if clean:
domains.append(clean)
except Exception as e:
print(f' {DIM}TLS SAN extraction skipped: {e}{RESET}')
return list(dict.fromkeys(domains)) # Preserve order, dedupe
# HTTP/HTTPS probe per domain
def _probe_domain_http(ip: str, domain: str, timeout: float = 6.0) -> dict[str, str]:
'''
Send an HTTP/HTTPS request to the IP with the given Host header.
Extracts status code, page title, and final URL after redirects.
Returns a dict with keys: domain, url, status, title, redirect.
'''
import re as _re
result: dict[str, str] = {
'domain': domain,
'url': f'https://{domain}',
'status': 'N/A',
'title': 'N/A',
'redirect': '',
'error': '',
}
for scheme in ('https', 'http'):
target_url = f'{scheme}://{ip}'
headers = {
'Host': domain,
'User-Agent': 'Mozilla/5.0 (compatible; ip-osint-tool/1.0)', # Iffy
'Accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',
}
try:
resp = requests.get(
target_url,
headers=headers,
timeout=timeout,
allow_redirects=True,
verify=False, # Cert likely won't match IP that's okay we just want content
)
result['status'] = str(resp.status_code)
result['url'] = f'{scheme}://{domain}'
# Check if it followed a redirect to a different domain
if resp.url and domain not in resp.url:
result['redirect'] = resp.url[:120]
# Extract <title> from response body
html = resp.text[:8192] # Only need the <head>
title_match = _re.search(r'<title[^>]*>([^<]{1,200})</title>', html, _re.IGNORECASE)
if title_match:
result['title'] = title_match.group(1).strip()[:120]
return result # Got a response so don't try http fallback
except requests.exceptions.SSLError:
continue # Try http
except Exception as e:
result['error'] = str(e)[:80]
return result
return result
def probe_domains_http(ip: str, domains: list[str], max_workers: int = 10) -> list[dict[str, str]]:
'''
Concurrently probe each domain in the list via HTTP/HTTPS Host-header injection.
Returns only domains that returned a real response (status != N/A).
'''
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Expected (didn't verify)
results: list[dict[str, str]] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
futures = {ex.submit(_probe_domain_http, ip, d): d for d in domains}
for future in concurrent.futures.as_completed(futures):
res = future.result()
if res['status'] != 'N/A':
results.append(res)
return sorted(results, key=lambda r: r['domain'])
# Orchestrator discovers and probes all domains
def discover_domains(
ip: str,
rdns: str,
passive_dns: list[PassiveDnsEntry],
shodan: 'ShodanInfo | None',
) -> DomainDiscovery:
'''
Aggregate domain names from all available sources, deduplicate,
then HTTP probe each to confirm live services.
'''
source_map: dict[str, list[str]] = {
'hackertarget': [],
'tls_san': [],
'shodan': [],
'passive_dns': [],
'rdns': [],
}
print(f'{DIM} → HackerTarget reverse IP...{RESET}')
source_map['hackertarget'] = fetch_hackertarget_reverseip(ip)
print(f'{DIM} → TLS certificate SAN extraction (port 443)...{RESET}')
source_map['tls_san'] = fetch_tls_san_domains(ip)
if shodan:
source_map['shodan'] = list(shodan.hostnames) + list(shodan.domains)
source_map['passive_dns'] = [e.rrname for e in passive_dns if e.rrname]
if rdns and rdns != 'N/A':
source_map['rdns'] = [rdns]
# Union + deduplicate, preserving rough priority order
seen: set[str] = set()
all_domains: list[str] = []
for source_domains in source_map.values():
for d in source_domains:
d_clean = d.strip().rstrip('.').lower()
if d_clean and d_clean not in seen:
seen.add(d_clean)
all_domains.append(d_clean)
print(f'{DIM} → HTTP probing {len(all_domains)} unique domains...{RESET}')
probed = probe_domains_http(ip, all_domains) if all_domains else []
return DomainDiscovery(
domains=all_domains,
source_map=source_map,
probed=probed,
)
# Port probe (TCP connect, if not Shodan)
def _probe_port(ip: str, port: int, service: str) -> PortResult:
'''Attempt a TCP connect to one port. Grab a banner if possible.'''
try:
with socket.create_connection((ip, port), timeout=PORT_TIMEOUT) as s:
banner = ''
try:
s.settimeout(1)
# Only attempt banner grab on text likely ports
if port in (21, 22, 25, 110, 143, 587, 993, 995):
raw = s.recv(256)
banner = raw.decode('utf-8', errors='replace').strip()[:80]
except Exception:
pass
return PortResult(port=port, service=service, open=True, banner=banner)
except Exception:
return PortResult(port=port, service=service, open=False, banner='')
def probe_common_ports(ip: str) -> list[PortResult]:
'''Probe COMMON_PORTS concurrently. Return only open ports.'''
results: list[PortResult] = []
with concurrent.futures.ThreadPoolExecutor(max_workers=PORT_WORKERS) as ex:
futures = {
ex.submit(_probe_port, ip, port, svc): port
for port, svc in COMMON_PORTS.items()
}
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result.open:
results.append(result)
return sorted(results, key=lambda r: r.port)
# Shodan (optional with paid API key)
# Docs: https://developer.shodan.io/api
def fetch_shodan(ip: str, api_key: str) -> ShodanInfo | None:
'''
Query the Shodan host endpoint for open ports, banners, and metadata.
Requires a paid Shodan account / API key.
PAID.
'''
url = f'https://api.shodan.io/shodan/host/{ip}'
try:
r = requests.get(url, params={'key': api_key.strip()}, timeout=10)
if r.status_code == 404:
print(f'\n {DIM}Shodan: no data for this IP.{RESET}')
return None
r.raise_for_status()
d = r.json()
except Exception as e:
print(f'\n {R}Shodan request failed: {e}{RESET}')
return None
port_details: list[dict[str, str]] = []
for item in d.get('data', []):
port_details.append({
'port': str(item.get('port', 'N/A')),
'transport': item.get('transport', 'tcp'),
'product': item.get('product', ''),
'version': item.get('version', ''),
'banner': str(item.get('data', ''))[:100].strip(),
})
return ShodanInfo(
open_ports=sorted(d.get('ports', [])),
port_details=port_details,
isp=d.get('isp', 'N/A'),
org=d.get('org', 'N/A'),
hostnames=d.get('hostnames', []),
domains=d.get('domains', []),
os=str(d.get('os') or 'N/A'),
tags=d.get('tags', []),
last_update=d.get('last_update', 'N/A'),
)
# AbuseIPDB (optional with free API key)
# Docs: https://www.abuseipdb.com/api
def fetch_abuseipdb(ip: str, api_key: str) -> AbuseInfo | None:
'''
Query AbuseIPDB for abuse reports and confidence score.
Requires a free AbuseIPDB account / API key.
maxAgeInDays=90 covers the last 3 months.
'''
url = 'https://api.abuseipdb.com/api/v2/check'
headers = {
'Key': api_key.strip(),
'Accept': 'application/json',
}
params = {'ipAddress': ip, 'maxAgeInDays': '90', 'verbose': ''}
try:
r = requests.get(url, headers=headers, params=params, timeout=8)
r.raise_for_status()
d = r.json().get('data', {})
except Exception as e:
print(f'\n {R}AbuseIPDB request failed: {e}{RESET}')
return None
def s(key: str) -> str:
val = d.get(key)
return str(val) if val is not None else 'N/A'
return AbuseInfo(
is_public=bool(d.get('isPublic', True)),
abuse_confidence_score=int(d.get('abuseConfidenceScore', 0)),
country_code=s('countryCode'),
isp=s('isp'),
domain=s('domain'),
usage_type=s('usageType'),
total_reports=int(d.get('totalReports', 0)),
num_distinct_users=int(d.get('numDistinctUsers', 0)),
last_reported_at=s('lastReportedAt'),
is_whitelisted=bool(d.get('isWhitelisted', False)),
)
# Why subprocess over a Python ICMP library:
# - Raw ICMP sockets require root on most systems
# - The system ping binary has the setuid bit set and makes it easy
# - No extra dependencies!
def run_ping(ip: str, count: int = 10) -> PingResult:
'''
Send count ICMP echo requests via the system ping binary.
Parses RTT statistics from the summary line,
should work on Linux and macOS.
Falls back semi gracefully if ping is not available or the host blocks ICMP.
'''
import subprocess
import re as _re
import sys as _sys
empty = PingResult(
packets_sent=count,
packets_received=0,
packet_loss_pct=100.0,
rtt_min_ms=0.0,
rtt_avg_ms=0.0,
rtt_max_ms=0.0,
rtt_mdev_ms=0.0,
raw_output='',
error='',
)
# Build the command — macOS uses -c for count same as linux
# -W / -w: per-packet timeout. macOS uses -W (ms), Linux uses -W (s)
# There is likely a better way to handle this
if _sys.platform == 'darwin':
cmd = ['ping', '-c', str(count), '-W', '1000', ip]
else:
cmd = ['ping', '-c', str(count), '-W', '1', ip]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=count * 3, # Should be generous enough
)
output = proc.stdout + proc.stderr
empty.raw_output = output.strip()
except FileNotFoundError:
empty.error = 'ping binary not found'
return empty
except subprocess.TimeoutExpired:
empty.error = 'ping timed out'
return empty
except Exception as e:
empty.error = str(e)
return empty
# Parse packet loss
# Linux: "10 packets transmitted, 8 received, 20% packet loss"
# macOS: "10 packets transmitted, 8 packets received, 20.0% packet loss"
loss_match = _re.search(
r'(\d+) packets transmitted,\s*(\d+) (?:packets )?received,\s*([\d.]+)%',
output,
)
received = 0
loss_pct = 100.0
if loss_match:
sent_parsed = int(loss_match.group(1))
received = int(loss_match.group(2))
loss_pct = float(loss_match.group(3))
else:
sent_parsed = count
# Parse RTT statistics
# Linux: "rtt min/avg/max/mdev = 12.3/15.1/18.4/1.2 ms"
# macOS: "round-trip min/avg/max/stddev = 12.3/15.1/18.4/1.2 ms"
rtt_min = rtt_avg = rtt_max = rtt_mdev = 0.0
rtt_match = _re.search(
r'(?:rtt|round-trip)\s+min/avg/max/(?:mdev|stddev)\s*=\s*'
r'([\d.]+)/([\d.]+)/([\d.]+)/([\d.]+)',