bash 是否可以在不使用 eval 的情况下在 shell 脚本中注入命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30071006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is command injection possible within shell scripts without the use of eval?
提问by aentgood
I was wondering, nowadays with the most recent versions of sh, bash, ksh etc. is it possible to get command injection by executing this (very simple) script?
我想知道,现在使用最新版本的 sh、bash、ksh 等是否可以通过执行这个(非常简单的)脚本来获得命令注入?
#!/bin/sh
echo "What is the name of the program you are looking for?"
read program
locate $program
Despite of the fact that one can already execute code if they have a shell of course, I am just wondering if a variable can contain malicious code like for example in PHP:
尽管事实上如果他们有一个 shell 当然已经可以执行代码了,我只是想知道一个变量是否可以包含恶意代码,例如在 PHP 中:
parameter=parameter;ls
Also shellshock (env variables) can be ignored in this question.
在这个问题中也可以忽略 shellshock(环境变量)。
采纳答案by Azize
Yes, it is possible. But it is not so simple as you mention. See below some example.
对的,这是可能的。但是没有你说的那么简单。请参阅下面的一些示例。
It will not works:
它不会工作:
$ read -p "Type some text:" var1
Type some text:Example;hostname
$ echo $var1
Example;hostname
$ $var1
Example;hostname: command not found
But if you use like this, yes, it will work:
但是如果你这样使用,是的,它会起作用:
$ read -p "Type some text:" var1
Type some text:hostname
$ echo $var1
hostname
$ $var1
SSBLZMVM1
回答by user1978011
If written like that, you never know if there isn't a shell implementation out there which could be tricked like that. You can be on the safe side however by putting the argument of locate in quotation marks. Then the expanded parameter will be treated as a singleword:
如果这样写,你永远不知道是否有一个 shell 实现可以像那样被欺骗。但是,您可以通过将 locate 的参数放在引号中来确保安全。然后扩展参数将被视为单个单词:
#!/bin/sh
echo "What is the name of the program you are looking for?"
read program
locate "${program}"