Orquesta Agentes IA que desarrollan por ti
Verificando...
43-secrets-scanning
Procedimiento: Escaneo de Secrets y Rotaci├│n
Seguridad
1 plugin(s)
Editor
Preview
Tareas
1
Info
Titulo
Escanea el repositorio en busca de secrets expuestos. Detecta API keys, passwords, tokens, y coordina su rotaci├│n si se encuentran comprometidos.
Descripcion
Contenido Markdown
14398 caracteres
Guardar
# Procedimiento: Escaneo de Secrets y Rotaci├│n ## Metadata - **ID**: PROC-43 - **Frecuencia**: Semanal (escaneo), Trimestral (rotaci├│n), Inmediato (si leak detectado) - **Duraci├│n estimada**: 30-60 min (escaneo), 2-4h (rotaci├│n completa) - **Requiere**: Git access, herramientas de scanning (TruffleHog/GitLeaks), acceso a secret managers - **Dependencias**: PROC-40 (Semgrep Security Review) - **Bloquea**: Merge a main si secrets detectados ## Objetivo Detectar secrets expuestos en c├│digo/commits, verificar configuraci├│n segura de credenciales, y ejecutar rotaci├│n programada de API keys y tokens seg├║n pol├¡tica de seguridad. ## Prerrequisitos ### Instalar Herramientas ```bash # TruffleHog (recomendado) pip install trufflehog # O GitLeaks brew install gitleaks # macOS # Windows: descargar de https://github.com/gitleaks/gitleaks/releases # Verificar instalaci├│n trufflehog --version gitleaks version ``` ```powershell # Windows - GitLeaks via Chocolatey choco install gitleaks # O descarga directa $url = "https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_windows_amd64.zip" Invoke-WebRequest -Uri $url -OutFile gitleaks.zip Expand-Archive gitleaks.zip -DestinationPath C:\tools\gitleaks ``` ## Checklist Ejecutable ### 1. Escanear Repositorio Completo ```bash # TruffleHog - Escaneo completo del repo trufflehog git file://. --json > trufflehog-results.json # Resumen de findings cat trufflehog-results.json | jq -r '.Raw' | sort | uniq -c | sort -rn # GitLeaks alternativa gitleaks detect --source . --report-path gitleaks-report.json --report-format json # Ver findings cat gitleaks-report.json | jq '.[] | {rule: .RuleID, file: .File, line: .StartLine}' ``` ```powershell # PowerShell con GitLeaks gitleaks detect --source . --report-path gitleaks-report.json --report-format json --verbose # Parsear resultados $results = Get-Content gitleaks-report.json | ConvertFrom-Json $results | Group-Object RuleID | Select-Object Count, Name | Sort-Object Count -Descending # Mostrar detalles $results | ForEach-Object { Write-Host "[$($_.RuleID)] $($_.File):$($_.StartLine)" -ForegroundColor Yellow Write-Host " Match: $($_.Match.Substring(0, [Math]::Min(50, $_.Match.Length)))..." -ForegroundColor Gray } ``` | Tipo de Secret | Encontrados | Archivos | Severidad | |----------------|-------------|----------|-----------| | AWS Keys | | | CRITICAL | | API Tokens | | | HIGH | | Passwords | | | HIGH | | Private Keys | | | CRITICAL | | Connection Strings | | | HIGH | - [ ] Escaneo completado - [ ] Findings documentados - [ ] Ning├║n secret cr├¡tico en c├│digo actual ### 2. Escanear Historial de Git ```bash # TruffleHog - Escaneo de todo el historial trufflehog git file://. --since-commit HEAD~500 --json > history-scan.json # Contar por tipo cat history-scan.json | jq -r '.DetectorName' | sort | uniq -c | sort -rn # GitLeaks - Historial completo gitleaks detect --source . --log-opts="--all" --report-path history-report.json ``` ```powershell # Escanear ├║ltimos N commits $commitRange = "HEAD~100..HEAD" gitleaks detect --source . --log-opts="$commitRange" --report-path recent-history.json # Buscar en branches espec├¡ficos git branch -r | ForEach-Object { $branch = $_.Trim() Write-Host "Scanning $branch..." -ForegroundColor Cyan gitleaks detect --source . --log-opts="$branch" --report-path "scan-$($branch -replace '/','-').json" 2>$null } ``` - [ ] Historial completo escaneado - [ ] Commits con secrets identificados - [ ] Plan de remediaci├│n para secrets hist├│ricos ### 3. Verificar .gitignore y Pre-commit Hooks ```bash # Verificar que archivos sensibles est├ín en .gitignore SENSITIVE_PATTERNS=( ".env" ".env.*" "*.pem" "*.key" "*credentials*" "*secrets*" "appsettings.*.json" "*.pfx" ) echo "=== Checking .gitignore ===" for pattern in "${SENSITIVE_PATTERNS[@]}"; do if grep -q "$pattern" .gitignore 2>/dev/null; then echo "Ô£à $pattern is in .gitignore" else echo "ÔÜá´©Å $pattern NOT in .gitignore" fi done # Verificar pre-commit hook existe if [ -f .git/hooks/pre-commit ]; then echo "Ô£à Pre-commit hook exists" grep -q "gitleaks\|trufflehog" .git/hooks/pre-commit && echo "Ô£à Secret scanning in pre-commit" else echo "ÔÜá´©Å No pre-commit hook configured" fi ``` ```powershell # Verificar .gitignore $sensitivePatterns = @(".env", "*.pem", "*.key", "*credentials*", "appsettings.*.json") $gitignore = Get-Content .gitignore -ErrorAction SilentlyContinue foreach ($pattern in $sensitivePatterns) { if ($gitignore -match [regex]::Escape($pattern)) { Write-Host "Ô£à $pattern in .gitignore" -ForegroundColor Green } else { Write-Host "ÔÜá´©Å $pattern NOT in .gitignore" -ForegroundColor Yellow } } # Verificar pre-commit $preCommit = ".git\hooks\pre-commit" if (Test-Path $preCommit) { $content = Get-Content $preCommit -Raw if ($content -match "gitleaks|trufflehog") { Write-Host "Ô£à Secret scanning configured in pre-commit" -ForegroundColor Green } } else { Write-Host "ÔÜá´©Å No pre-commit hook" -ForegroundColor Yellow } ``` - [ ] .gitignore incluye patrones sensibles - [ ] Pre-commit hook configurado con secret scanning ### 4. Auditar Variables de CI/CD ```bash # GitLab CI - Listar variables (requiere token con api scope) GITLAB_TOKEN="your-token" PROJECT_ID="your-project-id" curl --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \ "https://gitlab.com/api/v4/projects/$PROJECT_ID/variables" | jq '.[] | {key: .key, masked: .masked, protected: .protected}' # GitHub Actions - Listar secrets (solo nombres, no valores) gh secret list # Azure DevOps az pipelines variable list --pipeline-name "your-pipeline" ``` ```powershell # Azure DevOps - Auditar variable groups $org = "your-org" $project = "your-project" # Listar variable groups az pipelines variable-group list --org "https://dev.azure.com/$org" --project $project --output table # Ver variables de un grupo (valores secretos aparecen como null) az pipelines variable-group variable list --group-id 1 --org "https://dev.azure.com/$org" --project $project ``` **Checklist de Variables CI/CD:** | Variable | Masked | Protected | ├Ültima Rotaci├│n | Necesita Rotaci├│n | |----------|--------|-----------|-----------------|-------------------| | API_KEY | Ô£à | Ô£à | | | | DB_PASSWORD | Ô£à | Ô£à | | | | DEPLOY_TOKEN | Ô£à | ÔØî | | | - [ ] Todas las variables sensibles est├ín masked - [ ] Variables de producci├│n est├ín protected - [ ] No hay variables hardcodeadas en pipelines ### 5. Verificar Secret Managers ```powershell # Azure Key Vault - Listar secrets y verificar expiraci├│n $vaultName = "your-keyvault" $secrets = az keyvault secret list --vault-name $vaultName --query "[].{name:name, enabled:attributes.enabled, expires:attributes.expires}" -o json | ConvertFrom-Json foreach ($secret in $secrets) { $status = if ($secret.enabled) { "Ô£à" } else { "ÔØî" } $expiry = if ($secret.expires) { $daysLeft = ([DateTime]$secret.expires - (Get-Date)).Days if ($daysLeft -lt 30) { "ÔÜá´©Å $daysLeft days" } else { "$daysLeft days" } } else { "No expiry" } Write-Host "$status $($secret.name) - Expires: $expiry" } ``` ```bash # AWS Secrets Manager aws secretsmanager list-secrets --query 'SecretList[].{Name:Name,LastRotated:LastRotatedDate,LastAccessed:LastAccessedDate}' --output table # HashiCorp Vault vault secrets list vault kv list secret/ ``` | Secret | Ubicaci├│n | ├Ültima Rotaci├│n | Pr├│xima Rotaci├│n | Acceso | |--------|-----------|-----------------|------------------|--------| | | Key Vault | | | | | | CI/CD Var | | | | | | .env | | | | - [ ] Todos los secrets est├ín en secret manager (no hardcoded) - [ ] Secrets con expiraci├│n configurada - [ ] ├Ültimas rotaciones documentadas ### 6. Ejecutar Rotaci├│n de Secrets (Si Aplica) ```powershell # Rotaci├│n de API Key - Ejemplo gen├®rico function Rotate-ApiKey { param( [string]$ServiceName, [string]$KeyVaultName, [string]$SecretName ) Write-Host "=== Rotating $ServiceName API Key ===" -ForegroundColor Cyan # 1. Generar nueva key (esto var├¡a por servicio) # $newKey = Invoke-ServiceApiKeyRotation -Service $ServiceName # 2. Actualizar en Key Vault # az keyvault secret set --vault-name $KeyVaultName --name $SecretName --value $newKey # 3. Actualizar en aplicaci├│n (restart/redeploy) # Invoke-ApplicationRestart # 4. Verificar funcionamiento # Test-ServiceConnectivity -Service $ServiceName # 5. Revocar key antigua (despu├®s de confirmar nueva funciona) # Revoke-OldApiKey -Service $ServiceName -OldKey $oldKey Write-Host "Ô£à Rotation completed for $ServiceName" -ForegroundColor Green } # Ejemplo: Rotar Anthropic API Key # 1. Ir a console.anthropic.com > API Keys # 2. Crear nueva key # 3. Actualizar en Key Vault/CI # 4. Verificar que aplicaci├│n funciona # 5. Eliminar key antigua ``` **Procedimiento de Rotaci├│n Segura:** 1. **Generar** nueva credencial en el servicio origen 2. **Almacenar** nueva credencial en secret manager 3. **Desplegar** aplicaci├│n con nueva credencial 4. **Verificar** funcionamiento con nueva credencial 5. **Revocar** credencial antigua (solo despu├®s de verificar) - [ ] Secrets vencidos identificados - [ ] Rotaci├│n ejecutada seg├║n calendario - [ ] Verificaci├│n post-rotaci├│n completada ### 7. Remediaci├│n de Secrets Expuestos ```bash # Si se encuentra un secret en el historial de Git: # 1. INMEDIATAMENTE: Revocar/rotar el secret expuesto # (Ir al servicio correspondiente y generar nuevo secret) # 2. Eliminar del historial con BFG Repo-Cleaner java -jar bfg.jar --replace-text secrets.txt repo.git # O con git filter-repo (m├ís moderno) pip install git-filter-repo git filter-repo --replace-text expressions.txt # 3. Force push (CUIDADO - coordinar con equipo) git push --force --all # 4. Notificar al equipo # 5. Documentar el incidente ``` **Checklist Remediaci├│n:** - [ ] Secret expuesto rotado/revocado INMEDIATAMENTE - [ ] Historial de Git limpiado (si aplica) - [ ] Equipo notificado - [ ] Incidente documentado - [ ] Mejoras preventivas identificadas ### 8. Configurar Alertas de Secrets ```yaml # GitHub - Secret scanning alerts (autom├ítico en repos p├║blicos) # Para repos privados, habilitar en Settings > Security # GitLab - SAST con gitleaks # .gitlab-ci.yml include: - template: Security/Secret-Detection.gitlab-ci.yml secret_detection: stage: test variables: SECRET_DETECTION_HISTORIC_SCAN: "true" ``` ```powershell # Pre-commit hook para bloquear commits con secrets $hookContent = @' #!/bin/sh # Gitleaks pre-commit hook gitleaks protect --staged --verbose if [ $? -ne 0 ]; then echo "ÔØî Secrets detected! Commit blocked." echo "Review the findings above and remove secrets before committing." exit 1 fi '@ $hookContent | Out-File -FilePath ".git\hooks\pre-commit" -Encoding utf8 # En Linux: chmod +x .git/hooks/pre-commit ``` - [ ] Secret scanning habilitado en CI/CD - [ ] Pre-commit hook instalado - [ ] Alertas configuradas para nuevos findings ## Calendario de Rotaci├│n | Secret Type | Frecuencia | ├Ültima | Pr├│xima | Responsable | |-------------|------------|--------|---------|-------------| | API Keys (externos) | 90 d├¡as | | | | | Database passwords | 180 d├¡as | | | | | Service accounts | 365 d├¡as | | | | | SSH Keys | Anual | | | | | Certificates | Antes de expirar | | | | ## Troubleshooting | S├¡ntoma | Causa Probable | Acci├│n | |---------|----------------|--------| | Falsos positivos excesivos | Reglas muy amplias | Configurar allowlist en .gitleaksrc | | Secret en commit antiguo | Leak hist├│rico | Rotar inmediatamente, limpiar historial | | CI falla por secret detection | Commit con secret | Revertir, rotar secret, commit limpio | | Secret manager inaccesible | Permisos, red | Verificar IAM, conectividad | ## Resultado - **├ëxito**: - Cero secrets en c├│digo actual - Todos los secrets en secret manager - Rotaciones al d├¡a seg├║n calendario - Pre-commit hooks configurados - **Parcial**: - Secrets hist├│ricos detectados pero rotados - Algunos falsos positivos pendientes de allowlist - **Fallo**: - Secret activo expuesto en c├│digo ÔåÆ CR├ìTICO, rotar inmediatamente - Secrets no rotados seg├║n pol├¡tica ÔåÆ Escalaci├│n ## Escalaci├│n - **Secret expuesto activo**: Escalaci├│n INMEDIATA a Security Lead - **Secret en c├│digo de producci├│n**: Notificar DevOps + Security - **Rotaci├│n vencida > 30 d├¡as**: Notificar responsable del servicio ## Mensaje de Finalizaci├│n **ACCI├ôN REQUERIDA AL FINALIZAR:** ```bash echo "====== PROCESO TERMINADO [$(date +%H%M%S)] ======" && echo "RESULTADO: Secrets Scan - STATUS, Findings: X (Y critical), Rotations: Z pending" ``` --- ## Output Estructurado (Nexus) Al finalizar, el agente DEBE generar un bloque JSON con el siguiente formato para que Nexus pueda procesarlo automaticamente: ```json { "result": "success", "summary": "Ejecucion de PROC-43 completada. [Descripcion breve de resultados]", "metrics": { "issues_found": 0, "issues_resolved": 0, "findings_total": 5, "findings_critical": 0, "custom": { "procedure_specific_metric": "value" } }, "backlog_items": [ { "title": "Titulo del item de seguimiento", "description": "Descripcion detallada si se requiere accion futura", "priority": "medium", "type": "improvement", "tags": ["proc-43"] } ], "next_steps": [ "Accion recomendada 1", "Accion recomendada 2" ], "warnings": [ "Advertencias encontradas durante la ejecucion" ] } ``` **Campos requeridos:** - `result`: `"success"` | `"partial"` | `"failed"` - `summary`: Resumen ejecutivo en 1-3 lineas **Metricas especificas de este procedure:** - secrets_scanned, secrets_found, secrets_removed **Criterios de resultado:** - `success`: Procedimiento completado sin errores criticos - `partial`: Completado con algunos problemas menores o items pendientes - `failed`: Error critico o no se pudo completar ## Historial de Ejecuciones | Fecha | Ejecutor | Status | Findings | Critical | Rotaciones | Remediaciones | |-------|----------|--------|----------|----------|------------|---------------| | | | | | | | |
H1
H2
H3
Bold
Italic
Code
Lista
Num
Task
Code Block
Link
Nexus Platform
Reconectando
Recuperando la conexion
Se ha interrumpido la conexion con el servidor. Estamos reconectando automaticamente.
Reconectando...
Manten esta pestana abierta, volvemos enseguida.
No hemos podido reconectar
El servidor puede estar reiniciandose o tu conexion a internet es inestable.
Reintentar
La sesion ha expirado
Recarga la pagina para iniciar una nueva sesion.
Recargar
Si no vuelve en 30 segundos, recarga la pagina.