如何防止 bash 脚本中的目录遍历攻击,其中参数包含目录名称?
例子:
$STAGE=$1
$APP=$2
deploy.sh dist/ /opt/apps/"$STAGE"/"$APP"
$STAGE
和$APP
变量是从外部设置的。攻击者可以将其更改为任意路径".."
。
我知道通常的解决方案是将目录字符串与返回绝对路径的函数的结果进行比较。但我找不到现成的解决方案,也不想提出自己的解决方案。
如何防止 bash 脚本中的目录遍历攻击,其中参数包含目录名称?
例子:
$STAGE=$1
$APP=$2
deploy.sh dist/ /opt/apps/"$STAGE"/"$APP"
$STAGE
和$APP
变量是从外部设置的。攻击者可以将其更改为任意路径".."
。
我知道通常的解决方案是将目录字符串与返回绝对路径的函数的结果进行比较。但我找不到现成的解决方案,也不想提出自己的解决方案。
像这样的东西?
#! /bin/bash
STAGE=$1
APP=$2
expectedParentDir="/opt/apps/"
function testDir(){
arg=$1
if [[ ! -f $arg ]]
then
echo "File $arg does not exist."
exit 1
fi
rpath=$(realpath $arg)
if [[ $rpath != ${expectedParentDir}* ]]
then
echo "Please only reference files under $expectedParentDir directory."
exit 2
fi
}
testDir /opt/apps/"$STAGE"/"$APP"
... deploy ...
示例调用
test.sh "../../etc/" "passwd"
Please only reference files under /opt/apps/ directory.
------------
test.sh "../../etc/" "secret"
File /opt/apps/../../etc//secret does not exist.
-f
或使用测试文件的存在-d
realpath
解析路径== ${expectedParentDir}*
确定解析的路径是否以预期的字符串开头该脚本应以仅有权访问必要目录的用户身份运行。