Linux环境中精确控制普通用户的sudo权限

精准施控才能游刃有余。

需求背景

在持续集成的实践中,为了保障生产环境安全可靠避免意外事故的发生。需要限制用户的操作权限,又要满足构建需要,因此需要对持续集成过程中的操作命令权限进行精准控制。实现最小权限开放,最大灵活性保障。

sudo配置

  • 配置文件名不能包含.后缀(文件名中不能包含.),否则配置不生效。

  • 生成配置

    1
    2
    3
    4
    5
    6
    7
    cat > /etc/sudoers.d/jenkins_deploy << EOF
    Host_Alias JENKINS_SERVERS = $(echo -n $(ip addr show dev eth0 | awk '/inet/ {sub(/\//, " "); print $2}'|head -1)), 127.0.0.1
    Cmnd_Alias JENKINS_CMD = $(which rsync), $(which ln), $(which unlink), $(which readlink), $(which test), $(which mv), $(which mkdir)
    Defaults:jenkins !requiretty
    Defaults!JENKINS_CMD !syslog
    jenkins JENKINS_SERVERS=(root) NOPASSWD: JENKINS_CMD
    EOF
  • 配置范例

    1
    2
    3
    4
    5
    Host_Alias     JENKINS_SERVERS = 10.0.0.1, 127.0.0.1
    Cmnd_Alias JENKINS_CMD = /usr/bin/rsync, /bin/ln, /bin/unlink, /usr/bin/readlink, /usr/bin/test, /bin/mv, /bin/mkdir
    Defaults:jenkins !requiretty
    Defaults!JENKINS_CMD !syslog
    jenkins JENKINS_SERVERS=(root) NOPASSWD: JENKINS_CMD
  • 主机别名定义 sudo 用户有权在哪个服务器(或特定范围内的服务器)上发出命令。在主机别名中,可以使用 DNS 名称或 IP 地址,或者指定整个网络范围(例如 172.17.12.0/24)。要限制访问范围,应该仅指定群集节点的主机名。别名必须全部而且只能使用大写英文字母的组合
  • centos 5 的默认版本sudo-1.7.2p1-14.el5_8.4 不支持JENKINS_SERVERS中使用网段掩码

ALL ALL=(ALL) ALL 配置字段解释

1
2
3
4
5
ALL ALL=(ALL) ALL
The first ALL is the users allowed
The second one is the hosts
The third one is the user as you are running the command
The last one is the commands allowed

参考文档