本文へ移動
cccskills
無料GitHub で公開

security-audit

Phased risk-centric security assessment framework. Trigger when: - Auditing code for vulnerabilities, checking SQL injection, access control, or buffer overflows. - Prompt contains: /security-audit, security audit, taint analysis, threat model, vulnerability.

インストール方法を見る

含まれるファイル(2)

  • SKILL.md16.9 KB
  • scripts/run_audit.py5.6 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Security Audit Protocol

A structured, risk-centric framework for software security assessment. Designed for iterative human engagement with explicit checkpoints at each phase.

Adversarial path anchor. This lens is invoked on the Verification Dual's adversarial path (rules.md §2 Invariant 1): when no deterministic evaluator can close a security-correctness condition, context-free agents using this protocol supply the decorrelated review. See skills/refine/SKILL.md AUDIT §"Sibling Skills Consultation" for the wiring point.

Core Principle: The goal is not to maximize bug count, but to identify business risk, architectural flaws, and exploitable logic errors.


Prime Directives

Before beginning, internalize these cognitive framings:

  1. Risk > Findings: A bug is only a finding if it poses risk to business logic or data integrity. Context determines severity.

  2. Adversarial Mindset: Analyze every input, endpoint, and public function assuming a capable adversary is attempting to subvert the system.

  3. Taint Analysis Model: For every potential vulnerability, trace:

    • Source: Where does data enter? (user input, API body, URL param)
    • Sink: Where is it executed? (SQL query, eval(), HTML render, shell)
    • Sanitizer: Is there validation between Source and Sink? If not, it's a vulnerability.
  4. Assurance Spectrum:

    • Standard code: Pattern matching, control flow analysis
    • Crown jewels: Invariant checks, formal verification

Phase 0: Scope & Trust Model

Objective: Define boundaries and establish the security context before analyzing code.

0.1 Ingest System Context

  1. Read manifests (package.json, Cargo.toml, go.mod, requirements.txt)
  2. Identify tech stack and framework versions
  3. Check for known CVEs in dependencies

0.2 Define Trust Model

Establish the security context before analyzing code. Identify and document:

  • Untrusted sources (data entry points): API endpoints, CLI arguments, user file uploads, environment variables (if user-controlled).
  • Trusted components: internal services with mTLS, signed configuration files.
  • Crown jewels (what must be protected): database credentials, private keys, PII / user data, payment processing.
  • Trust boundaries (where data crosses zones): external API → internal handler, user input → database query.

0.3 Map Attack Surface

  • Enumerate all public API routes/endpoints
  • Identify CLI entry points and argument parsing
  • List external integrations (webhooks, OAuth, third-party APIs)
  • Document file upload/download paths
  • Note WebSocket or real-time communication channels

Checkpoint: Present scope and trust model. Await user approval before proceeding.


Phase 1: Automated Baseline

Objective: Establish security baseline through breadth-first automated analysis.

1.1 Secret Detection

Search for high-entropy strings and credential patterns:

  • AWS_ACCESS_KEY, AZURE_, GCP_
  • Bearer , Authorization:
  • Private key headers (-----BEGIN)
  • Database connection strings
  • API keys matching known formats

1.2 Dangerous Sink Detection

Search for risky function calls:

LanguageDangerous Patterns
Pythoneval(), exec(), subprocess.call(shell=True), os.system()
JavaScripteval(), Function(), innerHTML, dangerouslySetInnerHTML
Goos/exec without validation, template.HTML()
Rustunsafe, .unwrap() in library paths, raw pointer manipulation
C/C++strcpy, sprintf, gets, system(), raw malloc
SQLString concatenation in queries, missing parameterization

1.3 Configuration Audit

  • Debug mode disabled (DEBUG=False, no dev endpoints)
  • Binding addresses (no 0.0.0.0 in production)
  • TLS configuration (minimum TLS 1.2, strong ciphers)
  • CORS policy (no wildcard origins for sensitive APIs)
  • Security headers (CSP, X-Frame-Options, HSTS)

1.4 Dependency Vulnerability Check

  • Known CVEs in direct dependencies
  • Outdated packages with security patches available
  • Unmaintained dependencies (no updates in 2+ years)

Checkpoint: Present baseline findings. Await acknowledgment before deep review.


Phase 2: Manual White-Box Review

Objective: Deep analysis of logic, access control, and architectural patterns that tools miss.

Coherence Strategy: Analyze ONE component at a time. Present findings. Await acknowledgment before proceeding.

2.1 Authentication & Session Management

  • Passwords hashed with modern algorithm (bcrypt, argon2, scrypt)
  • No plaintext credential storage or logging
  • Session tokens generated with CSPRNG
  • Session invalidation on logout and password change
  • MFA implementation (if applicable)
  • Brute force protection (rate limiting, account lockout)

2.2 Authorization & Access Control

  • Consistent authZ checks on all protected resources
  • No IDOR (Insecure Direct Object Reference) vulnerabilities
  • Horizontal privilege escalation prevented (user A can't access user B's data)
  • Vertical privilege escalation prevented (user can't access admin functions)
  • Default deny policy (explicit grants, not explicit denies)

IDOR Trace Pattern:

API Endpoint → Extract resource_id from request
            → Verify current_user owns/can_access resource_id
            → If not verified: VULNERABILITY

2.3 Input Validation & Injection

  • All user input validated against allow-list schemas
  • SQL queries use parameterized statements / prepared statements
  • Command execution avoids shell; if unavoidable, input is escaped
  • Path traversal prevented (no ../ exploitation)
  • Deserialization uses safe parsers (no pickle, yaml.load() on user input)
  • Integer overflow/underflow handled (especially in financial logic)

2.4 Business Logic Errors

Apply state machine analysis:

  • Can user do X before Y? (sequence violations)
  • Can user trigger action twice? (replay attacks)
  • Can user manipulate timing? (TOCTOU)
  • Are negative values handled? (refund more than paid)

2.5 Concurrency & Race Conditions

  • Shared mutable state protected by locks/mutexes
  • Database transactions use appropriate isolation levels
  • Check-then-act patterns are atomic
  • File operations use proper locking

2.6 Cryptography

  • Standard algorithms only (AES-256, RSA-2048+, ECDSA, Ed25519)
  • No deprecated algorithms (MD5, SHA1, DES, RC4)
  • IVs/nonces are unique and random
  • Keys stored securely (vault, HSM, encrypted at rest)
  • No key/IV reuse
  • Proper padding schemes (OAEP for RSA, GCM for symmetric)

2.7 Error Handling & Information Disclosure

  • Stack traces not exposed to users
  • Error messages don't reveal system internals
  • Timing attacks mitigated for sensitive comparisons
  • Failed auth doesn't distinguish user existence

Component Audit Template

For each component, produce:

## Audit: [Component Name]

### Attack Surface
- Entry points: [list]
- Data handled: [list]

### Findings
| Category | Rating | Notes |
|:---------|:-------|:------|
| AuthN/AuthZ | PASS/WARN/FAIL | — |
| Input Validation | PASS/WARN/FAIL | — |
| Crypto | N/A/PASS/WARN/FAIL | — |
| Error Handling | PASS/WARN/FAIL | — |

### Vulnerabilities
1. **[SEVERITY]** Brief description — Location

### Questions for User
1. [Clarifying question if needed]

Checkpoint: Present findings for this component. Await acknowledgment before next component.


Phase 3: Formal Verification (Conditional)

Trigger: Apply ONLY to crown jewels—smart contracts, cryptographic primitives, safety-critical logic.

3.1 Invariant Definition

Define mathematical properties that must always hold:

  • total_supply == sum(all_balances)
  • user_balance >= 0
  • session.expires_at > now() implies session.valid

3.2 Property Verification

  • State machine transitions are exhaustively defined
  • No invalid state is reachable from any valid state
  • Critical invariants hold across all code paths

3.3 Traceability

  • Security requirements mapped to code locations
  • Each requirement has corresponding test/proof

Checkpoint: Present formal verification scope and findings.


Phase 4: Report Generation

Objective: Produce actionable, prioritized findings.

Severity Classification

LevelDefinitionExample
CriticalImmediate exploitation possible; complete compromiseRCE, auth bypass, SQLi with admin access
HighSignificant impact; exploitation requires minimal effortStored XSS, privilege escalation, IDOR on sensitive data
MediumModerate impact or requires specific conditionsCSRF, information disclosure, weak crypto
LowMinor impact; defense in depth issueMissing headers, verbose errors, weak rate limiting

Report Structure

# Security Audit Report: [Project Name]

## Executive Summary

- **Overall Risk:** [Critical / High / Medium / Low]
- **Summary:** [3-4 sentences, non-technical]
- **Priority Action:** [Single most important fix]

## Threat Model

- **Attack Surface:** [Entry points]
- **Crown Jewels:** [What's at risk]
- **Trust Boundaries:** [Where validation is critical]

## Findings

### [ID-001] [Vulnerability Name]

- **Severity:** Critical/High/Medium/Low
- **Location:** `file:line`
- **Description:** [Technical explanation]
- **Impact:** [Business consequence]
- **Proof of Concept:**
  > [Steps or payload to trigger]
- **Remediation:**
  - _Root Cause:_ [Why this happened]
  - _Fix:_ [Specific code change]

### [ID-002] ... (repeat)

## False Positives

- [Pattern investigated, determined safe, explanation]

## Recommendations (Systemic)

1. [Process or architectural improvement]

Master Checklist

Cross-reference all findings against these controls:

Architecture & Design

  • Trust boundaries defined and enforced
  • Principle of least privilege applied
  • Defense in depth implemented
  • Secrets not hardcoded

Authentication

  • Strong password policy enforced
  • MFA available for sensitive operations
  • Session management secure
  • Brute force protection in place

Authorization

  • RBAC correctly implemented
  • No privilege escalation paths
  • Default deny policy

Input Handling

  • All input validated
  • Output properly encoded
  • File uploads sanitized
  • No injection vulnerabilities

Cryptography

  • Modern algorithms only
  • Keys properly managed
  • TLS properly configured

Infrastructure

  • No security misconfigurations
  • Logging and monitoring adequate
  • Patch management in place

Domain-Specific Extensions

During Phase 0 (Scope), identify the tech stack and leverage the appropriate section of the unified security-audit skill (skills/security-audit/SKILL.md). These provide specialized checklists and vulnerability patterns.

Relevant Audit Sections

Apply Web3 section if:

  • Auditing Solidity, Vyper, or other smart contract languages
  • Target is a blockchain application, DeFi protocol, or NFT system
  • Code handles tokens, balances, or on-chain state
  • Upgrade patterns (proxy contracts) are in use

Apply Embedded section if:

  • Auditing C/C++ firmware or RTOS applications
  • Target has real-time constraints or safety requirements
  • DO-178C, ISO 26262, or IEC 62443 compliance is required
  • Code runs on microcontrollers, automotive ECUs, or medical devices

Apply Web section if:

  • Auditing a web application or REST/GraphQL API
  • Using Python, Node.js, Go, Ruby, or similar web frameworks
  • Target handles user authentication, sessions, or file uploads
  • Code is publicly exposed on the internet

Note: Multiple sections may apply. A Web3 project with a backend API might require auditing against both Web3 and Web sections of the security-audit skill.


Final Directive

This protocol enforces iterative human engagement. Never skip checkpoints. If findings accumulate beyond trackable scope, pause and summarize before continuing.

The goal is not a comprehensive bug list, but accurate risk assessment that enables informed remediation decisions.


Platform Checklists

This section provides domain-specific security checklists and threat models to guide code audits across different platforms, referencing the target stack identified in Phase 0.


1. Web & API Applications

Injection Attacks

  • SQL Injection: All queries use parameterized / prepared statements; ORM is used correctly (no .raw() with unvalidated user input).
  • Command Injection: Shell execution is avoided; arguments are passed as arrays/lists rather than raw shell strings; input is validated against a strict allow-list.
  • XSS (Cross-Site Scripting): Contextual output encoding is applied; template engines escape by default; unsafe methods (e.g., innerHTML, dangerouslySetInnerHTML) are avoided.
  • Path Traversal: File paths are validated against allowed directories using canonicalization (realpath) to prevent directory traversal (../).

Authentication & Authorization

  • Password Handling: Passwords hashed with argon2, bcrypt, or scrypt. Plaintext passwords never stored or logged.
  • Sessions: CSRF tokens enforced; session cookies configure HttpOnly, Secure, and SameSite flags; sessions invalidated on logout.
  • Access Control: Authorization checked server-side on every request (IDOR prevention). Resource ownership is explicitly verified.

Network & API Concerns

  • Rate Limiting: Enforced on authentication endpoints, password resets, and resource-intensive actions.
  • SSRF: URL schemes restricted to http/https, internal IP ranges blocked, DNS rebinding prevented, and redirects limited.
  • CORS: Wildcard (*) origin prohibited on credentialed endpoints.

2. Embedded & Safety-Critical Systems

Memory Safety (C/C++)

  • Buffer Overflows: Array bounds checked; unsafe string functions (strcpy, sprintf, gets) replaced with safe alternatives (strncpy, snprintf, fgets); stack protection enabled.
  • Use-After-Free: Pointers zeroed/cleared immediately after free(); no dangling references to stack variables.
  • Heap Discipline: Dynamic allocation avoided post-initialization. Use memory pools with fixed allocations instead.

Real-Time & Physical Controls

  • RTOS Constraints: No blocking operations in interrupt handlers; watchdog timers serviced; priority inversion prevented via inheritance mutexes.
  • Secure Boot: Root of trust verified in hardware; anti-rollback downgrade protection; debug interfaces (JTAG/SWD) locked.
  • Physical Security: Tamper-detection mechanisms; cryptographic keys zeroized on tamper event.

3. Web3 & Smart Contracts

Vulnerability Classes

  • Reentrancy: Implement Checks-Effects-Interactions pattern; state updates occur before external transfers; use ReentrancyGuard / nonReentrant modifiers.
  • Integer Overflow: Solidity 0.8+ checked math (or SafeMath library); bounds checks on user inputs.
  • Oracle Manipulation: Use decentralized price feeds (e.g. Chainlink TWAP); never rely on single DEX spot prices.
  • Access Control: Modifiers check authorization; ensure initialization functions can only be called once.
  • MEV / Front-Running: Implement slippage protection parameters, transaction deadline limits, and commit-reveal schemes where appropriate.

Utility Script Usage

You can run automated checks using the script located in scripts/run_audit.py. It automatically detects project files in the target path and runs the corresponding security audit tools (providing setup commands for missing tools):

  • Python: Runs static analysis with bandit.
  • Solidity: Scans contracts with slither.
  • Rust: Invokes cargo clippy (denying warnings) and cargo audit.
  • Go: Scans for known vulnerabilities using govulncheck.
  • JavaScript/TypeScript: Audits package dependencies using npm audit, yarn audit, or pnpm audit.
python3 skills/security-audit/scripts/run_audit.py <path-to-audit-target>

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

ai-audit

無料

SOP for auditing AI-generated code. Trigger when: - Reviewing, refactoring, or cleaning up AI-generated code to prevent regressions or hallucinated APIs. - Prompt contains: /ai-audit, code audit, AI cleanup, common flaws.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

api-audit

無料

Protocol for auditing API surface coherence and type safety. Trigger when: - Evaluating API designs, interface type safety, or design elegance. - Prompt contains: /api-audit, API surface, API coherence, type safety.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

boundary

無料

Normative sufficiency conditions for Initial Boundary Conditions (IBCs) and the SOP for the cheap-tier boundary refinement loop (/boundary). Trigger when: - Crafting, auditing, or refining a prompt/IBC destined for an expensive (architect-class) model or an autonomous worker dispatch. - Evaluating whether a task frame is sufficient to bound an agent walk. - Prompt contains: /boundary, IBC, initial boundary condition, boundary contract, sufficiency conditions, worker prompt, prompt refinement.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

campaign

無料

SOP for the architect-tier campaign workflow (/campaign): exhaustive survey, mitigation planning, tiered orchestration, and reconciliation. Trigger when: - Running a multi-workstream initiative where an expensive architect-tier council surveys, plans, emits worker prompts, and judges landed work. - Conducting production-readiness assessments that fan out into autonomous mitigation dispatches across model tiers. - Prompt contains: /campaign, campaign workflow, survey, orchestrate, reconcile, premise freshness, tier routing, worker IBC, scratch.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

chronicle

無料

Maintain and update the persistent project chronicle (docs/chronicle.md). Trigger when: - The human requests a history summary or chronicle update. - Starting work on a new codebase and needing context on its evolution. - Prompt contains keywords: /chronicle, chronicle, project history, git log summary, history summary.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

Rules, conventions, and constraints for formatting git commit messages and committing at logical boundaries. Trigger when: - Drafting, revising, or validating git commit messages. - Pausing at commit boundaries under the CORE or CONTINUE workflows. - Evaluating whether a changeset should be split into multiple commits. - Prompt contains keywords: commit message, git commit, conventional commits, commit hygiene, commit guidelines, logical boundary, spaghetti diff, atomic commit, commit boundary.

日本語の概要は準備中です。原文の説明を表示しています。

nrdxp/predicate102026年9月1日 更新

nrdxp のスキルをすべて見る

このスキルの問題を報告する