Skip to content

Commit 30cf038

Browse files
committed
security: add shell-injection prevention and pass NGC_API_KEY to NIM container
1 parent 867f27d commit 30cf038

4 files changed

Lines changed: 410 additions & 17 deletions

File tree

‎bin/lib/deploy.js‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
//
4+
// Deploy helpers — input validation and shell-free command builders.
5+
//
6+
// SSH/rsync/scp use runArgv() (argv arrays, no shell) to eliminate command
7+
// injection at the root cause. shellQuote() is retained for call sites that
8+
// still need run() (e.g. brev CLI with shell features).
9+
10+
const { runArgv } = require("./runner");
11+
12+
const INSTANCE_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
13+
14+
/**
15+
* Validate that name is a safe instance/hostname string.
16+
* @param {string} name - Instance name to validate.
17+
* @throws {Error} If name is invalid, non-string, or too long.
18+
*/
19+
function validateInstanceName(name) {
20+
if (!name || typeof name !== "string" || name.length > 253 || !INSTANCE_NAME_RE.test(name)) {
21+
throw new Error(
22+
`Invalid instance name: ${JSON.stringify(String(name).slice(0, 40))}. ` +
23+
"Must be a string, 1-253 chars, start with alphanumeric, and contain only [a-zA-Z0-9._-]."
24+
);
25+
}
26+
}
27+
28+
const SSH_OPTS = ["-o", "StrictHostKeyChecking=accept-new", "-o", "LogLevel=ERROR"];
29+
30+
/** @param remoteCmd — executed by the remote shell. Use only constant strings
31+
* or values wrapped in shellQuote(). Never interpolate unsanitized input. */
32+
function runSsh(host, remoteCmd, opts = {}) {
33+
validateInstanceName(host);
34+
const args = [...SSH_OPTS];
35+
if (opts.tty) args.unshift("-t");
36+
args.push(host);
37+
if (remoteCmd) args.push(remoteCmd);
38+
return runArgv("ssh", args, opts);
39+
}
40+
41+
/**
42+
* Copy a file to a remote host via scp using argv arrays (no shell).
43+
* @param {string} src - Local source path.
44+
* @param {string} destHostPath - Remote destination in host:path format.
45+
* @param {object} [opts] - Options forwarded to runArgv.
46+
*/
47+
function runScp(src, destHostPath, opts = {}) {
48+
const [host] = destHostPath.split(":");
49+
validateInstanceName(host);
50+
const args = ["-q", ...SSH_OPTS, src, destHostPath];
51+
return runArgv("scp", args, opts);
52+
}
53+
54+
/**
55+
* Sync files to a remote host via rsync using argv arrays (no shell).
56+
* @param {string[]} sources - Local paths to sync.
57+
* @param {string} host - Remote hostname (must pass validateInstanceName).
58+
* @param {string} dest - Remote destination directory.
59+
* @param {object} [opts] - Options forwarded to runArgv.
60+
*/
61+
function runRsync(sources, host, dest, opts = {}) {
62+
validateInstanceName(host);
63+
const args = [
64+
"-az", "--delete",
65+
"--exclude", "node_modules",
66+
"--exclude", ".git",
67+
"--exclude", "src",
68+
"-e", "ssh " + SSH_OPTS.join(" "),
69+
...sources,
70+
`${host}:${dest}`,
71+
];
72+
return runArgv("rsync", args, opts);
73+
}
74+
75+
/**
76+
* Wrap a string in POSIX single quotes, escaping embedded quotes.
77+
* @param {string} s - Value to quote.
78+
* @returns {string} Shell-safe single-quoted string.
79+
*/
80+
function shellQuote(s) {
81+
return "'" + s.replace(/'/g, "'\\''") + "'";
82+
}
83+
84+
module.exports = {
85+
INSTANCE_NAME_RE,
86+
validateInstanceName,
87+
runSsh,
88+
runScp,
89+
runRsync,
90+
shellQuote,
91+
SSH_OPTS,
92+
};

‎bin/lib/runner.js‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ if (dockerHost) {
1313
process.env.DOCKER_HOST = dockerHost.dockerHost;
1414
}
1515

16+
/** Execute a shell command via `bash -c`; exits the process on failure unless opts.ignoreError is set. */
1617
function run(cmd, opts = {}) {
1718
const stdio = opts.stdio ?? ["ignore", "inherit", "inherit"];
1819
const result = spawnSync("bash", ["-c", cmd], {
@@ -28,6 +29,7 @@ function run(cmd, opts = {}) {
2829
return result;
2930
}
3031

32+
/** Execute a shell command with full stdio inheritance (for interactive TTY). */
3133
function runInteractive(cmd, opts = {}) {
3234
const stdio = opts.stdio ?? "inherit";
3335
const result = spawnSync("bash", ["-c", cmd], {
@@ -43,6 +45,80 @@ function runInteractive(cmd, opts = {}) {
4345
return result;
4446
}
4547

48+
// Env vars that must never be overridden by callers — they enable code
49+
// execution, library injection, or trust-store hijacking in subprocesses.
50+
const BLOCKED_ENV_VARS = new Set([
51+
"PATH",
52+
"LD_PRELOAD", "LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES",
53+
"NODE_OPTIONS", "BASH_ENV", "ENV",
54+
"GIT_SSH_COMMAND", "SSH_AUTH_SOCK",
55+
"DOCKER_HOST", "KUBECONFIG",
56+
"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY",
57+
"CURL_CA_BUNDLE", "SSL_CERT_FILE", "NODE_EXTRA_CA_CERTS",
58+
]);
59+
60+
/**
61+
* Validate caller-supplied env vars against a blocklist of dangerous keys.
62+
* Throws if any blocked key is present; returns a shallow copy otherwise.
63+
* @param {object} [callerEnv] - Env overrides from the caller.
64+
* @returns {object} Sanitized env entries safe to merge with process.env.
65+
*/
66+
function sanitizeEnv(callerEnv) {
67+
if (!callerEnv) return {};
68+
const blocked = Object.keys(callerEnv).filter((k) => BLOCKED_ENV_VARS.has(k));
69+
if (blocked.length > 0) {
70+
throw new Error(`runArgv() does not allow overriding: ${blocked.join(", ")}`);
71+
}
72+
return { ...callerEnv };
73+
}
74+
75+
/**
76+
* Shell-free alternative to run(). Executes prog with an argv array via
77+
* spawnSync(prog, args) — no bash, no string interpolation, no injection.
78+
* Use this for any command that includes user-controlled values.
79+
*/
80+
function runArgv(prog, args, opts = {}) {
81+
const { env, ...spawnOpts } = opts;
82+
const result = spawnSync(prog, args, {
83+
stdio: "inherit",
84+
...spawnOpts,
85+
cwd: ROOT,
86+
env: { ...process.env, ...sanitizeEnv(env) },
87+
shell: false,
88+
});
89+
if (result.status !== 0 && !opts.ignoreError) {
90+
console.error(` Command failed (exit ${result.status}): ${prog} ${args.join(" ").slice(0, 60)}`);
91+
process.exit(result.status || 1);
92+
}
93+
return result;
94+
}
95+
96+
/**
97+
* Shell-free alternative to runCapture(). Uses execFileSync(prog, args)
98+
* with no shell. Returns trimmed stdout.
99+
*/
100+
function runCaptureArgv(prog, args, opts = {}) {
101+
const { env, encoding, stdio, ...execOpts } = opts;
102+
if (encoding !== undefined || stdio !== undefined) {
103+
throw new Error("runCaptureArgv() does not allow overriding encoding or stdio");
104+
}
105+
const { execFileSync } = require("child_process");
106+
try {
107+
return execFileSync(prog, args, {
108+
...execOpts,
109+
cwd: ROOT,
110+
env: { ...process.env, ...sanitizeEnv(env) },
111+
encoding: "utf-8",
112+
stdio: ["pipe", "pipe", "pipe"],
113+
shell: false,
114+
}).trim();
115+
} catch (err) {
116+
if (opts.ignoreError) return "";
117+
throw err;
118+
}
119+
}
120+
121+
/** Execute a shell command and return its trimmed stdout; returns "" on failure if opts.ignoreError is set. */
46122
function runCapture(cmd, opts = {}) {
47123
try {
48124
return execSync(cmd, {
@@ -58,4 +134,4 @@ function runCapture(cmd, opts = {}) {
58134
}
59135
}
60136

61-
module.exports = { ROOT, SCRIPTS, run, runCapture, runInteractive };
137+
module.exports = { ROOT, SCRIPTS, run, runCapture, runInteractive, runArgv, runCaptureArgv };

‎bin/nemoclaw.js‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const path = require("path");
77
const fs = require("fs");
88
const os = require("os");
99

10-
const { ROOT, SCRIPTS, run, runCapture, runInteractive } = require("./lib/runner");
10+
const { ROOT, SCRIPTS, run, runCapture, runInteractive, runArgv } = require("./lib/runner");
1111
const {
1212
ensureApiKey,
1313
ensureGithubToken,
@@ -17,6 +17,7 @@ const {
1717
const registry = require("./lib/registry");
1818
const nim = require("./lib/nim");
1919
const policies = require("./lib/policies");
20+
const { validateInstanceName, runSsh, runScp, runRsync, shellQuote: deployShellQuote } = require("./lib/deploy");
2021

2122
// ── Global commands ──────────────────────────────────────────────
2223

@@ -106,6 +107,7 @@ async function deploy(instanceName) {
106107
await ensureGithubToken();
107108
}
108109
const name = instanceName;
110+
validateInstanceName(name);
109111
const gpu = process.env.NEMOCLAW_GPU || "a2-highgpu-1g:nvidia-tesla-a100:1";
110112

111113
console.log("");
@@ -127,17 +129,18 @@ async function deploy(instanceName) {
127129

128130
if (!exists) {
129131
console.log(` Creating Brev instance '${name}' (${gpu})...`);
130-
run(`brev create ${name} --gpu "${gpu}"`);
132+
runArgv("brev", ["create", name, "--gpu", gpu]);
131133
} else {
132134
console.log(` Brev instance '${name}' already exists.`);
133135
}
134136

135-
run(`brev refresh`, { ignoreError: true });
137+
runArgv("brev", ["refresh"], { ignoreError: true });
136138

137139
console.log(" Waiting for SSH...");
140+
const { execFileSync } = require("child_process");
138141
for (let i = 0; i < 60; i++) {
139142
try {
140-
execSync(`ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no ${name} 'echo ok' 2>/dev/null`, { encoding: "utf-8", stdio: "pipe" });
143+
execFileSync("ssh", ["-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=accept-new", name, "echo ok"], { encoding: "utf-8", stdio: "pipe" });
141144
break;
142145
} catch {
143146
if (i === 59) {
@@ -149,8 +152,12 @@ async function deploy(instanceName) {
149152
}
150153

151154
console.log(" Syncing NemoClaw to VM...");
152-
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR ${name} 'mkdir -p /home/ubuntu/nemoclaw'`);
153-
run(`rsync -az --delete --exclude node_modules --exclude .git --exclude src -e "ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR" "${ROOT}/scripts" "${ROOT}/Dockerfile" "${ROOT}/nemoclaw" "${ROOT}/nemoclaw-blueprint" "${ROOT}/bin" "${ROOT}/package.json" ${name}:/home/ubuntu/nemoclaw/`);
155+
runSsh(name, "mkdir -p /home/ubuntu/nemoclaw");
156+
runRsync(
157+
[`${ROOT}/scripts`, `${ROOT}/Dockerfile`, `${ROOT}/nemoclaw`, `${ROOT}/nemoclaw-blueprint`, `${ROOT}/bin`, `${ROOT}/package.json`],
158+
name,
159+
"/home/ubuntu/nemoclaw/"
160+
);
154161

155162
const envLines = [`NVIDIA_API_KEY=${process.env.NVIDIA_API_KEY}`];
156163
const ghToken = process.env.GITHUB_TOKEN;
@@ -159,21 +166,25 @@ async function deploy(instanceName) {
159166
if (tgToken) envLines.push(`TELEGRAM_BOT_TOKEN=${tgToken}`);
160167
const envTmp = path.join(os.tmpdir(), `nemoclaw-env-${Date.now()}`);
161168
fs.writeFileSync(envTmp, envLines.join("\n") + "\n", { mode: 0o600 });
162-
run(`scp -q -o StrictHostKeyChecking=no -o LogLevel=ERROR "${envTmp}" ${name}:/home/ubuntu/nemoclaw/.env`);
169+
const scpResult = runScp(envTmp, `${name}:/home/ubuntu/nemoclaw/.env`, { ignoreError: true });
163170
fs.unlinkSync(envTmp);
171+
if (scpResult.status !== 0) {
172+
console.error(` Failed to copy .env to ${name}`);
173+
process.exit(scpResult.status || 1);
174+
}
164175

165176
console.log(" Running setup...");
166-
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR ${name} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/brev-setup.sh'`);
177+
runSsh(name, "cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/brev-setup.sh", { tty: true });
167178

168179
if (tgToken) {
169180
console.log(" Starting services...");
170-
run(`ssh -o StrictHostKeyChecking=no -o LogLevel=ERROR ${name} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/start-services.sh'`);
181+
runSsh(name, "cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && bash scripts/start-services.sh");
171182
}
172183

173184
console.log("");
174185
console.log(" Connecting to sandbox...");
175186
console.log("");
176-
runInteractive(`ssh -t -o StrictHostKeyChecking=no -o LogLevel=ERROR ${name} 'cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && openshell sandbox connect nemoclaw'`);
187+
runSsh(name, "cd /home/ubuntu/nemoclaw && set -a && . .env && set +a && openshell sandbox connect nemoclaw", { tty: true });
177188
}
178189

179190
async function start() {
@@ -260,8 +271,8 @@ function listSandboxes() {
260271

261272
function sandboxConnect(sandboxName) {
262273
// Ensure port forward is alive before connecting
263-
run(`openshell forward start --background 18789 "${sandboxName}" 2>/dev/null || true`, { ignoreError: true });
264-
runInteractive(`openshell sandbox connect "${sandboxName}"`);
274+
run(`openshell forward start --background 18789 ${shellQuote(sandboxName)} 2>/dev/null || true`, { ignoreError: true });
275+
runInteractive(`openshell sandbox connect ${shellQuote(sandboxName)}`);
265276
}
266277

267278
function sandboxStatus(sandboxName) {
@@ -276,7 +287,7 @@ function sandboxStatus(sandboxName) {
276287
}
277288

278289
// openshell info
279-
run(`openshell sandbox get "${sandboxName}" 2>/dev/null || true`, { ignoreError: true });
290+
run(`openshell sandbox get ${shellQuote(sandboxName)} 2>/dev/null || true`, { ignoreError: true });
280291

281292
// NIM health
282293
const nimStat = nim.nimStatus(sandboxName);
@@ -288,8 +299,8 @@ function sandboxStatus(sandboxName) {
288299
}
289300

290301
function sandboxLogs(sandboxName, follow) {
291-
const followFlag = follow ? " --tail" : "";
292-
run(`openshell logs "${sandboxName}"${followFlag}`);
302+
const followFlag = follow ? " --follow" : "";
303+
run(`openshell sandbox logs ${shellQuote(sandboxName)}${followFlag}`);
293304
}
294305

295306
async function sandboxPolicyAdd(sandboxName) {
@@ -332,7 +343,7 @@ function sandboxDestroy(sandboxName) {
332343
nim.stopNimContainer(sandboxName);
333344

334345
console.log(` Deleting sandbox '${sandboxName}'...`);
335-
run(`openshell sandbox delete "${sandboxName}" 2>/dev/null || true`, { ignoreError: true });
346+
run(`openshell sandbox delete ${shellQuote(sandboxName)} 2>/dev/null || true`, { ignoreError: true });
336347

337348
registry.removeSandbox(sandboxName);
338349
console.log(` ✓ Sandbox '${sandboxName}' destroyed`);

0 commit comments

Comments
 (0)