-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathspoof_finder.py
267 lines (211 loc) · 10 KB
/
spoof_finder.py
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
from asyncio import new_event_loop, gather
from datetime import datetime
from re import compile
from typing import Optional, List, Dict, Union, Tuple
from aioconsole import ainput
from httpx import AsyncClient
from netaddr import IPNetwork, AddrFormatError
from rich.console import Console
from search_engines import *
# Constants
USER_AGENT = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 '
'Safari/537.36')
REX_PHONE = compile(r"[+]\d+(?:[-\s]|)[\d\-\s]+")
REX_MAIL = compile(r"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.']\w+)*")
class SpoofFinder:
def __init__(self, target: str = None, loop=None):
self.logger = Console(force_terminal=True, markup=True, emoji=True, log_path=False)
self.loop = loop or new_event_loop()
self.target = target
self.client = AsyncClient(timeout=10, headers={"User-Agent": USER_AGENT})
self.search_engines = (
Google, Yahoo, Aol, Duckduckgo, Startpage, Dogpile, Ask, Mojeek, Qwant
)
async def fetch(self, url: str, as_json: bool = True) -> Union[Optional[Dict], Optional[str]]:
"""
Fetches the given URL using httpx and handles exceptions.
Args:
url (str): The URL to fetch.
as_json (bool, optional): Whether to parse the response as JSON. Defaults to True.
Returns:
Union[Optional[Dict], Optional[str]]: The parsed JSON response or the raw text if `as_json` is False.
"""
try:
response = await self.client.get(url)
return response.json() if as_json else response.text
except Exception as e:
self.logger.log(f"[red]Error fetching {url}: {str(e)}")
return None
@staticmethod
def parse_asn(target: str) -> str:
"""
Parses an ASN from the given target string.
If the target string starts with "AS", it removes the "AS" prefix and returns the remaining string.
If the target string is a digit-only string, it returns the string as it is.
Otherwise, it returns the target string as it is.
Args:
target (str): The target string to parse.
Returns:
str: The parsed ASN string.
"""
if target.lower().startswith("as"):
return target[2:]
return target if target.isdigit() else target
async def find_links(self, query: str) -> Optional[List[str]]:
"""
Searches the given query using multiple search engines and returns a list of links.
Args:
query (str): The query to search.
Returns:
Optional[List[str]]: A list of links found by the search engines, or None if no links are found.
"""
for engine in self.search_engines:
async with engine(print_func=lambda *args, **kwargs: None) as e:
e.set_headers({'User-Agent': USER_AGENT})
data = await e.search(query, pages=2)
links = data.links()
if links:
return links
return None
async def get_asn_info(self, target: str) -> Optional[Dict]:
"""
Fetches the ASN information for the given target string.
Args:
target (str): The target string to fetch ASN information for.
Returns:
Optional[Dict]: The ASN information as a dictionary, or None if no ASN information is found.
"""
return await self.fetch(f"https://ipapi.co/{target}/json/") or None
async def find_contact(self, asn: str) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""
Fetches the contact information for the given ASN.
Args:
asn (str): The ASN to fetch contact information for.
Returns: Tuple[Optional[str], Optional[str], Optional[str]]: A tuple containing the contact site, email,
and phone number, or None if no contact information is found.
"""
response = await self.fetch(f"https://rdap.arin.net/registry/autnum/{asn}", as_json=False)
if not response:
return None, None, None
mail_match = REX_MAIL.search(response)
phone_match = REX_PHONE.search(response)
site = mail_match.group(0).split('@')[1] if mail_match else None
return site, mail_match.group(0) if mail_match else None, phone_match.group(0) if phone_match else None
async def fetch_spoof_data(self, asn: str) -> Tuple[Optional[Dict], Optional[Dict]]:
"""
Fetches the spoofing data for the given ASN from the CAIDA API and the ASRank API.
Args:
asn (str): The ASN to fetch spoofing data for.
Returns: Tuple[Optional[Dict], Optional[Dict]]: A tuple containing two dictionaries. The first dictionary
contains the spoofing data from the CAIDA API, or None if no data is found. The second dictionary contains
the ASRank data, or None if no data is found.
"""
return await gather(
self.fetch(f"https://api.spoofer.caida.org/sessions?asn={asn}"),
self.fetch(f"https://api.asrank.caida.org/v2/restful/asns/{asn}")
)
async def handle_asn(self, asn: str) -> None:
"""
Handles the given ASN and fetches data from the CAIDA API and the ASRank API.
Args:
asn (str): The ASN to handle.
Returns:
None
"""
self.logger.log("[bold cyan]🔍 Fetching data for ASN: AS%s..." % asn)
spoof_data, asrank_data = await self.fetch_spoof_data(asn)
if not spoof_data or not asrank_data or not asrank_data["data"]["asn"]:
return self.logger.log("[bold red]❌ No data found for ASN: %s" % asn)
spoof_data = spoof_data.get("hydra:member", spoof_data)
if not spoof_data:
return self.logger.log("[bold red]❌ No data found for ASN: %s" % asn)
spoof_data = spoof_data[-1]
as_name = asrank_data['data']['asn']['asnName']
last_check = datetime.strptime(spoof_data["timestamp"], '%Y-%m-%dT%H:%M:%S+00:00')
spoofable_localv4, spoofable_internetv4 = spoof_data["routedspoof"] == "received", spoof_data["privatespoof"] == "sent"
spoofable_localv6, spoofable_internetv6 = spoof_data["routedspoof6"] == "received", spoof_data["privatespoof6"] == "sent"
ipv4_client, ipv6_client = spoof_data["client4"], spoof_data["client6"]
asn, asn6 = spoof_data["asn4"], spoof_data["asn6"]
site, mail, phone = await self.find_contact(asn)
# Log main ASN details
self.logger.log("[bold green]🌍 ASN Name: %s" % as_name)
if asn6:
self.logger.log("[bold blue]🔢 ASN6 Number: [cyan]AS%s" % asn6)
if asn:
self.logger.log("[bold blue]🔢 ASN Number: [cyan]AS%s" % asn)
if site:
self.logger.log("[bold yellow]🌐 Site: %s" % site)
self.logger.log("[bold magenta]🏆 ASN Rank: [cyan]%s" % asrank_data['data']['asn']['rank'])
# Log spoofability details
if spoofable_localv4 or spoofable_internetv4:
self.logger.log("[bold yellow]🛡️ Spoofable IPv4: [cyan]%s" % (', '.join([
label for label in [
'Local' if spoofable_localv6 else None,
'Internet' if spoofable_internetv6 else None
] if label
]) or 'No'))
elif spoofable_localv6 or spoofable_internetv6:
self.logger.log("[bold yellow]🛡️ Spoofable IPv6: [cyan]%s" % (', '.join([
label for label in [
'Local' if spoofable_localv6 else None,
'Internet' if spoofable_internetv6 else None
] if label
]) or 'No'))
else:
self.logger.log("[bold red]🛡️ Spoofable: [cyan]No")
self.logger.log("[bold cyan]🌍 Country: [green]%s" % spoof_data['country'].upper())
# Log client IPs
if ipv4_client:
self.logger.log("[bold cyan]🌐 Client IPv4: [yellow]%s" % ipv4_client)
if ipv6_client:
self.logger.log("[bold cyan]🌌 Client IPv6: [yellow]%s" % ipv6_client)
# Log last check date
self.logger.log("[bold cyan]⏱️ Last Checked: [green]%s" % last_check.strftime('%b %d %Y %I:%M %p'))
# Log contact information
if mail:
self.logger.log("[bold cyan]📧 Contact Email: [yellow]%s" % mail)
if phone:
self.logger.log("[bold cyan]📞 Contact Phone: [yellow]%s" % phone)
# Log related links
links = await self.find_links(as_name + " server")
if site:
site_links = await self.find_links(site)
if site_links:
links.extend(site_links)
if links:
self.logger.log("[bold green]🔗 Related Links:")
for link in links:
self.logger.log("[yellow]- %s" % link)
async def _run(self) -> None:
asn = self.target or (await ainput("Enter ASN, IP, CIDR: ")).strip()
asn = self.parse_asn(asn)
if "/" in asn or "-" in asn:
try:
asn = str(IPNetwork(asn)[0])
except AddrFormatError as e:
self.logger.log(f"[red]Invalid CIDR/Range: {str(e)}")
return
if not asn.isdigit():
asn_info = await self.get_asn_info(asn)
if not asn_info or not asn_info.get("asn"):
self.logger.log("[red]No ASN info found.")
return
asn = asn_info["asn"]
await self.handle_asn(asn)
def __enter__(self):
return self
def __exit__(self, *args):
self.loop.close()
def run(self) -> None:
self.loop.run_until_complete(self._run())
async def close(self):
await self.client.aclose()
def main() -> None:
import argparse
parser = argparse.ArgumentParser(description="Spoof Finder CLI")
parser.add_argument('-t', '--target', help="Target ASN, IP, or CIDR", required=False)
args = parser.parse_args()
with SpoofFinder(args.target) as spoof_finder:
spoof_finder.run()
if __name__ == "__main__":
main()