# Penetration Testing Orchestration Instructions

## Objective
Coordinate multi-phase security assessments, manage workflows, and integrate various testing components into a cohesive penetration testing process.

## Workflow Orchestration

### Standard Penetration Test Flow

```
┌─────────────────────────────────────────────────────┐
│  1. RECONNAISSANCE & SCOPE DEFINITION               │
│  - Identify target components                       │
│  - Determine testing boundaries                     │
│  - Select appropriate testing modules               │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│  2. STATIC ANALYSIS (SAST)                          │
│  - Code security review                             │
│  - Infrastructure configuration analysis            │
│  - Dependency vulnerability scanning                │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│  3. FINDING TRIAGE & PRIORITIZATION                 │
│  - Deduplicate findings                             │
│  - Apply false positive filters                     │
│  - Assign severity ratings                          │
│  - Prioritize for dynamic testing                   │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│  4. DYNAMIC TESTING (Future Phase)                  │
│  - Generate attack payloads                         │
│  - Execute test scenarios                           │
│  - Confirm vulnerabilities                          │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│  5. FINDING AGGREGATION & CORRELATION               │
│  - Combine SAST + dynamic results                   │
│  - Identify attack chains                           │
│  - Calculate business impact                        │
└─────────────────┬───────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────┐
│  6. REPORT GENERATION                               │
│  - Executive summary                                │
│  - Technical findings                               │
│  - Remediation guidance                             │
│  - Compliance mapping                               │
└─────────────────────────────────────────────────────┘
```

---

## Phase 1: Reconnaissance & Scoping

### Objectives
- Understand the target application/system architecture
- Define testing boundaries and exclusions
- Select appropriate testing strategies

### Actions

1. **Identify Components**:
   - Parse repository structure
   - Detect programming languages and frameworks
   - Identify infrastructure-as-code files (Terraform, K8s YAML)
   - Locate configuration files (Docker, CI/CD)

2. **Determine Scope**:
   - PR mode: Only changed files and their dependencies
   - Full scan: Entire codebase and infrastructure
   - Custom: User-defined paths/components

3. **Risk Profiling**:
   - High-risk components: Authentication, payment processing, admin panels
   - External interfaces: APIs, webhooks, integrations
   - Data handling: Database interactions, file uploads, encryption

### Output
```json
{
  "scope": {
    "mode": "pull_request",
    "changed_files": 12,
    "languages": ["Python", "JavaScript", "YAML"],
    "frameworks": ["Flask", "React"],
    "infrastructure": ["Docker", "Kubernetes"],
    "risk_profile": {
      "authentication_components": 2,
      "api_endpoints": 15,
      "database_interactions": 8,
      "file_operations": 3
    }
  }
}
```

---

## Phase 2: Static Analysis Execution

### Module Invocation

Execute SAST analyzers in parallel:

```python
parallel_tasks = [
    analyze_code_security(),      # Core SAST
    analyze_infrastructure(),     # IaC scanning
    analyze_dependencies(),       # CVE detection
    analyze_api_security(),       # API endpoint review
    analyze_configuration()       # Framework configs
]

findings = await asyncio.gather(*parallel_tasks)
```

### Analysis Modules

1. **Code Security Analysis**:
   - Input: Source code files
   - Process: Execute security-review.md instructions
   - Output: Code-level vulnerabilities

2. **Infrastructure Analysis**:
   - Input: Terraform, K8s, Docker files
   - Process: Check for misconfigurations
   - Output: Infrastructure vulnerabilities

3. **Dependency Analysis**:
   - Input: requirements.txt, package.json, go.mod
   - Process: CVE matching, version checks
   - Output: Vulnerable dependency list

4. **API Security Analysis**:
   - Input: Route definitions, API specs (OpenAPI)
   - Process: Check for insecure endpoints, missing auth
   - Output: API vulnerability findings

5. **Configuration Analysis**:
   - Input: Framework configs, environment files
   - Process: Security settings review
   - Output: Configuration weaknesses

### Progress Tracking

```
┌─────────────────────────────────────────────┐
│ STATIC ANALYSIS PROGRESS                    │
├─────────────────────────────────────────────┤
│ Code Security         [████████████] 100%   │
│ Infrastructure        [██████████  ] 80%    │
│ Dependencies          [████████████] 100%   │
│ API Security          [████████    ] 60%    │
│ Configuration         [████████████] 100%   │
└─────────────────────────────────────────────┘
```

---

## Phase 3: Finding Triage & Prioritization

### Objectives
- Deduplicate findings across modules
- Filter false positives
- Assign accurate severity ratings
- Create prioritized remediation list

### Deduplication Logic

```python
def deduplicate_findings(findings):
    """
    Group similar findings by:
    - File + line number
    - Vulnerability type (CWE)
    - Code pattern match
    """
    unique_findings = {}
    
    for finding in findings:
        fingerprint = generate_fingerprint(finding)
        
        if fingerprint in unique_findings:
            # Merge findings, keep highest severity
            existing = unique_findings[fingerprint]
            if finding.severity > existing.severity:
                unique_findings[fingerprint] = finding
        else:
            unique_findings[fingerprint] = finding
    
    return list(unique_findings.values())
```

### False Positive Filtering

Apply context-aware filters:

1. **Framework Protections**:
   - Django auto-escapes templates → XSS lower priority
   - Flask-SQLAlchemy uses parameterized queries → SQL injection false positive

2. **Input Validation**:
   - Check for upstream validation before flagging injection

3. **Test Code**:
   - Reduce severity for vulnerabilities in test files

4. **Configuration Context**:
   - Debug mode flagged, but check if production environment

### Severity Adjustment

```python
def adjust_severity(finding, context):
    """
    Adjust severity based on:
    - Exploitability
    - Attack complexity
    - Scope (local vs remote)
    - Data sensitivity
    """
    
    if finding.category == "SQL_INJECTION":
        if context.has_waf:
            finding.severity = reduce_severity(finding.severity)
        if context.database_contains_pii:
            finding.severity = increase_severity(finding.severity)
    
    return finding
```

### Prioritization

Sort findings by:
1. Severity (Critical > High > Medium > Low)
2. Exploitability (Remote > Local)
3. Business impact (PII exposure > Availability)
4. Confidence level (High > Medium > Low)

---

## Phase 4: Dynamic Testing Orchestration (Future)

### Test Plan Generation

```python
def generate_test_plan(sast_findings):
    """
    Convert static findings to executable test scenarios.
    """
    test_scenarios = []
    
    for finding in sast_findings:
        if finding.category == "SQL_INJECTION":
            scenario = {
                "type": "sql_injection",
                "target": finding.file,
                "endpoint": extract_endpoint(finding),
                "payloads": generate_sql_payloads(),
                "expected_behaviors": [
                    "error_message_leakage",
                    "time_based_blind",
                    "union_based"
                ]
            }
            test_scenarios.append(scenario)
    
    return test_scenarios
```

### Execution Strategy

```python
async def execute_dynamic_tests(test_scenarios, environment):
    """
    Execute tests with safety controls.
    """
    
    # Safety checks
    if environment == "production":
        raise ValueError("Dynamic testing not allowed in production")
    
    # Rate limiting
    rate_limiter = RateLimiter(requests_per_second=2)
    
    # Execute with monitoring
    results = []
    for scenario in test_scenarios:
        result = await execute_with_monitoring(
            scenario,
            timeout=30,
            rate_limiter=rate_limiter
        )
        results.append(result)
        
        # Circuit breaker
        if result.caused_service_disruption:
            logger.critical("Test caused disruption, halting")
            break
    
    return results
```

---

## Phase 5: Finding Aggregation

### Correlation Engine

Identify multi-step attack chains:

```python
def correlate_findings(sast_findings, dynamic_results):
    """
    Identify attack chains where exploiting one vulnerability
    enables exploitation of another.
    """
    
    chains = []
    
    # Example: Auth bypass → Data access
    auth_bypass = find_by_category(sast_findings, "AUTH_BYPASS")
    data_exposure = find_by_category(sast_findings, "IDOR")
    
    if auth_bypass and data_exposure:
        chain = AttackChain(
            steps=[auth_bypass, data_exposure],
            impact="Complete unauthorized data access",
            severity="CRITICAL"
        )
        chains.append(chain)
    
    return chains
```

### Business Impact Calculation

```python
def calculate_business_impact(finding, context):
    """
    Quantify business risk.
    """
    
    impact = {
        "financial": 0,
        "reputational": 0,
        "regulatory": 0
    }
    
    if finding.exposes_pii:
        impact["financial"] = context.records_exposed * 200  # $200 per record
        impact["regulatory"] = "GDPR/CCPA violation"
    
    if finding.allows_data_manipulation:
        impact["reputational"] = "HIGH - Customer trust loss"
    
    return impact
```

---

## Phase 6: Report Generation

### Report Assembly

```python
def generate_comprehensive_report(findings, metadata):
    """
    Assemble all components into final report.
    """
    
    report = {
        "executive_summary": generate_executive_summary(findings),
        "methodology": generate_methodology_section(metadata),
        "findings": format_findings(findings),
        "risk_matrix": generate_risk_matrix(findings),
        "remediation_roadmap": generate_roadmap(findings),
        "appendices": {
            "cvss_details": generate_cvss_appendix(findings),
            "compliance_mapping": map_to_compliance(findings),
            "evidence": collect_evidence(findings)
        }
    }
    
    return report
```

### Multi-Format Export

```python
# JSON for CI/CD integration
export_json(report, "pentest_results.json")

# HTML for human review
export_html(report, "pentest_report.html")

# PDF for executive distribution
export_pdf(report, "pentest_report.pdf")

# Markdown for PR comments
export_markdown(report, summary_only=True)
```

---

## Integration Points

### CI/CD Integration

**Trigger**: Pull request, scheduled scan, manual invocation

**Process**:
1. Checkout code at specified commit/branch
2. Run orchestrated assessment
3. Post results to PR comments / Slack / Jira
4. Block merge if critical findings (configurable)

**Example GitHub Action**:
```yaml
- name: Run Penetration Test
  uses: anthropics/pentesting-skill@v1
  with:
    severity-threshold: high
    fail-on-critical: true
    comment-pr: true
```

### Issue Tracker Integration

Auto-create tickets for findings:

```python
def create_jira_issues(findings):
    for finding in findings:
        if finding.severity in ["CRITICAL", "HIGH"]:
            jira.create_issue(
                project="SEC",
                summary=finding.title,
                description=finding.description,
                priority=map_severity_to_priority(finding.severity),
                labels=["security", "pentesting", finding.category]
            )
```

---

## Error Handling & Resilience

### Timeout Management

```python
async def run_with_timeout(task, timeout_minutes):
    try:
        return await asyncio.wait_for(task, timeout=timeout_minutes*60)
    except asyncio.TimeoutError:
        logger.warning(f"Task timed out after {timeout_minutes} minutes")
        return PartialResult(status="timeout")
```

### Graceful Degradation

If a module fails, continue with others:

```python
async def run_all_modules(modules):
    results = {}
    
    for module in modules:
        try:
            results[module.name] = await module.execute()
        except Exception as e:
            logger.error(f"Module {module.name} failed: {e}")
            results[module.name] = ErrorResult(error=str(e))
    
    return results
```

---

## Configuration

### Policy File Format

`.security/pen-test-policies.json`:

```json
{
  "scan_scope": "changed_files",
  "severity_threshold": "medium",
  "false_positive_filters": true,
  "custom_rules": [
    {
      "id": "CUSTOM-001",
      "pattern": "hardcoded_api_key",
      "severity": "critical",
      "message": "API keys must be in environment variables"
    }
  ],
  "excluded_paths": [
    "tests/",
    "vendor/",
    "node_modules/"
  ],
  "compliance_frameworks": ["OWASP", "PCI-DSS", "NIST"],
  "dynamic_testing": {
    "enabled": false,
    "environment": "staging",
    "max_requests_per_second": 2
  },
  "reporting": {
    "formats": ["json", "html"],
    "include_evidence": true,
    "executive_summary": true
  }
}
```

---

## Success Metrics

Track orchestration effectiveness:

```python
metrics = {
    "total_runtime_seconds": 245,
    "modules_executed": 5,
    "modules_failed": 0,
    "findings_discovered": 23,
    "findings_after_dedup": 18,
    "false_positives_filtered": 7,
    "report_generated": True,
    "integrations_notified": ["GitHub", "Slack"]
}
```

