sanitize user input for child_process.exec command

旧街凉风 提交于 2020-06-13 19:32:05

问题


I'm writing a CLI using node and I've arrived at the part where I take user input and append it to a string that is the command for the child_process.exec function.

const CURL_CHILD = exec('npm view --json ' + process.argv[2] + ...

I am trying to figure out what I need to do to process.argv[2] before I pass it to the exec function. I've surfed around for a while and haven't found any questions or answers that address this specific case.

What is the best way to sanitize this user input for this particular use case? What is actually needed here?

Update I'm still surfing around trying to learn and answer my own question and found this link which suggests I use js-string-escape (a node package). I'd really like to use something native/vanilla to do this. Does node have any tools for this?

Update 2

I finally stumbled upon the buzzwords "command injection" and found a slew of articles recommending the use of child_process.execFile or child_process.spawn. I'm still curious if there is a native way to sanitize the input, while still securing the full shell process created by child_process.exec. I am leaving this open in hopes someone can answer it.


回答1:


Your user input arguments may contain variable chars that the shell is going to interpret them in its own way. So for instance, in Linux, $ has a special meaning.

If you want to use such argument as-is avoiding the shell interpretation, you have to escape them. The same we do with some special chars in HTML (eg. < and > has special meaning so we use to escape them in HTML like &lt; and respectively &gt;). The same applies here.

So the answer to your question is first to find out the special chars in your shell/environment and escape them.

A good rule of thumb is to escape chars like double-quote ", single-quote ', space , the dollar-sign $ (because it's an Illuminati symbol, right? ;-), the grave-accent ` and obviously the backslash \.

So let's suppose that your command is the one below. To escape it just use some simple regex like this:

cmd = "npm view --json " + process.argv[2];
escapedCmd = cmd.replace(/(["\s'$`\\])/g,'\\$1');

I hope it helps :-)




回答2:


Try the npm package escape-it. Should work with *nix OSes, but has some support for Windows, too.



来源:https://stackoverflow.com/questions/49512370/sanitize-user-input-for-child-process-exec-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!