Jenkins入门教程(十四):用户权限管理与安全最佳实践

安全是Jenkins管理的重要方面。本文将详细介绍Jenkins的权限管理和安全最佳实践,包括完整的配置步骤和示例。

用户认证配置

Jenkins内置用户数据库

# 系统管理 > 安全配置

安全域: Jenkins' own user database
允许用户注册: 根据需要(生产环境建议关闭)

# 创建用户
# 系统管理 > 用户管理 > 创建用户
用户名: developer
密码: ********
全名: 开发者
邮箱: developer@example.com

LDAP认证

# 安装LDAP插件
# 系统管理 > 安全配置

安全域: LDAP
Server: ldap://ldap.example.com:389
root DN: dc=example,dc=com
User search base: ou=users
User search filter: uid={0}
Group search base: ou=groups
Group search filter: (| (member={0}) (uniqueMember={0}) (memberUid={1}))
Group membership filter: (&(cn={0})(objectclass=groupOfNames))
Manager DN: cn=admin,dc=example,dc=com
Manager Password: ********

# 测试LDAP连接
点击 "Test LDAP settings"
输入用户名和密码进行测试

GitHub OAuth

# 1. 在GitHub创建OAuth App
# Settings > Developer settings > OAuth Apps > New OAuth App

Application name: Jenkins CI
Homepage URL: https://jenkins.example.com
Authorization callback URL: https://jenkins.example.com/securityRealm/finishLogin

# 2. 安装GitHub Authentication插件

# 3. 配置Jenkins
安全域: GitHub Authentication Plugin
GitHub Web URI: https://github.com
GitHub API URI: https://api.github.com
Client ID: your-client-id
Client Secret: your-client-secret
OAuth Scope: read:org,user:email

授权策略

项目矩阵授权策略

# 系统管理 > 安全配置
授权策略: Project-based Matrix Authorization Strategy

# 配置全局权限矩阵
用户/组           Overall   Credentials   Agent      Job        View
admin             全选      全选          全选       全选       全选
developers        Read      -             -          Build,Read Read
viewers           Read      -             -          Read       Read

# 权限说明
Overall:
  - Administer: 完全管理权限
  - Read: 查看Jenkins
  - RunScripts: 运行脚本
  - ConfigureUpdateCenter: 管理插件

Job:
  - Build: 触发构建
  - Cancel: 取消构建
  - Configure: 配置Job
  - Create: 创建Job
  - Delete: 删除Job
  - Discover: 发现Job
  - Move: 移动Job
  - Read: 查看Job
  - Workspace: 访问工作空间

基于角色的授权策略

# 1. 安装Role-based Authorization Strategy插件

# 2. 启用角色策略
# 系统管理 > 安全配置
授权策略: Role-Based Strategy

# 3. 管理角色
# 系统管理 > Manage and Assign Roles > Manage Roles

# 创建全局角色
Global roles:
  admin:
    - 所有权限
  developer:
    - Overall: Read
    - Job: Build, Cancel, Read
    - View: Read
  viewer:
    - Overall: Read
    - Job: Read
    - View: Read

# 创建项目角色(基于正则匹配)
Project roles:
  frontend-dev:
    Pattern: frontend-.*
    权限: Build, Cancel, Configure, Read, Workspace
  
  backend-dev:
    Pattern: backend-.*
    权限: Build, Cancel, Configure, Read, Workspace
  
  qa-team:
    Pattern: .*-test
    权限: Build, Read

# 4. 分配角色
# 系统管理 > Manage and Assign Roles > Assign Roles

Global roles:
  admin: admin-user
  developer: dev1, dev2, dev3
  viewer: guest

Project roles:
  frontend-dev: frontend-team
  backend-dev: backend-team
  qa-team: qa-team

凭据安全

# 凭据作用域
- System: 仅系统级使用(如Agent连接)
- Global: 所有Job可用
- Folder: 仅特定文件夹内Job可用

# 配置凭据使用范围
# 系统管理 > 凭据 > 系统 > 全局凭据

# 在Pipeline中安全使用凭据
pipeline {
    agent any
    
    stages {
        stage('Use Credentials') {
            steps {
                // 凭据不会出现在日志中
                withCredentials([
                    usernamePassword(
                        credentialsId: 'deploy-creds',
                        usernameVariable: 'DEPLOY_USER',
                        passwordVariable: 'DEPLOY_PASS'
                    )
                ]) {
                    sh '''
                        # 密码会被自动遮蔽
                        echo "User: $DEPLOY_USER"
                        echo "Pass: $DEPLOY_PASS"  # 日志显示: ****
                        
                        # 使用凭据
                        curl -u $DEPLOY_USER:$DEPLOY_PASS https://api.example.com
                    '''
                }
            }
        }
    }
}

// 日志输出
[Pipeline] sh
+ echo 'User: deployer'
User: deployer
+ echo 'Pass: ****'
Pass: ****
+ curl -u deployer:**** https://api.example.com

安全加固

# 1. 启用CSRF保护
# 系统管理 > 安全配置
跨站请求伪造保护: 勾选
Crumb Issuer: Default Crumb Issuer

# 2. 启用Agent-to-Master访问控制
# 系统管理 > 安全配置
Agent -> Master Access Control: 勾选

# 3. 配置安全的脚本审批
# 系统管理 > In-process Script Approval
# 审批Pipeline中使用的危险方法

# 4. 禁用CLI远程访问(如不需要)
# 系统管理 > 系统配置
启用CLI: 取消勾选

# 5. 配置安全的JNLP协议
# 系统管理 > 安全配置 > Agent protocols
仅启用: JNLP4-connect
禁用: JNLP-connect, JNLP2-connect, JNLP3-connect

HTTPS配置

# 使用Nginx反向代理配置HTTPS

# /etc/nginx/sites-available/jenkins
upstream jenkins {
    server 127.0.0.1:8080 fail_timeout=0;
    keepalive 32;
}

server {
    listen 80;
    server_name jenkins.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name jenkins.example.com;
    
    ssl_certificate /etc/letsencrypt/live/jenkins.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/jenkins.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    
    # 安全头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    
    location / {
        proxy_pass http://jenkins;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
        
        # WebSocket支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        
        proxy_read_timeout 90;
    }
}

# 配置Jenkins使用代理
# /etc/default/jenkins
JENKINS_ARGS="--httpListenAddress=127.0.0.1"

审计日志

# 安装Audit Trail插件

# 系统管理 > 系统配置 > Audit Trail

# 配置日志记录器
Loggers:
  - Log File:
      Log Location: /var/log/jenkins/audit.log
      Log File Size: 100MB
      Log File Count: 10

# 日志内容示例
$ tail -f /var/log/jenkins/audit.log
2026-02-08 12:00:00 user:admin ip:192.168.1.100 op:job/my-job CONFIGURE
2026-02-08 12:01:00 user:developer ip:192.168.1.101 op:job/my-job BUILD
2026-02-08 12:02:00 user:admin ip:192.168.1.100 op:plugin INSTALL docker-workflow
2026-02-08 12:03:00 user:admin ip:192.168.1.100 op:credentials CREATE github-token

# 可以将日志发送到Syslog
Loggers:
  - Syslog:
      Syslog Server: syslog.example.com
      Syslog Port: 514
      Facility: USER

API Token管理

# 生成API Token
# 点击用户名 > 设置 > API Token > Add new Token

# 使用API Token调用Jenkins API
curl -u username:api-token https://jenkins.example.com/api/json

# 触发构建
curl -X POST -u username:api-token \
    https://jenkins.example.com/job/my-job/build

# 带参数触发构建
curl -X POST -u username:api-token \
    https://jenkins.example.com/job/my-job/buildWithParameters \
    --data "BRANCH=main&ENV=prod"

# 获取构建状态
curl -u username:api-token \
    https://jenkins.example.com/job/my-job/lastBuild/api/json | jq '.result'
# "SUCCESS"

安全检查清单

# Jenkins安全检查清单

[ ] 配置了用户认证(不是匿名访问)
[ ] 实施了最小权限原则
[ ] 敏感信息存储在凭据管理中
[ ] 启用了CSRF保护
[ ] 启用了HTTPS
[ ] 禁用了不需要的协议和端口
[ ] 配置了审计日志
[ ] 定期更新Jenkins和插件
[ ] 配置了网络防火墙
[ ] 定期审查用户权限

总结

本文详细介绍了Jenkins的权限管理和安全配置,包括用户认证、授权策略、凭据管理、安全加固等内容。安全是CI/CD系统的基石。

下一篇我们将学习Jenkins的备份与恢复。

发表回复

后才能评论