
Code Security
- 48 installs
- 7 repo stars
- Updated May 20, 2026
- daemon-blockint-tech/agentic-enteprises-skill
Reviews code for OWASP vulnerabilities (injection, XSS, auth, crypto, SSRF, XXE), secrets handling, and IaC security across languages.
About
An agent skill for secure coding and security-focused code review across languages and infrastructure, covering OWASP vulnerability patterns, secrets handling, and IaC security for Terraform, Kubernetes, Docker, and GitHub Actions. A developer uses it when writing or reviewing code that handles input, auth, files, databases, or infra config.
- OWASP-oriented findings with CWE/OWASP labels and secure alternatives
- Language-priority table with per-stack first checks
Code Security by the numbers
- 48 all-time installs (skills.sh)
- Ranked #1,338 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/daemon-blockint-tech/agentic-enteprises-skill --skill code-securityAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 48 |
|---|---|
| repo stars | ★ 7 |
| Last updated | May 20, 2026 |
| Repository | daemon-blockint-tech/agentic-enteprises-skill ↗ |
What it does
Reviews code for OWASP vulnerabilities (injection, XSS, auth, crypto, SSRF, XXE), secrets handling, and IaC security across languages.
Files
Code Security
When to Use
- Write or review application code for common vulnerability classes (injection, XSS, auth, crypto, SSRF, XXE, deserialization)
- Review secrets handling, session/JWT patterns, and transport security in code
- Review Terraform, Kubernetes manifests, Dockerfiles, or GitHub Actions for security misconfigurations
- Proactively harden code that accepts user input, performs I/O, queries databases, or calls external URLs
- Map findings to CWE/OWASP categories and suggest concrete secure patterns
When NOT to Use
- Plan or execute authorized penetration tests, exploit chains, or red-team campaigns →
ai-redteam,cybersecurity,penetration-tester,red-team-specialist - Map controls to SOC 2, ISO 27001, or build audit evidence packages →
compliance-engineer,compliance-specialist - Deploy SIEM, IdP, KMS, WAF, or operate security tooling →
information-security-engineer - Configure CI/CD scanners, SBOM, OIDC, or pipeline gates without secure-coding review →
devsecops - Author YARA or malware detection rules →
yara-rule-authoring - General feature design, RFCs, or refactoring without a security lens →
senior-software-engineer
Related skills
| Need | Skill |
|---|---|
| Security program strategy, policies, IR | cybersecurity |
| Control implementation, IdP, KMS, SIEM | information-security-engineer |
| CI/CD security gates, SBOM, pipeline OIDC | devsecops |
| Audit evidence and framework mapping | compliance-engineer |
| LLM/agent red team and prompt injection | ai-redteam |
| Code review, RFCs, reliability (non-security) | senior-software-engineer |
| Cloud account guardrails and CSPM | cloud-security-engineer |
| Cryptographic primitive/protocol design | cryptographer-specialist |
| Pentest findings reproduction | penetration-tester, web-pentester |
How to work
Modes
- Proactive — When writing or touching security-sensitive code (input, auth, files, DB, HTTP clients, crypto, IaC), check relevant categories without waiting for an explicit security ask.
- Reactive — When the user requests a security review, follow the review workflow in
references/review_checklist_and_owasp_mapping.md.
Workflow
1. Identify language/stack and what the code does (input? DB? shell? XML? outbound HTTP? secrets? IaC?). 2. Load the matching reference(s) below; prioritize Critical then High impact. 3. Flag vulnerable patterns with CWE/OWASP labels; propose secure alternatives from references (language-specific examples live there). 4. For reviews, produce severity-ordered findings with file/line context and fix guidance.
Language priority (first checks)
| Language / stack | Priority topics |
|---|---|
| Python | SQL/command injection, path traversal, code injection, SSRF, insecure crypto, deserialization |
| JavaScript/TypeScript | XSS, prototype pollution, code injection, CSRF, insecure transport |
| Java | SQL injection, XXE, insecure deserialization, SSRF, insecure crypto |
| Go | SQL/command injection, path traversal, SSRF, insecure transport |
| C/C++ | Memory safety, unsafe functions, command injection, path traversal |
| Ruby / PHP | SQL/command injection, XSS, deserialization (Ruby), code injection |
| HCL / YAML | Terraform (AWS/Azure/GCP), Kubernetes, Docker, GitHub Actions |
When to load references
Detailed vulnerable/secure patterns and multi-language examples are in references/ (condensed from 28 upstream rule categories). Do not expect per-language copies of every rule in SKILL.md.
| Topic | Reference |
|---|---|
| Scope, modes, language priorities | references/code_security_scope_and_workflow.md |
| SQL, command, XSS, path traversal, code injection | references/injection_and_input_validation.md |
| Secrets, JWT, CSRF, crypto, TLS | references/crypto_auth_and_session.md |
| XXE, deserialization, SSRF | references/deserialization_ssrf_xxe.md |
| Terraform, K8s, Docker, GitHub Actions | references/infrastructure_as_code_security.md |
| Review checklist, CWE/OWASP map, medium/low | references/review_checklist_and_owasp_mapping.md |
Quick prevention reference
| Vulnerability | Key prevention |
|---|---|
| SQL injection | Parameterized queries / prepared statements |
| XSS | Context-aware output encoding; CSP where appropriate |
| Command injection | Avoid shell; use APIs with argument lists |
| Path traversal | Canonicalize paths; allowlist base directories |
| SSRF | URL allowlists; block metadata/link-local ranges |
| Secrets | Env vars / secret managers; never commit credentials |
| Weak crypto | SHA-256+, AES-256-GCM; avoid MD5/SHA1/DES/ECB |
| XXE | Disable DTD/external entities in XML parsers |
| Deserialization | Do not deserialize untrusted data |
Code security scope and workflow
Table of contents
1. Purpose and boundaries 2. Proactive vs reactive modes 3. Review workflow 4. Language priority table 5. Impact tiers 6. Evidence and reporting
Purpose and boundaries
This skill covers secure coding guidance and security-focused code review for application and infrastructure-as-code artifacts. It distills OWASP-oriented patterns across 15+ languages and common IaC formats.
In scope: identifying vulnerable patterns, recommending secure replacements, mapping to CWE/OWASP, prioritizing fixes by impact.
Out of scope: running authorized offensive engagements, compliance attestation, operating enterprise security tools, or replacing language-specific exploit development.
Proactive vs reactive modes
Proactive
Apply when the agent writes or edits code that:
- Accepts HTTP/query/body/header/cookie input
- Builds SQL, shell commands, file paths, or dynamic code
- Parses XML, deserializes objects, or fetches user-supplied URLs
- Handles passwords, tokens, API keys, or session state
- Defines Terraform, Kubernetes, Docker, or GitHub Actions resources
Check Critical categories first, then High, without waiting for the user to mention security.
Reactive
When the user asks for a security review, audit, or “is this safe?”:
1. Confirm scope (paths, languages, threat assumptions). 2. Follow review_checklist_and_owasp_mapping.md. 3. Return findings ordered by severity with CWE/OWASP tags and fix snippets.
Review workflow
scope → language/stack → data flows (sources/sinks) → category checklist → findings → fixes| Step | Action |
|---|---|
| 1 | List files and languages in scope |
| 2 | Identify trust boundaries (user input, webhooks, CI events, admin APIs) |
| 3 | Trace sources to sinks (DB, shell, filesystem, HTTP client, eval, deserialize) |
| 4 | Run Critical checklist (injection, secrets, deserialization, XXE, memory) |
| 5 | Run High checklist (crypto, transport, SSRF, JWT, CSRF, IaC) |
| 6 | Note Medium/Low (ReDoS, races, correctness) when time permits |
| 7 | Summarize with severity, CWE, OWASP category, and remediation |
Language priority table
When multiple issues exist, start with the rows that match the stack under review.
| Language / stack | Check first (references) |
|---|---|
| Python | SQL/command injection, path traversal, eval/template injection, SSRF, pickle/YAML unsafe load, weak crypto |
| JavaScript/TypeScript | XSS, prototype pollution, eval/VM, CSRF on state-changing routes, TLS verification, JWT verify |
| Java | SQL injection, XXE on XML parsers, Java deserialization, SSRF, weak crypto algorithms |
| Go | SQL injection, exec with user strings, path traversal, SSRF, TLS config |
| C/C++ | Buffer overflows, unsafe libc (strcpy, gets), format strings, command injection |
| Ruby | SQL/command injection, YAML.load, Marshal.load, ERB injection |
| PHP | SQL injection, XSS, shell_exec, include path issues, deserialization |
| Rust | Unsafe blocks, command APIs, SQL via string concat, TLS |
| HCL (Terraform) | Public S3/storage, wildcard IAM, unencrypted disks, open security groups |
| Kubernetes YAML | Privileged pods, root user, host namespaces, secrets in manifests, excessive RBAC |
| Dockerfile | USER root, privileged, unpinned base images, secrets in build args |
| GitHub Actions | Script injection in run:, pull_request_target + checkout, unpinned actions |
Impact tiers
Aligned with upstream rule categories (28 total, grouped here):
| Tier | Categories |
|---|---|
| Critical | SQL injection, command injection, XSS, XXE, path traversal, insecure deserialization, code injection, hardcoded secrets, memory safety (C/C++) |
| High | Insecure crypto, insecure transport, SSRF, JWT issues, CSRF, prototype pollution, unsafe functions, Terraform (AWS/Azure/GCP), Kubernetes, Docker, GitHub Actions |
| Medium | Regex DoS, race conditions / TOCTOU, correctness bugs with security impact |
| Low | General best practices, performance, maintainability (only when tied to security) |
Evidence and reporting
Each finding should include:
- Location — file and line (or resource block in IaC)
- Issue — what can go wrong (one sentence)
- Severity — Critical / High / Medium / Low
- CWE — when applicable (e.g., CWE-89, CWE-79)
- OWASP — map to Top 10:2021 category (see review reference)
- Fix — concrete pattern (parameterize query, encode output, allowlist URL, etc.)
Avoid claiming exploitability without evidence; state assumptions (e.g., “if host is attacker-controlled”).
Cryptography, authentication, and session security
Table of contents
1. Hardcoded secrets 2. Cryptographic algorithms 3. Transport security (TLS) 4. JWT authentication 5. CSRF 6. Session management
CWE: 798 (hardcoded credentials), 327 (weak crypto), 319 (cleartext), 347 (JWT), 352 (CSRF)
---
Hardcoded secrets
Risk: Credentials in source, config committed to VCS, or logs—unauthorized access and difficult rotation.
Never hardcode: API keys, passwords, private keys, connection strings, signing secrets, webhook HMAC keys.
Secure patterns:
| Approach | Use when |
|---|---|
| Environment variables | Local dev, simple deploys |
| Secret manager (Vault, AWS SM, GCP SM) | Production |
| CI/CD secret stores | Pipelines (not literals in YAML) |
| Short-lived tokens | Prefer over long-lived API keys |
Review heuristics: High-entropy strings in code, AKIA, BEGIN PRIVATE KEY, password =, default credentials in samples.
On exposure: Rotate immediately; assume compromise if ever committed to git history.
---
Cryptographic algorithms
Avoid (broken or weak):
| Category | Weak | Prefer |
|---|---|---|
| Hashing passwords | MD5, SHA1, plain SHA256 alone | Argon2id, scrypt, bcrypt (with work factor) |
| Integrity | MD5, SHA1 for security | SHA-256+ or BLAKE2 |
| Symmetric encryption | DES, 3DES, RC4, AES-ECB | AES-256-GCM or ChaCha20-Poly1305 |
| Randomness | Math.random(), predictable seeds | secrets (Python), crypto.randomBytes (Node), SecureRandom (Java) |
Key management: Generate keys in HSM/KMS; separate encryption keys per tenant where required; document rotation.
Do not roll custom crypto protocols — use established libraries and protocols (TLS, NaCl/libsodium, framework crypto).
---
Transport security (TLS)
Risk: Credentials and data exposed on the wire; MITM if verification disabled.
Requirements:
- HTTPS for all production traffic; HSTS for browser apps.
- Verify certificates — never disable TLS verification in production (
rejectUnauthorized: false,verify=False). - Modern TLS versions (1.2+; prefer 1.3); disable weak ciphers.
- Certificate pinning only when justified and maintained.
Review heuristics: http:// in production URLs, custom TrustManager that accepts all certs, curl -k.
---
JWT authentication
Risk: Forged or altered tokens if verification is missing or weak.
Checks:
| Issue | Mitigation |
|---|---|
alg: none or algorithm confusion | Explicitly allow only expected algs (e.g., RS256); verify signature |
| Weak HMAC secret | Long random secret from secret manager; prefer asymmetric keys |
Missing exp / nbf | Validate time claims with clock skew tolerance |
| Sensitive data in payload | JWTs are signed, not encrypted—do not store PII/secrets in claims |
| Token in URL | Prefer Authorization: Bearer header; avoid query strings (logs, Referer) |
Pattern: Use maintained libraries; always call verify with issuer/audience checks.
---
CSRF
Risk: Browser sends authenticated requests the user did not intend.
Mitigate state-changing operations (POST/PUT/PATCH/DELETE):
- Synchronizer token (CSRF token in form + cookie/header).
SameSitecookies (StrictorLaxwhere compatible).- Double-submit cookie pattern only with care (still prefer framework CSRF middleware).
- For APIs: avoid cookie auth without CSRF protection; use tokens with explicit client actions.
Not required for: Pure read-only GET with no side effects (still avoid sensitive data in GET URLs).
---
Session management
| Practice | Detail |
|---|---|
| Session ID entropy | Cryptographically random, sufficient length |
| Cookie flags | HttpOnly, Secure, SameSite |
| Fixation | Regenerate session ID on login |
| Timeout | Idle and absolute timeouts |
| Logout | Invalidate server-side session |
| Storage | Server-side session store or hardened JWT strategy—not client-only trust |
Coordinate with information-security-engineer for enterprise IdP/SSO patterns.
Deserialization, SSRF, and XXE
Table of contents
1. XML External Entity (XXE) 2. Insecure deserialization 3. Server-Side Request Forgery (SSRF)
CWE: 611 (XXE), 502 (deserialization), 918 (SSRF) OWASP Top 10:2021: A05 Security Misconfiguration (XXE/parser), A10 SSRF (2021 dedicated category)
---
XML External Entity (XXE)
Risk: Malicious XML references external entities—local file read, SSRF, DoS (billion laughs).
Vulnerable: Default XML parsers accepting DTDs/external entities (DocumentBuilderFactory, xml.etree on untrusted XML, libxml2 without hardening).
Secure patterns:
- Disable DTD and external entities on every parser that handles untrusted XML.
- Prefer JSON or safer formats when XML is not required.
- Use well-maintained libraries with secure defaults; validate schema size limits.
| Platform | Hardening |
|---|---|
Java DocumentBuilderFactory | setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) plus disable external general/parameter entities |
| Python | Avoid xml.etree for untrusted input; use defusedxml |
| .NET | XmlReaderSettings with DTD processing prohibited |
Review heuristics: parse(, DocumentBuilder, SAX/DOM without feature flags on user-uploaded XML.
---
Insecure deserialization
Risk: Attacker supplies serialized objects that execute code or bypass auth on deserialize.
High-risk APIs (never on untrusted input):
| Language | Dangerous |
|---|---|
| Java | ObjectInputStream, unsafe JSON/XML to arbitrary types |
| Python | pickle.loads, unsafe yaml.load (use safe_load) |
| Ruby | Marshal.load, YAML.load |
| PHP | unserialize() |
| .NET | BinaryFormatter, unsafe TypeNameHandling.All in JSON.NET |
Secure patterns:
- Deserialize to limited DTOs with schema validation (JSON + strict types).
- Sign and encrypt serialized blobs if used; short TTL.
- Reject polymorphic type discriminators from untrusted sources.
Note: json.loads is not RCE by itself; risk is object graphs and gadget chains in native serializers.
---
Server-Side Request Forgery (SSRF)
Risk: Server fetches attacker-chosen URLs—internal services, cloud metadata (169.254.169.254), port scan, firewall bypass.
Common sinks: requests.get(url), axios.get(url), fetch(userUrl), image/PDF fetchers, webhook validators, import-from-URL features.
Secure patterns:
| Control | Implementation |
|---|---|
| Fixed base URL | Only allow path/query parameters on a known host |
| Allowlist | Explicit list of schemes, hosts, ports |
| Block metadata | Deny link-local, loopback, RFC1918 unless required (defense in depth) |
| No redirects to internal | Disable redirects or re-validate each hop |
| Split DNS rebinding | Resolve and connect with consistent IP checks where feasible |
Incorrect pattern: User supplies full URL or hostname.
# Vulnerable
requests.get(f"https://{user_host}/api/...")
# Better: allowlist host
ALLOWED = {"api.example.com"}
if user_host not in ALLOWED:
raise ValueError("host not allowed")
requests.get(f"https://{user_host}/api/...")Cloud: Block access to instance metadata from app roles unless strictly required; use IMDSv2 on AWS.
Review heuristics: HTTP client first argument from request params; URL parsers that accept file://, gopher://, or redirects.
Infrastructure-as-code security
Table of contents
1. Terraform (AWS, Azure, GCP) 2. Kubernetes 3. Docker 4. GitHub Actions 5. IaC review checklist
Distilled from upstream rules: terraform-aws, terraform-azure, terraform-gcp, kubernetes, docker, github-actions.
---
Terraform (AWS, Azure, GCP)
Common misconfigurations
| Area | Risk | Remediation |
|---|---|---|
| S3 / blob storage | Public buckets, no encryption | Block public access; SSE-KMS; bucket policies least privilege |
| IAM | Action: *, Resource: *, wildcard principals | Scope actions/resources; restrict sts:AssumeRole principals |
| Security groups / NSGs | 0.0.0.0/0 on admin ports | CIDR allowlists; bastion/zero-trust patterns |
| Disks / databases | Unencrypted volumes | Enable encryption at rest; CMK where required |
| Logging | Disabled audit trails | Enable CloudTrail / Activity Log / audit configs |
AWS patterns
# Prefer bucket-level encryption resource (provider v4+)
resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
bucket = aws_s3_bucket.data.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "aws:kms"
kms_master_key_id = aws_kms_key.data.arn
}
}
}- Avoid
principal = "*"in trust policies without tight conditions. - Use IAM roles for workloads—not long-lived access keys in Terraform outputs.
Azure / GCP (summary)
- Azure: Restrict public network access on storage/SQL; require TLS; managed identities over keys in templates.
- GCP: Avoid
allUsers/allAuthenticatedUserson buckets; enable uniform bucket-level access; least-privilege IAM bindings; VPC SC where required.
Review heuristics: 0.0.0.0/0, public = true, acl = "public-read", inline secrets, ignore_changes on security attributes.
---
Kubernetes
Pod and container security
| Misconfiguration | Secure default |
|---|---|
privileged: true | privileged: false |
runAsUser: 0 / missing runAsNonRoot | runAsNonRoot: true, runAsUser > 0 |
hostNetwork, hostPID, hostIPC | Disable unless strictly required |
| Writable root filesystem | readOnlyRootFilesystem: true where possible |
| Capabilities | Drop ALL, add only needed (capabilities.drop) |
| Secrets in env plain text | Use Secret mounts; restrict RBAC to Secret get |
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]Cluster hygiene
- Limit cluster-admin bindings; namespace-scoped roles.
- NetworkPolicies for east-west segmentation.
- Admission controllers (OPA/Gatekeeper, Kyverno) for policy-as-code.
- Pin images by digest in production; scan images in CI (
devsecops).
---
Docker
| Issue | Guidance |
|---|---|
| Run as root | USER nonroot after install |
--privileged | Avoid in production |
| Docker socket mount | Never mount /var/run/docker.sock into app containers |
| Secrets in layers | Use BuildKit secrets; no ENV API_KEY=... |
| Tags | Pin digests or immutable tags—not bare latest in prod |
| Attack surface | Minimal base images (distroless/alpine with updates) |
FROM node:20-bookworm-slim
RUN useradd -r appuser
USER appuser
WORKDIR /app
COPY --chown=appuser:appuser . .---
GitHub Actions
Script injection (CWE-78)
Risk: ${{ github.event.pull_request.title }} inside run: | executes as shell code.
Fix: Pass untrusted context values through env: and quote in shell:
- name: Check title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "$PR_TITLE"pull_request_target (CWE-913)
Runs with base repo secrets. Checking out PR head and running npm install / build can execute attacker code with secret access.
- Avoid checkout + build of untrusted PR code on
pull_request_target. - Use
pull_requestfor untrusted forks; separate approval for label-gated workflows.
Supply chain
- Pin actions to full commit SHA, not floating
@v4tags alone. - Minimize
permissions:to job needs (contents: readdefault). - Do not echo secrets to logs; use OIDC to cloud over long-lived cloud keys in secrets.
---
IaC review checklist
1. Exposure — public endpoints, open SGs, anonymous bucket access 2. Identity — wildcard IAM, overbroad AssumeRole, static keys 3. Encryption — at rest and in transit defaults 4. Secrets — literals in HCL/YAML/env 5. Workload hardening — K8s securityContext, non-root containers 6. CI trust — injection surfaces, PR workflows, pinned actions
For org-wide guardrails (SCPs, OPA, CSPM), coordinate with information-security-engineer and cloud-security-engineer.
Injection and input validation
Table of contents
1. SQL injection 2. Command injection 3. Cross-site scripting (XSS) 4. Path traversal 5. Code injection 6. General input validation
CWE: 89 (SQLi), 78 (OS command), 79 (XSS), 22 (path traversal), 94 (code injection) OWASP Top 10:2021: A03 Injection, A07 Identification and Authentication Failures (XSS session impact)
---
SQL injection
Risk: Attacker manipulates query logic—read, modify, or delete data; sometimes RCE via DB features.
Vulnerable patterns: String concatenation, .format(), % formatting, f-strings, template literals embedding user data in SQL.
Secure patterns:
- Parameterized queries / prepared statements — bind values separately from SQL text.
- ORM query APIs — use bound parameters; avoid raw SQL with interpolation.
- Identifiers (table/column names) — allowlist only; never parameterize identifiers as strings from users.
| Language | Prefer |
|---|---|
| Python (psycopg2) | cur.execute("SELECT * FROM users WHERE id = %s", [user_id]) |
| Node (pg) | pool.query('SELECT * FROM users WHERE id = $1', [userId]) |
| Java (JDBC) | PreparedStatement with setString / setInt |
| Go | db.Query("SELECT ... WHERE id = ?", id) |
Review heuristics: Search for execute(f"...", ` ...${var} , "SELECT" +, String.format` with SQL.
---
Command injection
Risk: Arbitrary OS command execution when user input reaches a shell.
Vulnerable patterns: os.system, subprocess with shell=True, exec of shell strings, backticks, Runtime.exec(String) with concatenation.
Secure patterns:
- Pass argument arrays without shell interpretation (
subprocess.run([...], shell=False)). - Use library APIs instead of CLI wrappers when possible.
- Strict allowlists for any unavoidable dynamic arguments.
| Language | Avoid | Prefer |
|---|---|---|
| Python | os.system(user_input) | subprocess.run(["tool", arg], shell=False) |
| Node | exec(\cmd ${user}\) | spawn with args array |
| Java | Runtime.getRuntime().exec("cmd " + user) | ProcessBuilder with separate args |
---
Cross-site scripting (XSS)
Risk: Inject script into pages viewed by other users—session theft, defacement, malware.
Types: Reflected, stored, DOM-based.
Secure patterns:
- Context-aware output encoding (HTML, attribute, JS, URL contexts differ).
- Use framework defaults that auto-escape (
reactJSX text, template engines with escape). - Content-Security-Policy as defense in depth.
- Never insert unsanitized HTML from users; if rich text is required, use a vetted sanitizer allowlist.
| Context | Guidance |
|---|---|
| HTML body | Encode <, >, &, quotes |
| Attribute | Encode quotes; prefer quoted attributes |
| JavaScript | Do not build JS from user strings; use JSON.parse on server-generated JSON |
| URL | Validate scheme (https only); encode |
Review heuristics: innerHTML, dangerouslySetInnerHTML, document.write, unescaped template insertion in server HTML.
---
Path traversal
Risk: Read or write files outside intended directory via ../ or absolute paths.
Secure patterns:
- Resolve to canonical path and verify prefix under an allowed base directory.
- Reject
.., NUL bytes, and alternate encodings in filenames. - Use framework-safe APIs (
send_filewith safe root,Path.resolve()checks).
# Pattern: canonicalize then prefix-check
base = Path("/var/app/uploads").resolve()
target = (base / user_filename).resolve()
if not str(target).startswith(str(base)):
raise ValueError("invalid path")---
Code injection
Risk: Execute attacker-controlled code via eval, Function(), template engines, or dynamic import.
Vulnerable patterns: eval(user_input), new Function(user), server-side template injection, pickle/Marshal on untrusted bytes (see deserialization reference).
Secure patterns:
- Never evaluate user input as code.
- Use safe DSLs or strict JSON parsing with schema validation.
- Sandboxing is a last resort—not a substitute for avoiding dynamic execution.
---
General input validation
Apply at trust boundaries:
| Principle | Practice |
|---|---|
| Allowlist over denylist | Accept known-good enums, formats, lengths |
| Type and range | Parse integers/dates explicitly; reject overflow |
| Normalize once | Unicode normalization before comparison |
| Fail closed | Reject invalid input; do not coerce silently |
| Log safely | Do not log secrets or full PII |
Prototype pollution (JavaScript): Validate object keys; avoid unsafe merge into prototypes (__proto__, constructor). Use Object.create(null) for maps when appropriate. CWE-1321.
Review checklist and OWASP mapping
Table of contents
1. Security review checklist 2. OWASP Top 10:2021 quick map 3. CWE quick reference 4. Medium and low impact 5. Finding template
---
Security review checklist
Use for reactive reviews. Check Critical before High.
Critical
- [ ] SQL injection — no dynamic SQL from user input; parameterized queries only
- [ ] Command injection — no shell with user data; argument arrays
- [ ] XSS — encoded output; no unsafe
innerHTML/ unescaped templates - [ ] XXE — XML parsers hardened on untrusted XML
- [ ] Path traversal — canonical paths under allowlisted base
- [ ] Insecure deserialization — no pickle/Marshal/Java serialization on untrusted data
- [ ] Code injection — no
eval/dynamic code on user input - [ ] Hardcoded secrets — no keys/passwords in repo
- [ ] Memory safety (C/C++) — bounds checks; avoid unsafe string APIs
High
- [ ] Weak crypto — modern algorithms; no MD5/SHA1/DES/ECB for security
- [ ] TLS — verify certs; HTTPS in production
- [ ] SSRF — URL allowlists; no user-controlled hosts
- [ ] JWT — verify signature/alg/exp; no secrets in payload
- [ ] CSRF — tokens or SameSite on state-changing cookie auth
- [ ] Prototype pollution (JS) — safe object merge
- [ ] Unsafe functions — no
gets,strcpy, recklesseval - [ ] Terraform — encryption, least IAM, no public data stores
- [ ] Kubernetes — non-root, non-privileged, drop caps
- [ ] Docker — non-root user, no socket mount, pinned images
- [ ] GitHub Actions — no script injection; careful
pull_request_target
Medium / Low (when time permits)
- [ ] ReDoS — catastrophic backtracking in user-supplied regex
- [ ] Race / TOCTOU — temp files, check-then-act
- [ ] Correctness — null derefs, error handling hiding failures
---
OWASP Top 10:2021 quick map
| OWASP 2021 | Representative issues in this skill | Primary references |
|---|---|---|
| A01 Broken Access Control | IDOR patterns (validate object ownership), path traversal | injection reference, scope workflow |
| A02 Cryptographic Failures | Weak hash/cipher, hardcoded keys, TLS off | crypto_auth reference |
| A03 Injection | SQLi, command, XSS, code injection | injection reference |
| A04 Insecure Design | Missing rate limits, unsafe architecture (out of code-only scope) | escalate to design review |
| A05 Security Misconfiguration | XXE defaults, K8s/Docker/Terraform misconfig | deserialization_ssrf_xxe, infrastructure reference |
| A06 Vulnerable Components | Unpinned deps, old base images | note for devsecops / dependency scan |
| A07 Identification & Auth Failures | JWT, session, CSRF | crypto_auth reference |
| A08 Software & Data Integrity | Unsigned updates, unsafe deserialization | deserialization reference |
| A09 Security Logging & Monitoring | Missing audit on auth failures (brief) | log without secrets |
| A10 SSRF | User-controlled outbound requests | deserialization_ssrf_xxe reference |
---
CWE quick reference
| CWE | Name | Category file |
|---|---|---|
| CWE-22 | Path traversal | injection_and_input_validation |
| CWE-78 | OS command injection | injection_and_input_validation |
| CWE-79 | XSS | injection_and_input_validation |
| CWE-89 | SQL injection | injection_and_input_validation |
| CWE-94 | Code injection | injection_and_input_validation |
| CWE-119 | Memory buffer issues | injection (C/C++); scope workflow |
| CWE-327 | Broken crypto | crypto_auth_and_session |
| CWE-347 | JWT issues | crypto_auth_and_session |
| CWE-352 | CSRF | crypto_auth_and_session |
| CWE-502 | Deserialization | deserialization_ssrf_xxe |
| CWE-611 | XXE | deserialization_ssrf_xxe |
| CWE-798 | Hardcoded credentials | crypto_auth_and_session |
| CWE-918 | SSRF | deserialization_ssrf_xxe |
| CWE-1333 | ReDoS | this file (medium) |
| CWE-1321 | Prototype pollution | injection_and_input_validation |
Full upstream index: 28 rule categories in source rules/_sections.md (not duplicated in this repo).
---
Medium and low impact
Regular expression DoS (ReDoS) — CWE-1333
Risk: User-supplied or attacker-influenced regex with catastrophic backtracking → CPU exhaustion.
Mitigations:
- Avoid nested quantifiers on overlapping alternations (
(a+)+). - Use regex timeouts (language-dependent) or RE2-style engines where appropriate.
- Prefer simple string operations or precompiled allowlists over complex regex on untrusted input.
Race conditions — CWE-367
Risk: TOCTOU between check and use (temp files, privilege checks).
Mitigations:
- Use atomic create (
O_EXCL), secure temp APIs. - File locks where appropriate; avoid predictable temp paths in shared
/tmp.
Correctness with security impact
Logic bugs (off-by-one bounds, null checks, swallowed exceptions) can become vulnerabilities when they bypass auth or leak data. Flag when they affect security controls.
Low-priority categories (source rules)
Best practice, performance, maintainability — address when they directly weaken security (e.g., deprecated crypto API usage). Do not expand scope into general style review; defer to senior-software-engineer.
---
Finding template
### [Critical|High|Medium|Low] Title (CWE-XXX, OWASP A0X)
**Location:** `path:line` or resource name
**Issue:** One sentence describing abuse scenario.
**Evidence:** Code snippet or config excerpt (minimal).
**Fix:** Specific secure pattern or config change.
**References:** OWASP cheat sheet or internal reference file name.Severity guidance:
| Level | Typical examples |
|---|---|
| Critical | RCE, full DB read, secret in public repo, auth bypass |
| High | SSRF to metadata, weak crypto on passwords, open SG to world |
| Medium | ReDoS, race on non-critical resource |
| Low | Defense-in-depth improvements, style-adjacent hardening |