Node.js:为exec()清理不受信任的用户输入 [英] Node.js: Sanitize untrusted user input for exec()
问题描述
一个小示例,从REST API node.js应用程序简化而来:
Small example, reduced from a REST API node.js app:
const { exec } = require('child_process');
var userInput = 'untrusted source';
var cmd = `/bin/echo "${userInput}"`;
exec(cmd, function(err, stdout, stderr) {
console.log('echo: ' + stdout);
});
假设 userInput
来自不受信任的来源,那么需要做些什么来避免任何漏洞?例如,用 echo
引用的"$ {userInput}"
参数可避免输入'evil.rm -rf/'
不会造成损坏.要保持安全还需要做些什么?
Assuming the userInput
is from an untrusted source, what needs to be done avoid any vulnerability? For example, the quoted "${userInput}"
parameter for echo
avoids input 'evil spirit; rm -rf /'
from causing damage. What else needs to be done to stay safe?
更新:目标是通过int ra 网络上的REST API使文件系统中的一些现有Shell脚本/命令可用.
Update: The objective is to make a few existing shell scripts/commands in the file system available via a REST API on the intranet.
推荐答案
基于官方Node.js child_process
文档,网址为
Based on the official Node.js child_process
doc at https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options it is (obviously) unsafe to use user input in shell scripts without sanitizing it:
如果启用了shell选项,请不要将未经处理的用户输入传递给此功能.任何包含外壳元字符的输入都可以用于触发任意命令执行.
If the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.
因此,这是我的问题中提到的示例,使用spawn而不是exec以安全的方式重写了该示例:
So, here is the example stated in my question, rewritten in a safe way using spawn instead of exec:
const { spawn } = require('child_process');
var userInput = 'untrusted source';
var args = [ userInput ];
var cmd = '/bin/echo';
var subprocess = spawn(cmd, args);
var stderr = '';
var stdout = '';
subprocess.stdout.on('data', function(data) {
stdout += data;
});
subprocess.stderr.on('data', function(data) {
stderr += data;
});
subprocess.on('close', function(exitCode) {
console.log('echo: ' + stdout);
});
这是CLI包装器Node.js应用程序的简化代码段,可通过REST API以安全的方式使内部网络上的现有命令和Shell脚本可用:
This is a simplified code snippet of a CLI wrapper Node.js app that make existing commands and shell scripts on an internal network available in a secure way via a REST API: https://github.com/peterthoeny/rest-cli-io
这篇关于Node.js:为exec()清理不受信任的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!