admin管理员组

文章数量:1542784

服务器root权限安全策略配置

linux系统中,root具有至高无上的权限,为了安全起见,项目生产环境一般会要求禁止root用户直接ssh登录,使用普通用户登录,有特殊需求时,特定组用户可以使用su切换到root用户,或sudo切换到root权限进行操作。

❗️❗️❗️ 注意: 整改有风险,请确认整改后的可能影响,并谨慎操作!

禁止root用户直接ssh登录

  1. 新建用户并设置密码
useradd admin && echo password123 | passwd --stdin admin


2. 将新用户加入sudoers

cat /etc/sudoers |grep -A 2 "## Allow root to run"                    # 显示匹配行和之后的2行
sed -i '/## Allow root to run/a\admin\tALL=(ALL)\tALL' /etc/sudoers   # 关键字匹配行之后插入一行
cat /etc/sudoers |grep -A 2 "## Allow root to run"


3. 用户登录和su测试

echo $UID
su
echo $UID


4. 日常运维操作测试

kubectl get pod -A
sudo kubectl get pod -A | grep -iv run
sudo kubectl get pod -A |wc -l
sudo kubectl get pod -A


5. 禁用root用户ssh登录

sed -i 's/PermitRootLogin yes/#PermitRootLogin yes/g' /etc/ssh/sshd_config    # 添加注释
cat /etc/ssh/sshd_config |grep PermitRootLogin
systemctl restart sshd


6. 再次登录测试
预期:
root用户无法ssh登录,新建用户ssh登录正常,sudo权限使用正常,可以su切换到root
验证:
root用户ssh登录失败

已加入sudoers的新建用户ssh登录正常,sudo权限使用正常,su切换到root正常

未加入sudoers用户ssh登录正常,不能使用sudo,但su切换到root正常

如果需要设置sudo的超时时间,请点击文末的链接查阅参考。

限制用户su切换到root

  1. 新建用户并加入wheel组
useradd abc && echo password123 | passwd --stdin abc
usermod -G wheel abc

或将已有用户加入wheel组

usermod -G wheel admin


2. 设置只允许wheel组用户使用su命令切换到root

cat /etc/pam.d/su |grep "pam_wheel.so use_uid"
sed -i '/pam_wheel.so use_uid/s/^#//' /etc/pam.d/su          # 去掉注释
cat /etc/pam.d/su |grep "pam_wheel.so use_uid"

echo "SU_WHEEL_ONLY yes" >> /etc/login.defs                  # 文末追加
tail /etc/login.defs


3. 验证测试
预期:
wheel组用户su切换root正常,sudo权限正常;
新建非wheel组用户,加入sudoers后,无法su切换到root,但sudo权限使用正常;
未加入sudoers且非wheel组用户,既无法su切换到root,也无法使用sudo权限

cat /etc/group |grep wheel                      # 查看wheel组用户


验证:
wheel组用户,su切换root正常,sudo权限正常


非wheel组用户-新建用户加入sudoers,sudo权限使用正常,不能su切换到root

useradd qaz && echo password123 | passwd --stdin qaz
cat /etc/sudoers |grep -A 3 "## Allow root to run"                    # 显示匹配行和之后的3行
sed -i '/## Allow root to run/a\qaz\tALL=(ALL)\tALL' /etc/sudoers     # 关键字匹配行之后插入一行
cat /etc/sudoers |grep -A 3 "## Allow root to run"



非wheel组用户-原有用户未加入sudoers,sudo和su切换都无法使用

参考文章

sudo 密码超时时间
只允许特定的组用户su切换到root

本文标签: 安全策略权限服务器root