# Code Security

> >

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

## Install

```sh
agentstack add skill-sam-dumont-claude-skills-code-security
```

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

## About

# Python Code Security Skill

This skill combines **static analysis tools** with **LLM-powered dynamic analysis** to provide
comprehensive security coverage. Static tools catch known patterns; Claude reasons about logic
flaws, business rule bypasses, and context-dependent vulnerabilities that no static tool can detect.

## Two-Layer Security Model

```
┌─────────────────────────────────────────────────────────┐
│  Layer 1: Static Analysis (Automated)                   │
│  Bandit · pip-audit · ruff S-rules · secrets detection  │
│  → Known vulnerability patterns, CVEs, exposed secrets  │
├─────────────────────────────────────────────────────────┤
│  Layer 2: LLM Dynamic Analysis (Claude)                 │
│  Code path reasoning · business logic review            │
│  → Logic flaws, auth bypasses, race conditions,         │
│    context-dependent vulnerabilities                    │
└─────────────────────────────────────────────────────────┘
```

---

## Layer 1: Static Analysis Tools

### Tool Stack

| Tool | Purpose | Invocation |
|------|---------|------------|
| **Bandit** | Python-specific security linter (SAST) | `uvx bandit -r src/` |
| **pip-audit** | Dependency CVE scanner | `uvx pip-audit` |
| **ruff S-rules** | Bandit rules integrated in ruff | `uv run ruff check --select S src/` |
| **detect-secrets** | Secrets/credentials in source code | `uvx detect-secrets scan` |
| **safety** | Alternative dependency vulnerability check | `uvx safety check` |

### Makefile Targets

Add these targets to the project Makefile:

```makefile
# =============================================================================
# Security
# =============================================================================

# Security lint (Bandit) — high severity only for CI gates
security-lint:
	uvx bandit -r src/ --severity-level high -q

# Full security lint (all severities) — for thorough review
security-lint-full:
	uvx bandit -r src/ -f json -o bandit-report.json || true
	@echo "Full report: bandit-report.json"
	uvx bandit -r src/

# Dependency vulnerability audit
pip-audit:
	uvx pip-audit -r = amount: user.balance -= amount  → without DB transaction lock
3. Check permission, then perform action in separate DB queries
```

#### 6. Cryptographic Issues

- Using MD5/SHA1 for security purposes (only acceptable for checksums)
- Hardcoded IVs or salts
- ECB mode encryption
- Custom crypto implementations (never roll your own)
- Insufficient key lengths

#### 7. Dependency & Supply Chain

- Are dependencies pinned to specific versions?
- Are there known-vulnerable transitive dependencies?
- Is `requirements.txt` used without hashes?
- Are lock files (`uv.lock`, `poetry.lock`) committed?

#### 8. Error Handling & Information Disclosure

- Do error messages expose internal paths, stack traces, or config?
- Are database errors returned directly to users?
- Do 500 errors reveal framework versions?
- Are different error messages returned for "user not found" vs "wrong password"? (user enumeration)

---

## Running a Full Security Audit

When asked to perform a security review, follow this protocol:

### Phase 1: Static Analysis (Automated)

```bash
# Run all static tools
make security-lint-full    # Bandit full report
make pip-audit             # Dependency CVEs
make secrets-scan          # Exposed secrets
uv run ruff check --select S src/  # Ruff security rules
```

### Phase 2: LLM Dynamic Analysis (Claude)

Systematically review these areas using parallel agents where possible:

1. **Entry points audit**: Map all HTTP endpoints, CLI commands, message handlers.
   For each: verify auth, input validation, output encoding.

2. **Data flow tracing**: Follow user input from entry to storage/output.
   Flag any point where input is used unsanitized.

3. **Auth & access control review**: Check every protected resource for IDOR,
   privilege escalation, missing auth checks.

4. **File & path operations**: Find all file I/O and verify paths are constrained.

5. **Crypto & secrets review**: Check for hardcoded secrets, weak algorithms,
   improper key management.

6. **Configuration review**: Check for debug modes, permissive CORS, missing
   security headers.

### Phase 3: Report

Structure findings using severity levels:

| Severity | Description | Example |
|----------|-------------|---------|
| **CRITICAL** | Exploitable now, data breach risk | SQL injection, auth bypass, RCE |
| **HIGH** | Exploitable with some effort | IDOR, path traversal, insecure deserialization |
| **MEDIUM** | Requires specific conditions | CSRF without state-changing impact, info disclosure |
| **LOW** | Best practice violation | Missing security headers, verbose errors in dev |
| **INFO** | Informational finding | Dependency update available, deprecated API usage |

For each finding, provide:
1. **Location**: File, line number, function
2. **Description**: What the vulnerability is
3. **Impact**: What an attacker could achieve
4. **Proof of concept**: How to exploit it (for authorized testing)
5. **Fix**: Exact code change to remediate

---

## CI Integration

Add to the CI pipeline (GitHub Actions example):

```yaml
security:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - uses: astral-sh/setup-uv@v4

    - name: Security lint (Bandit)
      run: uvx bandit -r src/ --severity-level high -q

    - name: Dependency audit
      run: uvx pip-audit -r  /tmp/secrets.json
        python -c "import json; r=json.load(open('/tmp/secrets.json')); exit(1) if r.get('results') else print('Clean')"
```

---

## Security Hardening Checklist

When setting up or reviewing a Python project, verify:

### Application
- [ ] All endpoints have authentication (unless explicitly public)
- [ ] Authorization checks verify resource ownership (no IDOR)
- [ ] All user input is validated with strict schemas (Pydantic, etc.)
- [ ] SQL queries use parameterized statements (never f-strings/format)
- [ ] File paths are resolved and constrained to allowed directories
- [ ] Secrets loaded from environment variables, never hardcoded
- [ ] Error responses don't leak internal details in production
- [ ] CORS is restricted to specific origins (not `*`)
- [ ] Security headers set (HSTS, X-Frame-Options, CSP, etc.)
- [ ] Rate limiting on authentication endpoints

### Dependencies
- [ ] All dependencies pinned with lock file committed
- [ ] `pip-audit` passes with no known CVEs
- [ ] No unnecessary dependencies (reduce attack surface)
- [ ] Lock file is up to date

### Infrastructure
- [ ] `.env` and secret files in `.gitignore`
- [ ] No secrets in Docker layers or build args
- [ ] Non-root user in Dockerfile
- [ ] Debug mode disabled in production config
- [ ] Logging does not include secrets or PII

---

## Common Vulnerability Patterns in Python

### Path Traversal
```python
# VULNERABLE
@app.get("/files/{filename}")
def get_file(filename: str):
    return FileResponse(f"/data/{filename}")  # ../../etc/passwd

# SAFE
@app.get("/files/{filename}")
def get_file(filename: str):
    base = Path("/data").resolve()
    target = (base / filename).resolve()
    if not target.is_relative_to(base):
        raise HTTPException(403, "Access denied")
    return FileResponse(target)
```

### SQL Injection
```python
# VULNERABLE
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

# SAFE
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
```

### Command Injection
```python
# VULNERABLE
os.system(f"convert {user_filename} output.png")

# SAFE
subprocess.run(["convert", user_filename, "output.png"], check=True)
```

### Insecure Deserialization
```python
# VULNERABLE
data = pickle.loads(user_data)  # Arbitrary code execution

# SAFE
data = json.loads(user_data)  # Only data, no code execution
```

### SSRF (Server-Side Request Forgery)
```python
# VULNERABLE
response = requests.get(user_provided_url)  # Can hit internal services

# SAFE
parsed = urlparse(user_provided_url)
if parsed.hostname in ALLOWED_HOSTS:
    response = requests.get(user_provided_url)
```

---

## Anti-Patterns This Skill Prevents

- **No security scanning in CI**: Every project needs at minimum Bandit + pip-audit
- **`# nosec` without justification**: Every Bandit suppression needs a comment explaining why
- **`verify=False` in requests**: Never disable SSL verification, even in dev
- **`shell=True` in subprocess**: Almost never needed — use list arguments
- **Pickle for untrusted data**: Use JSON or msgpack instead
- **String-formatted SQL**: Always use parameterized queries
- **Blanket exception handling**: `except Exception: pass` hides security errors
- **Secrets in source code**: Use environment variables or secret managers
- **Running as root in containers**: Always use a non-root user
- **Static tools only**: Pattern matching misses logic flaws — LLM analysis catches what static tools cannot

## Source & license

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

- **Author:** [sam-dumont](https://github.com/sam-dumont)
- **Source:** [sam-dumont/claude-skills](https://github.com/sam-dumont/claude-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:** no
- **Shell / process execution:** yes
- **Environment & secrets:** yes
- **Dynamic code execution:** yes

*"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-sam-dumont-claude-skills-code-security
- Seller: https://agentstack.voostack.com/s/sam-dumont
- 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%.
