Casos de Uso¶
Ejemplos practicos del mundo real para usar mcp-scan efectivamente.
Tabla de Contenidos¶
- Desarrollo de un Servidor MCP
- Auditoria de Seguridad
- Migracion de Codigo Legacy
- Revision de Codigo de Terceros
- Cumplimiento y Compliance
- Monitoreo Continuo
- Integracion con Herramientas Existentes
- Entrenamiento de Equipos
Desarrollo de un Servidor MCP¶
Escenario¶
Estas desarrollando un servidor MCP que permite a usuarios ejecutar consultas a una base de datos.
Codigo Inicial (Vulnerable)¶
# server.py
from mcp import Server, tool
import sqlite3
server = Server("db-query-server")
@tool
def query_database(sql_query: str) -> str:
"""Execute a SQL query against the database."""
conn = sqlite3.connect('app.db')
cursor = conn.cursor()
cursor.execute(sql_query) # VULNERABLE: SQL Injection
return str(cursor.fetchall())
@tool
def read_config(filename: str) -> str:
"""Read a configuration file."""
with open(filename, 'r') as f: # VULNERABLE: Path Traversal
return f.read()
if __name__ == "__main__":
server.run()
Paso 1: Escaneo Inicial¶
Resultados:
CRITICAL: 2
- MCP-D002: SQL injection via string concatenation (server.py:12)
- MCP-B002: Potential path traversal (server.py:17)
MSSS Score: 35/100
Compliance Level: 0 (Not Compliant)
Paso 2: Corregir Vulnerabilidades¶
# server.py (corregido)
from mcp import Server, tool
import sqlite3
import os
server = Server("db-query-server")
# Lista de consultas permitidas
ALLOWED_QUERIES = {
"list_users": "SELECT id, name FROM users",
"count_orders": "SELECT COUNT(*) FROM orders",
}
ALLOWED_CONFIG_FILES = ["app.yaml", "settings.yaml"]
CONFIG_DIR = "/etc/myapp/"
@tool
def query_database(query_name: str) -> str:
"""Execute a predefined SQL query.
Args:
query_name: Name of the query to execute. Must be one of:
'list_users', 'count_orders'
"""
if query_name not in ALLOWED_QUERIES:
return f"Error: Unknown query '{query_name}'. Allowed: {list(ALLOWED_QUERIES.keys())}"
sql = ALLOWED_QUERIES[query_name]
conn = sqlite3.connect('app.db')
cursor = conn.cursor()
cursor.execute(sql) # Seguro: SQL predefinido
return str(cursor.fetchall())
@tool
def read_config(filename: str) -> str:
"""Read a configuration file.
Args:
filename: Name of the config file. Must be one of:
'app.yaml', 'settings.yaml'
"""
# Validar nombre de archivo
if filename not in ALLOWED_CONFIG_FILES:
return f"Error: File '{filename}' not allowed"
# Usar basename para evitar path traversal
safe_name = os.path.basename(filename)
filepath = os.path.join(CONFIG_DIR, safe_name)
# Verificar que sigue en el directorio permitido
if not os.path.abspath(filepath).startswith(os.path.abspath(CONFIG_DIR)):
return "Error: Invalid path"
with open(filepath, 'r') as f:
return f.read()
if __name__ == "__main__":
server.run()
Paso 3: Re-escanear¶
Resultados:
Paso 4: Configurar CI/CD¶
# .github/workflows/security.yml
name: Security
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
curl -sSL https://raw.githubusercontent.com/mcphub/mcp-scan/main/install.sh | bash
mcp-scan scan . --fail-on high --output sarif > results.sarif
- uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
Auditoria de Seguridad¶
Escenario¶
Tu empresa necesita auditar un servidor MCP antes de desplegarlo en produccion.
Paso 1: Configuracion de Auditoria¶
# .mcp-scan-audit.yaml
include:
- "**/*.py"
- "**/*.ts"
- "**/*.js"
exclude:
- "**/tests/**"
- "**/node_modules/**"
scan:
mode: deep
timeout: 1h
fail_on: medium
rules:
disabled: []
severity_overrides:
MCP-E001: critical
MCP-E002: critical
output:
redact_snippets: true # Confidencialidad
llm:
enabled: true
threshold: 0.8
ml:
enabled: true
confidence_threshold: 0.8
codeql:
enabled: true
Paso 2: Ejecutar Auditoria¶
# Crear directorio de auditoria
mkdir -p audit-$(date +%Y%m%d)
cd audit-$(date +%Y%m%d)
# Ejecutar escaneo profundo
mcp-scan scan /path/to/mcp-server \
--config ../.mcp-scan-audit.yaml \
--mode deep \
--output evidence \
> evidence-bundle.json
# Generar reporte SARIF
mcp-scan scan /path/to/mcp-server \
--config ../.mcp-scan-audit.yaml \
--mode deep \
--output sarif \
> audit-sarif.sarif
# Extraer superficie MCP
mcp-scan surface /path/to/mcp-server \
--output json \
> mcp-surface.json
Paso 3: Analizar Resultados¶
# Resumen de hallazgos
jq '.summary' evidence-bundle.json
# Hallazgos criticos
jq '.findings[] | select(.severity == "critical")' evidence-bundle.json
# Score MSSS
jq '.msss_score' evidence-bundle.json
# Tools detectados
jq '.mcp_surface.tools[].name' evidence-bundle.json
Paso 4: Generar Reporte¶
# Script para generar reporte
cat > generate-report.sh << 'EOF'
#!/bin/bash
BUNDLE=$1
DATE=$(date +%Y-%m-%d)
echo "# Reporte de Auditoria de Seguridad"
echo "Fecha: $DATE"
echo ""
echo "## Resumen Ejecutivo"
echo ""
echo "| Metrica | Valor |"
echo "|---------|-------|"
echo "| Score MSSS | $(jq '.msss_score.score' $BUNDLE)/100 |"
echo "| Nivel de Cumplimiento | $(jq -r '.msss_score.level_name' $BUNDLE) |"
echo "| Total Hallazgos | $(jq '.summary.total' $BUNDLE) |"
echo "| Criticos | $(jq '.summary.by_severity.critical' $BUNDLE) |"
echo "| Altos | $(jq '.summary.by_severity.high' $BUNDLE) |"
echo ""
echo "## Hallazgos Criticos"
echo ""
jq -r '.findings[] | select(.severity == "critical") | "- **\(.rule_id)**: \(.title)\n - Archivo: \(.location.file):\(.location.line)\n - Remediacion: \(.remediation)"' $BUNDLE
EOF
chmod +x generate-report.sh
./generate-report.sh evidence-bundle.json > AUDIT-REPORT.md
Migracion de Codigo Legacy¶
Escenario¶
Tienes un servidor MCP antiguo que necesita ser actualizado y asegurado.
Paso 1: Evaluacion Inicial¶
# Escaneo completo del legacy
mcp-scan scan ./legacy-server \
--mode deep \
--output json \
> legacy-scan.json
# Ver resumen
jq '.summary' legacy-scan.json
# Listar todos los hallazgos por archivo
jq '[.findings[] | {file: .location.file, rule: .rule_id}] | group_by(.file) | map({file: .[0].file, count: length})' legacy-scan.json
Paso 2: Crear Baseline de Legacy¶
# Generar baseline para hallazgos que no se pueden arreglar inmediatamente
mcp-scan baseline generate \
--from legacy-scan.json \
--reason "Legacy code - scheduled for refactoring in Q2 2026" \
--accepted-by "tech-lead@example.com" \
--output legacy-baseline.json
# Revisar y editar baseline
nano legacy-baseline.json
Paso 3: Priorizar Correcciones¶
# Crear lista de prioridades
jq -r '.findings | group_by(.severity) | map({severity: .[0].severity, items: map({file: .location.file, rule: .rule_id, line: .location.line})})' legacy-scan.json > priorities.json
# Primero criticos
echo "=== CRITICOS (Arreglar inmediatamente) ==="
jq '.[] | select(.severity == "critical") | .items[]' priorities.json
# Despues altos
echo "=== ALTOS (Arreglar esta semana) ==="
jq '.[] | select(.severity == "high") | .items[]' priorities.json
Paso 4: Migracion Incremental¶
# Configuracion para migracion
cat > .mcp-scan-migration.yaml << 'EOF'
scan:
mode: fast
fail_on: critical # Solo bloquear criticos nuevos
# Usar baseline de legacy
# mcp-scan scan . --baseline legacy-baseline.json
EOF
# Escanear solo nuevos hallazgos
mcp-scan scan ./legacy-server \
--baseline legacy-baseline.json \
--fail-on critical
Paso 5: Tracking de Progreso¶
# Script para tracking
cat > track-progress.sh << 'EOF'
#!/bin/bash
DATE=$(date +%Y-%m-%d)
BASELINE_COUNT=$(jq '.entries | length' legacy-baseline.json)
SCAN_COUNT=$(jq '.summary.total' legacy-scan.json)
echo "$DATE,$BASELINE_COUNT,$SCAN_COUNT" >> migration-progress.csv
echo "Date: $DATE"
echo "Baselined: $BASELINE_COUNT"
echo "Total (pre-fix): $SCAN_COUNT"
echo "Fixed: $((SCAN_COUNT - BASELINE_COUNT))"
EOF
Revision de Codigo de Terceros¶
Escenario¶
Necesitas evaluar un servidor MCP de terceros antes de integrarlo.
Paso 1: Preparacion¶
# Clonar repositorio
git clone https://github.com/third-party/mcp-server.git
cd mcp-server
# Ver estructura
find . -name "*.py" -o -name "*.ts" -o -name "*.js" | head -20
Paso 2: Escaneo Completo¶
# Escaneo con todas las opciones
mcp-scan scan . \
--mode deep \
--output evidence \
> third-party-audit.json
# Ver superficie MCP
mcp-scan surface . --output json > surface.json
Paso 3: Analisis de Riesgo¶
# Script de analisis
cat > analyze-third-party.sh << 'EOF'
#!/bin/bash
EVIDENCE=$1
echo "=== ANALISIS DE RIESGO ==="
echo ""
# Score
SCORE=$(jq '.msss_score.score' $EVIDENCE)
echo "Score MSSS: $SCORE/100"
if [ $SCORE -lt 60 ]; then
echo "RIESGO: ALTO - No cumple requisitos minimos"
elif [ $SCORE -lt 80 ]; then
echo "RIESGO: MEDIO - Cumple requisitos basicos"
else
echo "RIESGO: BAJO - Cumple requisitos enterprise"
fi
echo ""
echo "=== SUPERFICIE DE ATAQUE ==="
TOOLS=$(jq '.mcp_surface.tools | length' $EVIDENCE)
echo "Tools expuestos: $TOOLS"
jq -r '.mcp_surface.tools[] | " - \(.name): \(.description // "Sin descripcion")"' $EVIDENCE
echo ""
echo "=== HALLAZGOS POR SEVERIDAD ==="
jq -r '.summary.by_severity | to_entries | map(" \(.key): \(.value)") | .[]' $EVIDENCE
echo ""
echo "=== HALLAZGOS CRITICOS ==="
jq -r '.findings[] | select(.severity == "critical") | " - \(.rule_id): \(.title)"' $EVIDENCE
echo ""
echo "=== RECOMENDACION ==="
CRITICAL=$(jq '.summary.by_severity.critical' $EVIDENCE)
HIGH=$(jq '.summary.by_severity.high' $EVIDENCE)
if [ $CRITICAL -gt 0 ]; then
echo "NO APROBAR - Contiene vulnerabilidades criticas"
elif [ $HIGH -gt 2 ]; then
echo "REVISAR - Multiples vulnerabilidades altas"
elif [ $SCORE -ge 80 ]; then
echo "APROBAR con condiciones"
else
echo "APROBAR para uso limitado"
fi
EOF
chmod +x analyze-third-party.sh
./analyze-third-party.sh third-party-audit.json
Paso 4: Documentar Decision¶
# Generar documento de decision
cat > SECURITY-REVIEW.md << EOF
# Revision de Seguridad: third-party/mcp-server
## Fecha: $(date +%Y-%m-%d)
## Resultado del Escaneo
- **Score MSSS:** $(jq '.msss_score.score' third-party-audit.json)/100
- **Nivel:** $(jq -r '.msss_score.level_name' third-party-audit.json)
## Hallazgos
| Severidad | Cantidad |
|-----------|----------|
| Critical | $(jq '.summary.by_severity.critical' third-party-audit.json) |
| High | $(jq '.summary.by_severity.high' third-party-audit.json) |
| Medium | $(jq '.summary.by_severity.medium' third-party-audit.json) |
| Low | $(jq '.summary.by_severity.low' third-party-audit.json) |
## Decision
[ ] Aprobado
[ ] Aprobado con condiciones
[ ] Rechazado
## Condiciones (si aplica)
-
## Revisado por
-
EOF
Cumplimiento y Compliance¶
Escenario¶
Tu organizacion requiere evidencias de analisis de seguridad para auditorias SOC2/ISO27001.
Paso 1: Configuracion para Compliance¶
# .mcp-scan-compliance.yaml
scan:
mode: deep
timeout: 1h
rules:
disabled: []
severity_overrides:
MCP-E001: critical
MCP-E002: critical
MCP-E005: critical
MCP-A003: critical
MCP-A004: critical
output:
redact_snippets: true
llm:
enabled: true
threshold: 0.9
codeql:
enabled: true
Paso 2: Escaneo con Evidencias¶
# Crear directorio de evidencias
AUDIT_DIR="compliance-evidence-$(date +%Y%m%d)"
mkdir -p $AUDIT_DIR
# Escaneo completo
mcp-scan scan . \
--config .mcp-scan-compliance.yaml \
--mode deep \
--output evidence \
> $AUDIT_DIR/evidence-bundle.json
# Hash de las evidencias
sha256sum $AUDIT_DIR/evidence-bundle.json > $AUDIT_DIR/evidence.sha256
# Metadata
cat > $AUDIT_DIR/metadata.json << EOF
{
"scan_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"tool": "mcp-scan",
"version": "$(mcp-scan version --short)",
"repository": "$(git remote get-url origin)",
"commit": "$(git rev-parse HEAD)",
"branch": "$(git branch --show-current)"
}
EOF
Paso 3: Generar Reporte de Compliance¶
# Script de reporte
cat > generate-compliance-report.py << 'EOF'
#!/usr/bin/env python3
import json
import sys
from datetime import datetime
with open(sys.argv[1]) as f:
evidence = json.load(f)
report = f"""
# Reporte de Compliance de Seguridad
## Informacion General
- **Fecha de Escaneo:** {evidence['scan_info']['started_at']}
- **Herramienta:** mcp-scan v{evidence['version']}
- **Modo:** {evidence['scan_info']['mode']}
- **Duracion:** {evidence['duration']['total_ms']}ms
## Resultado de Seguridad
| Metrica | Valor |
|---------|-------|
| Score MSSS | {evidence['msss_score']['score']}/100 |
| Nivel de Cumplimiento | {evidence['msss_score']['level_name']} |
### Mapeo a Requisitos
| Requisito | Estado | Evidencia |
|-----------|--------|-----------|
| Control de Acceso (A.9) | {'Cumple' if evidence['msss_score']['score'] >= 60 else 'No Cumple'} | Score >= 60 |
| Seguridad de Desarrollo (A.14) | {'Cumple' if evidence['summary']['by_severity'].get('critical', 0) == 0 else 'No Cumple'} | Sin criticos |
| Gestion de Vulnerabilidades (A.12) | Cumple | Escaneo automatizado |
## Hallazgos
| Severidad | Cantidad |
|-----------|----------|
| Critical | {evidence['summary']['by_severity'].get('critical', 0)} |
| High | {evidence['summary']['by_severity'].get('high', 0)} |
| Medium | {evidence['summary']['by_severity'].get('medium', 0)} |
| Low | {evidence['summary']['by_severity'].get('low', 0)} |
## Conclusion
El sistema {'cumple' if evidence['msss_score']['level'] >= 1 else 'NO cumple'} con los requisitos
minimos de seguridad establecidos.
---
Generado automaticamente por mcp-scan
"""
print(report)
EOF
python3 generate-compliance-report.py $AUDIT_DIR/evidence-bundle.json > $AUDIT_DIR/COMPLIANCE-REPORT.md
Paso 4: Archivar Evidencias¶
# Crear paquete de evidencias
cd $AUDIT_DIR
tar -czvf ../compliance-evidence-$(date +%Y%m%d).tar.gz .
# Verificar integridad
sha256sum ../compliance-evidence-$(date +%Y%m%d).tar.gz
Monitoreo Continuo¶
Escenario¶
Quieres monitorear la postura de seguridad de tu servidor MCP a lo largo del tiempo.
Paso 1: Script de Monitoreo¶
#!/bin/bash
# monitor-security.sh
REPO_PATH=$1
DATA_DIR="${2:-./security-metrics}"
mkdir -p $DATA_DIR
# Ejecutar escaneo
mcp-scan scan $REPO_PATH --mode fast --output json > /tmp/scan-result.json
# Extraer metricas
DATE=$(date +%Y-%m-%d)
SCORE=$(jq '.msss_score.score' /tmp/scan-result.json)
TOTAL=$(jq '.summary.total' /tmp/scan-result.json)
CRITICAL=$(jq '.summary.by_severity.critical' /tmp/scan-result.json)
HIGH=$(jq '.summary.by_severity.high' /tmp/scan-result.json)
MEDIUM=$(jq '.summary.by_severity.medium' /tmp/scan-result.json)
# Guardar metricas
echo "$DATE,$SCORE,$TOTAL,$CRITICAL,$HIGH,$MEDIUM" >> $DATA_DIR/metrics.csv
# Guardar resultado completo
cp /tmp/scan-result.json $DATA_DIR/scan-$DATE.json
# Mostrar resumen
echo "=== Security Metrics for $DATE ==="
echo "Score: $SCORE/100"
echo "Total: $TOTAL (C:$CRITICAL H:$HIGH M:$MEDIUM)"
# Alerta si score baja
if [ -f $DATA_DIR/last-score ]; then
LAST_SCORE=$(cat $DATA_DIR/last-score)
if [ $SCORE -lt $LAST_SCORE ]; then
echo "WARNING: Score decreased from $LAST_SCORE to $SCORE"
fi
fi
echo $SCORE > $DATA_DIR/last-score
Paso 2: Configurar Cron¶
# Ejecutar diariamente
crontab -e
# Agregar linea:
0 2 * * * /path/to/monitor-security.sh /path/to/repo /path/to/metrics >> /var/log/security-monitor.log 2>&1
Paso 3: Dashboard de Metricas¶
#!/usr/bin/env python3
# generate-dashboard.py
import csv
import json
from datetime import datetime
def generate_dashboard(metrics_file, output_file):
with open(metrics_file) as f:
reader = csv.reader(f)
data = list(reader)
html = """
<!DOCTYPE html>
<html>
<head>
<title>Security Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.card { border: 1px solid #ddd; padding: 20px; margin: 10px; border-radius: 8px; }
.score { font-size: 48px; font-weight: bold; }
.score.good { color: green; }
.score.medium { color: orange; }
.score.bad { color: red; }
</style>
</head>
<body>
<h1>Security Dashboard</h1>
<div class="card">
<h2>Current Score</h2>
<div class="score {score_class}">{current_score}/100</div>
</div>
<div class="card">
<h2>Score Trend</h2>
<canvas id="scoreChart"></canvas>
</div>
<script>
const ctx = document.getElementById('scoreChart').getContext('2d');
new Chart(ctx, {{
type: 'line',
data: {{
labels: {labels},
datasets: [{{
label: 'MSSS Score',
data: {scores},
borderColor: 'blue',
fill: false
}}]
}},
options: {{
scales: {{
y: {{ min: 0, max: 100 }}
}}
}}
}});
</script>
</body>
</html>
"""
labels = [row[0] for row in data[-30:]] # Ultimos 30 dias
scores = [int(row[1]) for row in data[-30:]]
current_score = scores[-1] if scores else 0
score_class = "good" if current_score >= 80 else "medium" if current_score >= 60 else "bad"
html = html.format(
current_score=current_score,
score_class=score_class,
labels=json.dumps(labels),
scores=json.dumps(scores)
)
with open(output_file, 'w') as f:
f.write(html)
if __name__ == "__main__":
import sys
generate_dashboard(sys.argv[1], sys.argv[2])
Integracion con Herramientas Existentes¶
Con SonarQube¶
# Convertir resultados a formato SonarQube Generic Issue
mcp-scan scan . --output json | jq '{
issues: [.findings[] | {
engineId: "mcp-scan",
ruleId: .rule_id,
severity: (if .severity == "critical" then "CRITICAL" elif .severity == "high" then "MAJOR" elif .severity == "medium" then "MINOR" else "INFO" end),
type: "VULNERABILITY",
primaryLocation: {
message: .title,
filePath: .location.file,
textRange: {
startLine: .location.line,
endLine: .location.end_line
}
}
}]
}' > sonar-issues.json
# Subir a SonarQube
sonar-scanner -Dsonar.externalIssuesReportPaths=sonar-issues.json
Con Jira¶
# Crear issues en Jira para hallazgos criticos
mcp-scan scan . --output json | jq -r '.findings[] | select(.severity == "critical") | @json' | while read finding; do
TITLE=$(echo $finding | jq -r '.title')
DESC=$(echo $finding | jq -r '.description')
FILE=$(echo $finding | jq -r '.location.file')
LINE=$(echo $finding | jq -r '.location.line')
curl -X POST \
-H "Content-Type: application/json" \
-u "$JIRA_USER:$JIRA_TOKEN" \
"$JIRA_URL/rest/api/2/issue" \
-d "{
\"fields\": {
\"project\": {\"key\": \"SEC\"},
\"summary\": \"[MCP-Scan] $TITLE\",
\"description\": \"$DESC\\n\\nUbicacion: $FILE:$LINE\",
\"issuetype\": {\"name\": \"Security Vulnerability\"},
\"priority\": {\"name\": \"Critical\"}
}
}"
done
Con Slack Webhooks¶
#!/bin/bash
# notify-slack.sh
WEBHOOK_URL=$1
RESULTS=$2
SCORE=$(jq '.msss_score.score' $RESULTS)
CRITICAL=$(jq '.summary.by_severity.critical' $RESULTS)
HIGH=$(jq '.summary.by_severity.high' $RESULTS)
if [ $CRITICAL -gt 0 ] || [ $HIGH -gt 0 ]; then
COLOR="danger"
EMOJI=":warning:"
else
COLOR="good"
EMOJI=":white_check_mark:"
fi
curl -X POST $WEBHOOK_URL \
-H 'Content-Type: application/json' \
-d "{
\"attachments\": [{
\"color\": \"$COLOR\",
\"title\": \"$EMOJI Security Scan Results\",
\"fields\": [
{\"title\": \"Score\", \"value\": \"$SCORE/100\", \"short\": true},
{\"title\": \"Critical\", \"value\": \"$CRITICAL\", \"short\": true},
{\"title\": \"High\", \"value\": \"$HIGH\", \"short\": true}
]
}]
}"
Entrenamiento de Equipos¶
Escenario¶
Quieres usar mcp-scan para entrenar a tu equipo en seguridad de MCP.
Material de Entrenamiento¶
# Crear proyecto de entrenamiento
mkdir mcp-security-training
cd mcp-security-training
# Crear ejercicios vulnerables
cat > exercise1_rce.py << 'EOF'
"""Ejercicio 1: Detectar RCE
Tu mision: Encontrar y corregir la vulnerabilidad de ejecucion de comandos.
"""
from mcp import tool
import subprocess
@tool
def run_command(cmd: str) -> str:
"""Run a system command."""
# TODO: Esta linea es vulnerable. Como la arreglarias?
return subprocess.check_output(cmd, shell=True).decode()
# HINT: Usa una lista de comandos permitidos o subprocess sin shell=True
EOF
cat > exercise2_sqli.py << 'EOF'
"""Ejercicio 2: Detectar SQL Injection
Tu mision: Encontrar y corregir la vulnerabilidad de SQL injection.
"""
from mcp import tool
import sqlite3
@tool
def search_user(name: str) -> str:
"""Search for a user by name."""
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
# TODO: Esta query es vulnerable. Como la arreglarias?
cursor.execute(f"SELECT * FROM users WHERE name = '{name}'")
return str(cursor.fetchall())
# HINT: Usa parametros en lugar de f-strings
EOF
# Crear guia de ejercicios
cat > TRAINING.md << 'EOF'
# Entrenamiento de Seguridad MCP
## Ejercicios
### Ejercicio 1: Ejecucion Remota de Comandos
- Archivo: exercise1_rce.py
- Objetivo: Identificar y corregir vulnerabilidad RCE
```bash
# Escanear
mcp-scan scan exercise1_rce.py
# Ver hallazgo
mcp-scan scan exercise1_rce.py --output json | jq '.findings[0]'
Ejercicio 2: SQL Injection¶
- Archivo: exercise2_sqli.py
- Objetivo: Identificar y corregir SQL injection
Verificacion¶
Despues de corregir, ejecuta:
Si no hay hallazgos, completaste el ejercicio. EOF
### Workshop Interactivo
```bash
#!/bin/bash
# workshop.sh - Workshop interactivo de seguridad
echo "=== Workshop de Seguridad MCP ==="
echo ""
echo "Este workshop te guiara a traves de la deteccion y correccion de vulnerabilidades."
echo ""
# Ejercicio 1
echo "=== EJERCICIO 1: RCE ==="
echo "Escaneando exercise1_rce.py..."
mcp-scan scan exercise1_rce.py
echo ""
read -p "Presiona Enter para ver la solucion..."
echo ""
echo "SOLUCION: Usa una whitelist de comandos permitidos:"
echo "
ALLOWED_COMMANDS = ['ls', 'pwd', 'date']
if cmd not in ALLOWED_COMMANDS:
return 'Comando no permitido'
return subprocess.check_output([cmd])
"
# Ejercicio 2
echo ""
echo "=== EJERCICIO 2: SQL Injection ==="
echo "Escaneando exercise2_sqli.py..."
mcp-scan scan exercise2_sqli.py
echo ""
read -p "Presiona Enter para ver la solucion..."
echo ""
echo "SOLUCION: Usa parametros SQL:"
echo "
cursor.execute('SELECT * FROM users WHERE name = ?', (name,))
"
echo ""
echo "=== WORKSHOP COMPLETADO ==="
Anterior: Integracion CI/CD | Volver al Indice: README