<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
---
name: performing-source-code-assisted-penetration-testing
description: >-
  Conduct penetration testing with source code access to identify vulnerabilities
  through combined static analysis and dynamic exploitation, targeting code-level
  weaknesses that black-box testing would miss.
domain: cybersecurity
subdomain: security-testing
tags:
  - source-code
  - grey-box
  - sast
  - code-review
  - exploitation
  - white-box
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190", "T1059", "T1078"]
  tools: ["python3", "semgrep", "codeql", "burp-suite", "gitleaks", "trufflehog"]
---

# Performing Source Code Assisted Penetration Testing

## Overview

Source code assisted penetration testing combines static code review with
dynamic exploitation. Access to source code allows testers to identify
vulnerabilities that scanners miss — custom authentication logic, business
rule bypasses, race conditions, and unsafe deserialization patterns — then
validate them through targeted exploitation.

## Prerequisites

| Requirement | Details |
|---|---|
| Source code repository access (read-only minimum) | Required |
| SAST tools | Semgrep, CodeQL, or SonarQube |
| Dynamic testing tools | Burp Suite, custom scripts |
| Running application instance for validation | Required |
| Development environment for code comprehension | Required |

## Key Concepts

- **Code-guided testing**: Use source to identify attack surface before testing
- **Sink analysis**: Trace dangerous function calls back to user input
- **Authentication review**: Analyze custom auth implementations for flaws
- **Business logic analysis**: Identify workflow violations from code paths
- **Secret scanning**: Find hardcoded credentials and API keys in source

## Workflow

### Step 1: Static Code Analysis

```bash
# Run Semgrep with security rules
semgrep scan --config p/security-audit --config p/owasp-top-ten \
  --json --output semgrep_results.json ./src/

# Secret scanning
gitleaks detect --source . --report-format json --report-path secrets.json
trufflehog filesystem --json --directory . > trufflehog_results.json

# CodeQL analysis for complex vulnerabilities
codeql database create codeql-db --language=python --source-root=./src
codeql database analyze codeql-db codeql/python-queries:codeql-suites/python-security-and-quality.qls \
  --format=sarif-latest --output=codeql_results.sarif
```

### Step 2: Map Code to Attack Surface

```python
def map_attack_surface(semgrep_results: list[dict]) -> dict:
    """Map SAST findings to exploitable attack surface."""
    surface = {
        "sql_injection": [],
        "xss": [],
        "auth_bypass": [],
        "ssrf": [],
        "deserialization": [],
        "command_injection": [],
    }
    for finding in semgrep_results:
        vuln_class = classify_finding(finding)
        if vuln_class in surface:
            surface[vuln_class].append({
                "file": finding["path"],
                "line": finding["start"]["line"],
                "rule": finding["check_id"],
                "snippet": finding.get("extra", {}).get("lines", ""),
            })
    return surface

def classify_finding(finding: dict) -> str:
    """Classify SAST finding into vulnerability category."""
    rule_id = finding.get("check_id", "").lower()
    if "sql" in rule_id:
        return "sql_injection"
    if "xss" in rule_id:
        return "xss"
    if "auth" in rule_id:
        return "auth_bypass"
    if "ssrf" in rule_id:
        return "ssrf"
    return "other"
```

### Step 3: Targeted Dynamic Exploitation

```python
import requests

def exploit_from_code_finding(
    finding: dict,
    base_url: str,
    auth_token: str,
) -> dict:
    """Build targeted exploit from code-level finding."""
    result = {
        "finding": finding["rule"],
        "file": finding["file"],
        "line": finding["line"],
        "exploited": False,
    }
    # Build payload based on sink function identified in code
    if finding["vuln_class"] == "sql_injection":
        endpoint = map_code_to_endpoint(finding["file"], finding["line"])
        payload = "' OR '1'='1' --"
        resp = requests.get(
            f"{base_url}{endpoint}",
            params={"q": payload},
            headers={"Authorization": f"Bearer {auth_token}"},
        )
        result["exploited"] = "error" not in resp.text.lower() and resp.status_code == 200
        result["evidence"] = {"status": resp.status_code, "length": len(resp.text)}
    return result

def map_code_to_endpoint(filepath: str, line: int) -> str:
    """Map source code location to API endpoint via route analysis."""
    # Parse route decorators to find endpoint for given code location
    return "/api/v1/search"
```

### Step 4: Report with Code Context

```bash
node agent.js scan --source ./src --rules security-audit
node agent.js exploit --findings sast_results.json --target https://app.target.com
node agent.js report --sast sast_results.json --dast dast_results.json --format detailed
```

## Detection

```yaml
title: Source Code Assisted Penetration Testing Detection
id: 17f0de12-7a2a-4030-95f5-988257d926f9
status: experimental
description: Detects suspicious activity related to performing source code assisted penetration testing techniques in security testing context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*performing*source*"
  condition: selection
level: medium
tags:
  - attack.t1190
  - attack.t1059
  - attack.t1078
  - attack.discovery
falsepositives:
  - Authorized security testing tools during scheduled assessment windows
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Source Code Assisted Penetration Testing Detection | windows/process_creation | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1190, T1059, T1078 |

## Verification

- [ ] SAST scan completed with security rulesets
- [ ] Secret scanning found no active credentials
- [ ] High-risk SAST findings validated dynamically
- [ ] Custom auth logic manually reviewed
- [ ] Business logic attack paths tested
- [ ] Combined SAST+DAST report delivered

## References

- [Semgrep Rules Registry](https://semgrep.dev/explore)
- [CodeQL Documentation](https://codeql.github.com/docs/)
- [OWASP Code Review Guide](https://owasp.org/www-project-code-review-guide/)
- [NIST SP 800-115 — Technical Guide to Security Testing](https://csrc.nist.gov/publications/detail/sp/800-115/final)
