2

如何防止 bash 脚本中的目录遍历攻击,其中参数包含目录名称?

例子:

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

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

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

4

2 回答 2

1

像这样的东西?

#! /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}*确定解析的路径是否以预期的字符串开头
于 2020-06-25T13:53:56.903 回答
0

该脚本应以仅有权访问必要目录的用户身份运行。

于 2020-06-25T13:19:26.837 回答