.claude/skills/defense-profiler/SKILL.md
Codebase defense analysis system for security profiling
npx skillsauth add alfredolopez80/multi-agent-ralph-loop defense-profilerInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
~/.claude/settings.json or CLI/env varsANTHROPIC_DEFAULT_*_MODEL env varsCodebase Defense Analysis System inspired by ZeroLeaks defense profiling.
Systematically analyzes code to build a comprehensive profile of security defenses, patterns, and weaknesses.
Before attacking (testing), understand the defenses. Build a mental model of:
/defense-profile src/
/defense-profile --focus security src/auth/
/defense-profile --output profile.json src/api/
| Level | Description | Characteristics |
|-------|-------------|-----------------|
| none | No apparent protection | Direct vulnerabilities, no validation |
| weak | Basic protections | Simple validation, incomplete coverage |
| moderate | Standard defenses | Input validation, error handling |
| strong | Good security | Multiple layers, proper sanitization |
| hardened | Defense in depth | Multi-layered, comprehensive coverage |
interface DefenseProfile {
// Overall assessment
level: DefenseLevel;
confidence: number; // 0-1
// Observed patterns
observedBehaviors: string[];
// Guardrails in place
guardrails: {
type: string;
strength: number;
coverage: string[];
bypassed: boolean;
bypassMethod?: string;
}[];
// Identified weaknesses
weaknesses: {
category: string;
description: string;
exploitability: number; // 0-1
location?: string;
}[];
// Trigger patterns
refusalTriggers: string[]; // What causes errors/rejects
safePatterns: string[]; // What passes through
// Response patterns
responsePatterns: {
pattern: string;
frequency: number;
defenseIndicator: boolean;
}[];
}
dimension: input_validation
checks:
- type_checking: Are inputs typed?
- null_handling: Are nulls handled?
- boundary_checks: Are limits enforced?
- sanitization: Is input sanitized?
- encoding_handling: Are encodings handled?
signals:
weak:
- No type annotations
- Missing null checks
- Unconstrained inputs
strong:
- Zod/Joi schemas
- TypeScript strict mode
- Comprehensive validation
dimension: auth_security
checks:
- auth_mechanism: How is auth implemented?
- session_management: How are sessions handled?
- permission_checks: Are permissions verified?
- token_validation: Are tokens properly validated?
signals:
weak:
- Plain text passwords
- No CSRF protection
- Missing auth middleware
strong:
- bcrypt/argon2 hashing
- JWT with refresh tokens
- RBAC implementation
dimension: error_handling
checks:
- error_exposure: Are errors exposed?
- logging_security: Are logs secure?
- graceful_degradation: Does it fail safely?
- recovery_patterns: Are there recovery mechanisms?
signals:
weak:
- Stack traces in responses
- Sensitive data in logs
- Unhandled promise rejections
strong:
- Generic error messages
- Structured logging
- Error boundaries
dimension: data_protection
checks:
- encryption_at_rest: Is data encrypted?
- encryption_in_transit: Is TLS used?
- secret_management: How are secrets handled?
- pii_handling: Is PII protected?
signals:
weak:
- Hardcoded secrets
- No encryption
- PII in logs
strong:
- Environment variables
- Key management service
- Data masking
dimension: injection_prevention
checks:
- sql_injection: Are queries parameterized?
- xss_prevention: Is output escaped?
- command_injection: Are commands sanitized?
- path_traversal: Are paths validated?
signals:
weak:
- String concatenation in queries
- innerHTML usage
- Shell commands with user input
strong:
- ORM with parameterization
- Content Security Policy
- Input whitelisting
Patterns that cause the code to reject/fail:
const refusalPatterns = [
// Authentication failures
/unauthorized|unauthenticated|forbidden/i,
// Validation failures
/invalid|malformed|bad request/i,
// Security blocks
/blocked|denied|not allowed/i,
// Rate limiting
/too many requests|rate limit/i
];
Patterns suggesting information exposure:
const leakPatterns = [
// Configuration exposure
/config|settings|environment/i,
// Implementation details
/stack trace|internal error|debug/i,
// Sensitive data
/password|secret|token|key/i
];
def build_defense_profile(codebase):
"""
Build comprehensive defense profile.
Returns:
DefenseProfile with all assessments
"""
profile = DefenseProfile()
# Phase 1: Static Analysis
patterns = analyze_static_patterns(codebase)
profile.observedBehaviors.extend(patterns)
# Phase 2: Dependency Analysis
deps = analyze_dependencies(codebase)
profile.guardrails.extend(identify_guardrails(deps))
# Phase 3: Pattern Matching
for file in codebase.files:
weak_signals = match_weak_patterns(file)
strong_signals = match_strong_patterns(file)
profile.weaknesses.extend(weak_signals)
profile.responsePatterns.extend(strong_signals)
# Phase 4: Level Assessment
profile.level = calculate_defense_level(profile)
profile.confidence = calculate_confidence(profile)
return profile
def calculate_defense_level(profile):
"""
Calculate overall defense level based on signals.
"""
weak_count = len(profile.weaknesses)
strong_count = len([g for g in profile.guardrails if g.strength > 0.7])
ratio = strong_count / (weak_count + strong_count + 1)
if ratio > 0.9:
return "hardened"
elif ratio > 0.7:
return "strong"
elif ratio > 0.4:
return "moderate"
elif ratio > 0.2:
return "weak"
else:
return "none"
Defense profiling runs early in the analysis:
Step 1b: GAP-ANALYST
- Defense Profiler (if security-related task)
Step 6: EXECUTE-WITH-SYNC
- 6a. LSA-VERIFY
- Check against Defense Profile
Step 7: VALIDATE
- 7c. ADVERSARIAL-CODE
- Use Defense Profile to guide analysis
Task:
subagent_type: "defense-profiler"
model: "sonnet"
prompt: |
TARGET_PATH: src/
FOCUS: security
DEPTH: comprehensive
Build defense profile for the target codebase.
Identify:
- Current defense level
- Active guardrails
- Weaknesses and their exploitability
- Patterns and signals
{
"defense_profile": {
"level": "moderate",
"confidence": 0.78,
"summary": "Codebase has standard defenses with some gaps",
"guardrails": [
{
"type": "input_validation",
"strength": 0.65,
"coverage": ["api/auth", "api/users"],
"bypassed": false
},
{
"type": "rate_limiting",
"strength": 0.80,
"coverage": ["api/*"],
"bypassed": false
}
],
"weaknesses": [
{
"category": "injection",
"description": "SQL concatenation in legacy queries",
"exploitability": 0.7,
"location": "src/db/legacy.ts:45"
},
{
"category": "auth",
"description": "Missing CSRF token validation",
"exploitability": 0.5,
"location": "src/middleware/auth.ts"
}
],
"recommendations": [
"Migrate legacy queries to parameterized ORM",
"Add CSRF middleware to state-changing endpoints",
"Implement rate limiting on auth endpoints"
]
},
"analysis_metadata": {
"files_analyzed": 156,
"patterns_matched": 23,
"duration_ms": 4500
}
}
| Category | Description | Examples |
|----------|-------------|----------|
| injection | Code injection vulnerabilities | SQL, XSS, Command |
| auth | Authentication/authorization issues | Missing checks, weak tokens |
| crypto | Cryptographic weaknesses | Weak algorithms, poor key management |
| config | Configuration problems | Hardcoded secrets, insecure defaults |
| data | Data protection issues | Unencrypted PII, logging sensitive data |
| trust | Trust boundary violations | SSRF, open redirects |
| resource | Resource management | Memory leaks, DoS vectors |
# Full profile
ralph defense-profile src/
# Focused on security
ralph defense-profile --focus security src/auth/
# Quick scan
ralph defense-profile --quick src/
# Output to file
ralph defense-profile src/ --output defense-profile.json
# Compare profiles
ralph defense-profile --compare baseline.json src/
Set up as pre-commit hook:
#!/bin/bash
# Run defense profile on changed files
CHANGED=$(git diff --cached --name-only)
ralph defense-profile --files "$CHANGED" --threshold moderate
# Fail if level dropped
if [ $? -ne 0 ]; then
echo "Defense level dropped below threshold"
exit 1
fi
Defense profiling patterns adapted from ZeroLeaks defense analysis system (FSL-1.1-Apache-2.0).
development
Living knowledge base management. Actions: search (query vault), save (store learning), index (update indices), compile (raw->wiki->rules graduation), init (create vault structure). Follows Karpathy pipeline: ingest->compile->query. Use when: (1) searching accumulated knowledge, (2) saving learnings, (3) compiling raw notes into wiki, (4) initializing a new vault. Triggers: /vault, 'vault search', 'knowledge base', 'save learning'.
testing
Produce a verifiable technical specification before coding. 6 mandatory sections: Interfaces, Behaviors, Invariants (from Aristotle Phase 2), File Plan, Test Plan, Exit Criteria (executable bash commands + expected results). Use when: (1) before implementing features with complexity > 4, (2) as Step 1.5 in orchestrator workflow, (3) when requirements need formalization. Triggers: /spec, 'create spec', 'write specification', 'technical spec'.
testing
Pre-launch shipping checklist orchestrating /gates, /security, /browser-test, /perf. Ensures nothing ships without passing all quality checks. Use when: (1) before deploying, (2) before merging to main, (3) before release. Triggers: /ship, 'ship it', 'ready to deploy', 'pre-launch check'.
development
Performance optimization skill. Core Web Vitals via Lighthouse, bundle size analysis, metrics tracking over time. Use when: (1) optimizing frontend performance, (2) analyzing bundle size, (3) tracking metrics regression. Triggers: /perf, 'performance audit', 'core web vitals', 'bundle size'.