Exploit database

GH-7f4812a4414dc2c407290e35878d3163

googlesky/cve-2026-76954

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-76954

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files4
googlesky/cve-2026-76954Revision 22d7174eb3cd

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

lab/service.py

Python · 6,205 bytes
#!/usr/bin/env python3
"""CVE-2026-76954 lab service.

Exercises the real, unmodified Synology DSM library the way the Auth API does:
a request supplies the pre-auth fields (device_id / user / scope / key / ...) and
the service runs /opt/driver as a child process, which dlopens the real
libsyno-pam-login.so.7.0 and calls the exported SynoPamKey::* API used by the
DSM pam_syno_otp.so module. A child crash is observed instead of taking down the
service. Only Python stdlib is used.
"""
import hashlib
import json
import os
import sqlite3
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

DB = "/usr/syno/etc/private/session/syno-pam-key.db"
LIBDIR = Path("/opt/dsm/lib")
DRIVER = "/opt/driver"
TRACE = "/opt/sqltrace.so"

DEFAULTS = {
    "device_id": "", "user": "", "scope": "webui", "key": "",
    "attribute1": "", "attribute2": "", "extrainfo": "", "enabled": 1,
}


def sha256(path):
    h = hashlib.sha256()
    h.update(Path(path).read_bytes())
    return h.hexdigest()


def escape_api(path):
    data = Path(path).read_bytes()
    return ("SYNODBEscapeStrAllocEX" if b"SYNODBEscapeStrAllocEX" in data
            else "SYNODBEscapeStringEX")


def versions():
    out = []
    for p in sorted(LIBDIR.glob("*.so")):
        out.append({"name": p.name, "sha256": sha256(p), "escape_api": escape_api(p)})
    return out


def reset_db():
    try:
        os.unlink(DB)
    except FileNotFoundError:
        pass
    for suffix in ("-journal", "-wal", "-shm"):
        try:
            os.unlink(DB + suffix)
        except FileNotFoundError:
            pass


def inspect_db():
    result = {"exists": False, "tables": [], "marker": False, "rows": []}
    if not os.path.exists(DB):
        return result
    result["exists"] = True
    try:
        con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
        tables = [r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")]
        result["tables"] = tables
        result["marker"] = "poc_marker" in tables
        try:
            for row in con.execute("SELECT id, user, length(id), length(user) FROM key LIMIT 5"):
                result["rows"].append({
                    "id_head": row[0][:24] if row[0] else "",
                    "id_len": row[2],
                    "user": row[1][:120] if row[1] else "",
                    "user_len": row[3],
                })
        except sqlite3.Error as exc:
            result["row_error"] = str(exc)
        con.close()
    except sqlite3.Error as exc:
        result["error"] = str(exc)
    return result


def run_login(body):
    lib = body.get("lib") or os.environ.get("PAMLOGIN_LIB")
    if not lib or not os.path.exists(lib):
        return {"error": "no target library", "lib": lib}, 400

    fields = dict(DEFAULTS)
    for k in DEFAULTS:
        if k in body:
            fields[k] = body[k]
    # Optional edge mitigation: cap the attacker-controlled device_id.
    cap = body.get("device_id_cap")
    capped = None
    if cap is not None:
        try:
            cap = int(cap)
            if cap >= 0 and len(str(fields["device_id"])) > cap:
                capped = {"from": len(str(fields["device_id"])), "to": cap}
                fields["device_id"] = str(fields["device_id"])[:cap]
        except (TypeError, ValueError):
            pass

    reset_db()
    args = [DRIVER, "key", lib,
            str(fields["device_id"]), str(fields["user"]), str(fields["scope"]),
            str(fields["key"]), str(fields["attribute1"]), str(fields["attribute2"]),
            str(fields["extrainfo"]), str(fields["enabled"])]
    env = dict(os.environ)
    env["LD_PRELOAD"] = TRACE
    child = subprocess.run(args, capture_output=True, text=True, env=env, timeout=60)
    log = child.stdout + child.stderr
    sql = [l[6:] for l in log.splitlines() if l.startswith("[SQL] ")]
    insert = next((s for s in sql if s.startswith("INSERT OR REPLACE")), None)
    save_ok = "Save() -> 0x1" in log

    result = {
        "lib": os.path.basename(lib),
        "lib_sha256": sha256(lib),
        "escape_api": escape_api(lib),
        "child_rc": child.returncode,
        "child_signal": -child.returncode if child.returncode < 0 else None,
        "save_ok": save_ok,
        "sql": insert,
        "sql_statements": sql,
        "marker": inspect_db()["marker"],
        "db": inspect_db(),
        "device_id_cap": capped,
        "requested_lengths": {k: len(str(v)) for k, v in fields.items() if isinstance(v, str)},
    }
    return result, 200


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        sys.stderr.write("[service] " + (fmt % args) + "\n")

    def send_json(self, code, payload):
        data = json.dumps(payload, ensure_ascii=False).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/health":
            lib = os.environ.get("PAMLOGIN_LIB", "")
            self.send_json(200, {"status": "ok", "lib": os.path.basename(lib),
                                "sha256": sha256(lib) if lib and os.path.exists(lib) else None,
                                "escape_api": escape_api(lib) if lib and os.path.exists(lib) else None})
        elif self.path == "/versions":
            self.send_json(200, {"versions": versions()})
        else:
            self.send_json(404, {"error": "not found"})

    def do_POST(self):
        if self.path != "/login":
            self.send_json(404, {"error": "not found"})
            return
        try:
            n = int(self.headers.get("Content-Length", "0"))
            body = json.loads(self.rfile.read(n) or b"{}")
            payload, code = run_login(body)
        except Exception as exc:
            payload, code = {"error": str(exc)}, 500
        self.send_json(code, payload)


if __name__ == "__main__":
    port = int(os.environ.get("LAB_PORT", "8080"))
    ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()