Chroot限制用户权限
-
创建chroot目录
# mkdir -p /home/test/{bin,dev,etc}
-
使用
mknod
命令创建/dev
下的文件。在下面的命令中,-m
标志用来指定文件权限位,c
意思是字符文件,两个数字分别是文件指向的主要号和次要号。
# cd /home/test/dev/
# mknod -m 666 null c 1 3
# mknod -m 666 tty c 5 0
# mknod -m 666 zero c 1 5
# mknod -m 666 random c 1 8
- 在此之后,在 chroot 监狱中设置合适的权限。注意 chroot 监狱和它的子目录以及子文件必须被
root
用户所有,并且对普通用户或用户组不可写:
# chown root:root /home/test
# chmod 0755 /home/test
# ls -ld /home/test
- 首先,创建
bin
目录并复制/bin/bash
到bin
中:
# cp -v /bin/bash /home/test/bin/
- 现在,识别 bash 所需的共享库,如下所示复制它们到
lib64
中:
# ldd /bin/bash
# mkdir -p /home/test/lib64
# cp -v /lib64/{libtinfo.so.5,libdl.so.2,libc.so.6,ld-linux-x86-64.so.2} /home/test/lib64/
觉得麻烦的话直接将 /usr/lib64 整个目录复制过来,后续只要复制需要的命令即可
# cp -r /usr/lib64 /home/test/
- 使用 useradd 命令创建 SSH 用户,并设置安全密码:
# useradd testint
# passwd testint
- 复制已更新的账号文件(
/etc/passwd
和/etc/group
)到/home/test/etc中:
# cp -vf /etc/{passwd,group} /home/test/etc/
注意:每次向系统添加更多 SSH 用户时,都需要将更新的帐户文件复制到 /home/test/etc 目录中。
-
配置ssh , 现在打开
sshd_config
文件。# vi /etc/ssh/sshd_config
在此文件中添加或修改下面这些行。
# 定义要使用 chroot 监狱的用户 Match User testint # 指定 chroot 监狱 ChrootDirectory /home/test
保存文件并退出,重启 sshd 服务:
-
测试 chroot 监狱的设置是否如希望的那样成功了:
# ssh testint@192.168.2.15
testint@192.168.2.15's password:
Last login: Thu May 28 11:50:02 2020 from 192.168.2.28
-bash-4.2$ ls
-bash: ls: command not found
-bash-4.2$ pwd
/
-bash-4.2$ date
-bash: date: command not found
我们可以看到 SSH 用户被锁定在了 chroot 监狱中,并且不能使用任何外部命令如(ls
、date
、uname
等等)。
用户只可以执行 bash
以及它内置的命令(比如:pwd
、history
、echo
等等):
- 从上面的步骤中,我们可以看到用户被锁定在了 root 目录,我们可以为 SSH 用户创建一个主目录(以及为所有将来的用户这么做):
```
# mkdir -p /home/test/home/testint
# chown -R testint:testint /home/test/home/testint
# chmod -R 0700 /home/test/home/testint
```
- 在
bin
目录中安装几个用户命令,如ls
、date
、 grep、awk、cat、vi、tail等命令
```
# cp -v /bin/ls /home/test/bin/
# cp -v /usr/bin/cat /home/test/bin/
...
# ls /home/test/bin/
awk bash cd cat date grep head ls netstat ping tail vi
//检查上面命令的共享库并将它们移到 chroot 监狱的库目录中:看第5步
```
-
将命令都添加到环境变量里
# echo "export PATH=$PATH:/bin" > /home/test/etc/profile # source /home/test/etc/profile
-
使用ping命令还要一些操作
# chmod u+s /home/test/bin/ping # cp /etc/resolv.conf /home/test/etc //dns
-
挂载日志存放目录
# mkdir /home/test/logs # mount --bind /var/log/ /home/test/logs/ //只是临时,将这条命令加到/etc/rc.local 开机挂载;如果还需要其它目录 也是同样的道理
参考网址 http://www.imooc.com/article/80589