0 Tage Serie
javascript / intermediate
Snippet

Sichere Prozessausführung mit ExecFile-Argumenten

Die Verwendung von `execFile` aus `node:child_process` verhindert Shell-Injection-Schwachstellen. Im Gegensatz zu `exec`, das Befehle in einem Shell-Interpreter ausführt, übergibt `execFile` Argumente direkt als Array-Elemente ohne Shell-Expansion an das Programm.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { execFile } from 'node:child_process';
const userInputFilename = 'report.txt; rm -rf /';
execFile('ls', ['-la', userInputFilename], (error, stdout, stderr) => {
if (error) {
console.error(`Execution error: ${error.message}`);
return;
}
console.log(`Directory listing:\n${stdout}`);
});
nodejs
Erklärung
1
import { execFile } from 'node:child_process';
Importiert die Funktion zur direkten Ausführung von Programmen ohne Aufruf einer Shell.
2
execFile('ls', ['-la', userInputFilename], (error, stdout, stderr) => {
Übergibt potenziell unsichere Eingaben sicher in einem Array und neutralisiert so Command-Injection-Vektoren.