Skill: jose-compu/self-improving-security (version 1.2.0)

--- name: self-improving-security description: "Captures vulnerabilities, misconfigurations, access control violations, compliance gaps, incident response patterns, and threat intelligence to enable continuous security improvement. Use when: (1) A CVE or vulnerability is discovered, (2) Secrets are exposed in logs or output, (3) Access control violations or unauthorized access attempts occur, (4) Compliance audit findings or gaps are identified, (5) Security misconfigurations are found in infrastructure or applications, (6) Incident response procedures are executed or improved, (7) Threat intelligence is gathered from advisories or pen test results." --- # Self-Improving Security Skill Log security learnings, incidents, and compliance findings to markdown files for continuous improvement. Security-specific entries track vulnerabilities, misconfigurations, access violations, and incident response outcomes. Mature patterns get promoted to security runbooks, hardening checklists, incident response playbooks, and compliance matrices. ## CRITICAL: Sensitive Data Redaction **NEVER log actual secrets, credentials, tokens, private keys, API keys, passwords, connection strings, or PII in any learning or incident entry.** Always redact sensitive values before writing. Use placeholders: | Sensitive Data | Redacted Form | |----------------|---------------| | API keys | `REDACTED_API_KEY` | | Passwords | `REDACTED_PASSWORD` | | Access tokens (JWT, bearer, session) | `REDACTED_TOKEN` | | Private keys | `REDACTED_PRIVATE_KEY` | | Connection strings | `REDACTED_CONNECTION_STRING` | | PII (emails, SSNs) | `REDACTED_PII` | | IP addresses (internal) | `REDACTED_INTERNAL_IP` | | Certificate contents | `REDACTED_CERT` | When logging an incident involving exposed secrets, describe *what kind* of secret was exposed, *where* it appeared, and *the remediation taken* — never the secret itself. ## First-Use Initialisation Before logging anything, ensure the `.learnings/` directory and files exist in the project or workspace root. If any are missing, create them: ```bash mkdir -p .learnings [ -f .learnings/LEARNINGS.md ] || printf "# Security Learnings\n\nVulnerabilities, misconfigurations, compliance gaps, and security insights.\n\n**Categories**: vulnerability | misconfiguration | access_violation | compliance_gap | incident_response | threat_intelligence\n**Areas**: authentication | authorization | encryption | network | endpoint | compliance | cloud\n\n---\n" > .learnings/LEARNINGS.md [ -f .learnings/SECURITY_INCIDENTS.md ] || printf "# Security Incidents Log\n\nVulnerability discoveries, access violations, secrets exposure, and active security incidents.\n\n---\n" > .learnings/SECURITY_INCIDENTS.md [ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Security Feature Requests\n\nSecurity capabilities and hardening improvements requested or identified.\n\n---\n" > .learnings/FEATURE_REQUESTS.md ``` Never overwrite existing files. This is a no-op if `.learnings/` is already initialised. If you want automatic reminders or setup assistance, use the opt-in hook workflow described in [Hook Integration](#hook-integration). No credentials or access tokens are required by this skill. ## Quick Reference | Situation | Action | |-----------|--------| | CVE found in dependency | Log to `.learnings/SECURITY_INCIDENTS.md` with category `vulnerability` | | Secrets exposed in logs/output | Log to `.learnings/SECURITY_INCIDENTS.md` — **REDACT the secret first** | | Access violation or unauthorized access | Log to `.learnings/SECURITY_INCIDENTS.md` with category `access_violation` | | Misconfigured permissions/policies | Log to `.learnings/LEARNINGS.md` with category `misconfiguration` | | Compliance audit failure | Log to `.learnings/LEARNINGS.md` with category `compliance_gap` | | Incident response executed | Log to `.learnings/LEARNINGS.md` with category `incident_response` | | Threat intelligence gathered | Log to `.learnings/LEARNINGS.md` with category `threat_intelligence` | | Security feature needed | Log to `.learnings/FEATURE_REQUESTS.md` | | Hardening improvement identified | Log to `.learnings/LEARNINGS.md` with category `misconfiguration` | | SSL/TLS or certificate issue | Log to `.learnings/SECURITY_INCIDENTS.md` with area `encryption` | | CORS misconfiguration | Log to `.learnings/LEARNINGS.md` with area `network` | | Authentication bypass found | Log to `.learnings/SECURITY_INCIDENTS.md` with area `authentication` | | Similar to existing entry | Link with `**See Also**`, consider priority bump | | Broadly applicable security pattern | Promote to hardening checklist, runbook, or playbook | | Proven incident workflow | Promote to `AGENTS.md` (OpenClaw workspace) | | Security tool gotcha | Promote to `TOOLS.md` (OpenClaw workspace) | | Security principles | Promote to `SOUL.md` (OpenClaw workspace) | ## OpenClaw Setup (Recommended) OpenClaw is the primary platform for this skill. It uses workspace-based prompt injection with automatic skill loading. ### Installation **Via ClawdHub (recommended):** ```bash clawdhub install self-improving-security ``` **Manual:** ```bash git clone https://github.com/jose-compu/self-improving-security.git ~/.openclaw/skills/self-improving-security ``` ### Workspace Structure OpenClaw injects these files into every session: ``` ~/.openclaw/workspace/ ├── AGENTS.md # Incident response workflows, delegation patterns ├── SOUL.md # Security principles, assume-breach mindset ├── TOOLS.md # Security tool capabilities, scanner configs ├── MEMORY.md # Long-term memory (main session only) ├── memory/ # Daily memory files │ └── YYYY-MM-DD.md └── .learnings/ # This skill's log files ├── LEARNINGS.md ├── SECURITY_INCIDENTS.md └── FEATURE_REQUESTS.md ``` ### Create Learning Files ```bash mkdir -p ~/.openclaw/workspace/.learnings ``` Then create the log files (or copy from `assets/`): - `LEARNINGS.md` — misconfigurations, compliance gaps, threat intelligence, best practices - `SECURITY_INCIDENTS.md` — vulnerabilities, access violations, secrets exposure - `FEATURE_REQUESTS.md` — security capabilities and hardening requests ### Promotion Targets When security learnings prove broadly applicable, promote them: | Learning Type | Promote To | Example | |---------------|------------|---------| | Security principles | `SOUL.md` | "Assume breach, defense in depth" | | Incident response workflows | `AGENTS.md` | "Rotate credentials before root cause analysis" | | Security tool hardening | `TOOLS.md` | "Always pass --no-cache to docker build in CI" | | Hardening checklist items | `HARDENING.md` | "Disable directory listing on all web servers" | | Incident response steps | `PLAYBOOKS.md` | "Secrets exposure containment procedure" | | Compliance requirements | `COMPLIANCE.md` | "GDPR data retention audit quarterly" | ### Optional: Enable Hook For automatic reminders at session start: ```bash cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-security openclaw hooks enable self-improving-security ``` See `references/openclaw-integration.md` for complete details. --- ## Generic Setup (Other Agents) For Claude Code, Codex, Copilot, or other agents, create `.learnings/` in the project or workspace root: ```bash mkdir -p .learnings ``` Create the files inline using the headers shown above. Avoid reading templates from the current repo or workspace unless you explicitly trust that path. ### Add reference to agent files Add to AGENTS.md, CLAUDE.md, or `.github/copilot-instructions.md`: #### Security Self-Improvement Workflow When security issues or findings occur: 1. Log to `.learnings/SECURITY_INCIDENTS.md`, `LEARNINGS.md`, or `FEATURE_REQUESTS.md` 2. **ALWAYS redact secrets before logging** 3. Review and promote broadly applicable findings to: - `CLAUDE.md` - security conventions and constraints - `AGENTS.md` - incident response workflows - `.github/copilot-instructions.md` - security context for Copilot ## Logging Format ### Learning Entry Append to `.learnings/LEARNINGS.md`: ```markdown ## [LRN-YYYYMMDD-XXX] category **Logged**: ISO-8601 timestamp **Priority**: low | medium | high | critical **Status**: pending **Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud **CVSS**: N/A or score (e.g., 7.5) ### Summary One-line description of the security finding or learning ### Details Full context: what was found, the security impact, affected systems, root cause ### Remediation Specific fix, hardening step, or compensating control ### Metadata - Source: cve_advisory | pen_test | audit | user_feedback | incident | scan - Related Files: path/to/file.ext - Tags: tag1, tag2 - CVE: CVE-YYYY-NNNNN (if applicable) - CWE: CWE-XXX (if applicable) - See Also: LRN-20250110-001 (if related to existing entry) - Pattern-Key: harden.input_validation | comply.gdpr_consent (optional) - Recurrence-Count: 1 (optional) - First-Seen: 2025-01-15 (optional) - Last-Seen: 2025-01-15 (optional) --- ``` ### Security Incident Entry Append to `.learnings/SECURITY_INCIDENTS.md`: ```markdown ## [SEC-YYYYMMDD-XXX] incident_type **Logged**: ISO-8601 timestamp **Priority**: critical | high | medium | low **Status**: pending **Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud **Severity**: critical | high | medium | low **CVSS**: score or N/A ### Summary Brief description of the security incident ### Incident Details ``` Sanitized error output, log excerpt, or finding description. NEVER include actual secrets, tokens, keys, or PII here. ``` ### Impact Assessment - Affected systems/services - Data at risk (type, not content) - Blast radius estimate ### Containment & Remediation - Immediate containment steps taken - Root cause (if known) - Long-term remediation plan ### Timeline - **Detected**: ISO-8601 - **Contained**: ISO-8601 (if applicable) - **Resolved**: ISO-8601 (if applicable) ### Metadata - CVE: CVE-YYYY-NNNNN (if applicable) - CWE: CWE-XXX (if applicable) - Attack Vector: network | adjacent | local | physical - Reproducible: yes | no | unknown - Related Files: path/to/file.ext - See Also: SEC-20250110-001 (if related) --- ``` ### Feature Request Entry Append to `.learnings/FEATURE_REQUESTS.md`: ```markdown ## [FEAT-YYYYMMDD-XXX] capability_name **Logged**: ISO-8601 timestamp **Priority**: medium **Status**: pending **Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud ### Requested Capability What security capability is needed ### Security Justification Why this capability matters — what risk it mitigates, what compliance requirement it satisfies ### Complexity Estimate simple | medium | complex ### Suggested Implementation How this could be built, what security controls it enables ### Metadata - Frequency: first_time | recurring - Related Features: existing_feature_name - Compliance: SOC2 | GDPR | HIPAA | PCI-DSS | ISO27001 (if applicable) --- ``` ## ID Generation Format: `TYPE-YYYYMMDD-XXX` - TYPE: `LRN` (learning), `SEC` (security incident), `FEAT` (feature request) - YYYYMMDD: Current date - XXX: Sequential number or random 3 chars (e.g., `001`, `A7B`) Examples: `LRN-20250415-001`, `SEC-20250415-A3F`, `FEAT-20250415-002` ## Resolving Entries When an issue is fixed or mitigated, update the entry: 1. Change `**Status**: pending` → `**Status**: resolved` 2. Add resolution block after Metadata: ```markdown ### Resolution - **Resolved**: 2025-01-16T09:00:00Z - **Commit/PR**: abc123 or #42 - **Remediation Applied**: Brief description of fix or compensating control - **Verified By**: pen test | scan | manual review ``` Other status values: - `in_progress` - Actively being investigated or remediated - `wont_fix` - Risk accepted (add justification in Resolution notes) - `promoted` - Elevated to hardening checklist, runbook, or playbook - `promoted_to_skill` - Extracted as a reusable skill ## Promoting to Security Documentation When a finding is broadly applicable, promote it to permanent security documentation. ### When to Promote - Finding applies across multiple services/environments - Pattern should be part of standard hardening - Prevents recurring security issues - Documents compliance requirements - Defines incident response procedures ### Promotion Targets | Target | What Belongs There | |--------|-------------------| | `CLAUDE.md` | Security constraints, banned patterns, safe defaults | | `AGENTS.md` | Incident response workflows, security scan automation | | `.github/copilot-instructions.md` | Security coding standards for Copilot | | `SOUL.md` | Security mindset: assume breach, defense in depth, least privilege | | `TOOLS.md` | Security scanner configs, tool-specific hardening | | `HARDENING.md` | Infrastructure and application hardening checklist | | `PLAYBOOKS.md` | Incident response playbooks | | `COMPLIANCE.md` | Compliance matrices and audit evidence | ### How to Promote 1. **Distill** the finding into a concise security rule or control 2. **Add** to appropriate section in target file (create file if needed) 3. **Update** original entry: - Change `**Status**: pending` → `**Status**: promoted` - Add `**Promoted**: HARDENING.md` (or whichever target) ## Recurring Pattern Detection If logging something similar to an existing entry: 1. **Search first**: `grep -r "keyword" .learnings/` 2. **Link entries**: Add `**See Also**: SEC-20250110-001` in Metadata 3. **Bump priority** if issue keeps recurring 4. **Consider systemic fix**: Recurring security issues often indicate: - Missing hardening baseline (→ promote to HARDENING.md) - Missing automation (→ add scanner or pre-commit hook) - Architectural weakness (→ create security architecture ticket) - Compliance gap (→ update compliance matrix) ## Detection Triggers Automatically log when you notice: **Vulnerability Indicators** (→ security incident): - `CVE-` prefix in output or advisories - `CRITICAL` or `HIGH` severity in scan results - `vulnerability` or `exploit` in dependency audit output - SQL injection, XSS, CSRF patterns in code review **Secrets Exposure** (→ security incident, **REDACT IMMEDIATELY**): - API keys, tokens, passwords in logs or output - Private keys or certificates in plaintext - Connection strings with embedded credentials - `.env` files with secrets committed to git **Access Control Issues** (→ security incident): - `Permission denied` in unexpected contexts - `403 Forbidden` or `401 Unauthorized` errors - Authentication failures or bypass attempts - Privilege escalation indicators **Infrastructure Signals** (→ learning): - `SSL` or `TLS` handshake failures - `certificate expired` or `certificate verify failed` - `CORS` policy violations or misconfigurations - Open ports or exposed services in scan results - `insecure` flag usage in tools or configs **Compliance Signals** (→ learning): - Audit exception or finding - Missing logging or monitoring - Data retention policy violations - Missing consent mechanisms **Feature Requests** (→ feature request): - "We need secret scanning..." - "Can we automate compliance checks..." - "Is there a way to detect..." - "We should add MFA for..." ## Priority Guidelines | Priority | When to Use | |----------|-------------| | `critical` | Active exploitation, data breach, secrets exposed in production, zero-day | | `high` | Known CVE unpatched, secrets in CI/CD logs, missing auth on public endpoint | | `medium` | Misconfiguration with compensating controls, compliance gap with workaround | | `low` | Hardening improvement, defense-in-depth enhancement, informational finding | ## Area Tags Use to filter findings by security domain: | Area | Scope | |------|-------| | `authentication` | Login, MFA, session management, credential storage | | `authorization` | RBAC, ABAC, permission models, access policies | | `encryption` | TLS/SSL, at-rest encryption, key management, certificates | | `network` | Firewalls, CORS, DNS, load balancers, ingress/egress | | `endpoint` | API security, input validation, rate limiting, WAF | | `compliance` | SOC2, GDPR, HIPAA, PCI-DSS, ISO 27001, audit trails | | `cloud` | IAM policies, S3 buckets, security groups, KMS, cloud posture | ## Security-Specific Best Practices 1. **Always redact** — never log actual secrets, credentials, tokens, or PII 2. **Assume breach** — treat every finding as if an attacker already has access 3. **Defense in depth** — one control failing should not mean total compromise 4. **Least privilege** — document the minimum permissions needed, not the maximum 5. **Log immediately** — security context degrades fast; capture details now 6. **Include CVSS/CWE** — standardized scoring enables consistent prioritization 7. **Document blast radius** — who and what is affected if this is exploited 8. **Track remediation timeline** — time-to-fix is a key security metric 9. **Link related entries** — attack chains often span multiple findings 10. **Promote aggressively** — proven security patterns belong in hardening checklists ## Periodic Review Review `.learnings/` at natural breakpoints: ### When to Review - Before deploying to production - After security incidents - Before compliance audits - After dependency updates - Weekly during active development - After pen test or vulnerability scan results ### Quick Status Check ```bash # Count pending security items grep -h "Status\*\*: pending" .learnings/*.md | wc -l # List pending critical/high items grep -B5 "Priority\*\*: critical\|Priority\*\*: high" .learnings/*.md | grep "^## \[" # Find findings for a specific area grep -l "Area\*\*: authentication" .learnings/*.md # List all CVEs referenced grep -h "CVE:" .learnings/*.md | sort -u ``` ## Hook Integration Enable automatic reminders through agent hooks. This is **opt-in**. ### Conservative Mode (Recommended) - Default to manual logging (no hooks); if reminders are useful, enable `UserPromptSubmit` with `scripts/activator.sh` only. - Enable `PostToolUse` (`scripts/error-detector.sh`) only in trusted environments when you explicitly want command-output pattern checks. ### Quick Setup (Claude Code / Codex) Create `.claude/settings.json` in your project: ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-security/scripts/activator.sh" }] }] } } ``` ### Advanced Setup (With Security Error Detection) ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-security/scripts/activator.sh" }] }], "PostToolUse": [{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "./skills/self-improving-security/scripts/error-detector.sh" }] }] } } ``` ### Available Hook Scripts | Script | Hook Type | Purpose | |--------|-----------|---------| | `scripts/activator.sh` | UserPromptSubmit | Reminds to evaluate security findings | | `scripts/error-detector.sh` | PostToolUse (Bash) | Detects security-relevant patterns in output | See `references/hooks-setup.md` for detailed configuration and troubleshooting. ## Automatic Skill Extraction When a security learning is valuable enough to become a reusable skill, extract it. ### Skill Extraction Criteria | Criterion | Description | |-----------|-------------| | **Recurring** | Has `See Also` links to 2+ similar findings | | **Verified** | Status is `resolved` with confirmed remediation | | **Non-obvious** | Required investigation or specialized knowledge | | **Broadly applicable** | Not environment-specific; useful across projects | | **User-flagged** | User says "save this as a security skill" | ### Extraction Workflow 1. **Identify candidate**: Finding meets extraction criteria 2. **Run helper** (or create manually): ```bash ./skills/self-improving-security/scripts/extract-skill.sh skill-name --dry-run ./skills/self-improving-security/scripts/extract-skill.sh skill-name ``` 3. **Customize SKILL.md**: Fill in template with finding content 4. **Update entry**: Set status to `promoted_to_skill`, add `Skill-Path` 5. **Verify**: Ensure no secrets or sensitive data leaked into the skill ### Extraction Detection Triggers **In conversation:** - "Save this security pattern" - "This vulnerability keeps appearing" - "Add this to our hardening checklist" - "Remember this incident response step" **In entries:** - Multiple `See Also` links (recurring vulnerability pattern) - Critical priority + resolved status - Category: `incident_response` with documented procedure - Compliance finding with reusable remediation ## Gitignore Options **Keep learnings local** (recommended for security): ```gitignore .learnings/ ``` Security findings may contain sensitive context. Default to local-only. **Track learnings in repo** (team-wide, sanitized): Only if all entries are confirmed free of secrets, credentials, and PII. ## Multi-Agent Support ### Claude Code **Activation**: Hooks (UserPromptSubmit, PostToolUse) **Setup**: `.claude/settings.json` with hook configuration **Detection**: Automatic via hook scripts ### Codex CLI **Activation**: Hooks (same pattern as Claude Code) **Setup**: `.codex/settings.json` with hook configuration ### GitHub Copilot **Activation**: Manual (no hook support) **Setup**: Add security self-improvement guidance to `.github/copilot-instructions.md` ### OpenClaw **Activation**: Workspace injection + inter-agent messaging **Setup**: See "OpenClaw Setup" section above ### Agent-Agnostic Guidance Regardless of agent, apply security self-improvement when you: 1. **Discover a vulnerability** — in dependencies, code, or configuration 2. **Find exposed secrets** — in logs, output, repos, or CI pipelines 3. **Identify access issues** — unauthorized access, privilege escalation, broken auth 4. **Note compliance gaps** — missing controls, audit failures, policy violations 5. **Improve incident response** — better containment, faster detection, clearer procedures 6. **Gather threat intelligence** — new attack vectors, advisory patterns, pen test results ## Stackability Contract (Standalone + Multi-Skill) This skill is standalone-compatible and stackable with other self-improving skills. ### Namespaced Logging (recommended for 2+ skills) - Namespace for this skill: `.learnings/security/` - Keep current standalone behavior if you prefer flat files. - Optional shared index for all skills: `.learnings/INDEX.md` ### Required Metadata Every new entry must include: ```markdown **Skill**: security ``` ### Hook Arbitration (when 2+ skills are enabled) - Use one dispatcher hook as the single entrypoint. - Dispatcher responsibilities: route by matcher, dedupe repeated events, and rate-limit reminders. - Suggested defaults: dedupe key = `event + matcher + file + 5m_window`; max 1 reminder per skill every 5 minutes. ### Narrow Matcher Scope (security) Only trigger this skill automatically for security signals such as: - `cve-|vulnerability|exploit|secret|token|credential|key leaked` - `auth bypass|privilege escalation|tls|ssl|cors misconfiguration` - explicit security intent in user prompt ### Cross-Skill Precedence When guidance conflicts, apply: 1. `security` 2. `engineering` 3. `coding` 4. `ai` 5. user-explicit domain skill 6. `meta` as tie-breaker ### Ownership Rules - This skill writes only to `.learnings/security/` in stackable mode. - It may read other skill folders for cross-linking, but should not rewrite their entries.

path: assets/FEATURE_REQUESTS.md
content: # Security Feature Requests

Security capabilities, hardening improvements, and compliance tooling requested or identified.

**Areas**: authentication | authorization | encryption | network | endpoint | compliance | cloud
**Statuses**: pending | in_progress | resolved | wont_fix

## Common Request Categories

| Category | Examples |
|----------|----------|
| Detection | Secret scanning, vulnerability scanning, anomaly detection |
| Prevention | WAF rules, input validation, rate limiting, CSP headers |
| Compliance | Audit logging, data retention, consent management, evidence collection |
| Automation | Pre-commit hooks, CI security gates, automated rotation |
| Monitoring | SIEM integration, alerting rules, dashboards |

---


path: assets/ERRORS.md
content: # Security Incidents Log

Vulnerability discoveries, access violations, secrets exposure, and active security incidents.

**Categories**: vulnerability | access_violation | secrets_exposure | active_incident
**Areas**: authentication | authorization | encryption | network | endpoint | compliance | cloud
**Statuses**: pending | in_progress | contained | resolved | wont_fix | promoted | promoted_to_skill

## Status Definitions

| Status | Meaning |
|--------|---------|
| `pending` | Not yet triaged or investigated |
| `in_progress` | Actively being investigated or remediated |
| `contained` | Immediate threat neutralized, root cause analysis ongoing |
| `resolved` | Fully remediated and verified |
| `wont_fix` | Risk accepted with documented justification |
| `promoted` | Elevated to hardening checklist, runbook, or playbook |
| `promoted_to_skill` | Extracted as a reusable security skill |

## CRITICAL REMINDER

**NEVER log actual secrets, credentials, tokens, private keys, or PII in this file.**
Always use `REDACTED_*` placeholders. Describe the *type* of exposure, not the *content*.

## Severity Definitions

| Severity | Criteria |
|----------|----------|
| `critical` | Active exploitation, data breach confirmed, zero-day in production |
| `high` | Known CVE unpatched, secrets in CI logs, auth bypass on public endpoint |
| `medium` | Misconfiguration with compensating controls, limited blast radius |
| `low` | Informational finding, defense-in-depth improvement |

---


path: assets/SKILL-TEMPLATE.md
content: # Security Skill Template

Template for creating security skills extracted from learnings and incidents. Copy and customize.

---

## SKILL.md Template

```markdown
---
name: skill-name-here
description: "Concise description of the security skill and when to use it. Include trigger conditions."
---

# Skill Name

Brief introduction explaining the security problem this skill addresses and its origin.

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Security trigger 1] | [Remediation 1] |
| [Security trigger 2] | [Remediation 2] |

## Background

Why this security knowledge matters. What vulnerabilities or risks it prevents. Context from the original finding.

## Remediation

### Step-by-Step

1. First remediation step with command or configuration
2. Second step
3. Verification step (scan, test, or manual check)

### Code/Config Example

\`\`\`language
// Example showing the secure configuration or code pattern
\`\`\`

## Common Variations

- **Variation A**: Different environment or platform specifics
- **Variation B**: Alternative remediation approach

## Gotchas

- Warning or common mistake during remediation #1
- Warning or common mistake during remediation #2
- **NEVER** log actual secrets — always redact before documenting

## Related Standards

- CWE: CWE-XXX
- OWASP: Reference
- Compliance: SOC2 / GDPR / HIPAA / PCI-DSS control reference

## Source

Extracted from security learning or incident entry.
- **Entry ID**: LRN-YYYYMMDD-XXX or SEC-YYYYMMDD-XXX
- **Original Category**: vulnerability | misconfiguration | compliance_gap | incident_response
- **Extraction Date**: YYYY-MM-DD
```

---

## Minimal Template

For simple security skills:

```markdown
---
name: skill-name-here
description: "What this security skill does and when to use it."
---

# Skill Name

[Security problem statement in one sentence]

## Remediation

[Direct fix with commands/configuration]

## Source

- Entry ID: LRN-YYYYMMDD-XXX or SEC-YYYYMMDD-XXX
```

---

## Template with Scripts

For security skills that include scanner helpers or hardening scripts:

```markdown
---
name: skill-name-here
description: "What this security skill does and when to use it."
---

# Skill Name

[Introduction]

## Quick Reference

| Command | Purpose |
|---------|---------|
| `./scripts/scan.sh` | [What it scans] |
| `./scripts/harden.sh` | [What it hardens] |
| `./scripts/verify.sh` | [What it verifies] |

## Usage

### Automated (Recommended)

\`\`\`bash
./skills/skill-name/scripts/scan.sh [target]
\`\`\`

### Manual Steps

1. Step one
2. Step two

## Scripts

| Script | Description |
|--------|-------------|
| `scripts/scan.sh` | Vulnerability or misconfiguration scanner |
| `scripts/harden.sh` | Applies hardening configuration |
| `scripts/verify.sh` | Verifies remediation was effective |

## Source

- Entry ID: SEC-YYYYMMDD-XXX
```

---

## Naming Conventions

- **Skill name**: lowercase, hyphens for spaces
  - Good: `s3-bucket-hardening`, `jwt-validation-patterns`, `secret-rotation`
  - Bad: `S3_Bucket_Hardening`, `JWTValidation`

- **Description**: Start with action verb, mention security trigger
  - Good: "Hardens S3 bucket configurations against public access. Use when S3 buckets are created or audited."
  - Bad: "S3 stuff"

- **Files**:
  - `SKILL.md` - Required, main documentation
  - `scripts/` - Optional, scanners and hardening scripts
  - `references/` - Optional, compliance mappings
  - `assets/` - Optional, templates

---

## Extraction Checklist

Before creating a skill from a security finding:

- [ ] Finding is verified (status: resolved, remediation confirmed)
- [ ] Solution is broadly applicable (not environment-specific one-off)
- [ ] **No secrets, credentials, or PII in any content**
- [ ] Content is complete (has all needed remediation context)
- [ ] Name follows conventions
- [ ] Description is concise but includes security triggers
- [ ] Quick Reference table maps threats to actions
- [ ] Code/config examples are tested
- [ ] CWE/CVE references included where applicable
- [ ] Source entry ID is recorded

After creating:

- [ ] Update original entry with `promoted_to_skill` status
- [ ] Add `Skill-Path: skills/skill-name` to entry metadata
- [ ] Test skill by reading it in a fresh session
- [ ] Verify no sensitive data leaked into the skill


path: assets/LEARNINGS.md
content: # Security Learnings

Vulnerabilities, misconfigurations, compliance gaps, and security insights captured during development and operations.

**Categories**: vulnerability | misconfiguration | access_violation | compliance_gap | incident_response | threat_intelligence
**Areas**: authentication | authorization | encryption | network | endpoint | compliance | cloud
**Statuses**: pending | in_progress | resolved | wont_fix | promoted | promoted_to_skill

## Status Definitions

| Status | Meaning |
|--------|---------|
| `pending` | Not yet addressed |
| `in_progress` | Actively being investigated or remediated |
| `resolved` | Issue fixed, control implemented, or knowledge integrated |
| `wont_fix` | Risk accepted (justification required in Resolution) |
| `promoted` | Elevated to hardening checklist, compliance matrix, or playbook |
| `promoted_to_skill` | Extracted as a reusable security skill |

## Skill Extraction Fields

When a learning is promoted to a skill, add these fields:

```markdown
**Status**: promoted_to_skill
**Skill-Path**: skills/skill-name
```

Example:
```markdown
## [LRN-20250415-001] misconfiguration

**Logged**: 2025-04-15T10:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/s3-bucket-hardening
**Area**: cloud

### Summary
S3 bucket misconfigured with public read access exposing internal assets
...
```

## CRITICAL REMINDER

**NEVER log actual secrets, credentials, tokens, private keys, or PII.**
Always redact sensitive values. Describe the *type* and *location*, not the *content*.

---


path: scripts/activator.sh
content: #!/bin/bash
# Security Self-Improvement Activator Hook
# Triggers on UserPromptSubmit to remind about security finding capture
# Keep output minimal (~80-120 tokens) to minimize overhead

set -e

cat << 'EOF'
<security-improvement-reminder>
After completing this task, evaluate if any security findings should be captured:
- Vulnerability discovered (CVE, injection, broken auth)?
- Misconfiguration found (permissions, policies, open ports)?
- Access control issue (unauthorized access, privilege escalation)?
- Secrets or credentials in output? → REDACT IMMEDIATELY before logging
- Compliance gap identified (missing control, audit finding)?

CRITICAL: NEVER log actual secrets, credentials, tokens, private keys, or PII.
Always use REDACTED_* placeholders.

If yes: Log to .learnings/ using the security self-improvement format.
  - Vulnerabilities/incidents → SECURITY_INCIDENTS.md [SEC-YYYYMMDD-XXX]
  - Misconfigs/compliance/intel → LEARNINGS.md [LRN-YYYYMMDD-XXX]
If high-value (recurring, broadly applicable): Promote to hardening checklist or playbook.
</security-improvement-reminder>
EOF


path: scripts/extract-skill.sh
content: #!/bin/bash
# Security Skill Extraction Helper
# Creates a new security skill from a learning or incident entry
# Usage: ./extract-skill.sh <skill-name> [--dry-run]

set -e

SKILLS_DIR="./skills"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

usage() {
    cat << EOF
Usage: $(basename "$0") <skill-name> [options]

Create a new security skill from a learning or incident entry.

Arguments:
  skill-name     Name of the skill (lowercase, hyphens for spaces)

Options:
  --dry-run      Show what would be created without creating files
  --output-dir   Relative output directory under current path (default: ./skills)
  -h, --help     Show this help message

Examples:
  $(basename "$0") s3-bucket-hardening
  $(basename "$0") jwt-validation-patterns --dry-run
  $(basename "$0") secret-rotation-playbook --output-dir ./skills/security

The skill will be created in: \$SKILLS_DIR/<skill-name>/
EOF
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

SKILL_NAME=""
DRY_RUN=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --output-dir)
            if [ -z "${2:-}" ] || [[ "${2:-}" == -* ]]; then
                log_error "--output-dir requires a relative path argument"
                usage
                exit 1
            fi
            SKILLS_DIR="$2"
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            log_error "Unknown option: $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "$SKILL_NAME" ]; then
                SKILL_NAME="$1"
            else
                log_error "Unexpected argument: $1"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

if [ -z "$SKILL_NAME" ]; then
    log_error "Skill name is required"
    usage
    exit 1
fi

if ! [[ "$SKILL_NAME" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
    log_error "Invalid skill name format. Use lowercase letters, numbers, and hyphens only."
    log_error "Examples: 's3-bucket-hardening', 'jwt-validation', 'secret-rotation'"
    exit 1
fi

if [[ "$SKILLS_DIR" = /* ]]; then
    log_error "Output directory must be a relative path under the current directory."
    exit 1
fi

if [[ "$SKILLS_DIR" =~ (^|/)\.\.(/|$) ]]; then
    log_error "Output directory cannot include '..' path segments."
    exit 1
fi

SKILLS_DIR="${SKILLS_DIR#./}"
SKILLS_DIR="./$SKILLS_DIR"

SKILL_PATH="$SKILLS_DIR/$SKILL_NAME"

if [ -d "$SKILL_PATH" ] && [ "$DRY_RUN" = false ]; then
    log_error "Skill already exists: $SKILL_PATH"
    log_error "Use a different name or remove the existing skill first."
    exit 1
fi

if [ "$DRY_RUN" = true ]; then
    log_info "Dry run - would create:"
    echo "  $SKILL_PATH/"
    echo "  $SKILL_PATH/SKILL.md"
    echo ""
    echo "Template content would be:"
    echo "---"
    cat << TEMPLATE
name: $SKILL_NAME
description: "[TODO: Describe the security skill and when to use it. Include threat/trigger conditions.]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction explaining the security problem this skill addresses]

## Quick Reference

| Threat/Trigger | Remediation |
|----------------|-------------|
| [Security trigger] | [What to do] |

## Background

[TODO: Why this matters — what vulnerability, risk, or compliance gap it addresses]

## Remediation

[TODO: Step-by-step remediation with commands/configuration]

## Verification

[TODO: How to verify the remediation was effective]

## CRITICAL REMINDER

NEVER include actual secrets, credentials, tokens, or PII in this skill.
All sensitive values must use REDACTED_* placeholders.

## Related Standards

- CWE: [TODO]
- Compliance: [TODO: SOC2 / GDPR / HIPAA / PCI-DSS reference]

## Source

This skill was extracted from a security finding.
- Entry ID: [TODO: LRN-YYYYMMDD-XXX or SEC-YYYYMMDD-XXX]
- Original File: .learnings/LEARNINGS.md or .learnings/SECURITY_INCIDENTS.md
TEMPLATE
    echo "---"
    exit 0
fi

log_info "Creating security skill: $SKILL_NAME"

mkdir -p "$SKILL_PATH"

cat > "$SKILL_PATH/SKILL.md" << TEMPLATE
---
name: $SKILL_NAME
description: "[TODO: Describe the security skill and when to use it. Include threat/trigger conditions.]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction explaining the security problem this skill addresses]

## Quick Reference

| Threat/Trigger | Remediation |
|----------------|-------------|
| [Security trigger] | [What to do] |

## Background

[TODO: Why this matters — what vulnerability, risk, or compliance gap it addresses]

## Remediation

[TODO: Step-by-step remediation with commands/configuration]

## Verification

[TODO: How to verify the remediation was effective]

## CRITICAL REMINDER

NEVER include actual secrets, credentials, tokens, or PII in this skill.
All sensitive values must use REDACTED_* placeholders.

## Related Standards

- CWE: [TODO]
- Compliance: [TODO: SOC2 / GDPR / HIPAA / PCI-DSS reference]

## Source

This skill was extracted from a security finding.
- Entry ID: [TODO: LRN-YYYYMMDD-XXX or SEC-YYYYMMDD-XXX]
- Original File: .learnings/LEARNINGS.md or .learnings/SECURITY_INCIDENTS.md
TEMPLATE

log_info "Created: $SKILL_PATH/SKILL.md"

echo ""
log_info "Security skill scaffold created."
echo ""
echo "Next steps:"
echo "  1. Edit $SKILL_PATH/SKILL.md"
echo "  2. Fill in TODO sections with content from your finding"
echo "  3. Verify NO secrets, credentials, or PII are included"
echo "  4. Add references/ folder for compliance mappings"
echo "  5. Add scripts/ folder for scanners or hardening scripts"
echo "  6. Update the original entry with:"
echo "     **Status**: promoted_to_skill"
echo "     **Skill-Path**: skills/$SKILL_NAME"


path: scripts/error-detector.sh
content: #!/bin/bash
# Security Self-Improvement Error Detector Hook (Optional)
# Conservative detector for high-signal security failures only.
# Reads CLAUDE_TOOL_OUTPUT (when provided by PostToolUse).

set -e

OUTPUT="${CLAUDE_TOOL_OUTPUT:-}"

# If hook context didn't provide output, do nothing.
[ -n "$OUTPUT" ] || exit 0

SECURITY_PATTERNS=(
    "CVE-"
    "CRITICAL"
    "HIGH severity"
    "unauthorized"
    "forbidden"
    "authentication failed"
    "invalid token"
    "expired token"
    "certificate expired"
    "certificate verify failed"
    "privilege escalation"
    "SQL injection"
    "command injection"
    "path traversal"
    "open redirect"
    "SSRF"
    "XXE"
)

contains_security_pattern=false
matched_pattern=""
for pattern in "${SECURITY_PATTERNS[@]}"; do
    if [[ "$OUTPUT" == *"$pattern"* ]]; then
        contains_security_pattern=true
        matched_pattern="$pattern"
        break
    fi
done

if [ "$contains_security_pattern" = true ]; then
    cat << EOF
<security-finding-detected>
High-signal security pattern detected in command output: "$matched_pattern"

Log only when the finding required investigation or is likely to recur.
- Vulnerability/CVE identified
- Access-control or authentication issue confirmed
- Critical transport/authn/authz failure observed

CRITICAL: NEVER log actual secrets, credentials, tokens, or PII.
Use REDACTED_* placeholders. Describe the type, not the content.

Format: [SEC-YYYYMMDD-XXX] for incidents, [LRN-YYYYMMDD-XXX] for learnings.
</security-finding-detected>
EOF
fi


path: hooks/openclaw/handler.js
content: /**
 * Security Self-Improvement Hook for OpenClaw
 *
 * Injects a reminder to evaluate security findings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 */

const REMINDER_CONTENT = `
## Security Self-Improvement Reminder

After completing tasks, evaluate if any security findings should be captured:

**Log when:**
- Vulnerability discovered (CVE, dependency, code) → \`.learnings/SECURITY_INCIDENTS.md\`
- Misconfiguration found (permissions, policies, configs) → \`.learnings/LEARNINGS.md\` (misconfiguration)
- Access control issue (unauthorized access, broken auth) → \`.learnings/SECURITY_INCIDENTS.md\`
- Compliance gap identified (audit finding, missing control) → \`.learnings/LEARNINGS.md\` (compliance_gap)
- Secrets in output or logs → \`.learnings/SECURITY_INCIDENTS.md\` — **REDACT IMMEDIATELY**
- Threat intelligence gathered → \`.learnings/LEARNINGS.md\` (threat_intelligence)

**CRITICAL: NEVER log actual secrets, credentials, tokens, private keys, or PII.**
Always use REDACTED_* placeholders. Describe the type and location, not the content.

**Promote when pattern is proven:**
- Security principles → \`SOUL.md\`
- Incident response workflows → \`AGENTS.md\`
- Security tool hardening → \`TOOLS.md\`
- Hardening checklist items → \`HARDENING.md\`
- Incident response playbooks → \`PLAYBOOKS.md\`

Keep entries actionable: what was found, impact, remediation, and verification.
`.trim();

const handler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'SECURITY_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

module.exports = handler;
module.exports.default = handler;


path: hooks/openclaw/HOOK.md
content: ---
name: self-improving-security
description: "Injects security self-improvement reminder during agent bootstrap"
metadata: {"openclaw":{"emoji":"🛡️","events":["agent:bootstrap"]}}
---

# Security Self-Improvement Hook

Injects a reminder to evaluate security findings during agent bootstrap.

## What It Does

- Fires on `agent:bootstrap` (before workspace files are injected)
- Adds a reminder block to check `.learnings/` for security-relevant entries
- Prompts the agent to log vulnerabilities, misconfigurations, access violations, and incidents
- Emphasizes **NEVER logging actual secrets, credentials, or PII**

## Configuration

No configuration needed. Enable with:

```bash
openclaw hooks enable self-improving-security
```


path: hooks/openclaw/handler.ts
content: /**
 * Security Self-Improvement Hook for OpenClaw
 *
 * Injects a reminder to evaluate security findings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 */

import type { HookHandler } from 'openclaw/hooks';

const REMINDER_CONTENT = `## Security Self-Improvement Reminder

After completing tasks, evaluate if any security findings should be captured:

**Log when:**
- Vulnerability discovered (CVE, dependency, code) → \`.learnings/SECURITY_INCIDENTS.md\`
- Misconfiguration found (permissions, policies, configs) → \`.learnings/LEARNINGS.md\` (misconfiguration)
- Access control issue (unauthorized access, broken auth) → \`.learnings/SECURITY_INCIDENTS.md\`
- Compliance gap identified (audit finding, missing control) → \`.learnings/LEARNINGS.md\` (compliance_gap)
- Secrets in output or logs → \`.learnings/SECURITY_INCIDENTS.md\` — **REDACT IMMEDIATELY**
- Threat intelligence gathered → \`.learnings/LEARNINGS.md\` (threat_intelligence)

**CRITICAL: NEVER log actual secrets, credentials, tokens, private keys, or PII.**
Always use REDACTED_* placeholders. Describe the type and location, not the content.

**Promote when pattern is proven:**
- Security principles → \`SOUL.md\`
- Incident response workflows → \`AGENTS.md\`
- Security tool hardening → \`TOOLS.md\`
- Hardening checklist items → \`HARDENING.md\`
- Incident response playbooks → \`PLAYBOOKS.md\`

Keep entries actionable: what was found, impact, remediation, and verification.`;

const handler: HookHandler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  const sessionKey = event.sessionKey || '';
  if (sessionKey.includes(':subagent:')) {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'SECURITY_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

export default handler;


path: references/examples.md
content: # Security Entry Examples

Concrete examples of well-formatted security entries with all fields.

## Learning: Vulnerability (SQL Injection)

```markdown
## [LRN-20250415-001] vulnerability

**Logged**: 2025-04-15T09:30:00Z
**Priority**: critical
**Status**: pending
**Area**: endpoint
**CVSS**: 9.8

### Summary
SQL injection vulnerability in legacy `/api/v1/users/search` endpoint via unparameterized query

### Details
The legacy search endpoint constructs SQL queries by concatenating user-supplied
`q` parameter directly into the WHERE clause without parameterization. The endpoint
was excluded from the newer ORM-based query builder during the v2 migration.

Affected code: `src/api/v1/controllers/userSearch.js:47`
Pattern: `"SELECT * FROM users WHERE name LIKE '%" + req.query.q + "%'"`

### Remediation
1. Replace string concatenation with parameterized query using the ORM
2. Add input validation middleware for the `q` parameter
3. Add SQL injection tests to the security test suite
4. Consider deprecating the v1 endpoint entirely

### Metadata
- Source: pen_test
- Related Files: src/api/v1/controllers/userSearch.js
- Tags: sql-injection, legacy-code, input-validation
- CWE: CWE-89
- CVE: N/A (internal finding)
- See Also: LRN-20250320-003

---
```

## Learning: Misconfiguration (S3 Bucket Public Access)

```markdown
## [LRN-20250415-002] misconfiguration

**Logged**: 2025-04-15T11:00:00Z
**Priority**: high
**Status**: resolved
**Area**: cloud
**CVSS**: 7.5

### Summary
S3 bucket `company-internal-docs` configured with public read access, exposing internal documentation

### Details
During cloud posture review, discovered that the `company-internal-docs` S3 bucket
had `PublicReadAccess` enabled via a legacy bucket policy. The bucket contained
internal architecture diagrams, API documentation, and onboarding guides. No
credentials or PII were stored in the bucket.

The misconfiguration was introduced during the 2024 migration from the old
storage account when the bucket policy was copied without review.

### Remediation
1. Immediately set bucket to private: `aws s3api put-public-access-block`
2. Audit all S3 buckets for public access: `aws s3api get-public-access-block`
3. Enable S3 Block Public Access at the account level
4. Add Terraform policy to enforce private-by-default on all new buckets

### Metadata
- Source: audit
- Related Files: terraform/modules/s3/main.tf
- Tags: s3, public-access, cloud-posture, aws
- CWE: CWE-732
- Pattern-Key: harden.s3_public_access
- Recurrence-Count: 1
- First-Seen: 2025-04-15
- Last-Seen: 2025-04-15

### Resolution
- **Resolved**: 2025-04-15T13:00:00Z
- **Commit/PR**: #287
- **Remediation Applied**: Bucket set to private, account-level public access block enabled
- **Verified By**: manual review + AWS Config rule

---
```

## Learning: Compliance Gap (GDPR Consent)

```markdown
## [LRN-20250415-003] compliance_gap

**Logged**: 2025-04-15T14:00:00Z
**Priority**: high
**Status**: in_progress
**Area**: compliance
**CVSS**: N/A

### Summary
Missing explicit GDPR consent mechanism for marketing email collection on signup form

### Details
The signup form collects email addresses and automatically opts users into marketing
communications without a separate, unambiguous consent checkbox. Under GDPR Article 7,
consent must be freely given, specific, informed, and unambiguous. The current
implementation bundles marketing consent with account creation consent.

Discovered during Q2 compliance audit. Affects all EU users who signed up since
the form was redesigned in January 2025.

### Remediation
1. Add separate opt-in checkbox for marketing communications (unchecked by default)
2. Store consent timestamp and version in the users table
3. Implement consent withdrawal mechanism (unsubscribe endpoint)
4. Backfill: send re-consent email to affected EU users
5. Update privacy policy to reflect the change

### Metadata
- Source: audit
- Related Files: src/components/SignupForm.tsx, src/api/auth/register.ts
- Tags: gdpr, consent, compliance, marketing, privacy
- CWE: N/A
- Compliance: GDPR Article 7
- Pattern-Key: comply.gdpr_consent
- Recurrence-Count: 1
- First-Seen: 2025-04-15
- Last-Seen: 2025-04-15

---
```

## Security Incident: Secrets Exposed in CI Logs

```markdown
## [SEC-20250415-001] secrets_exposure

**Logged**: 2025-04-15T08:15:00Z
**Priority**: critical
**Status**: resolved
**Area**: cloud
**Severity**: critical
**CVSS**: N/A

### Summary
Database connection string with embedded credentials printed to GitHub Actions build logs

### Incident Details
```
Build step "Run integration tests" printed the full DATABASE_URL environment variable
to stdout, which included embedded credentials:
  DATABASE_URL=postgres://REDACTED_USER:REDACTED_PASSWORD@REDACTED_HOST:5432/REDACTED_DB

The log was visible to all repository collaborators (~40 people) for approximately
2 hours before detection.
```

NOTE: Actual credentials have been redacted above. The original values were
rotated immediately upon detection.

### Impact Assessment
- Affected systems: Production PostgreSQL database
- Data at risk: All application data (user records, transactions)
- Blast radius: Repository collaborators with Actions log access

### Containment & Remediation
- **Immediate**: Rotated database credentials within 15 minutes of detection
- **Short-term**: Deleted the exposed GitHub Actions run logs
- **Root cause**: Test script used `echo $DATABASE_URL` for debugging and was merged without review
- **Long-term**:
  1. Added GitHub Actions log redaction for all `*_URL`, `*_KEY`, `*_SECRET` patterns
  2. Enabled GitHub secret scanning on the repository
  3. Added pre-merge CI check that greps for credential patterns in test scripts
  4. Implemented `GITHUB_ACTIONS` environment detection to suppress debug output in CI

### Timeline
- **Detected**: 2025-04-15T08:15:00Z (via secret scanning alert)
- **Contained**: 2025-04-15T08:30:00Z (credentials rotated)
- **Resolved**: 2025-04-15T10:00:00Z (logs deleted, preventive controls deployed)

### Metadata
- CVE: N/A
- CWE: CWE-532 (Insertion of Sensitive Information into Log File)
- Attack Vector: network (logs accessible via GitHub web UI)
- Reproducible: yes (any push triggering the test workflow)
- Related Files: .github/workflows/integration-tests.yml, scripts/run-tests.sh
- See Also: LRN-20250310-007

---
```

## Security Incident: Unauthorized API Access via Expired JWT

```markdown
## [SEC-20250415-002] access_violation

**Logged**: 2025-04-15T16:30:00Z
**Priority**: high
**Status**: resolved
**Area**: authentication
**Severity**: high
**CVSS**: 8.1

### Summary
Expired JWT tokens accepted by `/api/v2/admin` endpoints due to missing expiry validation in custom middleware

### Incident Details
```
Monitoring detected admin API calls from a token issued 72 hours ago (tokens
should expire after 1 hour). Investigation revealed the custom JWT middleware
on admin routes checked signature validity but skipped the `exp` claim check.

The standard middleware used on user routes correctly validates expiry.
The admin middleware was a copy-paste that omitted the expiry check.
```

### Impact Assessment
- Affected systems: Admin API endpoints (/api/v2/admin/*)
- Data at risk: Admin operations (user management, config changes, reports)
- Blast radius: Any holder of a previously valid admin JWT could access admin APIs indefinitely

### Containment & Remediation
- **Immediate**: Deployed hotfix adding `exp` validation to admin middleware
- **Short-term**: Revoked all existing admin JWTs by rotating the signing key
- **Root cause**: Admin middleware was a copy of user middleware with the `exp` check accidentally removed
- **Long-term**:
  1. Consolidated JWT validation into a single shared middleware
  2. Added integration test that verifies expired tokens are rejected on all protected routes
  3. Added middleware audit to the security review checklist

### Timeline
- **Detected**: 2025-04-15T16:30:00Z (monitoring alert on stale token usage)
- **Contained**: 2025-04-15T17:00:00Z (hotfix deployed)
- **Resolved**: 2025-04-15T18:30:00Z (signing key rotated, all old tokens invalidated)

### Metadata
- CVE: N/A
- CWE: CWE-613 (Insufficient Session Expiration)
- Attack Vector: network
- Reproducible: yes
- Related Files: src/middleware/adminAuth.ts, src/middleware/auth.ts
- See Also: LRN-20250401-002

---
```

## Feature Request: Automated Secret Scanning in Pre-Commit

```markdown
## [FEAT-20250415-001] secret_scanning_precommit

**Logged**: 2025-04-15T12:00:00Z
**Priority**: high
**Status**: pending
**Area**: endpoint

### Requested Capability
Automated secret scanning as a pre-commit hook to prevent credentials, API keys,
and tokens from being committed to the repository.

### Security Justification
SEC-20250415-001 demonstrated that secrets can reach CI logs via committed debug code.
A pre-commit hook would catch these at the developer's machine before they ever enter
the repository. This is a preventive control that reduces the blast radius of accidental
secret exposure to zero (the commit never happens).

### Complexity Estimate
medium

### Suggested Implementation
1. Integrate `gitleaks` or `trufflehog` as a pre-commit hook via `.pre-commit-config.yaml`
2. Configure custom regex patterns for organization-specific secret formats
3. Add allowlist for known false positives (test fixtures, documentation examples)
4. Provide bypass mechanism for emergencies: `SKIP=gitleaks git commit`
5. Add CI-side scanning as a backup (in case developers skip the hook)

### Metadata
- Frequency: recurring (multiple secret exposure incidents)
- Related Features: GitHub secret scanning, CI log redaction
- Compliance: SOC2 CC6.1, PCI-DSS Requirement 6.5
- See Also: SEC-20250415-001

---
```

## Learning: Promoted to Hardening Checklist

```markdown
## [LRN-20250415-004] misconfiguration

**Logged**: 2025-04-15T10:00:00Z
**Priority**: high
**Status**: promoted
**Promoted**: HARDENING.md
**Area**: network

### Summary
CORS misconfiguration allowing wildcard origin on authenticated API endpoints

### Details
The API server was configured with `Access-Control-Allow-Origin: *` on all
endpoints, including authenticated ones. This allows any website to make
cross-origin requests to the API using the user's cookies/tokens, enabling
potential CSRF-like attacks and data exfiltration.

### Remediation
1. Replace wildcard with explicit allowed origins list
2. Use `Access-Control-Allow-Credentials: true` only with specific origins
3. Add CORS configuration to the infrastructure-as-code templates

### Metadata
- Source: pen_test
- Related Files: src/middleware/cors.ts, terraform/modules/api-gateway/main.tf
- Tags: cors, api-security, network
- CWE: CWE-942
- Pattern-Key: harden.cors_wildcard

---
```

## Learning: Promoted to Skill

```markdown
## [LRN-20250415-005] incident_response

**Logged**: 2025-04-15T09:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/secret-rotation-playbook
**Area**: authentication

### Summary
Documented and tested procedure for emergency credential rotation across all environments

### Details
After SEC-20250415-001, formalized the credential rotation procedure that was
executed ad-hoc during the incident. The procedure covers database credentials,
API keys, JWT signing keys, and service account tokens across dev, staging, and
production environments.

### Remediation
Procedure documented as a reusable skill with verification steps for each
credential type and environment.

### Metadata
- Source: incident
- Related Files: docs/runbooks/credential-rotation.md
- Tags: incident-response, credential-rotation, runbook
- See Also: SEC-20250415-001, SEC-20250310-002

---
```


path: references/openclaw-integration.md
content: # OpenClaw Security Integration

Complete setup and usage guide for integrating the security self-improvement skill with OpenClaw.

## Overview

OpenClaw uses workspace-based prompt injection combined with event-driven hooks. Security context is injected from workspace files at session start, and hooks trigger on lifecycle events to remind the agent about security finding capture.

## Workspace Structure

```
~/.openclaw/
├── workspace/                   # Working directory
│   ├── AGENTS.md               # Incident response workflows, security automation
│   ├── SOUL.md                 # Security principles, assume-breach mindset
│   ├── TOOLS.md                # Security tool configs, scanner gotchas
│   ├── HARDENING.md            # Infrastructure and application hardening checklist
│   ├── PLAYBOOKS.md            # Incident response playbooks
│   ├── COMPLIANCE.md           # Compliance matrices and audit evidence
│   ├── MEMORY.md               # Long-term memory (main session only)
│   └── .learnings/             # Security finding logs
│       ├── LEARNINGS.md
│       ├── SECURITY_INCIDENTS.md
│       └── FEATURE_REQUESTS.md
├── skills/                      # Installed skills
│   └── self-improving-security/
│       └── SKILL.md
└── hooks/                       # Custom hooks
    └── self-improving-security/
        ├── HOOK.md
        └── handler.ts
```

## Quick Setup

### 1. Install the Skill

```bash
clawdhub install self-improving-security
```

Or copy manually:

```bash
cp -r self-improving-security ~/.openclaw/skills/
```

### 2. Install the Hook (Optional)

Copy the hook to OpenClaw's hooks directory:

```bash
cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-security
```

Enable the hook:

```bash
openclaw hooks enable self-improving-security
```

### 3. Create Learning Files

```bash
mkdir -p ~/.openclaw/workspace/.learnings
```

Or copy from `assets/`:

```bash
cp assets/LEARNINGS.md ~/.openclaw/workspace/.learnings/
cp assets/ERRORS.md ~/.openclaw/workspace/.learnings/SECURITY_INCIDENTS.md
cp assets/FEATURE_REQUESTS.md ~/.openclaw/workspace/.learnings/
```

## Injected Prompt Files

### AGENTS.md (Security Workflows)

Purpose: Incident response workflows and security automation patterns.

```markdown
# Security Agent Coordination

## Incident Response Workflow
1. Detect: Identify the security finding or incident
2. Triage: Assess severity, blast radius, and urgency
3. Contain: Apply immediate containment measures
4. Remediate: Fix the root cause
5. Verify: Confirm remediation is effective
6. Document: Log to .learnings/ with full context

## Delegation Rules
- Use explore agent for vulnerability pattern searches across codebase
- Spawn sub-agents for parallel security scans
- Use sessions_send to share critical findings across sessions
```

### SOUL.md (Security Principles)

Purpose: Security mindset and principles.

```markdown
# Security Principles

## Core Mindset
- Assume breach: act as if attackers already have access
- Defense in depth: never rely on a single control
- Least privilege: grant minimum permissions needed
- Zero trust: verify explicitly, never trust implicitly

## Handling Sensitive Data
- NEVER log actual secrets, credentials, tokens, or PII
- Always use REDACTED_* placeholders
- Describe the type and location, not the content
- When in doubt, redact more rather than less
```

### TOOLS.md (Security Tools)

Purpose: Security tool capabilities, scanner configurations, and integration gotchas.

```markdown
# Security Tools

## Dependency Scanning
- `npm audit` / `pnpm audit` for Node.js dependencies
- `safety check` for Python dependencies
- `trivy` for container image scanning

## Secret Scanning
- `gitleaks` for git history scanning
- `trufflehog` for deep secret detection
- GitHub Secret Scanning for repository-level alerts

## Static Analysis
- `semgrep` for pattern-based code scanning
- `bandit` for Python security linting
- `eslint-plugin-security` for JavaScript/TypeScript
```

## Security-Specific Promotion Decision Tree

```
Is the finding a one-off or broadly applicable?
├── One-off → Keep in .learnings/
└── Broadly applicable →
    ├── Security principle or mindset? → SOUL.md
    ├── Incident response procedure? → PLAYBOOKS.md
    ├── Infrastructure hardening? → HARDENING.md
    ├── Compliance requirement? → COMPLIANCE.md
    ├── Tool configuration or gotcha? → TOOLS.md
    └── Workflow or automation? → AGENTS.md
```

## Inter-Agent Communication

OpenClaw provides tools for cross-session sharing of security findings.

Use these only when cross-session sharing is explicitly needed and the environment is trusted. **Never forward raw secrets, credentials, or unredacted sensitive data.**

### sessions_send (Security Alerts)

Send critical security findings to other sessions:
```
sessions_send(sessionKey="session-id", message="SECURITY: Expired JWT bypass found in admin middleware. See SEC-20250415-002.")
```

Prefer sending a concise finding summary plus entry ID rather than raw details.

### sessions_spawn (Security Scans)

Spawn background agents for security tasks:
```
sessions_spawn(task="Run dependency audit and report CVEs with CVSS >= 7.0", label="security-scan")
```

## OpenClaw-Specific Detection Triggers

| Trigger | Action |
|---------|--------|
| Dependency audit finds CVEs | Log to SECURITY_INCIDENTS.md with CVE details |
| Tool reports misconfiguration | Log to LEARNINGS.md with misconfiguration category |
| Session detects secret in output | Log to SECURITY_INCIDENTS.md, REDACT immediately |
| Cross-session security alert | Evaluate and log locally if applicable |
| Compliance check failure | Log to LEARNINGS.md with compliance_gap category |

## Available Hook Events

| Event | When It Fires |
|-------|---------------|
| `agent:bootstrap` | Before workspace files inject |
| `command:new` | When `/new` command issued |
| `command:reset` | When `/reset` command issued |
| `command:stop` | When `/stop` command issued |
| `gateway:startup` | When gateway starts |

## Verification

Check hook is registered:

```bash
openclaw hooks list
```

Check skill is loaded:

```bash
openclaw status
```

## Troubleshooting

### Hook not firing

1. Ensure hooks enabled in config
2. Restart gateway after config changes
3. Check gateway logs for errors

### Learnings not persisting

1. Verify `.learnings/` directory exists
2. Check file permissions
3. Ensure workspace path is configured correctly

### Skill not loading

1. Check skill is in skills directory
2. Verify SKILL.md has correct frontmatter
3. Run `openclaw status` to see loaded skills


path: references/hooks-setup.md
content: # Security Hook Setup Guide

Configure automatic security self-improvement triggers for AI coding agents.

## Overview

Hooks can help capture security findings with minimal overhead:
- **UserPromptSubmit** (recommended): Reminder after each prompt to evaluate security findings
- **PostToolUse (Bash)** (optional): Detection when high-signal security patterns appear in command output (trusted environments only)

## Claude Code Setup

### Option 1: Project-Level Configuration

Create `.claude/settings.json` in your project root (activator-only recommended):

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-security/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

### Optional: Add PostToolUse Error Detector

Enable this only when you explicitly want command-output pattern checks in trusted environments:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-security/scripts/error-detector.sh"
          }
        ]
      }
    ]
  }
}
```

### Option 2: User-Level Configuration

Add to `~/.claude/settings.json` for global activation:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/skills/self-improving-security/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

### Minimal Setup (Activator Only)

For lower overhead, use only the UserPromptSubmit hook:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-security/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## Codex CLI Setup

Codex uses the same hook system. Create `.codex/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-security/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## GitHub Copilot Setup

Copilot doesn't support hooks directly. Add guidance to `.github/copilot-instructions.md`:

```markdown
## Security Self-Improvement

After completing tasks that involved:
- Reviewing or modifying authentication/authorization code
- Working with secrets, credentials, or environment variables
- Configuring cloud resources or network policies
- Addressing vulnerability scan findings
- Handling compliance requirements

Consider logging the finding to `.learnings/` using the security self-improvement skill format.

CRITICAL: NEVER include actual secrets, credentials, tokens, or PII in learning entries.
Always redact sensitive values before documenting.
```

## Verification

### Test Activator Hook

1. Enable the hook configuration
2. Start a new Claude Code session
3. Send any prompt
4. Verify you see `<security-improvement-reminder>` in the context

### Test Error Detector Hook

1. Enable PostToolUse hook for Bash
2. Run a command that produces security-relevant output: `curl -k https://expired.badssl.com/`
3. Verify you see `<security-finding-detected>` reminder

### Dry Run Extract Script

```bash
./skills/self-improving-security/scripts/extract-skill.sh test-skill --dry-run
```

## Troubleshooting

### Hook Not Triggering

1. **Check script permissions**: `chmod +x scripts/*.sh`
2. **Verify path**: Use absolute paths or paths relative to project root
3. **Check settings location**: Project vs user-level settings
4. **Restart session**: Hooks are loaded at session start

### Permission Denied

```bash
chmod +x ./skills/self-improving-security/scripts/activator.sh
chmod +x ./skills/self-improving-security/scripts/error-detector.sh
chmod +x ./skills/self-improving-security/scripts/extract-skill.sh
```

### Script Not Found

If using relative paths, ensure you're in the correct directory or use absolute paths:

```json
{
  "command": "/absolute/path/to/skills/self-improving-security/scripts/activator.sh"
}
```

### Too Much Overhead

If the activator feels intrusive:

1. **Use minimal setup**: Only UserPromptSubmit, skip PostToolUse
2. **Add matcher filter**: Only trigger for security-related prompts:

```json
{
  "matcher": "security|vuln|CVE|auth|permission|secret|credential|compliance",
  "hooks": [...]
}
```

## Hook Output Budget

The activator is designed to be lightweight:
- **Target**: ~80-120 tokens per activation
- **Content**: Structured reminder with security-specific guidance
- **Format**: XML tags for easy parsing

## Security Considerations

- Hook scripts run with the same permissions as Claude Code
- Scripts only output text; they do not modify files or run commands
- Error detector reads `CLAUDE_TOOL_OUTPUT` environment variable
- Treat `CLAUDE_TOOL_OUTPUT` as potentially sensitive — **never log or forward it verbatim**
- All scripts are opt-in (you must configure them explicitly)
- Recommended default: enable `UserPromptSubmit` only
- No credentials or access tokens are required by this skill

## Disabling Hooks

To temporarily disable without removing configuration:

1. **Comment out in settings**:
```json
{
  "hooks": {
    // "UserPromptSubmit": [...]
  }
}
```

2. **Or delete the settings file**: Hooks won't run without configuration


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)