-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsource-rer.py
390 lines (342 loc) · 12 KB
/
source-rer.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
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
import base64
import os
from urllib.parse import urljoin, urlparse
from pathlib import Path
import re
import shutil
import argparse
try:
from bs4 import BeautifulSoup
from colorama import Fore
import requests
import sourcemaps # python-sourcemaps
except ImportError:
print("Required module(s) not found. Please install them using:")
print("\033[32mpip install -r requirements.txt\033[0m")
exit(1)
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""
▒█▀▀▀█ █▀▀█ █░░█ █▀▀█ █▀▀ █▀▀ ░░ █▀▀█ █▀▀ █▀▀█
░▀▀▀▄▄ █░░█ █░░█ █▄▄▀ █░░ █▀▀ ▀▀ █▄▄▀ █▀▀ █▄▄▀
▒█▄▄▄█ ▀▀▀▀ ░▀▀▀ ▀░▀▀ ▀▀▀ ▀▀▀ ░░ ▀░▀▀ ▀▀▀ ▀░▀▀
- By github.com/ItzzMeGrrr
Download source code from JavaScript sourcemaps
""",
epilog="""
Examples:
python source-rer.py -l js_links.txt -o output_dir
python3 source-rer.py -u https://example.com -o output_dir -H 'Cookie: SESSION=1234567890'
""",
)
args_input = parser.add_mutually_exclusive_group(required=True)
args_input.add_argument(
"-l",
"--links",
help="File containing js file links to download source code from",
)
args_input.add_argument("-u", "--url", help="Link to page find js links from")
parser.add_argument(
"-o", "--output", help="Output directory to save source code", required=True
)
parser.add_argument(
"-knm",
"--keep",
help="Keep node_modules as well, (default: skip)",
action="store_true",
)
parser.add_argument(
"-X",
"--method",
help="HTTP method to use (default: GET)",
default="GET",
choices=["GET", "POST"],
)
parser.add_argument(
"-H",
"--header",
help="HTTP header to add to request (multiple -H flags are accepted)",
action="append",
default=[],
)
parser.add_argument(
"-q",
"--quiet",
help="Don't print any output except errors",
action="store_true",
)
parser.add_argument(
"-v", "--verbose", help="Print verbose output", action="store_true"
)
args = parser.parse_args()
VERBOSE = args.verbose
QUIET = args.quiet
def print_custom(text, color, override=False):
global VERBOSE, QUIET
if (override or VERBOSE) and not QUIET:
print(f"{color}{text}{Fore.RESET}")
return
KEEP_NODE_MODULES = args.keep
js_links = args.links
url = args.url
method = args.method
headers = {}
if args.header:
for header in args.header:
if header.count(":") < 1:
print_custom(
f"Invalid header {header}, header name and value should be separated by a colon ':' Ex. {Fore.CYAN}-H 'HeaderName: HeaderValue'",
Fore.YELLOW,
override=True,
)
header_split = header.split(":")
headers.update(
{f"{header_split[0].strip()}": f"{''.join(header_split[1:]).strip()}"}
)
output_directory = args.output
links = []
source_mapping_urls = []
def sanatize_filename(filename):
# remove multiple slashes and replace .. with .
filename = re.sub(r"(/)+", "/", filename.replace("..", "."))
# remove all characters except a-z, A-Z, 0-9, -, /, . and _
pattern = r"[^a-zA-Z0-9\-/._]"
return re.sub(pattern, "", filename)
def fetch(url):
global method, headers
try:
if method == "POST":
res = requests.post(url, headers=headers)
if not res.status_code == 200:
print_custom(
f" ^-- Got status code: {Fore.RED}{res.status_code}{Fore.YELLOW} from '{url}'",
Fore.YELLOW,
override=True,
)
return res
else:
res = requests.get(url, headers=headers)
if not res.status_code == 200:
print_custom(
f" ^-- Got status code: {Fore.RED}{res.status_code}{Fore.YELLOW} from '{url}'",
Fore.YELLOW,
override=True,
)
return res
except Exception as e:
print(f"{Fore.RED}Exception:", e)
print(f"{Fore.RESET}")
return None
def extract_sourcemap(js_content):
# Pattern for sourcemap URL
sourcemap_url_pattern = r"\/\/# sourceMappingURL=(.+\.map)"
# Pattern for embedded base64 sourcemap
base64_sourcemap_pattern = r"\/\/# sourceMappingURL=data:application\/json;(.+)"
url_match = re.search(sourcemap_url_pattern, js_content)
base64_match = re.search(base64_sourcemap_pattern, js_content)
if url_match:
return ("url", url_match.group(1))
elif base64_match:
base64_sourcemap_data = base64_match.group(1)
return ("data", base64_sourcemap_data)
else:
return ("not-found", None)
def dump_content(content, out_dir):
global KEEP_NODE_MODULES
for source in content:
if not KEEP_NODE_MODULES and "node_modules" in source:
print_custom(f"Skipping {source}", Fore.YELLOW)
continue
filtered_source = sanatize_filename(source)
print_custom(f"Saving file {filtered_source}", Fore.GREEN)
fileName = os.path.basename(filtered_source)
path = os.path.dirname(urlparse(filtered_source).path)
try:
out_path = os.path.join(out_dir, path)
path = Path(f"{out_path}")
path.mkdir(parents=True, exist_ok=True)
except Exception as e:
print(f"{Fore.RED}Exception:", e)
print(f"{Fore.RESET}")
continue
file_path = os.path.join(path, fileName)
try:
with open(f"{file_path}", "w", encoding="utf-8") as file:
file.write(content.get(source))
except Exception as e:
print(f"{Fore.RED}Exception:", e)
print(f"{Fore.RESET}")
continue
def get_sourcemap_content(source_type, src, link):
if source_type == "url":
url = urljoin(link, src)
res = fetch(url)
if res.status_code == 200:
return res.text
else:
print_custom(
f" ^-- Got status code: {Fore.RED}{res.status_code}{Fore.YELLOW} for map link '{url}'",
Fore.YELLOW,
override=True,
)
return None
elif source_type == "data":
try:
return base64.b64decode(src).decode("utf-8")
except:
print_custom(
f" ^-- Failed to decode base64 sourcemap for {Fore.RED}{link}",
Fore.RED,
override=True,
)
return None
return None
def save_original_source(sourcemap_data, output_directory):
link = sourcemap_data["link"]
source_type = sourcemap_data["source_type"]
src = sourcemap_data["src"]
source_content = get_sourcemap_content(source_type, src, link)
if not source_content:
if source_type == "not-found":
print_custom(
f" ^-- SourceMappingURL not found in {Fore.RED}{link}",
Fore.WHITE,
override=True,
)
else:
print_custom(
f" ^-- Failed to download source for {Fore.RED}{link}",
Fore.RED,
override=True,
)
return
source_map_content = sourcemaps.decode(source_content).sources_content
dump_content(source_map_content, output_directory)
def find_js_links(url):
# validate url using urlparse
parsed_url = urlparse(url)
if not parsed_url.scheme or not parsed_url.netloc:
print_custom(f"Invalid URL: {url}", Fore.RED, override=True)
exit(1)
res = fetch(parsed_url.geturl())
soup = BeautifulSoup(res.text, "html.parser")
script_tags = soup.find_all("script", src=True)
# Extract the 'src' attribute values (JS file URLs)
js_file_urls = []
for tag in script_tags:
js_file_urls.append(tag["src"])
# Join relative URLs with the base URL
final_js_file_urls = []
for js_url in js_file_urls:
if not js_url.startswith("http"):
final_js_file_urls.append(urljoin(url, js_url))
else:
final_js_file_urls.append(js_url)
print_custom(
f"Found {Fore.CYAN}{len(final_js_file_urls)}{Fore.WHITE} JS files",
Fore.WHITE,
override=True,
)
return final_js_file_urls
def load_js_links(filename):
unique_lines = set()
uniques = 0
invalid = 0
with open(filename, "r") as file:
for line in file:
cleaned_line = line.strip()
try:
parsed_url = urlparse(cleaned_line)
path = parsed_url.path
file_extension = os.path.splitext(path)[1]
if not file_extension.lower() == ".js":
print_custom(
f"Ignoring non js link: {Fore.CYAN}{cleaned_line}",
Fore.YELLOW,
)
invalid += 1
continue
except:
print_custom(
f"Invalid URL: {Fore.RED}{cleaned_line}",
Fore.RED,
override=True,
)
invalid += 1
continue
if cleaned_line not in unique_lines:
unique_lines.add(cleaned_line)
uniques += 1
else:
invalid += 1
print_custom(
f"Ignoring duplicate line: {Fore.CYAN}{cleaned_line}", Fore.YELLOW
)
print_custom(
f"Loaded {Fore.CYAN}{uniques}{Fore.WHITE} links and ignored {Fore.CYAN}{invalid}{Fore.WHITE} duplicate/invalid links",
Fore.WHITE,
override=True,
)
unique_lines_list = list(unique_lines)
return unique_lines_list
def main():
global KEEP_NODE_MODULES, js_links, url, output_directory, VERBOSE
banner()
if js_links:
if not os.path.exists(js_links):
print_custom(f"File not found: {js_links}", Fore.RED, override=True)
exit(1)
# Validate output directory
if os.path.exists(output_directory):
if os.listdir(output_directory):
print_custom(
f"Output directory {output_directory} is not empty.",
Fore.YELLOW,
override=True,
)
overwrite = input("Do you want to overwrite the existing files? (y/n): ")
if overwrite.lower() == "y":
shutil.rmtree(output_directory)
os.makedirs(output_directory, exist_ok=True)
pass
else:
exit(1)
else:
os.makedirs(output_directory, exist_ok=True)
# Load js links
if js_links:
source_mapping_urls = load_js_links(js_links)
if url:
source_mapping_urls = find_js_links(url)
if not source_mapping_urls:
print(f"{Fore.RED}No JS files found.{Fore.RESET}")
exit(1)
# Save original source
for url in source_mapping_urls:
print_custom(
f"Saving original source for {Fore.CYAN}{url}{Fore.RESET}",
Fore.WHITE,
override=True,
)
src = extract_sourcemap(fetch(url).text)
data = {
"link": url,
"source_type": src[0],
"src": src[1],
}
save_original_source(data, output_directory)
def banner():
global QUIET
if not QUIET:
print(
f"""{Fore.YELLOW}
▒█▀▀▀█ █▀▀█ █░░█ █▀▀█ █▀▀ █▀▀ ░░ █▀▀█ █▀▀ █▀▀█
░▀▀▀▄▄ █░░█ █░░█ █▄▄▀ █░░ █▀▀ ▀▀ █▄▄▀ █▀▀ █▄▄▀
▒█▄▄▄█ ▀▀▀▀ ░▀▀▀ ▀░▀▀ ▀▀▀ ▀▀▀ ░░ ▀░▀▀ ▀▀▀ ▀░▀▀
{Fore.GREEN}- By github.com/ItzzMeGrrr{Fore.RESET}\n"""
)
try:
main()
except KeyboardInterrupt:
print_custom("\nExiting...", Fore.RED)
exit(1)