Como construir pipelines de segurança (DevSecOps) integrados ao CI/CD
1. Fundamentos do DevSecOps e a integração com CI/CD
1.1. Conceitos-chave: Shift-left, segurança como código e automação de compliance
O DevSecOps representa a evolução natural do DevOps, onde a segurança deixa de ser uma etapa final para tornar-se parte integrante de todo o ciclo de desenvolvimento. Três pilares sustentam essa abordagem:
- Shift-left: mover verificações de segurança para o início do pipeline, reduzindo custos e retrabalho
- Segurança como código: políticas e regras definidas em arquivos versionados (YAML, HCL, Rego)
- Automação de compliance: verificações contínuas contra frameworks como OWASP Top 10, PCI-DSS e ISO 27001
1.2. Diferença entre segurança reativa e proativa no ciclo de desenvolvimento
| Segurança Reativa | Segurança Proativa (DevSecOps) |
|---|---|
| Scan após deploy | Scan em cada commit |
| Correção em lotes | Correção imediata |
| Equipe de segurança isolada | Segurança distribuída |
| Relatórios mensais | Dashboards em tempo real |
1.3. Mapeamento das fases do pipeline CI/CD com gates de segurança
Commit → Build → Test → Staging → Deploy
│ │ │ │ │
SAST SCA DAST OPA Runtime
Secrets Trivy IaC Policy Monitoring
2. Etapa de Commit: Análise estática e varredura de segredos
2.1. Implementação de SAST com SonarQube e Semgrep
Exemplo de configuração para GitHub Actions:
name: SAST Scan
on: [push]
jobs:
sast:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Semgrep Scan
uses: semgrep/semgrep-action@v1
with:
config: p/owasp-top-ten
- name: SonarQube Scan
uses: sonarsource/sonarqube-scan-action@v2
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
2.2. Varredura de segredos e credenciais no código-fonte
# .gitleaks.toml
[allowlist]
description = "Global allowlist"
paths = [
"vendor/",
"node_modules/",
"*.test.js"
]
[[rules]]
id = "aws-access-token"
description = "AWS Access Key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA)[A-Z0-9]{16}'''
tags = ["aws", "credentials"]
2.3. Políticas de bloqueio automático para falhas críticas
# pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
args: ['--verbose']
- repo: https://github.com/returntocorp/semgrep
rev: v1.60.0
hooks:
- id: semgrep
args: ['--config=auto', '--error']
3. Etapa de Build: Análise de dependências e imagens de contêiner
3.1. SCA para dependências vulneráveis
# pipeline.yml - GitLab CI
dependency_scan:
stage: build
script:
- snyk test --all-projects --severity-threshold=high
- snyk monitor
allow_failure: false
artifacts:
reports:
sast: gl-sast-report.json
3.2. Varredura de imagens Docker com Trivy
# Jenkinsfile
stage('Container Security Scan') {
steps {
sh '''
trivy image --severity CRITICAL,HIGH --exit-code 1 \
--ignore-unfixed --format sarif \
myapp:$BUILD_NUMBER
'''
}
}
3.3. Assinatura e verificação de artefatos
# Assinar imagem com Cosign
COSIGN_PASSWORD='' cosign sign \
--key gcpkms://projects/my-project/locations/global/keyRings/mykey/cryptoKeys/cosign \
registry.example.com/myapp:latest
# Verificar assinatura
cosign verify \
--key gcpkms://projects/my-project/locations/global/keyRings/mykey/cryptoKeys/cosign \
registry.example.com/myapp:latest
4. Etapa de Teste: Testes dinâmicos e de infraestrutura como código
4.1. DAST em ambientes efêmeros
# ZAP Baseline Scan em ambiente temporário
docker run -v $(pwd):/zap/wrk/:rw \
-t ghcr.io/zaproxy/zaproxy:stable \
zap-baseline.py \
-t https://staging-$CI_COMMIT_SHORT_SHA.example.com \
-r testreport.html \
-w testreport.md \
-x testreport.xml
4.2. Validação de segurança em IaC
# Checkov para Terraform
checkov -d terraform/ \
--framework terraform \
--skip-check CKV_AWS_123 \
--compact \
--output junitxml > checkov-report.xml
# tfsec com severidade mínima
tfsec terraform/ \
--minimum-severity HIGH \
--exclude-dir .terraform \
--format sarif \
--out tfsec-results.sarif
4.3. Testes de penetração automatizados
# Nikto scan automatizado
nikto -h https://staging.example.com \
-ssl \
-Format xml \
-output nikto_scan.xml \
-Tuning 123456789
# Nuclei para vulnerabilidades conhecidas
nuclei -u https://staging.example.com \
-severity critical,high,medium \
-json \
-o nuclei_results.json
5. Etapa de Deploy: Controle de acesso e compliance contínuo
5.1. Políticas de deploy baseadas em assinaturas
# ArgoCD Application com verificação de assinatura
apiVersion: argoproj.io/v1alpha1
kind: Application
spec:
source:
repoURL: https://charts.example.com
targetRevision: 1.2.3
helm:
parameters:
- name: image.tag
value: v1.2.3-signed
syncPolicy:
automated:
prune: true
selfHeal: true
validate: true
5.2. Implementação de OPA para compliance
# policy.rego - OPA Gatekeeper
package k8srequiredlabels
violation[{"msg": msg}] {
input.request.kind.kind == "Deployment"
not input.request.object.metadata.labels.security
msg := "Todos os Deployments devem ter label 'security'"
}
# Teste de política
opa eval --data policy.rego --input input.json "data.k8srequiredlabels"
5.3. Monitoramento de runtime com Falco
# Falco rule para shell reverso
- rule: Reverse Shell Detected
desc: Detect reverse shell attempts
condition: >
spawned_process and
proc.name in (bash, sh, nc, ncat, python, perl) and
evt.type in (connect, sendto) and
fd.net.ip != "127.0.0.1" and
fd.net.port > 1024
output: "Reverse shell from %user.name (command=%proc.cmdline)"
priority: CRITICAL
tags: [network, shell]
6. Orquestração e ferramentas de integração no pipeline
6.1. Uso de plugins e ações nativas
# GitHub Actions workflow completo
name: DevSecOps Pipeline
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: SAST Scan
uses: github/codeql-action/analyze@v3
with:
languages: python,javascript
- name: Dependency Scan
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --severity-threshold=high
- name: Container Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myapp:latest'
format: 'sarif'
output: 'trivy-results.sarif'
exit-code: '1'
6.2. Centralização de relatórios e dashboards
# DefectDojo API para upload de resultados
curl -X POST "https://defectdojo.example.com/api/v2/import-scan/" \
-H "Authorization: Token $DEFECTDOJO_TOKEN" \
-F "scan_type=Trivy Scan" \
-F "file=@trivy-results.sarif" \
-F "engagement=123" \
-F "active=true" \
-F "verified=true"
6.3. Estratégias de fail-fast e rollback automático
# GitLab CI com fail-fast condicional
security_gate:
stage: deploy
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: manual
- when: always
script:
- |
if [ $(cat vulnerability_count.txt) -gt 5 ]; then
echo "CRITICAL: Mais de 5 vulnerabilidades altas encontradas"
exit 1
fi
needs: ["container_scan", "dependency_scan"]
7. Governança, métricas e cultura DevSecOps
7.1. Definição de SLAs para correção de vulnerabilidades
# SLA matrix para vulnerabilidades
| Severidade | SLA Correção | SLA Descoberta |
|------------|--------------|----------------|
| Critical | 24h | Imediato |
| High | 72h | 1h |
| Medium | 7 dias | 24h |
| Low | 30 dias | 7 dias |
7.2. Métricas de pipeline
# Prometheus metrics para DevSecOps
# HELP pipeline_security_blocked_total Total blocked pipelines
# TYPE pipeline_security_blocked_total counter
pipeline_security_blocked_total{reason="critical_vuln"} 42
pipeline_security_blocked_total{reason="secret_leak"} 15
# HELP pipeline_security_scan_duration_seconds Scan duration
# TYPE pipeline_security_scan_duration_seconds histogram
pipeline_security_scan_duration_seconds{scan_type="sast"} 120.5
7.3. Treinamento da equipe e playbooks
# Playbook para incidente: vazamento de segredo
1. Identificar commit com segredo via gitleaks
2. Rotacionar credencial imediatamente
3. Remover segredo do histórico git:
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch config/credentials.json" \
--prune-empty --tag-name-filter cat -- --all
4. Notificar equipe de segurança
5. Revisar logs de acesso nos últimos 30 dias
6. Atualizar políticas de pre-commit hooks
Referências
- OWASP DevSecOps Guideline — Guia oficial da OWASP com práticas recomendadas para integrar segurança em pipelines CI/CD
- Trivy Documentation - Aqua Security — Documentação completa do Trivy para varredura de vulnerabilidades em contêineres, dependências e IaC
- GitLab DevSecOps Documentation — Guia oficial do GitLab para implementação de SAST, DAST, SCA e container scanning
- OPA Gatekeeper Documentation — Documentação oficial do Open Policy Agent para políticas de compliance em Kubernetes
- Falco Rules Documentation — Catálogo oficial de regras do Falco para detecção de ameaças em runtime
- Snyk Documentation for CI/CD — Guia de integração do Snyk para análise de dependências em pipelines
- Cosign - Sigstore Documentation — Documentação oficial do Cosign para assinatura e verificação de artefatos de software