Skip to content

Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.

feat(security): Implementar pipeline completa de seguridad

irraz59ec406aa4a0
diff --git a/.github/BRANCH-PROTECTION.md b/.github/BRANCH-PROTECTION.md
new file mode 100644
index 0000000..d7ec580
--- /dev/null
+++ b/.github/BRANCH-PROTECTION.md
@@ -0,0 +1,241 @@
+# 🛡️ Configuración de Protección de Ramas
+
+## Pasos para Configurar Branch Protection en GitHub
+
+Para asegurar que la pipeline de seguridad se ejecute **obligatoriamente** antes de hacer merge a `main`, sigue estos pasos:
+
+### 1. Acceder a Branch Protection Rules
+
+1. Ve a tu repositorio en GitHub
+2. Click en **Settings** (⚙️)
+3. En el menú lateral, click en **Branches**
+4. En "Branch protection rules", click en **Add branch protection rule**
+
+### 2. Configuración Recomendada
+
+#### Branch name pattern:
+```
+main
+```
+
+#### ✅ Checks Obligatorios que DEBES Habilitar:
+
+**Require a pull request before merging**
+- ☑️ Require approvals: `1` (al menos 1 aprobación)
+- ☑️ Dismiss stale pull request approvals when new commits are pushed
+- ☑️ Require review from Code Owners (opcional)
+
+**Require status checks to pass before merging**
+- ☑️ Require branches to be up to date before merging
+- **Status checks que deben pasar** (búscalos y selecciónalos):
+ ```
+ ☑️ TruffleHog - Detección de Secretos
+ ☑️ CodeQL - Análisis de Código
+ ☑️ Python Linting
+ ☑️ Escaneo de Dependencias
+ ☑️ Trivy - Escaneo de Imágenes Docker
+ ☑️ Validación de PR
+ ☑️ Dockerfile Linting
+ ```
+
+**Require conversation resolution before merging**
+- ☑️ Todos los comentarios deben resolverse antes del merge
+
+**Require signed commits** (opcional pero recomendado)
+- ☑️ Require signed commits
+
+**Require linear history** (opcional)
+- ☑️ Previene merge commits, solo permite rebase y squash
+
+**Do not allow bypassing the above settings**
+- ☑️ Aplicar a administradores también
+- ⚠️ Desactiva esto solo si necesitas hacer hotfixes de emergencia
+
+#### 🔒 Protecciones Adicionales Recomendadas:
+
+**Restrict who can push to matching branches**
+- Limitar push directo solo a:
+ - Administradores
+ - Service accounts para CI/CD
+
+**Allow force pushes**
+- ❌ **Deshabilitado** (NUNCA permitir force push a main)
+
+**Allow deletions**
+- ❌ **Deshabilitado** (Prevenir borrado accidental de main)
+
+### 3. Guardar
+
+Click en **Create** o **Save changes**
+
+---
+
+## 📋 Configuración Completa (Copiar/Pegar Template)
+
+Si prefieres usar la API de GitHub o Terraform, aquí está la configuración en formato JSON:
+
+```json
+{
+ "required_status_checks": {
+ "strict": true,
+ "contexts": [
+ "secrets-scan",
+ "codeql-analysis",
+ "python-lint",
+ "dependency-scan",
+ "docker-scan",
+ "pr-validation",
+ "dockerfile-lint"
+ ]
+ },
+ "enforce_admins": true,
+ "required_pull_request_reviews": {
+ "dismissal_restrictions": {},
+ "dismiss_stale_reviews": true,
+ "require_code_owner_reviews": false,
+ "required_approving_review_count": 1,
+ "require_last_push_approval": true
+ },
+ "restrictions": null,
+ "required_linear_history": false,
+ "allow_force_pushes": false,
+ "allow_deletions": false,
+ "block_creations": false,
+ "required_conversation_resolution": true,
+ "lock_branch": false,
+ "allow_fork_syncing": true
+}
+```
+
+### Aplicar con GitHub CLI:
+
+```bash
+gh api repos/:owner/:repo/branches/main/protection \
+ --method PUT \
+ --input branch-protection.json
+```
+
+---
+
+## 🔐 Configuración de CODEOWNERS (Opcional)
+
+Crea el archivo `.github/CODEOWNERS` para asignar revisores automáticos:
+
+```
+# Default owners para todo el repo
+* @irraz
+
+# Security-sensitive files
+/.github/workflows/ @irraz @security-team
+/docker/ @irraz @devops-team
+.env.example @irraz @security-team
+docker-compose*.yml @irraz @devops-team
+
+# Python security
+*.py @irraz @dev-team
+requirements.txt @irraz @security-team
+```
+
+---
+
+## 🚨 Política de Excepciones
+
+### ¿Cuándo saltarse las protecciones?
+
+**NUNCA** en situaciones normales. Solo en:
+
+1. **Hotfix crítico de producción**:
+ - Documentar en el commit el motivo
+ - Crear issue post-mortem
+ - Abrir PR retrospectivo con los checks
+
+2. **Emergencia de seguridad**:
+ - Parchear vulnerabilidad crítica
+ - Notificar al equipo inmediatamente
+ - Ejecutar pipeline manualmente después
+
+### Proceso de Excepción:
+
+```bash
+# 1. Documentar
+git commit -m "HOTFIX: [TICKET-123] Descripción del problema crítico"
+
+# 2. Push con bypass (si tienes permisos)
+git push origin main
+
+# 3. Inmediatamente después, crear PR de verificación
+git checkout -b hotfix/verify-TICKET-123
+git push origin hotfix/verify-TICKET-123
+gh pr create --title "Verificación post-hotfix TICKET-123" --body "Ejecutar pipeline completa sobre el hotfix"
+```
+
+---
+
+## ✅ Verificación
+
+Después de configurar, verifica que funciona:
+
+1. Crea una rama de prueba:
+ ```bash
+ git checkout -b test/branch-protection
+ echo "test" >> README.md
+ git add README.md
+ git commit -m "test: Verificar branch protection"
+ git push origin test/branch-protection
+ ```
+
+2. Abre un PR hacia `main`
+
+3. Intenta hacer merge **sin esperar a que pasen los checks**:
+ - ❌ Debería estar **deshabilitado**
+ - ✅ Mensaje: "Required status checks must pass"
+
+4. Espera a que pasen todos los checks
+
+5. Intenta hacer merge **sin aprobación**:
+ - ❌ Debería estar **deshabilitado**
+ - ✅ Mensaje: "At least 1 approving review is required"
+
+6. Aprueba el PR y haz merge
+ - ✅ Ahora **sí debería permitir** el merge
+
+---
+
+## 📊 Monitoring
+
+### Ver Intentos de Bypass
+
+Settings → Branches → Ver "Protection rule activity"
+
+### Auditoría
+
+Settings → Security → Audit log → Filtrar por "protected branch"
+
+---
+
+## 🆘 Troubleshooting
+
+### "Status check no aparece en la lista"
+
+**Causa**: El check debe ejecutarse al menos una vez para aparecer.
+
+**Solución**:
+1. Abre cualquier PR
+2. Espera a que se ejecute la pipeline
+3. Vuelve a la configuración de protección
+4. Ahora debería aparecer en la lista
+
+### "No puedo hacer merge aunque los checks pasen"
+
+**Verifica**:
+- ¿Tiene al menos 1 aprobación?
+- ¿Todos los comentarios están resueltos?
+- ¿La rama está actualizada con main?
+
+### "Los administradores pueden saltarse las reglas"
+
+**Solución**: Marca "Do not allow bypassing the above settings" y aplica a administradores.
+
+---
+
+**Configuración recomendada aplicada a**: `main`, `master`, `develop`, `production`
diff --git a/.github/QUICKSTART.md b/.github/QUICKSTART.md
new file mode 100644
index 0000000..dd3b37d
--- /dev/null
+++ b/.github/QUICKSTART.md
@@ -0,0 +1,294 @@
+# 🚀 Inicio Rápido - Pipeline de Seguridad
+
+## ⚡ Setup en 5 Minutos
+
+### Paso 1: Habilitar Funciones de GitHub (30 segundos)
+
+Ve a tu repositorio en GitHub → **Settings** → **Security**:
+
+```
+☑️ Dependabot alerts
+☑️ Dependabot security updates
+☑️ Code scanning
+☑️ Secret scanning (solo repos públicos)
+```
+
+### Paso 2: Subir la Pipeline (1 minuto)
+
+```bash
+# Ya tienes los archivos, solo súbelos:
+git add .github/
+git add .pre-commit-config.yaml
+git commit -m "feat: Agregar pipeline de seguridad completa con TruffleHog, CodeQL, Trivy"
+git push origin main
+```
+
+### Paso 3: Configurar Branch Protection (2 minutos)
+
+**Opción A - Interfaz Web:**
+1. Settings → Branches → Add rule
+2. Branch name: `main`
+3. Habilita: ☑️ Require status checks (selecciona todos los checks de la pipeline)
+4. Habilita: ☑️ Require pull request reviews (mínimo 1)
+5. Save changes
+
+**Opción B - GitHub CLI (más rápido):**
+```bash
+gh api repos/:owner/:repo/branches/main/protection \
+ --method PUT \
+ --input - <<EOF
+{
+ "required_status_checks": {
+ "strict": true,
+ "contexts": ["secrets-scan", "codeql-analysis", "python-lint", "dependency-scan", "docker-scan"]
+ },
+ "enforce_admins": true,
+ "required_pull_request_reviews": {
+ "required_approving_review_count": 1,
+ "dismiss_stale_reviews": true
+ },
+ "restrictions": null,
+ "allow_force_pushes": false,
+ "allow_deletions": false
+}
+EOF
+```
+
+### Paso 4: (Opcional) Pre-commit Hooks Locales (1 minuto)
+
+```bash
+# Instalar pre-commit
+pip install pre-commit
+
+# Activar hooks
+pre-commit install
+
+# Ejecutar una vez para verificar
+pre-commit run --all-files
+```
+
+---
+
+## ✅ ¡Listo!
+
+Ahora tu repositorio tiene:
+
+- ✅ **TruffleHog** detectando secretos en cada PR
+- ✅ **CodeQL** analizando vulnerabilidades de seguridad
+- ✅ **Trivy** escaneando imágenes Docker
+- ✅ **Bandit** revisando código Python
+- ✅ **Safety** verificando dependencias vulnerables
+- ✅ **Dependabot** creando PRs automáticos de actualizaciones
+- ✅ **Hadolint** validando Dockerfiles
+- ✅ **Branch Protection** bloqueando merges inseguros
+
+---
+
+## 🧪 Verificar que Funciona
+
+### Test 1: Crear un PR de Prueba
+
+```bash
+git checkout -b test/security-pipeline
+echo "# Test" >> TEST.md
+git add TEST.md
+git commit -m "test: Verificar pipeline de seguridad"
+git push origin test/security-pipeline
+
+# Abrir PR
+gh pr create --title "Test: Security Pipeline" --body "Verificar que todos los checks se ejecuten"
+```
+
+### Test 2: Verificar los Checks
+
+1. Ve al PR en GitHub
+2. En la pestaña "Checks" deberías ver:
+ - 🔐 TruffleHog - Detección de Secretos
+ - 🔍 CodeQL - Análisis de Código
+ - 🐍 Python Linting
+ - 📦 Escaneo de Dependencias
+ - 🐳 Trivy - Escaneo Docker
+ - ✅ Validación de PR
+ - 🐳 Dockerfile Linting
+
+3. ⚠️ El botón "Merge" debería estar **deshabilitado** hasta que:
+ - ✅ Todos los checks pasen
+ - ✅ Alguien apruebe el PR
+
+### Test 3: Probar Detección de Secretos (¡NO HAGAS ESTO EN MAIN!)
+
+```bash
+# EN UNA RAMA DE PRUEBA SOLAMENTE
+git checkout -b test/secret-detection
+echo "AWS_SECRET_KEY=AKIAIOSFODNN7EXAMPLE" > fake-secret.txt
+git add fake-secret.txt
+git commit -m "test: Trigger secret detection"
+git push origin test/secret-detection
+
+# TruffleHog DEBERÍA detectarlo y FALLAR el check
+```
+
+---
+
+## 📊 Dónde Ver Resultados
+
+### Durante el Desarrollo (Local)
+```bash
+# Ejecutar checks localmente antes de push
+pre-commit run --all-files
+
+# Solo un check específico
+pre-commit run bandit --all-files
+```
+
+### En GitHub
+
+**Pestaña "Actions"**: Estado de todos los workflows
+- https://github.com/OWNER/REPO/actions
+
+**Pestaña "Security"**: Alertas consolidadas
+- Code scanning: https://github.com/OWNER/REPO/security/code-scanning
+- Dependabot: https://github.com/OWNER/REPO/security/dependabot
+
+**En cada PR**:
+- Tab "Checks": Estado detallado
+- Tab "Files changed": Anotaciones inline de CodeQL
+
+---
+
+## 🔧 Personalización Rápida
+
+### Cambiar tu usuario en Dependabot
+
+```bash
+# Editar .github/dependabot.yml
+sed -i '' 's/irraz/TU-USUARIO/g' .github/dependabot.yml
+```
+
+### Deshabilitar un check temporalmente
+
+```bash
+# Comentar el job en el workflow
+sed -i '' 's/docker-scan:/# docker-scan:/g' .github/workflows/security.yml
+```
+
+### Ajustar severidad de TruffleHog
+
+```yaml
+# En .github/workflows/security.yml
+# Cambiar:
+extra_args: --only-verified
+# A:
+extra_args: --debug # Detecta TODO
+```
+
+---
+
+## 🆘 Solución de Problemas Comunes
+
+### "El check no aparece en Branch Protection"
+
+**Causa**: Debe ejecutarse al menos una vez.
+
+**Solución**: Abre un PR cualquiera, espera que se ejecute, vuelve a Settings.
+
+### "Pre-commit falla con 'command not found'"
+
+```bash
+# Reinstalar
+pip install --upgrade pre-commit
+pre-commit clean
+pre-commit install
+```
+
+### "CodeQL tarda mucho"
+
+Normal en la primera vez. Cachea resultados y es más rápido después.
+
+### "Dependabot crea demasiados PRs"
+
+```yaml
+# En .github/dependabot.yml
+open-pull-requests-limit: 2 # Reducir de 5 a 2
+```
+
+### "False positivo en TruffleHog"
+
+```bash
+# Crear .trufflehogignore en la raíz
+echo "labs/**" >> .trufflehogignore
+echo "tests/**" >> .trufflehogignore
+```
+
+---
+
+## 📚 Siguiente Nivel
+
+### 1. **Notificaciones Slack/Discord**
+
+Agrega al final de `.github/workflows/security.yml`:
+
+```yaml
+- name: Notify on Slack
+ if: failure()
+ uses: 8398a7/action-slack@v3
+ with:
+ status: ${{ job.status }}
+ webhook_url: ${{ secrets.SLACK_WEBHOOK }}
+```
+
+### 2. **Badges en README**
+
+```markdown
+![Security Pipeline](https://github.com/OWNER/REPO/workflows/Security%20Pipeline/badge.svg)
+![CodeQL](https://github.com/OWNER/REPO/workflows/CodeQL/badge.svg)
+```
+
+### 3. **SAST Adicional con Semgrep**
+
+```yaml
+- name: Semgrep
+ uses: returntocorp/semgrep-action@v1
+ with:
+ config: auto
+```
+
+### 4. **Cobertura de Tests**
+
+```yaml
+- name: Coverage
+ run: |
+ pytest --cov=. --cov-report=xml
+- name: Upload to Codecov
+ uses: codecov/codecov-action@v3
+```
+
+---
+
+## 🎯 Checklist Final
+
+- [ ] Pipeline subida a GitHub
+- [ ] Branch protection configurada en `main`
+- [ ] Dependabot habilitado
+- [ ] Code scanning habilitado
+- [ ] Pre-commit hooks instalados localmente
+- [ ] PR de prueba exitoso
+- [ ] Equipo notificado del nuevo proceso
+- [ ] Documentación SECURITY-PIPELINE.md revisada
+
+---
+
+## 💡 Pro Tips
+
+1. **Ejecuta los checks localmente** con pre-commit antes de push para iterar más rápido
+2. **Revisa Dependabot semanalmente** en lugar de ignorar sus PRs
+3. **No ignores warnings** de Bandit, aunque no bloqueen el PR
+4. **Mantén actualizado `.env.example`** para que nuevos devs sepan qué variables necesitan
+5. **Revisa la pestaña Security** al menos una vez al mes
+
+---
+
+**¿Problemas?** Abre un issue o revisa [SECURITY-PIPELINE.md](./SECURITY-PIPELINE.md) para más detalles.
+
+**Tiempo total de setup**: ~5 minutos
+**Beneficio**: Seguridad enterprise-grade **gratis** 🎉
diff --git a/.github/SECURITY-PIPELINE.md b/.github/SECURITY-PIPELINE.md
new file mode 100644
index 0000000..2229741
--- /dev/null
+++ b/.github/SECURITY-PIPELINE.md
@@ -0,0 +1,255 @@
+# 🔐 Pipeline de Seguridad - Vulnerator AI
+
+## Descripción General
+
+Este proyecto implementa una **pipeline de seguridad completa y gratuita** utilizando GitHub Actions, diseñada para ejecutarse automáticamente en cada PR antes de la aprobación.
+
+## 🛡️ Componentes de Seguridad
+
+### 1. **TruffleHog** - Detección de Secretos
+- **Qué hace**: Escanea todo el historial de Git buscando secretos expuestos (API keys, tokens, passwords)
+- **Cuándo se ejecuta**: En cada PR y push a ramas principales
+- **Configuración**: `.github/workflows/security.yml` (job: `secrets-scan`)
+- **Gravedad**: ❌ **BLOQUEA el PR** si encuentra secretos verificados
+
+### 2. **CodeQL** - Análisis Estático de Código (SAST)
+- **Qué hace**: Análisis profundo de seguridad del código Python
+- **Detecta**:
+ - Inyección SQL
+ - XSS (Cross-Site Scripting)
+ - Deserialización insegura
+ - Path traversal
+ - Command injection
+ - Vulnerabilidades CWE comunes
+- **Cuándo se ejecuta**: En cada PR, push y semanalmente
+- **Configuración**: `.github/workflows/security.yml` (job: `codeql-analysis`)
+- **Resultados**: Visibles en la pestaña "Security" → "Code scanning alerts"
+
+### 3. **Linting Python** - Calidad y Seguridad de Código
+- **Herramientas**:
+ - **flake8**: Detección de errores de sintaxis y estilo
+ - **black**: Verificación de formato consistente
+ - **bandit**: Análisis de seguridad específico para Python
+- **Cuándo se ejecuta**: En cada PR
+- **Configuración**: `.github/workflows/security.yml` (job: `python-lint`)
+- **Gravedad**: ⚠️ **NO bloquea** pero genera reportes
+
+### 4. **Safety** - Escaneo de Dependencias Vulnerables
+- **Qué hace**: Verifica vulnerabilidades conocidas en dependencias Python
+- **Escanea**:
+ - `docker/kali/requirements.txt`
+ - `docker/mcp/requirements.txt`
+- **Base de datos**: CVE y advisories de seguridad
+- **Cuándo se ejecuta**: En cada PR
+- **Configuración**: `.github/workflows/security.yml` (job: `dependency-scan`)
+
+### 5. **Trivy** - Escaneo de Imágenes Docker
+- **Qué hace**: Escanea vulnerabilidades en las imágenes Docker
+- **Detecta**:
+ - CVEs en paquetes del sistema operativo
+ - Vulnerabilidades en dependencias
+ - Misconfigurations
+- **Imágenes escaneadas**:
+ - `vulnerator-kali`
+ - `vulnerator-mcp`
+- **Cuándo se ejecuta**: En cada PR
+- **Configuración**: `.github/workflows/security.yml` (job: `docker-scan`)
+- **Gravedad**: Solo reporta CRITICAL y HIGH
+
+### 6. **Hadolint** - Linting de Dockerfiles
+- **Qué hace**: Valida best practices en Dockerfiles
+- **Detecta**:
+ - Uso de `latest` tag
+ - Capas innecesarias
+ - Secretos hardcodeados
+ - Problemas de caché
+- **Cuándo se ejecuta**: En cada PR
+- **Configuración**: `.github/workflows/pr-checks.yml` (job: `dockerfile-lint`)
+
+### 7. **Dependabot** - Actualizaciones Automáticas
+- **Qué hace**: Crea PRs automáticos para actualizar dependencias
+- **Monitorea**:
+ - Dependencias Python (pip)
+ - Imágenes base de Docker
+ - GitHub Actions
+- **Frecuencia**: Semanal
+- **Configuración**: `.github/dependabot.yml`
+- **Alertas de seguridad**: Automáticas en la pestaña "Security" → "Dependabot alerts"
+
+## 🚀 Flujo de Trabajo
+
+### Cuando abres un PR:
+
+```
+1. PR abierto
+ ↓
+2. Se ejecutan automáticamente:
+ ├─ TruffleHog (secretos)
+ ├─ CodeQL (vulnerabilidades)
+ ├─ Python Lint (calidad)
+ ├─ Safety (deps vulnerables)
+ ├─ Trivy (Docker)
+ ├─ Hadolint (Dockerfiles)
+ └─ Validaciones de PR
+ ↓
+3. Resultados visibles en:
+ - Checks del PR
+ - Pestaña "Security"
+ - Comentarios automáticos
+ ↓
+4. ✅ Si todos pasan → PR listo para revisar
+ ❌ Si fallan → Corregir antes de merge
+```
+
+## 📊 Dónde Ver los Resultados
+
+### En el PR:
+- **Checks tab**: Estado de todos los workflows
+- **Files changed**: Anotaciones inline de CodeQL y linters
+- **Comentarios**: Resumen automático de quality checks
+
+### En el Repositorio:
+- **Security tab**:
+ - `Code scanning alerts`: Vulnerabilidades de CodeQL y Trivy
+ - `Dependabot alerts`: Dependencias vulnerables
+ - `Secret scanning`: Secretos detectados (si está habilitado en el repo)
+
+### Artifacts:
+- Reportes JSON de bandit: `bandit-security-report`
+- Reportes JSON de safety: `safety-reports`
+
+## ⚙️ Configuración Inicial
+
+### 1. Habilitar Funciones de Seguridad en GitHub
+
+En tu repositorio, ve a **Settings** → **Security**:
+
+```
+☑️ Dependabot alerts (GRATIS)
+☑️ Dependabot security updates (GRATIS)
+☑️ Code scanning (GRATIS para repos públicos)
+☑️ Secret scanning (GRATIS para repos públicos)
+```
+
+### 2. Subir los Archivos
+
+```bash
+git add .github/
+git commit -m "feat: Agregar pipeline de seguridad completa"
+git push origin main
+```
+
+### 3. Verificar que Funciona
+
+1. Crea un PR de prueba
+2. Ve a la pestaña "Actions" del repositorio
+3. Deberías ver los workflows ejecutándose
+
+## 🔧 Personalización
+
+### Ajustar Severidad de TruffleHog
+
+En `.github/workflows/security.yml`, línea del job `secrets-scan`:
+
+```yaml
+extra_args: --debug --only-verified # Solo secretos verificados
+# O para detectar todos:
+extra_args: --debug # Detecta todos los potenciales secretos
+```
+
+### Cambiar Reviewers de Dependabot
+
+En `.github/dependabot.yml`:
+
+```yaml
+reviewers:
+ - "tu-usuario-github"
+ - "otro-colaborador"
+```
+
+### Deshabilitar un Check
+
+Comenta o elimina el job correspondiente en los archivos YAML.
+
+### Ajustar Frecuencia de Escaneos
+
+En `.github/workflows/security.yml`:
+
+```yaml
+schedule:
+ - cron: '0 2 * * 1' # Lunes a las 2 AM
+ # Cambiar a diario: '0 2 * * *'
+ # Cambiar a mensual: '0 2 1 * *'
+```
+
+## 🐛 Troubleshooting
+
+### TruffleHog encuentra falsos positivos
+
+Crea un archivo `.trufflehogignore` en la raíz:
+
+```
+# Ejemplo de patrones a ignorar
+docker/kali/tests/*.py
+labs/**/*.py
+```
+
+### Safety reporta vulnerabilidad no crítica
+
+Si necesitas ignorar temporalmente:
+
+```bash
+# En el job dependency-scan, agregar:
+safety check --ignore=51457 # Reemplaza con el CVE ID
+```
+
+### CodeQL tarda mucho
+
+Es normal en la primera ejecución. Los escaneos posteriores son incrementales y más rápidos.
+
+## 📈 Métricas y Reportes
+
+### Ver Tendencias de Seguridad
+
+1. Ve a **Insights** → **Security**
+2. Gráficos de:
+ - Alertas abiertas vs cerradas
+ - Tiempo de resolución
+ - Tipos de vulnerabilidades
+
+### Exportar Reportes
+
+Los artifacts JSON están disponibles por 90 días y pueden descargarse desde la pestaña "Actions".
+
+## 🎯 Best Practices
+
+1. **No ignores los warnings**: Revisa cada alerta aunque no bloquee el PR
+2. **Actualiza dependencias regularmente**: Aprueba los PRs de Dependabot
+3. **Revisa los escaneos semanales**: Aunque no haya PR, el scan semanal puede detectar nuevas vulnerabilidades
+4. **Mantén actualizado `.env.example`**: Nunca commites `.env` real
+5. **Usa GitHub Secrets**: Para CI/CD variables sensibles
+
+## 🆓 Costos
+
+**TODO ES GRATUITO** para repositorios públicos y privados (con límites generosos):
+
+- ✅ GitHub Actions: 2,000 minutos/mes gratis
+- ✅ Dependabot: Ilimitado
+- ✅ CodeQL: Gratis para repos públicos
+- ✅ TruffleHog: Open source, gratis
+- ✅ Trivy: Open source, gratis
+
+Para repos privados, los minutos se consumen, pero la cuota gratuita suele ser suficiente.
+
+## 📚 Referencias
+
+- [TruffleHog Docs](https://github.com/trufflesecurity/trufflehog)
+- [CodeQL Docs](https://codeql.github.com/docs/)
+- [Trivy Docs](https://aquasecurity.github.io/trivy/)
+- [Dependabot Docs](https://docs.github.com/en/code-security/dependabot)
+- [GitHub Actions Security](https://docs.github.com/en/actions/security-guides)
+
+---
+
+**Mantenido por**: [@irraz](https://github.com/irraz)
+**Última actualización**: 2026-10-23
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..685ba9d
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,117 @@
+# Configuración de Dependabot para mantener las dependencias actualizadas
+# y recibir alertas de seguridad automáticas
+
+version: 2
+updates:
+ # ============================================================================
+ # DEPENDENCIAS PYTHON - KALI
+ # ============================================================================
+ - package-ecosystem: "pip"
+ directory: "/docker/kali"
+ schedule:
+ interval: "weekly"
+ day: "monday"
+ time: "03:00"
+ open-pull-requests-limit: 5
+ reviewers:
+ - "irraz"
+ labels:
+ - "dependencies"
+ - "python"
+ - "security"
+ commit-message:
+ prefix: "deps(kali)"
+ include: "scope"
+ # Agrupar actualizaciones menores y de parches
+ groups:
+ python-minor-updates:
+ patterns:
+ - "*"
+ update-types:
+ - "minor"
+ - "patch"
+
+ # ============================================================================
+ # DEPENDENCIAS PYTHON - MCP
+ # ============================================================================
+ - package-ecosystem: "pip"
+ directory: "/docker/mcp"
+ schedule:
+ interval: "weekly"
+ day: "monday"
+ time: "03:00"
+ open-pull-requests-limit: 5
+ reviewers:
+ - "irraz"
+ labels:
+ - "dependencies"
+ - "python"
+ - "security"
+ commit-message:
+ prefix: "deps(mcp)"
+ include: "scope"
+ groups:
+ python-minor-updates:
+ patterns:
+ - "*"
+ update-types:
+ - "minor"
+ - "patch"
+
+ # ============================================================================
+ # DEPENDENCIAS DOCKER
+ # ============================================================================
+ - package-ecosystem: "docker"
+ directory: "/docker/kali"
+ schedule:
+ interval: "weekly"
+ day: "tuesday"
+ time: "03:00"
+ open-pull-requests-limit: 3
+ reviewers:
+ - "irraz"
+ labels:
+ - "dependencies"
+ - "docker"
+ - "security"
+ commit-message:
+ prefix: "deps(docker)"
+
+ - package-ecosystem: "docker"
+ directory: "/docker/mcp"
+ schedule:
+ interval: "weekly"
+ day: "tuesday"
+ time: "03:00"
+ open-pull-requests-limit: 3
+ reviewers:
+ - "irraz"
+ labels:
+ - "dependencies"
+ - "docker"
+ - "security"
+ commit-message:
+ prefix: "deps(docker)"
+
+ # ============================================================================
+ # GITHUB ACTIONS
+ # ============================================================================
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ day: "wednesday"
+ time: "03:00"
+ open-pull-requests-limit: 5
+ reviewers:
+ - "irraz"
+ labels:
+ - "dependencies"
+ - "github-actions"
+ - "security"
+ commit-message:
+ prefix: "deps(actions)"
+ groups:
+ github-actions-updates:
+ patterns:
+ - "*"
diff --git a/.github/scripts/local-security-check.sh b/.github/scripts/local-security-check.sh
new file mode 100755
index 0000000..276a051
--- /dev/null
+++ b/.github/scripts/local-security-check.sh
@@ -0,0 +1,261 @@
+#!/bin/bash
+# Script para ejecutar los checks de seguridad LOCALMENTE antes de push
+# Simula lo que ejecutará la pipeline de GitHub Actions
+#
+# Uso: .github/scripts/local-security-check.sh [--fix]
+
+set -e
+
+# Colores
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Flags
+FIX_MODE=false
+if [[ "$1" == "--fix" ]]; then
+ FIX_MODE=true
+fi
+
+echo -e "${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}"
+echo -e "${BLUE}║ 🔐 LOCAL SECURITY CHECK - Vulnerator AI ║${NC}"
+echo -e "${BLUE}╚════════════════════════════════════════════════════════════════╝${NC}"
+echo ""
+
+FAILED_CHECKS=0
+TOTAL_CHECKS=0
+
+# Función para reportar resultado
+report_check() {
+ local check_name=$1
+ local status=$2
+ TOTAL_CHECKS=$((TOTAL_CHECKS + 1))
+
+ if [[ $status -eq 0 ]]; then
+ echo -e "${GREEN}✓${NC} $check_name"
+ else
+ echo -e "${RED}✗${NC} $check_name"
+ FAILED_CHECKS=$((FAILED_CHECKS + 1))
+ fi
+}
+
+# ==============================================================================
+# 1. VERIFICAR DEPENDENCIAS
+# ==============================================================================
+echo -e "\n${YELLOW}[1/7]${NC} Verificando dependencias..."
+
+if ! command -v docker &> /dev/null; then
+ echo -e "${RED}✗ Docker no está instalado${NC}"
+ exit 1
+fi
+
+if ! command -v python3 &> /dev/null; then
+ echo -e "${RED}✗ Python3 no está instalado${NC}"
+ exit 1
+fi
+
+# Verificar/instalar herramientas Python
+pip3 install --quiet --upgrade pip 2>/dev/null || true
+pip3 install --quiet flake8 black bandit safety 2>/dev/null || true
+
+echo -e "${GREEN}✓${NC} Dependencias verificadas"
+
+# ==============================================================================
+# 2. DETECCIÓN DE SECRETOS (TruffleHog simulado con grep)
+# ==============================================================================
+echo -e "\n${YELLOW}[2/7]${NC} 🔐 Escaneando secretos..."
+
+# Patrones comunes de secretos
+SECRET_PATTERNS=(
+ "AKIA[0-9A-Z]{16}" # AWS Access Key
+ "(?i)api[_-]?key['\"]?\s*[:=]\s*['\"][0-9a-zA-Z]{32,45}['\"]"
+ "(?i)password['\"]?\s*[:=]\s*['\"][^'\"]{8,}['\"]"
+ "(?i)secret['\"]?\s*[:=]\s*['\"][0-9a-zA-Z]{32,}['\"]"
+ "-----BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-----"
+)
+
+SECRETS_FOUND=false
+for pattern in "${SECRET_PATTERNS[@]}"; do
+ if grep -rE "$pattern" . \
+ --exclude-dir={.git,.venv,venv,node_modules,.pytest_cache,__pycache__} \
+ --exclude={"*.log","*.pyc",".secrets.baseline"} \
+ --exclude-dir=".github" \
+ 2>/dev/null | grep -v ".env.example" | grep -v "QUICKSTART.md" | grep -v "local-security-check.sh"; then
+ SECRETS_FOUND=true
+ fi
+done
+
+if [[ "$SECRETS_FOUND" == true ]]; then
+ report_check "Detección de secretos" 1
+else
+ report_check "Detección de secretos" 0
+fi
+
+# ==============================================================================
+# 3. PYTHON LINTING (flake8)
+# ==============================================================================
+echo -e "\n${YELLOW}[3/7]${NC} 🐍 Linting Python (flake8)..."
+
+if flake8 . \
+ --count \
+ --select=E9,F63,F7,F82 \
+ --exclude=.venv,venv,.git,__pycache__,.pytest_cache \
+ --show-source \
+ --statistics \
+ &> /tmp/flake8-critical.log; then
+ report_check "Flake8 (errores críticos)" 0
+else
+ cat /tmp/flake8-critical.log
+ report_check "Flake8 (errores críticos)" 1
+fi
+
+# Warnings no bloquean
+flake8 . \
+ --count \
+ --max-complexity=10 \
+ --max-line-length=127 \
+ --exclude=.venv,venv,.git,__pycache__,.pytest_cache \
+ --exit-zero \
+ --statistics \
+ > /tmp/flake8-warnings.log 2>&1
+
+WARNING_COUNT=$(grep -c "^" /tmp/flake8-warnings.log || echo 0)
+if [[ $WARNING_COUNT -gt 0 ]]; then
+ echo -e "${YELLOW}⚠${NC} $WARNING_COUNT warnings de estilo (no bloquean)"
+fi
+
+# ==============================================================================
+# 4. CODE FORMATTING (black)
+# ==============================================================================
+echo -e "\n${YELLOW}[4/7]${NC} 🎨 Verificando formato (black)..."
+
+if [[ "$FIX_MODE" == true ]]; then
+ black . --exclude='/(\.venv|venv|\.git|__pycache__|\.pytest_cache)/' &> /dev/null
+ report_check "Black (auto-formateado)" 0
+else
+ if black --check --diff . --exclude='/(\.venv|venv|\.git|__pycache__|\.pytest_cache)/' &> /tmp/black.log; then
+ report_check "Black (formato)" 0
+ else
+ echo -e "${YELLOW}💡 Ejecuta con --fix para auto-formatear${NC}"
+ report_check "Black (formato)" 1
+ fi
+fi
+
+# ==============================================================================
+# 5. SECURITY CHECK (bandit)
+# ==============================================================================
+echo -e "\n${YELLOW}[5/7]${NC} 🛡️ Análisis de seguridad (bandit)..."
+
+if bandit -r docker/ agent-ooda/ -ll -f text 2>/dev/null > /tmp/bandit.log; then
+ report_check "Bandit (seguridad Python)" 0
+else
+ ISSUES=$(grep -c "Issue:" /tmp/bandit.log || echo 0)
+ if [[ $ISSUES -gt 0 ]]; then
+ echo -e "${YELLOW}⚠${NC} $ISSUES problemas de seguridad encontrados:"
+ cat /tmp/bandit.log
+ report_check "Bandit (seguridad Python)" 1
+ else
+ report_check "Bandit (seguridad Python)" 0
+ fi
+fi
+
+# ==============================================================================
+# 6. DEPENDENCY SCANNING (safety)
+# ==============================================================================
+echo -e "\n${YELLOW}[6/7]${NC} 📦 Escaneando dependencias vulnerables..."
+
+VULN_FOUND=false
+
+# Kali deps
+if [[ -f "docker/kali/requirements.txt" ]]; then
+ if safety check -r docker/kali/requirements.txt --json > /tmp/safety-kali.json 2>/dev/null; then
+ echo -e "${GREEN} ✓${NC} Kali dependencies OK"
+ else
+ VULNS=$(jq '. | length' /tmp/safety-kali.json 2>/dev/null || echo 0)
+ if [[ $VULNS -gt 0 ]]; then
+ echo -e "${RED} ✗${NC} $VULNS vulnerabilidades en Kali dependencies"
+ VULN_FOUND=true
+ fi
+ fi
+fi
+
+# MCP deps
+if [[ -f "docker/mcp/requirements.txt" ]]; then
+ if safety check -r docker/mcp/requirements.txt --json > /tmp/safety-mcp.json 2>/dev/null; then
+ echo -e "${GREEN} ✓${NC} MCP dependencies OK"
+ else
+ VULNS=$(jq '. | length' /tmp/safety-mcp.json 2>/dev/null || echo 0)
+ if [[ $VULNS -gt 0 ]]; then
+ echo -e "${RED} ✗${NC} $VULNS vulnerabilidades en MCP dependencies"
+ VULN_FOUND=true
+ fi
+ fi
+fi
+
+if [[ "$VULN_FOUND" == true ]]; then
+ report_check "Escaneo de dependencias" 1
+else
+ report_check "Escaneo de dependencias" 0
+fi
+
+# ==============================================================================
+# 7. DOCKER LINTING (hadolint si está disponible)
+# ==============================================================================
+echo -e "\n${YELLOW}[7/7]${NC} 🐳 Verificando Dockerfiles..."
+
+if command -v hadolint &> /dev/null; then
+ DOCKER_ERRORS=0
+
+ if hadolint docker/kali/Dockerfile 2>/dev/null; then
+ echo -e "${GREEN} ✓${NC} Kali Dockerfile OK"
+ else
+ echo -e "${RED} ✗${NC} Issues en Kali Dockerfile"
+ DOCKER_ERRORS=1
+ fi
+
+ if hadolint docker/mcp/Dockerfile 2>/dev/null; then
+ echo -e "${GREEN} ✓${NC} MCP Dockerfile OK"
+ else
+ echo -e "${RED} ✗${NC} Issues en MCP Dockerfile"
+ DOCKER_ERRORS=1
+ fi
+
+ report_check "Dockerfile linting" $DOCKER_ERRORS
+else
+ echo -e "${YELLOW}⚠${NC} hadolint no instalado (opcional)"
+ echo " Instalar: brew install hadolint (macOS) o docker run --rm -i hadolint/hadolint"
+fi
+
+# ==============================================================================
+# RESUMEN FINAL
+# ==============================================================================
+echo -e "\n${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}"
+echo -e "${BLUE}║ RESUMEN FINAL ║${NC}"
+echo -e "${BLUE}╚════════════════════════════════════════════════════════════════╝${NC}"
+echo ""
+
+PASSED=$((TOTAL_CHECKS - FAILED_CHECKS))
+echo -e "Total de checks: ${BLUE}$TOTAL_CHECKS${NC}"
+echo -e "Pasaron: ${GREEN}$PASSED${NC}"
+echo -e "Fallaron: ${RED}$FAILED_CHECKS${NC}"
+echo ""
+
+if [[ $FAILED_CHECKS -eq 0 ]]; then
+ echo -e "${GREEN}╔════════════════════════════════════════════════════════════════╗${NC}"
+ echo -e "${GREEN}║ ✅ TODOS LOS CHECKS PASARON - Listo para push ║${NC}"
+ echo -e "${GREEN}╚════════════════════════════════════════════════════════════════╝${NC}"
+ exit 0
+else
+ echo -e "${RED}╔════════════════════════════════════════════════════════════════╗${NC}"
+ echo -e "${RED}║ ❌ ALGUNOS CHECKS FALLARON - Corregir antes de push ║${NC}"
+ echo -e "${RED}╚════════════════════════════════════════════════════════════════╝${NC}"
+ echo ""
+ echo -e "${YELLOW}💡 Sugerencias:${NC}"
+ echo " - Ejecutar con --fix para auto-formatear código"
+ echo " - Revisar los logs arriba para detalles específicos"
+ echo " - Si necesitas saltarte checks: git commit --no-verify"
+ echo ""
+ exit 1
+fi
diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml
new file mode 100644
index 0000000..e5764c5
--- /dev/null
+++ b/.github/workflows/pr-checks.yml
@@ -0,0 +1,172 @@
+name: PR Quality Checks
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened]
+
+jobs:
+ # ============================================================================
+ # VERIFICACIÓN RÁPIDA DE PR
+ # ============================================================================
+ pr-validation:
+ name: ✅ Validación de PR
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check PR title format
+ run: |
+ PR_TITLE="${{ github.event.pull_request.title }}"
+ echo "PR Title: $PR_TITLE"
+
+ # Verificar que el título no esté vacío y tenga longitud razonable
+ if [ ${#PR_TITLE} -lt 10 ]; then
+ echo "❌ El título del PR es demasiado corto (mínimo 10 caracteres)"
+ exit 1
+ fi
+
+ if [ ${#PR_TITLE} -gt 100 ]; then
+ echo "⚠️ El título del PR es muy largo (recomendado <100 caracteres)"
+ fi
+
+ echo "✅ Título del PR válido"
+
+ - name: Check for merge conflicts
+ run: |
+ git fetch origin ${{ github.base_ref }}
+ if git merge-tree $(git merge-base HEAD origin/${{ github.base_ref }}) HEAD origin/${{ github.base_ref }} | grep -q '<<<<<<'; then
+ echo "❌ El PR tiene conflictos de merge"
+ exit 1
+ fi
+ echo "✅ No hay conflictos de merge"
+
+ - name: Check for large files
+ run: |
+ # Verificar que no se añadan archivos muy grandes (>10MB)
+ git diff --name-only origin/${{ github.base_ref }}...HEAD | while read file; do
+ if [ -f "$file" ]; then
+ size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null || echo 0)
+ if [ $size -gt 10485760 ]; then
+ echo "⚠️ Archivo grande detectado: $file ($(numfmt --to=iec $size 2>/dev/null || echo $size bytes))"
+ fi
+ fi
+ done
+
+ # ============================================================================
+ # VERIFICACIÓN DE CAMBIOS SENSIBLES
+ # ============================================================================
+ sensitive-changes:
+ name: 🔒 Revisión de Cambios Sensibles
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Check for sensitive file changes
+ run: |
+ echo "Revisando cambios en archivos sensibles..."
+
+ # Lista de patrones de archivos sensibles
+ SENSITIVE_PATTERNS=(
+ "*.pem"
+ "*.key"
+ "*.p12"
+ "*.pfx"
+ "*.jks"
+ ".env"
+ "*secret*"
+ "*password*"
+ "docker-compose*.yml"
+ )
+
+ FOUND_SENSITIVE=false
+
+ for pattern in "${SENSITIVE_PATTERNS[@]}"; do
+ files=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -i "$pattern" || true)
+ if [ ! -z "$files" ]; then
+ echo "⚠️ Cambios detectados en archivos sensibles que coinciden con: $pattern"
+ echo "$files"
+ FOUND_SENSITIVE=true
+ fi
+ done
+
+ if [ "$FOUND_SENSITIVE" = true ]; then
+ echo ""
+ echo "⚠️⚠️⚠️ ATENCIÓN ⚠️⚠️⚠️"
+ echo "Se detectaron cambios en archivos potencialmente sensibles."
+ echo "Por favor, revisa que no contengan secretos o credenciales."
+ echo "Este es un WARNING, no bloquea el PR."
+ else
+ echo "✅ No se detectaron cambios en archivos sensibles"
+ fi
+
+ # ============================================================================
+ # VERIFICACIÓN DE DOCKERFILE
+ # ============================================================================
+ dockerfile-lint:
+ name: 🐳 Dockerfile Linting
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Lint Dockerfiles with hadolint
+ uses: hadolint/[email protected]
+ with:
+ dockerfile: docker/kali/Dockerfile
+ failure-threshold: warning
+
+ - name: Lint MCP Dockerfile
+ uses: hadolint/[email protected]
+ with:
+ dockerfile: docker/mcp/Dockerfile
+ failure-threshold: warning
+
+ # ============================================================================
+ # COMENTARIO AUTOMÁTICO EN PR
+ # ============================================================================
+ pr-comment:
+ name: 💬 Comentario Automático
+ runs-on: ubuntu-latest
+ needs: [pr-validation, sensitive-changes, dockerfile-lint]
+ if: always()
+ permissions:
+ pull-requests: write
+ steps:
+ - name: Comment PR
+ uses: actions/github-script@v7
+ with:
+ script: |
+ const jobs = ${{ toJSON(needs) }};
+ let status = '✅ Todos los checks pasaron';
+ let emoji = '🎉';
+
+ const failedJobs = Object.entries(jobs).filter(([_, job]) => job.result === 'failure');
+ const warningJobs = Object.entries(jobs).filter(([_, job]) => job.result === 'success');
+
+ if (failedJobs.length > 0) {
+ status = '❌ Algunos checks fallaron';
+ emoji = '⚠️';
+ }
+
+ const comment = `
+ ## ${emoji} Reporte de Quality Checks
+
+ **Status**: ${status}
+
+ ### Resultados:
+ ${Object.entries(jobs).map(([name, job]) => {
+ const icon = job.result === 'success' ? '✅' : job.result === 'failure' ? '❌' : '⏭️';
+ return `- ${icon} **${name}**: ${job.result}`;
+ }).join('\n')}
+
+ ---
+ *Pipeline de seguridad ejecutada automáticamente*
+ `;
+
+ github.rest.issues.createComment({
+ issue_number: context.issue.number,
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ body: comment
+ });
diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml
new file mode 100644
index 0000000..8f30f80
--- /dev/null
+++ b/.github/workflows/security.yml
@@ -0,0 +1,218 @@
+name: Security Pipeline
+
+on:
+ pull_request:
+ branches: [ main, master, develop ]
+ push:
+ branches: [ main, master, develop ]
+ schedule:
+ # Ejecutar escaneo completo semanalmente (lunes a las 2 AM UTC)
+ - cron: '0 2 * * 1'
+
+jobs:
+ # ============================================================================
+ # DETECCIÓN DE SECRETOS CON TRUFFLEHOG
+ # ============================================================================
+ secrets-scan:
+ name: 🔐 TruffleHog - Detección de Secretos
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0 # Historial completo para TruffleHog
+
+ - name: TruffleHog OSS
+ uses: trufflesecurity/trufflehog@main
+ with:
+ path: ./
+ base: ${{ github.event.repository.default_branch }}
+ head: HEAD
+ extra_args: --debug --only-verified
+
+ # ============================================================================
+ # ANÁLISIS DE SEGURIDAD CON CODEQL (SAST)
+ # ============================================================================
+ codeql-analysis:
+ name: 🔍 CodeQL - Análisis de Código
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+
+ strategy:
+ fail-fast: false
+ matrix:
+ language: [ 'python' ]
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v3
+ with:
+ languages: ${{ matrix.language }}
+ queries: security-extended,security-and-quality
+
+ - name: Autobuild
+ uses: github/codeql-action/autobuild@v3
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v3
+ with:
+ category: "/language:${{matrix.language}}"
+
+ # ============================================================================
+ # LINTING Y FORMATEO DE CÓDIGO PYTHON
+ # ============================================================================
+ python-lint:
+ name: 🐍 Python Linting
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.13'
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install flake8 black pylint bandit
+
+ - name: Lint with flake8
+ run: |
+ # Detener el build si hay errores de sintaxis o nombres indefinidos
+ flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
+ # Advertencias por complejidad y longitud de línea
+ flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
+ continue-on-error: true
+
+ - name: Check code formatting with black
+ run: |
+ black --check --diff .
+ continue-on-error: true
+
+ - name: Security check with bandit
+ run: |
+ bandit -r docker/ agent-ooda/ -ll -f json -o bandit-report.json || true
+ bandit -r docker/ agent-ooda/ -ll
+ continue-on-error: true
+
+ - name: Upload bandit results
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: bandit-security-report
+ path: bandit-report.json
+
+ # ============================================================================
+ # ESCANEO DE DEPENDENCIAS PYTHON
+ # ============================================================================
+ dependency-scan:
+ name: 📦 Escaneo de Dependencias
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.13'
+
+ - name: Install safety
+ run: pip install safety
+
+ - name: Check Kali dependencies
+ run: |
+ pip install -r docker/kali/requirements.txt
+ safety check --json > safety-kali-report.json || true
+ safety check
+ continue-on-error: true
+
+ - name: Check MCP dependencies
+ run: |
+ pip install -r docker/mcp/requirements.txt
+ safety check --json > safety-mcp-report.json || true
+ safety check
+ continue-on-error: true
+
+ - name: Upload safety reports
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: safety-reports
+ path: |
+ safety-kali-report.json
+ safety-mcp-report.json
+
+ # ============================================================================
+ # ESCANEO DE CONTENEDORES DOCKER
+ # ============================================================================
+ docker-scan:
+ name: 🐳 Trivy - Escaneo de Imágenes Docker
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Build Kali image
+ run: docker build -t vulnerator-kali:test -f docker/kali/Dockerfile docker/kali
+
+ - name: Run Trivy vulnerability scanner on Kali
+ uses: aquasecurity/trivy-action@master
+ with:
+ image-ref: 'vulnerator-kali:test'
+ format: 'sarif'
+ output: 'trivy-kali-results.sarif'
+ severity: 'CRITICAL,HIGH'
+
+ - name: Upload Trivy results to GitHub Security
+ uses: github/codeql-action/upload-sarif@v3
+ if: always()
+ with:
+ sarif_file: 'trivy-kali-results.sarif'
+ category: 'trivy-kali'
+
+ - name: Build MCP image
+ run: docker build -t vulnerator-mcp:test -f docker/mcp/Dockerfile docker/mcp
+
+ - name: Run Trivy vulnerability scanner on MCP
+ uses: aquasecurity/trivy-action@master
+ with:
+ image-ref: 'vulnerator-mcp:test'
+ format: 'sarif'
+ output: 'trivy-mcp-results.sarif'
+ severity: 'CRITICAL,HIGH'
+
+ - name: Upload Trivy results to GitHub Security
+ uses: github/codeql-action/upload-sarif@v3
+ if: always()
+ with:
+ sarif_file: 'trivy-mcp-results.sarif'
+ category: 'trivy-mcp'
+
+ # ============================================================================
+ # ESCANEO DE ARCHIVOS DE CONFIGURACIÓN Y SECRETOS
+ # ============================================================================
+ config-scan:
+ name: ⚙️ Escaneo de Configuración
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Detect secrets in config files
+ run: |
+ echo "Verificando archivos de configuración sensibles..."
+ # Verificar que no haya archivos .env con secretos reales
+ if [ -f .env ]; then
+ echo "⚠️ Archivo .env encontrado - verificar que no contenga secretos reales"
+ grep -i "api_key\|password\|secret\|token" .env || echo "✅ No se detectaron patrones de secretos"
+ fi
+
+ - name: Check Docker secrets
+ run: |
+ echo "Verificando secretos en Dockerfiles..."
+ grep -rn "ENV.*\(PASSWORD\|SECRET\|TOKEN\|KEY\)" docker/ || echo "✅ No se encontraron secretos hardcodeados en Dockerfiles"
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..80d977a
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,134 @@
+# Pre-commit hooks para ejecutar checks localmente antes de push
+# Instalación: pip install pre-commit && pre-commit install
+#
+# Uso:
+# - Automático: Se ejecuta en cada git commit
+# - Manual: pre-commit run --all-files
+#
+# Para saltar hooks (emergencias): git commit --no-verify
+
+repos:
+ # ============================================================================
+ # HOOKS BÁSICOS DE CALIDAD
+ # ============================================================================
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.6.0
+ hooks:
+ # Evitar commits directos a main
+ - id: no-commit-to-branch
+ args: ['--branch', 'main', '--branch', 'master']
+
+ # Detectar archivos grandes (>500KB)
+ - id: check-added-large-files
+ args: ['--maxkb=500']
+
+ # Verificar que archivos terminen con newline
+ - id: end-of-file-fixer
+
+ # Remover whitespace al final de líneas
+ - id: trailing-whitespace
+
+ # Verificar sintaxis YAML
+ - id: check-yaml
+ args: ['--unsafe'] # Permite tags de Docker Compose
+
+ # Verificar sintaxis JSON
+ - id: check-json
+
+ # Detectar merge conflict markers
+ - id: check-merge-conflict
+
+ # Verificar que scripts tengan shebang
+ - id: check-shebang-scripts-are-executable
+
+ # Detectar private keys
+ - id: detect-private-key
+
+ # Verificar formato de archivos Docker Compose
+ - id: check-yaml
+ files: docker-compose.*\.yml$
+
+ # ============================================================================
+ # SEGURIDAD - DETECCIÓN DE SECRETOS
+ # ============================================================================
+ - repo: https://github.com/Yelp/detect-secrets
+ rev: v1.5.0
+ hooks:
+ - id: detect-secrets
+ args:
+ - '--baseline'
+ - '.secrets.baseline'
+ exclude: |
+ (?x)^(
+ \.env\.example|
+ \.pre-commit-config\.yaml|
+ package-lock\.json|
+ .*\.lock
+ )$
+
+ # ============================================================================
+ # PYTHON - FORMATEO Y LINTING
+ # ============================================================================
+ - repo: https://github.com/psf/black
+ rev: 24.10.0
+ hooks:
+ - id: black
+ language_version: python3.13
+
+ - repo: https://github.com/pycqa/flake8
+ rev: 7.1.1
+ hooks:
+ - id: flake8
+ args:
+ - '--max-line-length=127'
+ - '--extend-ignore=E203,W503'
+ exclude: |
+ (?x)^(
+ .*/__pycache__/.*|
+ .*/.venv/.*|
+ .*/.pytest_cache/.*
+ )$
+
+ - repo: https://github.com/pycqa/bandit
+ rev: 1.7.10
+ hooks:
+ - id: bandit
+ args: ['-ll', '-i'] # Low severity, ignore nosec comments
+ files: \.py$
+ exclude: |
+ (?x)^(
+ .*/tests/.*|
+ .*/test_.*\.py
+ )$
+
+ # ============================================================================
+ # DOCKER - LINTING
+ # ============================================================================
+ - repo: https://github.com/hadolint/hadolint
+ rev: v2.12.0
+ hooks:
+ - id: hadolint-docker
+ args: ['--ignore', 'DL3008', '--ignore', 'DL3009']
+
+ # ============================================================================
+ # PYTHON - IMPORTS Y TYPE CHECKING
+ # ============================================================================
+ - repo: https://github.com/pycqa/isort
+ rev: 5.13.2
+ hooks:
+ - id: isort
+ args: ['--profile', 'black']
+
+ # ============================================================================
+ # MARKDOWN Y DOCUMENTACIÓN
+ # ============================================================================
+ - repo: https://github.com/pre-commit/mirrors-prettier
+ rev: v4.0.0-alpha.8
+ hooks:
+ - id: prettier
+ types_or: [markdown, yaml, json]
+ exclude: |
+ (?x)^(
+ CHANGELOG\.md|
+ .*\.min\.json
+ )$
diff --git a/.secrets.baseline b/.secrets.baseline
new file mode 100644
index 0000000..f292d53
--- /dev/null
+++ b/.secrets.baseline
@@ -0,0 +1,65 @@
+{
+ "version": "1.5.0",
+ "plugins_used": [
+ {
+ "name": "ArtifactoryDetector"
+ },
+ {
+ "name": "AWSKeyDetector"
+ },
+ {
+ "name": "Base64HighEntropyString",
+ "limit": 4.5
+ },
+ {
+ "name": "BasicAuthDetector"
+ },
+ {
+ "name": "CloudantDetector"
+ },
+ {
+ "name": "HexHighEntropyString",
+ "limit": 3.0
+ },
+ {
+ "name": "JwtTokenDetector"
+ },
+ {
+ "name": "KeywordDetector",
+ "keyword_exclude": "example|sample|test|demo|fake|dummy"
+ },
+ {
+ "name": "MailchimpDetector"
+ },
+ {
+ "name": "PrivateKeyDetector"
+ },
+ {
+ "name": "SlackDetector"
+ },
+ {
+ "name": "SquareOAuthDetector"
+ },
+ {
+ "name": "StripeDetector"
+ },
+ {
+ "name": "TwilioKeyDetector"
+ }
+ ],
+ "filters_used": [
+ {
+ "path": "detect_secrets.filters.allowlist.is_line_allowlisted"
+ },
+ {
+ "path": "detect_secrets.filters.common.is_baseline_file",
+ "filename": ".secrets.baseline"
+ },
+ {
+ "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
+ "min_level": 2
+ }
+ ],
+ "results": {},
+ "generated_at": "2026-10-23T00:00:00Z"
+}
diff --git a/README.md b/README.md
index 25989ba..3565083 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,42 @@
</a>
</p>
+<p align="center">
+ <a href="https://github.com/irraz/vulnerator-ai/actions/workflows/security.yml">
+ <img src="https://github.com/irraz/vulnerator-ai/workflows/Security%20Pipeline/badge.svg" alt="Security Pipeline">
+ </a>
+ &nbsp;
+ <a href="https://github.com/irraz/vulnerator-ai/actions/workflows/pr-checks.yml">
+ <img src="https://github.com/irraz/vulnerator-ai/workflows/PR%20Quality%20Checks/badge.svg" alt="PR Checks">
+ </a>
+ &nbsp;
+ <a href="https://github.com/irraz/vulnerator-ai/security/code-scanning">
+ <img src="https://img.shields.io/badge/CodeQL-enabled-success?style=flat-square&logo=github" alt="CodeQL">
+ </a>
+ &nbsp;
+ <a href=".github/SECURITY-PIPELINE.md">
+ <img src="https://img.shields.io/badge/security-pipeline-blue?style=flat-square&logo=security" alt="Security">
+ </a>
+</p>
+
+<p align="center">
+ <a href="https://github.com/irraz/vulnerator-ai/actions/workflows/security.yml">
+ <img src="https://github.com/irraz/vulnerator-ai/workflows/Security%20Pipeline/badge.svg" alt="Security Pipeline">
+ </a>
+ &nbsp;
+ <a href="https://github.com/irraz/vulnerator-ai/actions/workflows/pr-checks.yml">
+ <img src="https://github.com/irraz/vulnerator-ai/workflows/PR%20Quality%20Checks/badge.svg" alt="PR Checks">
+ </a>
+ &nbsp;
+ <a href="https://github.com/irraz/vulnerator-ai/security/code-scanning">
+ <img src="https://img.shields.io/badge/CodeQL-enabled-success?style=flat-square&logo=github" alt="CodeQL">
+ </a>
+ &nbsp;
+ <a href=".github/SECURITY-PIPELINE.md">
+ <img src="https://img.shields.io/badge/security-TruffleHog%20|%20Trivy%20|%20Bandit-blue?style=flat-square&logo=security" alt="Security Tools">
+ </a>
+</p>
+
<p align="center">
<sub><b>Built with</b></sub>
</p>