Este projeto demonstra uma implementação robusta e completa de DevSecOps utilizando GitHub Actions para automatizar análises de segurança em todas as fases do desenvolvimento. A aplicação de exemplo é uma API RESTful construída em Python/Flask com foco em práticas de segurança modernas.
- 🔍 6 ferramentas de segurança automatizadas (2 SAST + SCA + Secrets + 2 Container/IaC)
- 🚀 Integração nativa com GitHub Security
- 🐳 Container security com Trivy
- 📦 Dependências monitoradas via Dependabot
- 🔐 Zero secrets no código-fonte
- ⚡ Feedback imediato em Pull Requests
- Análise contínua desde o primeiro commit
- Feedback imediato em Pull Requests
- Bloqueio automático para vulnerabilidades críticas
- Integração nativa com ferramentas de desenvolvimento
- Múltiplas camadas de análise de segurança
- Diferentes perspectivas (código, dependências, containers, IaC)
- Redundância inteligente (Semgrep + CodeQL para SAST)
- Cobertura completa do ciclo de desenvolvimento
🟢 Semgrep v1.0
├── 📋 p/security-audit # Auditoria geral de segurança
├── 🔐 p/secrets # Detecção de credenciais
├── 🎯 p/owasp-top-ten # Top 10 OWASP
├── 🐍 p/python # Específico para Python
├── 🌐 p/flask # Framework Flask
├── 💾 p/sql-injection # Prevenção SQL Injection
└── ⚡ p/command-injection # Prevenção Command Injection🟢 GitHub CodeQL
├── 🧠 Semantic analysis # Análise semântica do código
├── 🔍 Data flow tracking # Rastreamento de fluxo de dados
├── 🎯 Security queries # Queries de segurança específicas
└── 🐍 Python coverage # Cobertura Python nativa🟢 Dependabot
├── 🐍 Python packages # requirements.txt
├── 🐳 Docker images # Dockerfile
└── ⚙️ GitHub Actions # workflows🟢 Gitleaks v8.0
├── 🔍 API keys detection
├── 🔑 SSH keys scanning
├── 🎫 JWT tokens analysis
└── 📄 Certificate validation🟢 Trivy Scanner
├── 🔍 Image vulnerabilities
├── 📦 Package scanning
├── 🐧 OS vulnerabilities
└── 📋 Configuration issues🟢 Trivy Config
├── 🐳 Dockerfile analysis
├── ⚙️ Kubernetes configs
├── 🔧 YAML configurations
└── 🛡️ Security policiesgraph TD
A[💻 Push/PR] --> B[🔍 SAST]
A --> C[🔐 Secrets]
A --> D[🐳 Container]
A --> E[🏗️ IaC]
B --> F[GitHub Security]
C --> F
D --> F
E --> F
F --> G[✅ Report]
F --> H[🚨 Block Critical]
| Workflow | Trigger | Duração | Status |
|---|---|---|---|
| Security Scan | Push/PR | ~3-5min | ✅ Ativo |
| Dependabot | Semanal | ~1min | ✅ Ativo |
| Container Build | Push/PR | ~2-4min | ✅ Ativo |
- 📤 Push para
main: Análise completa - 🔄 Pull Requests: Verificação delta
- 📅 Agendado: Scan semanal completo
- 🚨 Dependências: Atualizações automáticas
Todos os resultados são centralizados em:
- Security Overview → Visão geral
- Code Scanning → Análise SAST
- Dependabot → Vulnerabilidades de dependências
- Secret Scanning → Credenciais expostas
- ⚡ Feedback imediato em PRs
- 📧 Emails automáticos para vulnerabilidades críticas
- 🔔 Notificações GitHub em tempo real
- 📊 Dashboards integrados
# Clone o repositório
git clone https://github.com/jmessiass/devsecops.git
cd devsecops
# Crie uma branch para seu trabalho
git checkout -b feature/minha-feature
# Faça suas alterações
# ...
# Commit e push
git add .
git commit -m "feat: minha nova feature"
git push origin feature/minha-feature- 🔄 Abra um Pull Request no GitHub
- ⏱️ Aguarde 3-5 minutos para a análise completa
- 📊 Verifique os resultados na aba "Checks"
- 🔍 Corrija possíveis vulnerabilidades encontradas
| Status | Significado | Ação |
|---|---|---|
| ✅ All checks passed | Sem vulnerabilidades | ✅ Pode fazer merge |
| Vulnerabilidades baixas/médias | 🔍 Revisar e corrigir | |
| ❌ Critical issues | Vulnerabilidades críticas | 🚨 Bloqueado - Corrija antes do merge |
Para repositórios privados (requer GitHub Advanced Security):
- Vá para Settings → Security & analysis
- Habilite as seguintes opções:
✅ Dependency graph
✅ Dependabot alerts
✅ Dependabot security updates
✅ Code scanning (CodeQL)
✅ Secret scanning
✅ Secret scanning push protection# .github/workflows/codeql.yml (GitHub cria automaticamente)
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 8 * * 1' # Segunda-feira 8h
jobs:
analyze:
runs-on: ubuntu-latest
strategy:
matrix:
language: [ 'python' ]O GitHub detecta automaticamente:
- 🔑 API Keys (AWS, Google, etc.)
- 🎫 Tokens (JWT, OAuth, etc.)
- 🔐 Database URLs
- 📧 Email credentials
- 🔒 Certificates
# Instalar Semgrep
pip install semgrep
# Executar análise completa
semgrep --config=p/security-audit \
--config=p/secrets \
--config=p/owasp-top-ten \
--config=p/python \
--config=p/flask \
--sarif --output=semgrep.sarif .
# Executar análise rápida
semgrep --config=auto .# Instalar Gitleaks
brew install gitleaks # macOS
# ou
go install github.com/gitleaks/gitleaks/v8@latest
# Scan do repositório completo
gitleaks detect --source . --verbose
# Scan apenas dos novos commits
gitleaks protect --verbose# Instalar Trivy
brew install trivy # macOS
# ou
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
# Scan da imagem Docker
docker build -t devsecops-app .
trivy image devsecops-app
# Scan do filesystem
trivy fs .
# Scan de configurações (IaC)
trivy config .
# Gerar relatório SARIF
trivy image --format sarif --output results.sarif devsecops-app# Safety - Verificação de dependências Python
pip install safety
safety check
# Pip-audit - Auditoria de dependências
pip install pip-audit
pip-audit
# Verificar dependências desatualizadas
pip list --outdated- Navegue para:
https://github.com/seu-usuario/seu-repo/security - Seções disponíveis:
- 📊 Overview - Resumo geral
- 🔍 Code scanning - Resultados SAST
- 📦 Dependabot - Vulnerabilidades de dependências
- 🔐 Secret scanning - Credenciais expostas
📋 Security Scan Status:
├── ✅ SAST (Semgrep) # ~2 min
├── ✅ Secrets (Gitleaks) # ~30 sec
├── ✅ Container (Trivy) # ~3 min
├── ✅ IaC (Trivy Config) # ~1 min
└── ✅ Dependencies (Dependabot) # ~1 minVulnerabilidades Críticas/Altas:
- 🔍 Analise o alerta detalhadamente
- 🛠️ Implemente a correção sugerida
- ✅ Teste a solução localmente
- 📤 Commit e push da correção
- ✔️ Verifique se o alerta foi resolvido
False Positives:
# Para Semgrep - .semgrepignore
# Ignorar arquivo específico
path/to/file.py
# Ignorar regra específica
# semgrep:ignore python.flask.security.audit.app-run-debug-true
app.run(debug=True) # Apenas em desenvolvimento# .github/workflows/security.yml
- name: Run Semgrep
uses: returntocorp/semgrep-action@v1
with:
config: p/security-audit
generateBaseline: true
env:
SEMGREP_RULES: |
rules:
- id: custom-rule
severity: ERROR # INFO, WARNING, ERROR# .semgrep.yml
rules:
- id: flask-debug-true
message: Flask debug mode enabled in production
languages: [python]
severity: ERROR
pattern: app.run(debug=True)
paths:
include:
- "*.py"
exclude:
- "tests/"# .gitleaks.toml
[allowlist]
description = "Allowlist configuration"
files = [
"^.gitleaks.toml$",
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
regexes = [
"example@email.com", # Email de exemplo
]- ⚙️ .github/workflows/security.yml - Pipeline de segurança
- 🛡️ .github/dependabot.yml - Configuração Dependabot
- 📚 OWASP DevSecOps Guidelines
- 🔍 Semgrep Rules Documentation
- 🛡️ Trivy Security Scanner
- 🔒 GitHub Security Features
- 🔍 Análise estática de código - SAST (Semgrep + CodeQL)
- 📦 Análise de dependências - SCA (Dependabot + Trivy)
- 🔐 Detecção de secrets (Gitleaks)
- 🐳 Segurança de containers (Trivy)
- 🏗️ Infrastructure as Code scanning (Trivy Config)
- 🚨 Bloqueio automático para vulnerabilidades críticas
- 📊 Integração com GitHub Security
- 🔄 Monitoramento contínuo
- 🤖 AI-powered security analysis
- 🔧 Auto-remediation workflows
- 📊 Custom security dashboards
Contribuições são bem-vindas! Por favor:
- 🍴 Fork o projeto
- 🌿 Crie uma branch (
git checkout -b feature/amazing-security) - ✅ Commit suas mudanças (
git commit -m 'Add amazing security feature') - 📤 Push para a branch (
git push origin feature/amazing-security) - 🔄 Abra um Pull Request
Este projeto está licenciado sob a MIT License.
devsecops security automation github-actions python flask docker sast sca semgrep trivy gitleaks dependabot
Desenvolvido com ❤️ para demonstrar as melhores práticas de DevSecOps
⭐ Se este projeto foi útil, considere dar uma estrela! ⭐