forked from NVIDIA/NemoClaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity-c2-dockerfile-injection.test.js
More file actions
369 lines (343 loc) · 14.8 KB
/
security-c2-dockerfile-injection.test.js
File metadata and controls
369 lines (343 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Security regression test: C-2 — CHAT_UI_URL Python code injection in Dockerfile.
//
// The vulnerable pattern interpolates Docker build-args directly into a
// python3 -c source string. A single-quote in the value closes the Python
// string literal and allows arbitrary code execution at image build time.
//
// The fixed pattern reads values via os.environ (data, not source code).
import { describe, it, expect } from "vitest";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
const DOCKERFILE = path.join(import.meta.dirname, "..", "Dockerfile");
function runPython(src, env = {}) {
return spawnSync("python3", ["-c", src], {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, ...env },
timeout: 5000,
});
}
// Simulate what Docker ARG substitution produces (the VULNERABLE pattern)
function vulnerableSource(chatUiUrlValue) {
return (
"import json, os, secrets; " +
"from urllib.parse import urlparse; " +
`chat_ui_url = '${chatUiUrlValue}'; ` +
"parsed = urlparse(chat_ui_url); " +
"print(repr(chat_ui_url))"
);
}
// Simulate the FIXED pattern (env var, no source interpolation)
function fixedSource() {
return (
"import json, os, secrets; " +
"from urllib.parse import urlparse; " +
"chat_ui_url = os.environ['CHAT_UI_URL']; " +
"parsed = urlparse(chat_ui_url); " +
"print(repr(chat_ui_url))"
);
}
// ═══════════════════════════════════════════════════════════════════
// 1. PoC — vulnerable pattern allows code injection
// ═══════════════════════════════════════════════════════════════════
describe("C-2 PoC: vulnerable pattern (ARG interpolation into python3 -c)", () => {
it("benign URL works in the vulnerable pattern (baseline)", () => {
const src = vulnerableSource("http://127.0.0.1:18789");
const result = runPython(src);
expect(result.status).toBe(0);
expect(result.stdout.includes("127.0.0.1")).toBeTruthy();
});
it("single-quote in URL causes SyntaxError", () => {
const src = vulnerableSource("http://x'.evil.com");
const result = runPython(src);
expect(result.status).not.toBe(0);
expect(result.stderr.includes("SyntaxError")).toBeTruthy();
});
it("injection payload writes canary file — arbitrary Python executes", () => {
const canary = path.join(os.tmpdir(), `nemoclaw-c2-poc-${Date.now()}`);
try {
const payload = `http://x'; open('${canary}','w').write('PWNED') #`;
const src = vulnerableSource(payload);
runPython(src);
expect(fs.existsSync(canary)).toBeTruthy();
expect(fs.readFileSync(canary, "utf-8")).toBe("PWNED");
} finally {
try {
fs.unlinkSync(canary);
} catch {
/* cleanup */
}
}
});
});
// ═══════════════════════════════════════════════════════════════════
// 2. Fix verification — env var pattern treats all payloads as data
// ═══════════════════════════════════════════════════════════════════
describe("C-2 fix: env var pattern (os.environ) is safe", () => {
it("benign URL works through env var", () => {
const result = runPython(fixedSource(), { CHAT_UI_URL: "http://127.0.0.1:18789" });
expect(result.status).toBe(0);
expect(result.stdout.includes("127.0.0.1")).toBeTruthy();
});
it("single-quote in URL is treated as data, not a code boundary", () => {
const result = runPython(fixedSource(), { CHAT_UI_URL: "http://x'.evil.com" });
expect(result.status).toBe(0);
expect(result.stdout.includes("x'.evil.com")).toBeTruthy();
});
it("injection payload does NOT execute — URL is inert data", () => {
const canary = path.join(os.tmpdir(), `nemoclaw-c2-fixed-${Date.now()}`);
try {
const payload = `http://x'; open('${canary}','w').write('PWNED') #`;
const result = runPython(fixedSource(), { CHAT_UI_URL: payload });
expect(result.status).toBe(0);
expect(fs.existsSync(canary)).toBe(false);
} finally {
try {
fs.unlinkSync(canary);
} catch {
/* cleanup */
}
}
});
it("semicolons and import statements in URL are literal data", () => {
const dangerous = "http://x; import subprocess; subprocess.run(['id'])";
const result = runPython(fixedSource(), { CHAT_UI_URL: dangerous });
// The URL is treated as data — urlparse may or may not raise, but
// the key property is that no code injection occurs. Check stdout or stderr
// does NOT contain evidence of os.system/subprocess execution.
const combined = result.stdout + result.stderr;
expect(!combined.includes("uid=")).toBeTruthy();
});
});
// ═══════════════════════════════════════════════════════════════════
// 3. Dockerfile regression guard — source must use the fixed pattern
// ═══════════════════════════════════════════════════════════════════
describe("C-2 regression: Dockerfile must not interpolate build-args into Python source", () => {
it("Dockerfile does not interpolate CHAT_UI_URL into a Python string literal", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const vulnerablePattern = /\$(?:\{CHAT_UI_URL\}|CHAT_UI_URL\b)/;
const lines = src.split("\n");
let inPythonRunBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
inPythonRunBlock = true;
}
if (inPythonRunBlock && vulnerablePattern.test(line)) {
expect.unreachable(
`Dockerfile:${i + 1} interpolates CHAT_UI_URL into a Python string literal.\n` +
` Line: ${line.trim()}\n` +
` Fix: use os.environ['CHAT_UI_URL'] instead.`,
);
}
if (inPythonRunBlock && !/\\\s*$/.test(line)) {
inPythonRunBlock = false;
}
}
});
it("Dockerfile does not interpolate NEMOCLAW_MODEL into a Python string literal", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const vulnerablePattern = /\$(?:\{NEMOCLAW_MODEL\}|NEMOCLAW_MODEL\b)/;
const lines = src.split("\n");
let inPythonRunBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
inPythonRunBlock = true;
}
if (inPythonRunBlock && vulnerablePattern.test(line)) {
expect.unreachable(
`Dockerfile:${i + 1} interpolates NEMOCLAW_MODEL into a Python string literal.\n` +
` Line: ${line.trim()}\n` +
` Fix: use os.environ['NEMOCLAW_MODEL'] instead.`,
);
}
if (inPythonRunBlock && !/\\\s*$/.test(line)) {
inPythonRunBlock = false;
}
}
});
it("Dockerfile promotes CHAT_UI_URL to ENV before the RUN layer", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const lines = src.split("\n");
let chatUiUrlPromoted = false;
let inEnvBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Reset on new build stage — ENV must be in the same stage as the RUN layer
if (/^\s*FROM\b/.test(line)) {
chatUiUrlPromoted = false;
inEnvBlock = false;
}
// Detect start of an ENV instruction
if (/^\s*ENV\b/.test(line)) {
inEnvBlock = true;
}
// Check if CHAT_UI_URL is set in the current ENV block (same line or continuation)
if (inEnvBlock && /CHAT_UI_URL[=\s]/.test(line)) {
chatUiUrlPromoted = true;
}
// ENV block ends when the line does NOT end with a backslash continuation
if (inEnvBlock && !/\\\s*$/.test(line)) {
inEnvBlock = false;
}
// Verify promotion happened before the python3 -c RUN layer
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
expect(chatUiUrlPromoted).toBeTruthy();
return; // Found the RUN layer and verified — done
}
}
expect(chatUiUrlPromoted).toBeTruthy();
});
it("Python script uses os.environ to read CHAT_UI_URL", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const lines = src.split("\n");
let inPythonRunBlock = false;
let hasEnvRead = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
inPythonRunBlock = true;
}
if (inPythonRunBlock) {
if (
line.includes("os.environ['CHAT_UI_URL']") ||
line.includes('os.environ["CHAT_UI_URL"]') ||
line.includes("os.environ.get('CHAT_UI_URL'") ||
line.includes('os.environ.get("CHAT_UI_URL"')
) {
hasEnvRead = true;
}
}
if (inPythonRunBlock && !/\\\s*$/.test(line)) {
inPythonRunBlock = false;
}
}
expect(hasEnvRead).toBeTruthy();
});
it("Dockerfile promotes NEMOCLAW_MODEL to ENV before the RUN layer", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const lines = src.split("\n");
let nemoModelPromoted = false;
let inEnvBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Reset on new build stage — ENV must be in the same stage as the RUN layer
if (/^\s*FROM\b/.test(line)) {
nemoModelPromoted = false;
inEnvBlock = false;
}
// Detect start of an ENV instruction
if (/^\s*ENV\b/.test(line)) {
inEnvBlock = true;
}
// Check if NEMOCLAW_MODEL is set in the current ENV block (same line or continuation)
if (inEnvBlock && /NEMOCLAW_MODEL[=\s]/.test(line)) {
nemoModelPromoted = true;
}
// ENV block ends when the line does NOT end with a backslash continuation
if (inEnvBlock && !/\\\s*$/.test(line)) {
inEnvBlock = false;
}
// Verify promotion happened before the python3 -c RUN layer
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
expect(nemoModelPromoted).toBeTruthy();
return; // Found the RUN layer and verified — done
}
}
expect(nemoModelPromoted).toBeTruthy();
});
it("Python script uses os.environ to read NEMOCLAW_MODEL", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const lines = src.split("\n");
let inPythonRunBlock = false;
let hasEnvRead = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
inPythonRunBlock = true;
}
if (inPythonRunBlock) {
if (
line.includes("os.environ['NEMOCLAW_MODEL']") ||
line.includes('os.environ["NEMOCLAW_MODEL"]') ||
line.includes("os.environ.get('NEMOCLAW_MODEL'") ||
line.includes('os.environ.get("NEMOCLAW_MODEL"')
) {
hasEnvRead = true;
}
}
if (inPythonRunBlock && !/\\\s*$/.test(line)) {
inPythonRunBlock = false;
}
}
expect(hasEnvRead).toBeTruthy();
});
});
// ═══════════════════════════════════════════════════════════════════
// 4. Gateway auth hardening — no hardcoded insecure defaults (#117)
// ═══════════════════════════════════════════════════════════════════
describe("Gateway auth hardening: Dockerfile must not hardcode insecure auth defaults", () => {
it("dangerouslyDisableDeviceAuth is not hardcoded to True", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
// Must not contain a literal `'dangerouslyDisableDeviceAuth': True`
expect(src).not.toMatch(/'dangerouslyDisableDeviceAuth':\s*True/);
});
it("allowInsecureAuth is not hardcoded to True", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
// Must not contain a literal `'allowInsecureAuth': True`
expect(src).not.toMatch(/'allowInsecureAuth':\s*True/);
});
it("dangerouslyDisableDeviceAuth is derived from NEMOCLAW_DISABLE_DEVICE_AUTH env var", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
// The Python config generation must read the env var
expect(src).toMatch(/os\.environ\.get\(['"]NEMOCLAW_DISABLE_DEVICE_AUTH['"]/);
// And use the derived variable in the config dict
expect(src).toMatch(/'dangerouslyDisableDeviceAuth':\s*disable_device_auth/);
});
it("allowInsecureAuth is derived from URL scheme (explicit http allowlist)", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
// Must use explicit 'http' allowlist — not `!= 'https'` which would allow
// insecure auth for malformed or unknown schemes (CodeRabbit review on #123)
expect(src).toMatch(/allow_insecure\s*=\s*parsed\.scheme\s*==\s*'http'/);
expect(src).not.toMatch(/allow_insecure\s*=\s*parsed\.scheme\s*!=\s*'https'/);
// And use the derived variable in the config dict
expect(src).toMatch(/'allowInsecureAuth':\s*allow_insecure/);
});
it("NEMOCLAW_DISABLE_DEVICE_AUTH defaults to '0' (secure by default)", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
expect(src).toMatch(/ARG\s+NEMOCLAW_DISABLE_DEVICE_AUTH=0/);
});
it("NEMOCLAW_DISABLE_DEVICE_AUTH is promoted to ENV before the Python RUN layer", () => {
const src = fs.readFileSync(DOCKERFILE, "utf-8");
const lines = src.split("\n");
let promoted = false;
let inEnvBlock = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^\s*FROM\b/.test(line)) {
promoted = false;
inEnvBlock = false;
}
if (/^\s*ENV\b/.test(line)) {
inEnvBlock = true;
}
if (inEnvBlock && /NEMOCLAW_DISABLE_DEVICE_AUTH[=\s]/.test(line)) {
promoted = true;
}
if (inEnvBlock && !/\\\s*$/.test(line)) {
inEnvBlock = false;
}
if (/^\s*RUN\b.*python3\s+-c\b/.test(line)) {
expect(promoted).toBeTruthy();
return;
}
}
expect(promoted).toBeTruthy();
});
});