防止bash脚本中的目录遍历漏洞

时间:2020-06-25 13:14:29

标签: bash directory-traversal

在参数包含目录名称的b​​ash脚本中,如何防止目录遍历攻击?

示例:

$STAGE=$1
$APP=$2
deploy.sh dist/ /opt/apps/"$STAGE"/"$APP"

$STAGE$APP变量是从外部设置的。攻击者可以使用".."将其更改为任意路径。

我知道通常的解决方案是将目录字符串与返回绝对路径的函数的结果进行比较。但是我找不到合适的解决方案,也不想提出自己的解决方案。

2 个答案:

答案 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.
  1. 使用-f测试文件是否存在,或者如果目标必须是目录,则使用-d
  2. 使用realpath来解析路径
  3. 使用== ${expectedParentDir}*来确定解析路径是否以预期的字符串开头
相关问题