如何在 Linux 中限制用户命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21498667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:56:26  来源:igfitidea点击:

How to limit user commands in Linux

linuxbashcommandrestriction

提问by mortezaipo

I have a user in a group : "demo".

我在一个组中有一个用户:“演示”。

I wanna set the policy that this users just can run 10 commands, like "vim","nano","cd" and etc.

我想设置这个用户只能运行 10 个命令的策略,比如“vim”、“nano”、“cd”等。

Or, set the policy to have access on all commands except "ssh" and "cat" commands.

或者,将策略设置为可以访问除“ssh”和“cat”命令之外的所有命令。

Thanks

谢谢

采纳答案by Dodzi Dzakuma

There are lots of different ways that you could achieve this. I'm going to list one of several possible solutions.

有很多不同的方法可以实现这一目标。我将列出几种可能的解决方案之一。

I would propose using several different layers of protection to prevent users from running the commands that they shouldn't be allowed to access. All of the directions here assume that users have their own /home/[username]directory, that their shell is /bin/bashand you would like them to be use the bash shell when they log in to the system.

我建议使用几个不同的保护层来防止用户运行他们不应该被允许访问的命令。这里的所有说明都假设用户有自己的/home/[username]目录,他们的 shell 是,/bin/bash并且您希望他们在登录系统时使用 bash shell。

1) Change the user's bash to restricted bash mode so that they can't change directories(if you don't have a restricted bash mode on your system, this linkwill help and give you more information) chsh -s /bin/rbash [username]

1)将用户的 bash 更改为受限 bash 模式,以便他们无法更改目录(如果您的系统上没有受限 bash 模式,此链接将有所帮助并为您提供更多信息) chsh -s /bin/rbash [username]

2) Change directory permissions so that only the user can edit the contents of their home directory

2) 更改目录权限,以便只有用户可以编辑其主目录的内容

chmod 755 /home/[username]

chmod 755 /home/[username]

3) Remove the user's .bashrcfile

3) 删除用户的.bashrc文件

rm /home/[username]/.bashrcThis sitehas more information as to why it might be a good idea to delete the .bashrcin this situation.

rm /home/[username]/.bashrc这个站点有更多关于为什么.bashrc在这种情况下删除它可能是个好主意的信息。

4) Create a .bash_profileand add "safe" aliases for all the commands that you would like to disable

4).bash_profile为要禁用的所有命令创建一个并添加“安全”别名

./bash_profile file example

./bash_profile 文件示例

alias apt-get="printf ''"  
alias aptitude="printf ''"  
[...]  
alias vi="vi -Z" #this is vi's safe mode and shell commands won't be run from within vi
alias alias="printf ''"  

A please check the full list of bash commandsfor more information. You must make sure that the alias alias="printf ''"command is the last command on the list otherwise you lose your ability to alias all of those commands.

A 请查看完整的 bash 命令列表以获取更多信息。您必须确保该alias alias="printf ''"命令是列表中的最后一个命令,否则您将失去为所有这些命令设置别名的能力。

NoteRunning the commands below will search for almost all the commands available on your system and output a ready made file will almost all available commands pre-aliased. The [command is the testcommandin bash. So if you see that in the file, it is not an error.

注意运行下面的命令将搜索系统上几乎所有可用的命令,并输出一个现成的文件,几乎所有可用的命令都将预先设置别名。该[命令是testbash 中命令。因此,如果您在文件中看到它,则这不是错误。

#search /bin and /usr/bin for any commands that exist on our system
ls /bin -1 > commands_on_system.txt && ls /usr/bin -1 >> commands_on_system.txt

#format and save this information to a bash variable
IFS=$'\n' GLOBIGNORE='*' command eval  'COMMANDS_ON_SYSTEM=($(cat ./commands_on_system.txt))'
IFS=$'\n' COMMANDS_ON_SYSTEM=($(sort <<<"${COMMANDS_ON_SYSTEM[*]}"))
unset IFS

#save these commands in aliased format for easy usage
for linux_command in "${COMMANDS_ON_SYSTEM[@]}"
do :
   #you can change how this works to automatically
   #setup the command file for you 
   echo "alias ${linux_command}=\"printf ''\"" >> ./startup_functions_for_beginners.sh
done

5) Disable shell commands in vi by aliasing the vi command to restricted mode
The syntax is alias vi="vi -Z", but please see this sitefor more information.

5) 通过将 vi 命令别名为受限模式来禁用 vi 中的 shell 命令
语法为alias vi="vi -Z",但请参阅此站点以获取更多信息。

6) Change the ownership of the user's .bash_profileto root
chown root:root /home/[username]/.bash_profile

6)将用户的所有权更改.bash_profile为root
chown root:root /home/[username]/.bash_profile

7) Finally, remove write permissions on the user's .bash_profile
chmod 755 /home/[username/.bash_profile]

7)最后,删除用户的写权限 .bash_profile
chmod 755 /home/[username/.bash_profile]

Now when the users log in they won't be able to change directories, all of the commands that you don't want them to use will output the same information as if the user pressed the [ENTER]key with no command specified, and your /bin/bashfunctions stay intact.

现在,当用户登录时,他们将无法更改目录,您不希望他们使用的所有命令都将输出相同的信息,就像用户按下[ENTER]未指定命令的键一样,您的/bin/bash功能将保持不变完整。

Depending on what functions you choose to or not to alias this way, users may still be able to circumvent some of the controls that you implemented. However, since we implemented a few safety buffers, the user would really have to know about computer systems to do any dangerous.

根据您选择或不以这种方式别名的功能,用户可能仍然能够绕过您实施的某些控件。然而,由于我们实现了一些安全缓冲区,用户真的必须了解计算机系统才能做任何危险的事情。

On a related note and something that you might want to consider, if you directly place these aliases into each and every users' .bash_profileyou would have difficulty maintaining which functions should and shouldn't be aliased, and if you need to change the alias on anything you would have to change all of them individually. Also, since users can use vimor vito view files, they could see the contents of their .bash_profileand understand what restrictions they have and don't have.

在相关说明和您可能想要考虑的事情上,如果您直接将这些别名放入每个用户的中,.bash_profile您将难以维护哪些功能应该和不应该使用别名,并且如果您需要更改任何别名您必须单独更改所有这些。此外,由于用户可以使用vimvi查看文件,他们可以查看文件的内容.bash_profile并了解他们有哪些限制和没有哪些限制。

To get around this I would suggest.

为了解决这个问题,我建议。

1) Putting all of the aliases in a directory not accessible by the users (paste the contents of the .bash_profilehere)

1) 将所有别名放在用户无法访问的目录中(粘贴.bash_profile此处的内容)

/[path_to_file]/startup_functions_for_beginners.sh

/[path_to_file]/startup_functions_for_beginners.sh

2) Sourcing the aliases into their .bash_profile

2)将别名采购到他们的 .bash_profile

improved ./bash_profile file example

改进的 ./bash_profile 文件示例

if [[ -f /[path_to_file]/startup_functions_for_beginners.sh ]]; then
    . /[path_to_file]/startup_functions_for_beginners.sh
fi

This should put you on your way, but remember that there are almost always ways to circumvent restrictions.

这应该让您继续前进,但请记住,几乎总有方法可以规避限制。

Also, feel free to remix the information in this answer to suit your needs. These can most definitely be combined with a number of other restrictions as well.

此外,请随意重新混合此答案中的信息以满足您的需求。这些绝对可以与许多其他限制相结合。

Q: I need users to have access to fgand bg, but I don't want them to be able to access aptitudeor bash

问:我需要用户有权访问fgbg,但我不希望他们能够访问aptitudebash

alias apt-get="printf ''"  #the user won't be able to run this  
alias aptitude="printf ''"  #the user won't be able to run this  
alias bash="printf ''"  #the user won't be able to run this  
#alias fg="printf ''" #this will run as a bash built-in  
#alias bg="printf ''" #you actually don't need to include these in your script  

List of common commands as per this Harvard Website(NOT EXHAUSTIVE)

根据此哈佛网站的常用命令列表(非详尽)

As you install programs to Linux what you have available to you changes. I suggest that you run the commands listed above in step 4 to help find new commands after they have been installed.

当您将程序安装到 Linux 时,您可以使用的内容会发生变化。我建议您运行上面第 4 步中列出的命令,以帮助在安装后查找新命令。

caution should be taken care of with editors because some allow for the excution of shell commands from within the program

编辑器应该小心,因为有些编辑器允许从程序内部执行 shell 命令

nano
emacs
pico
sed
vi
vim  

Everything Else

其他一切

exit
logout
passwd
rlogin
ssh
slogin
yppasswd
mail
mesg
pine
talk
write
as
awk
bc
cc
csh
dbx
f77
gdb
gprof
kill
ld
lex
lint
make
maple
math
nice
nohup
pc
perl
prof
python
sh
yacc
xcalc
apropos
find
info
man
whatis
whereis
cd
chmod
chown
chgrp
cmp
comm
cp
crypt
diff
file
grep
gzip
ln
ls
lsof
mkdir
mv
pwd
quota
rm
rmdir
stat
sync
sort
tar
tee
tr
umask
uncompress
uniq
wc
cat
fold
head
lpq
lpr
lprm
more
less
page
pr
tail
zcat
xv
gv
xpdf
ftp
rsync
scp
alias
chquota
chsh
clear
echo
pbm
popd
pushd
script
setenv
stty
netstat
rsh
ssh
bg
fg
jobs
^y
^z
clock
date
df
du
env
finger
history
last
lpq
manpath
printenv
ps
pwd
set
spend
stty
time
top
uptime
w
who
whois
whoami
gimp
xfig
xv
xvscan
xpaint
kpaint
mplayer
realplay
timidity
xmms
abiword
addbib
col
diction
diffmk
dvips
explain
grap
hyphen
ispell
latex
pdfelatex
latex2html
lookbib
macref
ndx
neqn
nroff
pic
psdit
ptx
refer
roffbib
sortbib
spell
ispell
style
tbl
tex
tpic
wget
grabmode
import
xdpyinfo
xkill
xlock
xterm
xwininfo
html2ps
latex2html
lynx
netscape
sitecopy
weblint

回答by abligh

The standard answer would be to use a restricted shell, making this the last entry in the password file for users in that group. As you can run external commands from things like vim: http://web.physics.ucsb.edu/~pcs/apps/editors/vi/vi_unix.html

标准答案是使用受限 shell,使其成为该组用户密码文件中的最后一个条目。因为您可以从 vim 之类的东西运行外部命令:http: //web.physics.ucsb.edu/~pcs/apps/editors/vi/vi_unix.html

this does not seem like a great idea if you are trying to produce a restricted environment. The first thing a user could do is use the commands in the above link to run /bin/bashand he'd be outside the restricted environment.

如果您尝试创建受限环境,这似乎不是一个好主意。用户可以做的第一件事是使用上面链接中的命令来运行/bin/bash,他会在受限环境之外。

A better idea would be to put each user's login into a chroot jail or perhaps a lightweight container (so if they break anything it's their own container). Have a look at Docker - http://docker.io.

一个更好的主意是将每个用户的登录信息放入一个 chroot jail 或一个轻量级容器中(因此如果他们破坏了任何东西,那就是他们自己的容器)。看看 Docker - http://docker.io

回答by AnythingIsFine

I know I'm late to the party, 2 years late in fact, but I stumbled on a workaround for your situation just now. I had a user, let's call him "test1" that needed to have some commands restricted, like "su", but the rest should be available. To apply this restriction I just used ACL (assuming you have acls enabled on your FS) on the binary file behind the command itself like so:

我知道我参加聚会迟到了,实际上已经晚了 2 年,但我刚刚偶然发现了一种解决您情况的方法。我有一个用户,让我们称他为“test1”,需要限制一些命令,例如“su”,但其余的应该可用。为了应用此限制,我只是在命令本身后面的二进制文件上使用了 ACL(假设您在 FS 上启用了 acls),如下所示:

setfacl -m u:test1:r /bin/su

setfacl -mu:test1:r /bin/su

The above command changes the permissions for that specific binary file, which is in fact the "su" command, to grant user "test1" only read access to that file. As such, when user "test1" tries to "execute" the "su" command he can't run the script behind it and gets "Permission denied".

上面的命令更改了该特定二进制文件的权限,实际上是“su”命令,授予用户“test1”对该文件的只读访问权限。因此,当用户“test1”尝试“执行”“su”命令时,他无法运行其背后的脚本并获得“权限被拒绝”。

Just run "which command_you_want_restricted" to see the file behind it.

只需运行“which command_you_want_restricted”即可查看其背后的文件。

I have tested this method on Red Hat 6.5 & 7 and it just affects user "test1", all the other users can continue running "su" at will.

我已经在 Red Hat 6.5 & 7 上测试过这个方法,它只影响用户“test1”,所有其他用户可以继续随意运行“su”。

As for you specific request:

至于你的具体要求:

"Or, set the policy to have access on all commands except "ssh" and "cat" commands."

“或者,将策略设置为可以访问除“ssh”和“cat”命令之外的所有命令。”

You can do the same thing with ACLs for the group "demo" on the command binaries you wish, but I HAVE NOT TESTED this with groups and I suggest you try it on a test VM or something beforehand.

您可以对您希望的命令二进制文件中的组“演示”使用 ACL 执行相同的操作,但我尚未对组进行测试,我建议您事先在测试 VM 或其他设备上进行尝试。

Regards,

问候,

回答by Robbert

I'm a bit surprised that nobody yet used the native SSH functionality in their answer... I know I'm 4 years late but it could still be handy :)

我有点惊讶,没有人在他们的回答中使用原生 SSH 功能......我知道我迟到了 4 年,但它仍然很方便:)

When using SSH you should use keys for logging in; as we are talking about securing a server, disabling password login should be one of the first things you should do. So, as you are using keys, you now have the ability to allow only one single command per key by adding this in the authorized_keys file:

使用 SSH 时,您应该使用密钥登录;当我们谈论保护服务器时,禁用密码登录应该是您应该做的第一件事。因此,当您使用密钥时,您现在可以通过在 authorized_keys 文件中添加以下内容来允许每个密钥只执行一个命令:

command="only" ssh-rsa AAABBBCC....

The onlycommand is a whitelisting feature which allows the user to run only those commands. You do not have to make exceptions on your system(s) by changing the default binary permissions (which is an admin hell..). Make sure you set the authorized_keysfile to be non-writable for the user.

only命令是白名单功能,允许用户仅运行这些命令。您不必通过更改默认的二进制权限(这是管理员地狱..)来在您的系统上设置例外。确保将authorized_keys文件设置为用户不可写。

The only command is a script that must be installed in /usr/bin/with 775 permissions.

唯一的命令是必须/usr/bin/以 775 权限安装的脚本。

Read all about it: The OnlyWay For SSH Forced Commands

阅读所有相关信息:SSH 强制命令唯一方法

Now you understand how it works, you can simply whitelist any command that you allow the user to execute:

现在您了解了它的工作原理,您可以简单地将允许用户执行的任何命令列入白名单:

command="only cal cowsay factor figlet fortune" ssh-rsa AAABBBCC....

Or use an .onlyrulesfile with the proper syntax, be careful not to use any greedy regex..

或者使用.onlyrules具有正确语法的文件,注意不要使用任何贪婪的正则表达式。

  ----------------------
  <   I'm restricted   >
  ----------------------
         \   ^__^ 
          \  (oo)\_______
             (__)\       )\/\
                 ||----w |
                 ||     ||

回答by Victor Wong

@Dodzi Dzakuma solution is great if you only have a few commands that you wish to disable.

如果您只有几个要禁用的命令,@Dodzi Dzakuma 解决方案非常棒。

However if you only want to allow the user to run several commands, here is a better solution:

但是,如果您只想允许用户运行多个命令,这里有一个更好的解决方案:

  1. Change the user shell to restricted bash

    chsh -s /bin/rbash <username>
    
  2. Create a bin directory under the user home directory

    sudo mkdir /home/<username>/bin
    sudo chmod 755 /home/<username>/bin
    
  3. Change the user's default PATH to the bin directory

    echo "PATH=$HOME/bin" >> /home/<username>/.bashrc
    echo "export PATH >> /home/<username>/.bashrc
    
  4. Create symlinks of the command(s) that the user require

    sudo ln -s /bin/<command> /home/<username>/bin/
    
  5. Restrict the user from modifying ~/.bashrc

    chattr +i /home/<username>/.bashrc
    
  1. 将用户 shell 更改为受限 bash

    chsh -s /bin/rbash <username>
    
  2. 在用户家目录下创建bin目录

    sudo mkdir /home/<username>/bin
    sudo chmod 755 /home/<username>/bin
    
  3. 将用户的默认PATH更改为bin目录

    echo "PATH=$HOME/bin" >> /home/<username>/.bashrc
    echo "export PATH >> /home/<username>/.bashrc
    
  4. 创建用户需要的命令的符号链接

    sudo ln -s /bin/<command> /home/<username>/bin/
    
  5. 限制用户修改 ~/.bashrc

    chattr +i /home/<username>/.bashrc
    

This is better IF you only want to allow the user to run several commands because instead of setting aliases of ALL commands to disable, you only set the symlink of the commands that you wish to allow.

如果您只想允许用户运行多个命令,这会更好,因为不是将所有命令的别名设置为禁用,而是只设置您希望允许的命令的符号链接。

回答by Shammi Shailaj

I have faced a similar situation at my organization where I had to restrict people to access only certain commands.

我在我的组织中遇到过类似的情况,我不得不限制人们只能访问某些命令。

So far, I have found 2 different ways to do it.

到目前为止,我已经找到了 2 种不同的方法来做到这一点。

  1. The onlyapproach
  2. Having a different Shell altogether viz. rbash, lshell, dockersh
  1. 唯一途径
  2. 完全有一个不同的 Shell,即。rbash, lshell, dockersh

Here are my thoughts on the same.

以下是我对此的看法。

  1. Take the only approach if you want the users to login and execute a certain command and then exit the shell entirely. Its better to you couple it with Rbash.

  2. Out of the 3 shells, I feel lshellwould be the easiest to implement especially if you are on Ubuntu and its derivatives. You just have to install a package via apt and then edit the configuration. It is the simplest.

  1. 如果您希望用户登录并执行某个命令,然后完全退出 shell,请采用唯一的方法。最好将它与Rbash 结合使用

  2. 在 3 个 shell 中,我觉得lshell是最容易实现的,尤其是如果您使用的是 Ubuntu 及其衍生产品。你只需要通过 apt 安装一个包,然后编辑配置。这是最简单的。

The rbashis good for basic stuff like blocking redirection and certain characters on the cli but to do the advanced stuff like whitelisting certain commands, you would need to go the extra mile.

rbash是好基本的东西像上阻塞CLI重定向和某些字符但要做到像白名单某些命令先进的东西,你就需要多走一英里。

Dockershis a completely fresh and modern approach to restricting shells. Here you allow everything but you limit all the user's action to a container.

Dockersh是一种全新且现代的限制 shell 的方法。在这里,您允许所有内容,但将所有用户的操作限制在一个容器中。

In my use-case, I had to limit my users to a single command with shell based redirection , piping etc. turned-off hence I chose lshell. Took hardly 5 minutes to configure. Find details here.

在我的用例中,我不得不将我的用户限制为一个命令,并关闭基于 shell 的重定向、管道等,因此我选择了lshell。花了不到 5 分钟的时间进行配置。在此处查找详细信息。