在参数包含目录名称的bash脚本中,如何防止目录遍历攻击?
示例:
$STAGE=$1
$APP=$2
deploy.sh dist/ /opt/apps/"$STAGE"/"$APP"
$STAGE
和$APP
变量是从外部设置的。攻击者可以使用".."
将其更改为任意路径。
我知道通常的解决方案是将目录字符串与返回绝对路径的函数的结果进行比较。但是我找不到合适的解决方案,也不想提出自己的解决方案。
答案 0 :(得分:0)
该脚本应以仅具有访问必要目录权限的用户身份运行。
答案 1 :(得分:0)
像这样吗?
#! /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}*
来确定解析路径是否以预期的字符串开头