给出基于“OWASP Dependency-Check”的每日扫描 Jenkinsfile,自动创建安全 JIRA

解读

面试官想验证三件事:

  1. 你是否能把安全左移真正落地到 CI/CD 流水线,而不是停留在“知道有工具”;
  2. 对国内合规(等保、关基、信创)与外企常见流程(JIRA + Jenkins)都能兼顾;
  3. 对 Storm 这类 7×24 实时计算框架的“补丁窗口”有体感:扫描不能影响 Topology 运行,漏洞修复必须可灰度、可回滚。

因此,Jenkinsfile 必须:

  • 每日定时触发,支持手动重跑;
  • 生成 CycloneDX SBOM 供国内监管审计;
  • 利用 Dependency-Check 官方 Jenkins 插件,把 CVSS≥7 的缺陷自动推到 JIRA,字段符合国内安全团队习惯(漏洞编号、影响集群、修复截止日、补丁分支);
  • 流水线结果回写 GitLab MR/PR,实现“安全门禁”;
  • 用 Storm 的“灰度 Topology”思路做版本隔离:新依赖先在 canary 集群跑 30 min 无异常再全量发布。

知识点

  1. OWASP Dependency-Check 原理:调用 NVD、CNVD、GitHub Advisory 等多源漏洞库,通过哈希+坐标匹配生成 CVSS 报告。
  2. Jenkins 凭据域:global 域存放 JIRA token、Sonatype OSS 账号;folder 级存放国内 Maven 私库凭据,避免明文。
  3. JIRA REST API 字段映射:国内项目常用“发现版本”填 Topology 版本号,“修复版本”填待发布的 Storm 补丁版本;customfield_10201 存 CVSS 分值。
  4. Storm 灰度发布:利用 storm-kill + storm-submit 的“-w”等待拓扑退位机制,保证零热数据丢失。
  5. 等保 2.0 要求:三级系统 30 天内修复高危漏洞,日志留存 6 个月;Jenkins 需开审计日志并转存到 ELK。
  6. 信创环境:龙芯 / 麒麟 的 OpenJDK 需额外加 dependency-check 的“central 仓库镜像”参数,否则 NVD 下载超时。

答案

// 每日 02:30 执行,避开 Storm 夜间批高峰
pipeline {
  agent { label 'storm-cicd' }   // 专用节点,提前装 dependency-check 4.0.2+
  triggers { cron('H 30 2 * * *') }
  options {
    buildDiscarder(logRotator(numToKeepStr: '30'))
    timeout(time: 45, unit: 'MINUTES')
  }
  environment {
    // Jenkins 凭据 ID
    JIRA_TOKEN     = credentials('jira-security-token')
    NEXUS_USER     = credentials('nexus-cn-user')
    NEXUS_PASS     = credentials('nexus-cn-pass')
    // Storm 相关
    STORM_HOME     = tool name: 'storm-2.4.0', type: 'org.jenkinsci.plugins.storm.StormInstallation'
    TOPOLOGY_NAME  = 'payment-risk-topo'
    CANARY_CLUSTER = 'storm-canary'
    PROD_CLUSTER   = 'storm-prod'
  }
  stages {
    stage('Checkout') {
      steps {
        checkout scm
        script {
          env.GIT_SHORT_COMMIT = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
        }
      }
    }

    stage('Build SBOM') {
      steps {
        sh 'mvn org.cyclonedx:cyclonedx-maven-plugin:makeAggregateBom -DoutputFormat=json'
        stash includes: 'target/bom.json', name: 'sbom'
      }
    }

    stage('Dependency-Check') {
      steps {
        dependencyCheck additionalArguments: """
          --scan target/bom.json
          --format ALL
          --nvdApiKey ${env.NVD_API_KEY}
          --cveValidForHours 24
          --centralMirror https://repo.huaweicloud.com/repository/maven/
          --dataDirectory /opt/dependency-check/data
          --out dependency-check-report
        """, odcInstallation: 'dependency-check-4.0.2'

        dependencyCheckPublisher pattern: 'dependency-check-report/dependency-check-report.xml', failedTotalHigh: 1
      }
    }

    stage('Create JIRA') {
      when {
        expression {
          def high = currentBuild.result == null || currentBuild.result == 'UNSTABLE'
          return high
        }
      }
      steps {
        script {
          def xml = readFile 'dependency-check-report/dependency-check-report.xml'
          def vulnerabilities = new XmlSlurper().parseText(xml).dependencies.dependency.findAll { dep ->
            dep.vulnerabilities.vulnerability.find { vul -> vul.cvssScore.toFloat() >= 7.0 }
          }
          vulnerabilities.each { dep ->
            def cvss = dep.vulnerabilities.vulnerability.cvssScore.toFloat()
            def cve  = dep.vulnerabilities.vulnerability.name.text()
            def coords = "${dep.fileName}".replace('.jar','')
            def jiraPayload = """
              {
                "fields": {
                  "project": {"key": "SEC"},
                  "summary": "[Storm][${TOPOLOGY_NAME}] ${coords} 存在 ${cve}",
                  "description": "CVSS: ${cvss}\\nTopology: ${TOPOLOGY_NAME}\\nCommit: ${GIT_SHORT_COMMIT}\\n建议修复截止日: ${java.time.LocalDate.now().plusDays(30)}",
                  "issuetype": {"name": "安全漏洞"},
                  "priority": {"name": "${cvss >= 9 ? 'Critical' : 'High'}"},
                  "customfield_10201": "${cvss}",
                  "customfield_10202": "${TOPOLOGY_NAME}",
                  "labels": ["dependency-check", "storm", "auto"]
                }
              }
            """
            sh """
              curl -X POST -H 'Content-Type: application/json' \
                   -H 'Authorization: Bearer ${JIRA_TOKEN}' \
                   --data '${jiraPayload}' \
                   https://jira.company.cn/rest/api/2/issue/
            """
          }
        }
      }
    }

    stage('Canary Deploy') {
      when {
        branch 'main'
      }
      steps {
        sh """
          ${STORM_HOME}/bin/storm kill ${TOPOLOGY_NAME}-canary -w 60 || true
          ${STORM_HOME}/bin/storm jar target/payment-risk-topo-*.jar \
               com.company.storm.PaymentRiskTopo \
               ${TOPOLOGY_NAME}-canary \
               -c nimbus.seeds=${CANARY_CLUSTER} \
               -c topology.acker.executors=2
        """
        sleep time: 30, unit: 'MINUTES'   // 观察 canary 30 min
        sh """
          ${STORM_HOME}/bin/storm list -c nimbus.seeds=${CANARY_CLUSTER} | grep ${TOPOLOGY_NAME}-canary
        """
      }
    }

    stage('Prod Deploy') {
      when {
        allOf {
          branch 'main'
          expression { currentBuild.result == null }
        }
      }
      steps {
        input message: 'Canary 30 min 无异常,确认全量?', ok: '发布'
        sh """
          ${STORM_HOME}/bin/storm kill ${TOPOLOGY_NAME} -w 60 -c nimbus.seeds=${PROD_CLUSTER} || true
          ${STORM_HOME}/bin/storm jar target/payment-risk-topo-*.jar \
               com.company.storm.PaymentRiskTopo \
               ${TOPOLOGY_NAME} \
               -c nimbus.seeds=${PROD_CLUSTER} \
               -c topology.acker.executors=8
        """
      }
    }
  }

  post {
    always {
      archiveArtifacts artifacts: 'dependency-check-report/*', fingerprint: true
      publishHTML([allowMissing: false, alwaysLinkToLastBuild: true, keepAll: true,
                   reportDir: 'dependency-check-report', reportFiles: 'dependency-check-report.html',
                   reportName: 'OWASP Dependency-Check'])
    }
    failure {
      dingtalk (
        robot: 'security-team',
        type: 'TEXT',
        text: "[Storm][${env.TOPOLOGY_NAME}] 每日依赖扫描失败,请查看 ${env.BUILD_URL}"
      )
    }
  }
}

拓展思考

  1. 如果公司改用信创 Maven 中心,需要把 dependency-check 的 centralMirror 换成内网 Nexus 地址,并在 Jenkins 节点预置更新 NVD 的离线包,避免外网不通导致扫描假阴性。
  2. 对 Storm 的“状态拓扑”而言,升级第三方库可能改变 Kryo 序列化格式,建议在 canary 阶段打开 topology.testing.always.try.serialize: true,提前发现不兼容类。
  3. 国内等保测评要求“漏洞闭环”,可在 JIRA 增加自定义状态“已验证补丁”,通过 Jenkins 调用 Storm 的 REST API 读取 Topology 版本号,自动把 JIRA 状态流转到“已上线”,实现端到端闭环。
  4. 若企业无 JIRA,可替换为禅道或飞书多维表格,思路一致:用流水线解析 XML → 调接口 → 写缺陷单,再把单号回写到 Git Commit Status,实现门禁。
  5. 未来可接入 eBPF + OpenTelemetry,对升级后的 jar 做运行时行为对比,确保无异常网络外联,进一步降低“依赖升级”带来的供应链风险。