首页 > 解决方案 > 带有少量命令的 Bash,将少量内置命令列入白名单

问题描述

尝试打开命令能力有限的 bash shell。

尝试了 -r 限制等命令行选项,但没有给出预期的结果。还尝试了 shopt & unset 命令。

bash --noprofile --noediting --verbose --version --init-file test.sh

unset ls

shopt -u -o history

仅使用很少的内置命令启动 bash shell。例如,仅限 cd、ls、cat。这种外壳的使用将用于目录导航、列表和文件查看目的的只读目的

标签: bashshellbuilt-in

解决方案


您可以获取所有内置函数的列表并声明具有相同名称的函数。

我是这样做的:

文件bash_limited.sh

#!/bin/bash


export PATH=
eval "$(
echo '
:
.
[
alias
bg
bind
break
builtin
caller
cd
command
compgen
complete
compopt
continue
declare
dirs
disown
echo
enable
eval
exec
exit
export
fc
fg
getopts
hash
help
history
jobs
kill
let
local
logout
mapfile
popd
printf
pushd
pwd
read
readarray
readonly
return
set
shift
shopt
source
test
times
trap
type
typeset
ulimit
umask
unalias
unset
wait
' |
while IFS= read -r line; do
    case "$line" in
    ''|ls|cat|cd|return|printf) continue; ;; 
    esac

    printf "%s\n" "function $line () { /bin/printf -- 'bash: $line: Command not found.\n' >&2; return 127; }"
done

echo 'function ls() { /bin/ls "$@"; }'
echo 'function cat() { /bin/cat "$@"; }'

)" ## eval

然后我打开一个新的 shell 并执行以下操作:

$ source bash_limited.sh

之后它只是:

$ .
bash: .: Command not found.
$ :
bash: :: Command not found.
$ source
bash: source: Command not found.
$ declare
bash: declare: Command not found.

您还可以使用一些chroot具有其他 PATH 限制的技术,并且很难摆脱。


推荐阅读