是否可以在shell脚本中使用命令注入而不使用eval?

时间:2022-01-07 09:56:21

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(env变量)。

2 个解决方案

#1


1  

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

#2


1  

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 single word:

如果这样写,你永远不知道是否有一个shell实现可能会被欺骗。但是,通过将locate的参数放在引号中,您可以安全地使用。然后,展开的参数将被视为单个单词:

#!/bin/sh

echo "What is the name of the program you are looking for?"
read program
locate "${program}"

#1


1  

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

#2


1  

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 single word:

如果这样写,你永远不知道是否有一个shell实现可能会被欺骗。但是,通过将locate的参数放在引号中,您可以安全地使用。然后,展开的参数将被视为单个单词:

#!/bin/sh

echo "What is the name of the program you are looking for?"
read program
locate "${program}"