flawopen.com/Command Injection/Node child_process.exec
Node.js child_process.exec() में command injection का जोखिम
exec() को command string देना ऐसा है जैसे टाइपसेटर को एक वाक्य देकर विराम चिह्नों से निर्देशों की सीमाएँ तय करने देना। अविश्वसनीय टेक्स्ट में shell syntax हो तो shell उसे control instruction मान सकता है। execFile() एक तय program और अलग-अलग arguments देता है; डिफ़ॉल्ट रूप से shell parsing नहीं होती।
const { exec } = require('node:child_process');
function inspectFile(filename) {
return exec(`file ${filename}`);
}
const { execFile } = require('node:child_process');
const allowed = new Map([
['report-1', '/srv/reports/1.pdf'],
['report-2', '/srv/reports/2.pdf']
]);
function inspectReport(reportId) {
const path = allowed.get(reportId);
if (!path) throw new Error('Unknown report');
return execFile('/usr/bin/file', ['--', path], {
shell: false,
timeout: 3000,
maxBuffer: 64 * 1024
});
}
execFile() command injection का जोखिम कैसे घटाता है
exec() shell शुरू करके उसे एक command string देता है। यदि कोड में attacker-controlled टेक्स्ट जोड़ा जाए, तो shell metacharacters को syntax की तरह parse करता है—यही CWE-78 में बताया गया command-injection path है। execFile() argument array के साथ तय executable चलाता है और डिफ़ॉल्ट रूप से shell शुरू नहीं करता, इसलिए shell separators को shell दोबारा parse नहीं करता। उदाहरण caller ID को एक fixed path से map करता है। इससे हर target program सुरक्षित नहीं हो जाता: उसके स्वीकार किए गए arguments validate करें, समर्थन होने पर -- से option parsing रोकें, और अविश्वसनीय values के लिए shell: true कभी न लगाएँ।
असुरक्षित exec() calls कैसे खोजें
exec() और execSync() खोजें और हर command string को request parameters, database fields, filenames और environment variables तक trace करें। Executable और प्रत्येक argument की सीमा दर्ज करें। सीधे library API को प्राथमिकता दें; अन्यथा fixed executable, validated arguments, runtime limit और output limit के साथ execFile() उपयोग करें।
grep -RInE 'exec(Sync)?[[:space:]]*\(' --include='*.js' --include='*.cjs' --include='*.mjs' --include='*.ts' .अक्सर पूछे जाने वाले प्रश्न
execSync() वही shell-based command string उपयोग करता है, इसलिए injection का वही जोखिम है और यह event loop को block भी करता है। execFileSync() डिफ़ॉल्ट रूप से shell parsing से बचता है, लेकिन executable और arguments फिर भी validate करें।