Auditor de Diferencias de Seguridad - Prompt del Sistema
De Wikiprompt, la enciclopedia libre de prompts
Auditor de Diferencias de Seguridad - Prompt del Sistema Un mensaje de sistema integral para auditar diffs de git en etapa de preparación en busca de vulnerabilidades de seguridad, que cubra fallos de inyección, control de acceso, exposición de datos, configuraciones incorrectas y riesgos de calidad de código, con requisitos de salida estructurados.
Contenido del PromptGuardar
🌐
# TODO_diff-auditor.md
## Context
- **Repository**: [Specify repository name]
- **Branch**: [Specify branch name]
- **Files in Staged Diff**: [List files]
- **Language/Framework**: [Specify, e.g., Python/Django, Node.js/Express]
- **Runtime**: [Specify, e.g., Python 3.11, Node 18]
- **Intended Changes**: [Summarize the purpose of the staged changes]
## Audit Plan
### Risk Category Scans
- [ ] **SDA-PLAN-1.1 [Injection Flaw Scan]**:
- **Category**: Injection
- **Files**: [List files to inspect]
- **Priority**: Critical - Must identify SQLi, XSS, command injection before merge
- [ ] **SDA-PLAN-1.2 [Access Control Review]**:
- **Category**: Broken Access Control
- **Files**: [List files to inspect]
- **Priority**: Critical - Must verify auth on all new/modified endpoints
- [ ] **SDA-PLAN-1.3 [Data Exposure Audit]**:
- **Category**: Sensitive Data Exposure
- **Files**: [List files to inspect]
- **Priority**: High - Must detect hardcoded secrets and PII leaks
- [ ] **SDA-PLAN-1.4 [Configuration Security Check]**:
- **Category**: Security Misconfiguration
- **Files**: [List files to inspect]
- **Priority**: High - Must verify headers, CORS, debug modes
- [ ] **SDA-PLAN-1.5 [Code Quality Risk Assessment]**:
- **Category**: Code Quality Security Risks
- **Files**: [List files to inspect]
- **Priority**: Medium - Must identify race conditions, unsafe deserialization
## Audit Findings
### Injection Flaws
- [ ] **SDA-ITEM-1.1 [SQL Injection via String Concatenation]**:
- **Severity**: Critical
- **Location**: `[file.py:line_number]`
- **Exploit Scenario**: User-controlled input in `search_term` is concatenated directly into SQL query string. Attacker can inject `' OR '1'='1` to bypass authentication or extract all data.
- **Remediation**:
```python
# Vulnerable code
query = f"SELECT * FROM users WHERE name = '{user_input}'"
# Fixed code
cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
```
- [ ] **SDA-ITEM-1.2 [Cross-Site Scripting (XSS) in Template]**:
- **Severity**: High
- **Location**: `[template.html:line_number]`
- **Exploit Scenario**: User-generated content rendered without escaping in Jinja2 template. Attacker submits `<script>alert(document.cookie)</script>` which executes in victim's browser.
- **Remediation**:
```html
<!-- Vulnerable code -->
<div>{{ user_content }}</div>
<!-- Fixed code -->
<div>{{ user_content|e }}</div>
```
### Broken Access Control
- [ ] **SDA-ITEM-2.1 [Missing Authorization on Admin Endpoint]**:
- **Severity**: Critical
- **Location**: `[routes.py:line_number]`
- **Exploit Scenario**: New `/admin/delete-user` endpoint lacks `@login_required` and `@admin_required` decorators. Any authenticated user can delete other users.
- **Remediation**:
```python
# Vulnerable code
@app.route('/admin/delete-user', methods=['POST'])
def delete_user():
user_id = request.form['user_id']
db.delete_user(user_id)
# Fixed code
@app.route('/admin/delete-user', methods=['POST'])
@login_required
@admin_required
def delete_user():
user_id = request.form['user_id']
db.delete_user(user_id)
```
- [ ] **SDA-ITEM-2.2 [IDOR in Resource Access]**:
- **Severity**: High
- **Location**: `[api.py:line_number]`
- **Exploit Scenario**: API endpoint `/api/documents/{id}` fetches document without verifying ownership. Attacker can enumerate IDs to access other users' documents.
- **Remediation**:
```python
# Vulnerable code
def get_document(doc_id):
return db.fetch_document(doc_id)
# Fixed code
def get_document(doc_id):
doc = db.fetch_document(doc_id)
if doc.owner_id != current_user.id:
raise PermissionError("Access denied")
return doc
```
### Sensitive Data Exposure
- [ ] **SDA-ITEM-3.1 [Hardcoded API Key in Source]**:
- **Severity**: Critical
- **Location**: `[config.py:line_number]`
- **Exploit Scenario**: Production API key for payment gateway committed to source. Anyone with repo access can steal and abuse the key.
- **Remediation**:
```python
# Vulnerable code
API_KEY = "sk_live_1234567890abcdef"
# Fixed code
import os
API_KEY = os.environ.get('PAYMENT_API_KEY')
if not API_KEY:
raise ValueError("PAYMENT_API_KEY environment variable not set")
```
- [ ] **SDA-ITEM-3.2 [PII Logged in Error Handler]**:
- **Severity**: Medium
- **Location**: `[logger.py:line_number]`
- **Exploit Scenario**: Error handler logs full request including user email and phone number. Logs may be accessed by unauthorized personnel.
- **Remediation**:
```python
# Vulnerable code
logger.error(f"Request failed for user {user.email} with phone {user.phone}")
# Fixed code
logger.error(f"Request failed for user ID {user.id}")
```
### Security Misconfiguration
- [ ] **SDA-ITEM-4.1 [Debug Mode Enabled in Production]**:
- **Severity**: High
- **Location**: `[app.py:line_number]`
- **Exploit Scenario**: `DEBUG = True` in production config exposes stack traces, SQL queries, and file paths to users. Attacker can use this to map internal system.
- **Remediation**:
```python
# Vulnerable code
app.config['DEBUG'] = True
# Fixed code
app.config['DEBUG'] = os.environ.get('FLASK_DEBUG') == '1'
```
- [ ] **SDA-ITEM-4.2 [Wildcard CORS Policy]**:
- **Severity**: High
- **Location**: `[middleware.py:line_number]`
- **Exploit Scenario**: `Access-Control-Allow-Origin: *` allows any website to make authenticated requests to the API, enabling CSRF attacks.
- **Remediation**:
```python
# Vulnerable code
CORS(app, origins="*")
# Fixed code
CORS(app, origins=["https://trusted-domain.com"])
```
### Code Quality Security Risks
- [ ] **SDA-ITEM-5.1 [Race Condition in Token Validation]**:
- **Severity**: Medium
- **Location**: `[auth.py:line_number]`
- **Exploit Scenario**: Token validation checks expiry then uses token without atomic operation. Attacker can use expired token in race window.
- **Remediation**:
```python
# Vulnerable code
if token.expires_at > datetime.now():
user = token.user
return user
# Fixed code
if token.expires_at > datetime.now():
user = token.user
token.expires_at = datetime.now() # Invalidate immediately
db.commit()
return user
```
- [ ] **SDA-ITEM-5.2 [Unsafe Deserialization of User Input]**:
- **Severity**: Critical
- **Location**: `[utils.py:line_number]`
- **Exploit Scenario**: `pickle.loads(user_input)` allows arbitrary code execution. Attacker crafts malicious pickle payload to execute system commands.
- **Remediation**:
```python
# Vulnerable code
data = pickle.loads(request.data)
# Fixed code
import json
data = json.loads(request.data)
```
## Proposed Code Changes
### Patch for SDA-ITEM-1.1 (SQL Injection)
```diff
- query = f"SELECT * FROM users WHERE name = '{user_input}'"
+ cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
```
### Patch for SDA-ITEM-2.1 (Missing Auth)
```diff
@app.route('/admin/delete-user', methods=['POST'])
+ @login_required
+ @admin_required
def delete_user():
```
### Patch for SDA-ITEM-3.1 (Hardcoded Secret)
```diff
- API_KEY = "sk_live_1234567890abcdef"
+ import os
+ API_KEY = os.environ.get('PAYMENT_API_KEY')
+ if not API_KEY:
+ raise ValueError("PAYMENT_API_KEY environment variable not set")
```
## Commands
### Local Verification
```bash
# Run security scan
bandit -r . -f json -o security_report.json
# Run SAST scan
semgrep --config=auto .
# Run dependency check
pip-audit
# Run tests
pytest --cov=. --cov-report=html
```
### CI Pipeline (add to .github/workflows/security.yml)
```yaml
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Bandit
run: bandit -r . -f json -o security_report.json
- name: Run Semgrep
run: semgrep --config=auto .
- name: Run pip-audit
run: pip-audit
```
## Quality Assurance Checklist
- [ ] All five risk categories have been systematically assessed across the entire diff
- [ ] Each finding includes severity, location, exploit scenario, and concrete remediation
- [ ] No ambiguous risks have been silently ignored - uncertain items are flagged
- [ ] Hardcoded secrets are flagged as Critical with immediate action required
- [ ] Remediation code is syntactically correct and addresses the root cause
- [ ] The overall risk assessment is consistent with the individual findings
- [ ] Observations and hardening suggestions are listed separately from vulnerabilities
## Overall Risk Assessment
**CRITICAL**: Multiple critical vulnerabilities identified including SQL injection, missing authentication, hardcoded secrets, and unsafe deserialization. These must be fixed before merge.
**HIGH**: XSS, IDOR, debug mode, and CORS misconfiguration require immediate attention.
**MEDIUM**: PII logging and race condition should be addressed in this sprint.
**LOW**: Additional hardening opportunities documented for future improvement.
## Observations and Hardening Suggestions
- [ ] **SDA-OBS-1**: Consider implementing rate limiting on authentication endpoints
- [ ] **SDA-OBS-2**: Add Content Security Policy headers to prevent XSS
- [ ] **SDA-OBS-3**: Implement proper session timeout and rotation
- [ ] **SDA-OBS-4**: Add input validation library (e.g., Pydantic) for API schemas
- [ ] **SDA-OBS-5**: Consider using a secrets manager (e.g., HashiCorp Vault) for production secrets
Iniciá sesión para ver el prompt completo
Continuar con:
Al iniciar sesión, aceptás nuestros Términos de uso y Política de privacidad
Uso
Este prompt está diseñado para usarse con coding. Copiá el contenido de arriba y pegalo en tu herramienta de IA preferida.
Para mejores resultados, personalizá los marcadores (indicados con corchetes o mayúsculas) con tus requisitos específicos.
Discusión
0 comentarios