# Code Security Audit

> Use when the user wants to audit a codebase for security vulnerabilities, perform a security review, do penetration testing, run a 代码审计 or 安全审查, check for security issues, or verify that security fixes have been applied. Triggers on phrases like "audit this repo", "security review", "find vulnerabilities", "安全审计", "代码审计", "再审计", "verify fixes", "安全扫描".

- **Type:** Skill
- **Install:** `agentstack add skill-azzygoatcoder-claude-useful-skills-code-security-audit`
- **Verified:** Pending review
- **Seller:** [Azzygoatcoder](https://agentstack.voostack.com/s/azzygoatcoder)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [Azzygoatcoder](https://github.com/Azzygoatcoder)
- **Source:** https://github.com/Azzygoatcoder/claude-useful-skills/tree/master/code-security-skills/skills/code-security-audit

## Install

```sh
agentstack add skill-azzygoatcoder-claude-useful-skills-code-security-audit
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Code Security Audit

## Overview

Systematic security audit of any codebase using parallel domain exploration. Launch independent review agents across three security domains simultaneously, then synthesize findings into a structured audit report with severity ratings and concrete remediation steps.

**Core principle:** Coverage through parallelization. Three focused agents catch more than one broad agent — each domain has different grep patterns, different mental models, and different blind spots.

## Slash Commands

| Command | Action |
|---------|--------|
| `/audit` | Full security audit — explore → verify → report (Phase 1–3) |
| `/reaudit` | Verify previous audit fixes were applied (Phase 4) |
| `/reaudit mark-fixed ` | Lightweight: mark a finding as fixed (update status annotation only, no file read) |
| `/reaudit mark-deferred ` | Mark a finding as structurally deferred |
| `/reaudit status` | Show current fix progress (count by status from annotations) |
| `/code-security-audit` | Same as `/audit` (canonical name) |

## When to Use

Trigger when the user asks to:
- Audit a repository or codebase for security issues
- Perform a security review or vulnerability assessment
- Check if security fixes were properly applied (re-audit)
- Find vulnerabilities before a release or deployment

Do NOT use for:
- Reviewing a single PR diff (use `/security-review` or manual review)
- Checking one specific function for bugs (use systematic-debugging)
- General code review for style/architecture (use `/code-review`)

## Audit Workflow

### Pre-Flight — REQUIRED BEFORE Step 0

BEFORE launching any agent or reading any code, complete these checks. This gate is **unconditional** — do not first decide whether the task "needs" it.

1. **Read `references/vulnerability-patterns.md`** — MUST finish before Phase 1. This is a required read, not a reference to skim later.
2. **Run `git rev-parse HEAD`** — store the audit commit hash for the report header.
3. **Identify the project language/framework** — run `ls *.py *.js *.ts *.go *.rs *.java 2>/dev/null` to probe. Customize agent grep patterns accordingly. If no code files found, ask the user what language the project uses.
4. **Check for prior report** — if `docs/SECURITY_AUDIT.md` exists, read the `**Audit commit:**` field. This feeds Step 0.

Any check skipped = audit validity compromised. If you must skip a check, state which one and why BEFORE proceeding.

### Step 0 — Scope Discovery

Before launching Phase 1, determine the review scope:

1. **Check for a previous audit report** at `docs/SECURITY_AUDIT.md`. If it exists, read the `**Audit commit:** ` field.

2. **If a previous audit exists**, run:
   ```bash
   git diff --name-only ..HEAD
   ```
   These are the **changed files** since the last audit. Inject them into each Phase 1 agent prompt as:
   ```
   **Priority files (changed since last audit):** 
   Focus 70% of attention on these files; cover the rest at normal depth.
   ```

3. **If this is the first audit** (no previous report), skip this step. All files get equal attention.

### Phase 1 — Parallel Exploration

Launch **3 Explore agents simultaneously** (single message, parallel tool calls). Each agent covers one security domain.

**Agent A: Secrets & Credentials**
Prompt template:
```
Explore the codebase at  for security issues related to secrets, credentials, and sensitive data handling:
1. Hardcoded API keys, tokens, passwords in source files
2. .env files, config files that might contain secrets
3. How credentials are stored, accessed, and written
4. Any logging or error messages that might leak sensitive data
5. Check .gitignore — are sensitive file patterns properly excluded?
6. Check git history for accidentally committed secrets
For each finding, assign a stable category prefix:
  SECRET (leaked keys/tokens), DEP (file permissions/temp files)
Report findings with specific file paths, line numbers, and code snippets.

**Confidence annotation — REQUIRED on every finding:**
- CONFIDENCE=high: exploit confirmed by code trace to user input
- CONFIDENCE=medium: pattern matches but reachability unclear from grep alone
- CONFIDENCE=low: suspicious pattern, likely requires context to confirm

CONFIDENCE=low findings MUST still be reported — never suppress them. That filtering decision belongs to Phase 2, not Phase 1.
```

**Agent B: Input Validation & Injection**
Prompt template:
```
Explore the codebase at  for security issues related to input validation, injection, and unsafe data handling:
1. Command injection: shell=True, os.system, subprocess with user input in command strings
2. SQL injection if database queries exist
3. Path traversal: user input used in file paths without validation
4. Insecure deserialization: pickle, yaml.load, marshal
5. XSS: innerHTML, document.write, unsanitized user data in HTML context
6. SSRF: user-controlled URLs in HTTP clients without allowlist validation
7. Unsafe eval/exec usage
8. Template injection (SSTI)
For each finding, assign a stable category prefix:
  SSRF (SSRF), PATH (path traversal), CMD (command injection),
  XSS (cross-site scripting), CODE (eval/exec)
Report findings with specific file paths, line numbers, and code snippets.

**Confidence annotation — REQUIRED on every finding:**
- CONFIDENCE=high: exploit confirmed by code trace to user input
- CONFIDENCE=medium: pattern matches but reachability unclear from grep alone
- CONFIDENCE=low: suspicious pattern, likely requires context to confirm

CONFIDENCE=low findings MUST still be reported — never suppress them. That filtering decision belongs to Phase 2, not Phase 1.
```

**Agent C: Auth, Cryptography & Dependencies**
Prompt template:
```
Explore the codebase at  for security issues related to:
1. Authentication and authorization: missing auth checks, weak auth mechanisms
2. Cryptography: weak algorithms (MD5, SHA1, DES), hardcoded keys, improper TLS
3. Session management: insecure cookies, missing HttpOnly/Secure/SameSite
4. CSRF protections on state-changing endpoints
5. Dependency security — check ALL of the following:
   a. Unpinned versions, missing lockfile
   b. Run the appropriate command for the project's ecosystem:
      - Python: pip check (detects version conflicts), safety check (known CVEs)
      - Node: npm audit, npx check-for-known-vulnerabilities
      - Rust: cargo audit
      - Go: govulncheck ./...
      - Java: mvn dependency-check:check
   c. If a previous audit report exists, diff the dependency file:
      git diff ..HEAD -- requirements.txt package.json pyproject.toml Cargo.toml go.mod pom.xml
   d. Flag new dependencies added since last audit — these need extra scrutiny
6. File permissions: credential files with weak permissions
7. Temp file handling: predictable names, missing cleanup
For each finding, assign a stable category prefix:
  AUTH (missing/weak auth), CRYPTO (weak crypto/TLS),
  DEP (dependencies/file-perms/temp-files)
Report findings with specific file paths, line numbers, and code snippets.

**Confidence annotation — REQUIRED on every finding:**
- CONFIDENCE=high: exploit confirmed by code trace to user input
- CONFIDENCE=medium: pattern matches but reachability unclear from grep alone
- CONFIDENCE=low: suspicious pattern, likely requires context to confirm

CONFIDENCE=low findings MUST still be reported — never suppress them. That filtering decision belongs to Phase 2, not Phase 1.
```

**Category-Prefixed IDs are stable** — they don't shift when new findings are added across audits. Use the prefix table in the report template (Phase 3).

**Customize the prompts** based on the codebase language and framework. Add language-specific patterns (e.g., for Python add `os.popen`, for JS add `eval`, for Go add `text/template` without escaping).

**Fallback: if parallel agents fail.** After launching Phase 1 agents, check how many returned valid findings:
- **3 or 2 valid reports** → proceed normally to Phase 2.
- **1 or 0 valid reports** → parallel launch failed. Immediately launch a **single comprehensive Agent** covering all three domains:

```
Explore the codebase at  for ALL security issues across three domains:

Domain A — Secrets & Credentials:
  Hardcoded keys, .env files, credential storage, logging leaks, .gitignore gaps, git history

Domain B — Input Validation & Injection:
  Command injection, SQL injection, path traversal, deserialization, XSS, SSRF, eval/exec

Domain C — Auth, Cryptography & Dependencies:
  Auth checks, weak crypto, session management, CSRF, dependency security, file permissions

For each finding, assign a category prefix (SECRET/DEP, SSRF/PATH/CMD/XSS/CODE, AUTH/CRYPTO/DEP).
Report findings with specific file paths, line numbers, and code snippets.

**Confidence annotation — REQUIRED on every finding.**
Same scale: high/medium/low. Low-confidence findings must still be reported.
```

The comprehensive agent's report replaces the missing parallel reports. Proceed to Phase 2 with whatever results are available.

### Phase 2 — Deep-Dive Verification

After receiving all three agent reports:

1. **Read the flagged files** yourself. Agents provide summaries but you must verify each finding is real.
2. **Filter false positives**. Not everything an agent flags is exploitable. Check context: is user input actually reachable? Is the vulnerable function guarded?
3. **Deduplicate overlapping findings**. Agents A, B, and C may flag the same issue independently. Merge findings that:
   - Share the same file AND lines are within 15 of each other → same root cause
   - Share the same vulnerability category AND same file → likely the same issue
   - Keep the most detailed description; note both agent sources in the merged entry
4. **Run the Finding Self-Check** on every finding BEFORE it enters the report. A finding that fails ANY of these checks is NOT a finding — it is a note or a false positive:

   | # | Check | Fail Action |
   |---|-------|-------------|
   | 1 | Can I trace user input to this code without auth? | No → downgrade severity by 1 level |
   | 2 | Is there a compensating guard within 20 lines? | Yes → document the guard; this is NOT a finding |
   | 3 | Was this confirmed by a DIFFERENT grep/search than the one that found it? | No → mark UNCONFIRMED; do NOT assign above Low |
   | 4 | Can this code path execute in production? | No → informational only; NOT a finding |
   | 5 | Is this a code-quality opinion disguised as a security finding? ("use const", "extract function") | Yes → discard; NOT a finding |

   **Self-Check examples — concrete cases:**

   ```
   CORRECT kill (check 2): Agent flags "subprocess.run(cmd, shell=True)" at line 42.
   Guard at line 38: cmd = shlex.quote(user_input). Check 2 finds the guard → NOT a finding.

   CORRECT downgrade (check 3): Agent flags "pickle.load(open(f))" in a test file.
   Grep found it; no second method confirmed. Check 3 fails → UNCONFIRMED, ceiling = Low.

   CORRECT discard (check 5): "var should be const" → NOT a security finding. Discard.

   WRONG kill: Agent flags "open(user_file)" as path traversal. The agent didn't
   read the allowlist validation 5 lines above. Check 2 SHOULD have caught this.
   ```

5. **Assign severity** to each confirmed (and deduplicated) finding:

| Severity | Criteria | MANDATORY ACTION |
|----------|----------|------------------|
| **Critical** | Remote + unauthenticated → secret access OR arbitrary code execution | **BLOCKER**: Must be confirmed by 2 independent methods. Do not proceed to next finding until a verified exploit path is documented. |
| **High** | Authenticated privilege escalation, injection with confirmed data impact | Must include reproduction steps. Single-method detection → downgrade to Medium. |
| **Medium** | Information disclosure, missing hardening, defense-in-depth gaps | Must note whether compensating controls exist within the codebase. |
| **Low** | Best-practice violations with minimal direct risk | Aggregate into one section. Do NOT spend more than 2 minutes verifying per finding. |

NON-NEGOTIABLE: If a finding cannot meet its severity tier's mandatory action, it MUST be downgraded to the next tier where the action is achievable.

5. **Assign a stable category-prefixed ID** to each finding using this table:

| Prefix | Category | Typical patterns |
|--------|----------|------------------|
| `SSRF` | SSRF / URL injection | Unsanitized URL in HTTP client, Playwright navigation |
| `PATH` | Path traversal | `../` in file paths, missing `is_relative_to` |
| `AUTH` | Missing/weak authentication | Unguarded endpoint, missing auth check |
| `CMD` | Command injection | `shell=True`, `os.system`, MATLAB -batch |
| `XSS` | Cross-site scripting | `innerHTML`, unsanitized HTML output |
| `SECRET` | Secrets/credentials leak | Hardcoded keys, tokens in logs/URL |
| `CRYPTO` | Weak cryptography | MD5/SHA1, `verify=False`, hardcoded keys |
| `DEP` | Dependencies / files / config | Unpinned deps, missing lockfile, temp files, file perms |
| `STATE` | Shared mutable state | Global state without isolation |

Number sequentially within each prefix: `SSRF-1`, `SSRF-2`, `PATH-1`, etc.

### Meta-Cognition Trap — watch for these internal signals

During Phase 2 verification, if you find yourself thinking any of the following, STOP. These are rationalization signals, not valid verification:

- **"This is probably fine in practice"** → That IS the signal to escalate, not dismiss. Probabilities are not verification. Trace the dataflow before closing.
- **"User input will never reach this code"** → Assumption-based dismissal is the #1 source of false negatives. Verify with a concrete code path, not intuition.
- **"The fix is obvious, no need to document it"** → Every finding MUST include concrete remediation code. No exceptions. An undocumented fix is not a fix.
- **"This is just how the framework works"** → Frameworks have CVEs too. Flag it; let the report reader decide.

These are NOT valid reasons to close a finding. When you catch yourself using them, reopen the finding for deeper review.

### Phase 3 — Report Compilation

Write the audit report to an agreed location. Use this exact structure:

```
# [Project Name] Security Audit Report

**Date:** [date]
**Audit commit:** [git rev-parse HEAD]
**Scope:** [what was reviewed]
**Methodology:** Three parallel reviews covering (1) secrets & credentials,
  (2) input validation & injection, (3) authentication, cryptography & dependencies

## Executive Summary
One paragraph: total findings by severity, most critical issues, overall risk posture.

## Risk Distribution
Table: | Severity | Count | Finding IDs |

## Critical Findings
One subsection per finding:

### SSRF-1 — [title]

- **Finding:** title
- **Severity:** Critical
- **File:** path (line numbers)
- **Description:** what and why it matters
- **Vulnerable code:** fenced code block
- **Remediation:** concrete fix with corrected code

## High Findings
[Same format with category-prefixed IDs]

## Medium Findings
[Same format with category-prefixed IDs]

## Low Findings
[Same format with category-prefixed IDs]

## Cross-Cutting Recommendations
Themes spanning multiple findings.

## Remediation Priority Matrix
Table: | ID | Finding | Effort | Impact | Priority (P1-P4) |

## Appendix
Commit hash, verification guidance per finding.
```

**Status annotation format** (the `` line after each finding title):

```

```

| Field | Required | Values |
|-------|----------|--------|
| `STATUS` | Yes | `open` → `fixed` → `deferred` → `not-fixed` → `partial` |
| `SEVERITY` | Yes | `critical` / `high` / `medium` / `low` |
| `FILE` | Yes | Relative path from repo root |
| `LINES` | Yes | Line range (e.g., `123-145`) |
| `COMMIT` | On fix | Hash of the commit that resolved this finding |

This annotation enables lightweight `mark-fixed` (just edit this line) and diff-based incremental re-audit (compare `FILE` + `LINES` against `git diff`).

### Phase 4 — Re-Audit (When Fixes Are Applied)

When the user says fix

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [Azzygoatcoder](https://github.com/Azzygoatcoder)
- **Source:** [Azzygoatcoder/claude-useful-skills](https://github.com/Azzygoatcoder/claude-useful-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** yes
- **Shell / process execution:** yes
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: flagged — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-azzygoatcoder-claude-useful-skills-code-security-audit
- Seller: https://agentstack.voostack.com/s/azzygoatcoder
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
