---
name: "pentest-audit"
description: "In-depth security audit and penetration testing of web, API, and mobile applications. Static source-code analysis, dynamic testing, configuration checks, and generation of structured reports with severity ratings and recommendations. Use this skill whenever the user mentions: pentest, security audit, vulnerability, OWASP, SQL injection, XSS, CSRF, SSRF, IDOR, broken access control, security review, security headers, CSP, CORS, TLS, exposed secrets, fuzzing, security scan, 'is this secure', 'check the security', 'find the flaws', 'audit this code', 'penetration test', 'security check', or any question involving the security of an application, an API, or application infrastructure. Also trigger when the user shares code and asks whether there are potential security issues, even implicitly. Do NOT use for pure architecture questions (that's architecture-conceptor) or for code review without a security angle (that's senior-dev)."
---

# Pentest Audit

## Context

This skill is designed for security audits of your own projects. Every test is performed within an authorized scope — the source code is available, the environment is controlled, and the objective is defensive: find and fix vulnerabilities before an attacker can exploit them.

The approach combines static analysis (reading the code) and dynamic testing (running tools) to produce an actionable report.

## References

Consult these files when the corresponding phase requires it:

- `references/owasp-checklist.md` — Detailed OWASP Top 10 checklist with vulnerable-code patterns per language. **Read during** the static analysis phase.
- `references/dynamic-tools.md` — Usage guide for dynamic testing tools (curl, nuclei, sqlmap, etc.). **Read during** the dynamic testing phase.
- `references/report-template.md` — Exact structure of the security report. **Read when** writing the final report.

---

## 5-phase workflow

Every audit follows these phases in order. Don't skip a phase — the results of each step feed into the next.

### Phase 1: Reconnaissance and mapping

Before hunting for flaws, understand what you're auditing. An audit without mapping produces false positives and misses the real risks.

**Actions:**
1. Identify the tech stack (framework, language, database, third-party services)
2. Map the entry points: HTTP routes, API endpoints, WebSockets, async jobs
3. Identify the authentication and authorization mechanisms
4. Locate sensitive data flows (PII, tokens, passwords, financial data)
5. List external dependencies and their versions

**Tools:**
- `grep`/`glob` to explore the code structure
- Reading configuration files (package.json, docker-compose, .env.example, etc.)
- `npm audit` / `pnpm audit` / `pip audit` for vulnerable dependencies

**Phase 1 deliverable:** A mental map of the application — stack, entry points, data flows, attack surface.

---

### Phase 2: Static code analysis

Read the source code with an attacker's eye. Look for code patterns that lead to exploitable vulnerabilities, not just abstract bad practices.

**Consult `references/owasp-checklist.md` for the specific patterns to look for.**

**Categories to cover systematically:**

#### Injection (SQL, NoSQL, Command, LDAP)
- String concatenation in queries instead of parameterized queries
- User input passed to `exec()`, `eval()`, `child_process`, `os.system()`
- Template strings in SQL/MongoDB queries

#### Broken Authentication
- Passwords stored in plaintext or with a weak hash (MD5, SHA1 without salt)
- JWT tokens without signature verification or with a weak secret
- Sessions that aren't invalidated on logout
- No rate limiting on login endpoints

#### Broken Access Control (IDOR, privilege escalation)
- Endpoints with no authorization check
- Predictable IDs used to access resources without verifying ownership
- Roles checked only on the client side
- Admin endpoints accessible without admin authentication

#### Data Exposure
- Hardcoded secrets (API keys, passwords) in the source code
- Sensitive data in logs
- API responses that return more data than necessary (over-fetching)
- Debug information exposed in production

#### Security Misconfiguration
- Overly permissive CORS (`Access-Control-Allow-Origin: *` with credentials)
- Missing security headers (CSP, X-Frame-Options, HSTS, etc.)
- Debug mode enabled in production
- Sensitive files accessible (.env, .git, backups)

#### XSS (Cross-Site Scripting)
- User data inserted into the DOM without escaping
- `dangerouslySetInnerHTML` in React, `v-html` in Vue, `[innerHTML]` in Angular
- Redirects based on unvalidated parameters (Open Redirect)

#### SSRF (Server-Side Request Forgery)
- User-supplied URLs used in server-side requests without validation
- No allowlist for permitted domains in server-side HTTP calls

#### Deserialization / File Upload
- Deserialization of user-supplied objects without validation
- File uploads without MIME type and extension checks
- File paths built from user input (Path Traversal)

**Working method:**
- For each endpoint/route, trace the data path from user input to storage/display
- Check every validation/sanitization point along that path
- Note the places where validation is missing or insufficient

---

### Phase 3: Configuration audit

Configuration vulnerabilities are the easiest to exploit and the easiest to fix. This phase is a systematic quick win.

**Checks:**

#### Security HTTP headers
```
Content-Security-Policy        — Present and restrictive?
Strict-Transport-Security      — Sufficient max-age (≥ 31536000)?
X-Content-Type-Options         — nosniff?
X-Frame-Options                — DENY or SAMEORIGIN?
Referrer-Policy                — strict-origin-when-cross-origin minimum?
Permissions-Policy             — Restricts camera, microphone, geolocation?
```

#### TLS / HTTPS
- Forced HTTP → HTTPS redirect?
- Minimum TLS version (1.2+)?
- Valid, non-expired certificates?

#### CORS
- Allowed origins explicitly listed (not `*` with credentials)?
- Allowed methods and headers restricted to what's needed?

#### Cookies
- `Secure` flag on all sensitive cookies?
- `HttpOnly` flag on session cookies?
- `SameSite` flag configured (Lax or Strict)?
- Reasonable expiration?

#### Secrets and environment variables
- No secrets in the source code or versioned files?
- `.env` in `.gitignore`?
- Different secrets between dev and production?

#### Docker / Infrastructure (if applicable)
- Containers not running as root?
- Exposed ports limited to the strict minimum?
- Base images up to date?
- Health checks configured?

**Tools:**
- `curl -I <url>` to inspect response headers
- Reading config files directly (nginx.conf, Dockerfile, docker-compose.yml, Traefik config)
- `grep -r` to search for potential secrets in the code

---

### Phase 4: Dynamic testing

Dynamic tests validate what the static analysis found and uncover what the code alone doesn't reveal. Run these tests only against your own environments.

**Consult `references/dynamic-tools.md` for the exact commands.**

**Tests to perform:**

#### Injection
- Send basic SQL injection payloads on input parameters (`' OR 1=1 --`, `'; DROP TABLE--`)
- Test NoSQL injections if using MongoDB (`{"$gt": ""}`, `{"$ne": null}`)
- Test command injections if system calls are detected (`; ls`, `| cat /etc/passwd`)

#### Authentication
- Test brute force on login endpoints (is there a rate limit?)
- Verify that expired tokens are rejected
- Test token reuse after logout

#### Authorization (IDOR)
- Access user A's resource with user B's token
- Modify IDs in URLs/body to access unauthorized resources
- Test access to admin endpoints without an admin role

#### XSS
- Inject `<script>alert(1)</script>` into input fields
- Test encoded payloads (`%3Cscript%3E`, `&#x3C;script&#x3E;`)
- Check API responses that reflect user input

#### SSRF
- If URLs are accepted as input, test access to `http://localhost`, `http://169.254.169.254` (cloud metadata)

#### Rate Limiting
- Send 50+ requests in a burst on sensitive endpoints (login, reset password, expensive APIs)
- Verify that a throttling mechanism exists

**Important:** Record every test performed, the payload used, and the result obtained. This evidence feeds into the report.

---

### Phase 5: Security report

**Consult `references/report-template.md` for the exact structure.**

The report is the final deliverable. It must be actionable — each finding must contain enough information for a developer to fix it without asking questions.

**Report structure:**

```markdown
# Security audit report — [Project name]
Date: [YYYY-MM-DD]
Scope: [What was audited]
Auditor: Claude (assisted by [name])

## Executive summary
[2-3 sentences: overall security posture, number of findings per severity, priority recommendations]

## Metrics
| Severity | Count |
|----------|-------|
| Critical | X     |
| High     | X     |
| Medium   | X     |
| Low      | X     |
| Info     | X     |

## Findings

### [SEVERITY] F-001: [Short title]
- **Category:** OWASP [category]
- **Location:** `file:line` or endpoint
- **Description:** What's wrong and why it's a problem
- **Evidence:** Vulnerable code or dynamic test result
- **Impact:** What an attacker could do
- **Recommendation:** Fixed code or action to take
- **Effort:** [Low / Medium / High]

## Passed checks
[List of checked items that are OK — this matters for showing coverage]

## General recommendations
[Systemic improvements: WAF, monitoring, training, etc.]
```

**Severity scale:**
- **Critical** — Remote exploitation without authentication, full takeover, massive data leak
- **High** — Exploitation requiring basic authentication, privilege escalation, confirmed injection
- **Medium** — Stored XSS, CSRF on sensitive actions, IDOR on non-critical data
- **Low** — Missing headers, minor information disclosure, best practices not followed
- **Info** — Observations, improvement suggestions, no immediate risk

---

## Usage modes

The skill adapts to the context of the request:

### Full audit
The user says: "audit this project", "pentest this app", "do a full security audit"
→ Run all 5 phases in order, produce the complete report.

### Targeted audit
The user says: "check the security headers", "is this route vulnerable to XSS", "check for SQL injections"
→ Run only the relevant phase, produce a focused mini-report.

### Security code review
The user says: "review this file for security", "is this code safe"
→ Phase 2 only on the provided code, with inline findings.

### Fix verification
The user says: "I fixed this vuln, is it good?", "is this patch sufficient"
→ Analyze the fix, verify that it covers the identified attack vector, test whether other vectors exist.

---

## Failure Modes and Recovery

| Problem | Action |
|---------|--------|
| The app isn't running locally (dynamic tests impossible) | Switch to static-only mode, note the dynamic tests to do later in the report |
| A tool (nuclei, sqlmap) isn't installed | Use `curl` as a fallback for manual tests, suggest installing the tool |
| Too many findings to cover in one pass | Prioritize by severity, deliver a partial report noting the areas not covered |
| The request is vague ("is it secure?") | Ask for the scope: the whole project? A file? An endpoint? A type of vulnerability? |
| Suspected false positive | Note it as "to verify" rather than a confirmed finding |
| The code uses an unusual framework/language | Research known vulnerabilities specific to that framework before auditing |
| Restricted network access (no internet for dynamic tests) | Focus on static analysis and local tests, note the tests that require network access |
