Get the FREE Ultimate OpenClaw Setup Guide →

security-patterns

npx machina-cli add skill aiskillstore/marketplace/security-patterns --openclaw
Files (1)
SKILL.md
4.8 KB

Security Patterns

Essential security patterns for web applications.

OWASP Top 10 Quick Reference

RankVulnerabilityPrevention
A01Broken Access ControlCheck permissions server-side, deny by default
A02Cryptographic FailuresUse TLS, hash passwords, encrypt sensitive data
A03InjectionParameterized queries, validate input
A04Insecure DesignThreat modeling, secure defaults
A05Security MisconfigurationHarden configs, disable unused features
A06Vulnerable ComponentsUpdate dependencies, audit regularly
A07Auth FailuresMFA, rate limiting, secure session management
A08Data Integrity FailuresVerify signatures, use trusted sources
A09Logging FailuresLog security events, protect logs
A10SSRFValidate URLs, allowlist destinations

Input Validation

# WRONG - Trust user input
def search(query):
    return db.execute(f"SELECT * FROM users WHERE name = '{query}'")

# CORRECT - Parameterized query
def search(query):
    return db.execute("SELECT * FROM users WHERE name = ?", [query])

Validation Rules

Always validate:
- Type (string, int, email format)
- Length (min/max bounds)
- Range (numeric bounds)
- Format (regex for patterns)
- Allowlist (known good values)

Never trust:
- URL parameters
- Form data
- HTTP headers
- Cookies
- File uploads

Output Encoding

// WRONG - Direct HTML insertion
element.innerHTML = userInput;

// CORRECT - Text content (auto-escapes)
element.textContent = userInput;

// CORRECT - Template with escaping
render(`<div>${escapeHtml(userInput)}</div>`);

Encoding by Context

ContextEncoding
HTML bodyHTML entity encode
HTML attributeAttribute encode + quote
JavaScriptJS encode
URL parameterURL encode
CSSCSS encode

Authentication

# Password hashing (use bcrypt, argon2, or scrypt)
import bcrypt

def hash_password(password: str) -> bytes:
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

def verify_password(password: str, hashed: bytes) -> bool:
    return bcrypt.checkpw(password.encode(), hashed)

Auth Checklist

  • Hash passwords with bcrypt/argon2 (cost factor 12+)
  • Implement rate limiting on login
  • Use secure session tokens (random, long)
  • Set secure cookie flags (HttpOnly, Secure, SameSite)
  • Implement account lockout after failed attempts
  • Support MFA for sensitive operations

Authorization

# WRONG - Check only authentication
@login_required
def delete_post(post_id):
    post = Post.get(post_id)
    post.delete()

# CORRECT - Check authorization
@login_required
def delete_post(post_id):
    post = Post.get(post_id)
    if post.author_id != current_user.id and not current_user.is_admin:
        raise Forbidden("Not authorized to delete this post")
    post.delete()

Secrets Management

# WRONG - Hardcoded secrets
API_KEY = "sk-1234567890abcdef"

# CORRECT - Environment variables
API_KEY = os.environ["API_KEY"]

# BETTER - Secrets manager
API_KEY = secrets_client.get_secret("api-key")

Secret Handling Rules

DO:
- Use environment variables or secrets manager
- Rotate secrets regularly
- Use different secrets per environment
- Audit secret access

DON'T:
- Commit secrets to git
- Log secrets
- Include secrets in error messages
- Share secrets in plain text

Security Headers

Content-Security-Policy: default-src 'self'; script-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000; includeSubDomains
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), camera=()

Quick Security Audit

# Find hardcoded secrets
rg -i "(password|secret|api_key|token)\s*=\s*['\"][^'\"]+['\"]" --type py

# Find SQL injection risks
rg "execute\(f['\"]|format\(" --type py

# Find eval/exec usage
rg "\b(eval|exec)\s*\(" --type py

# Check for TODO security items
rg -i "TODO.*security|FIXME.*security"

Additional Resources

  • ./references/owasp-detailed.md - Full OWASP Top 10 details
  • ./references/auth-patterns.md - JWT, OAuth, session management
  • ./references/crypto-patterns.md - Encryption, hashing, signatures
  • ./references/secure-headers.md - HTTP security headers guide

Scripts

  • ./scripts/security-scan.sh - Quick security grep patterns
  • ./scripts/dependency-audit.sh - Check for vulnerable dependencies

Source

git clone https://github.com/aiskillstore/marketplace/blob/main/skills/0xdarkmatter/security-patterns/SKILL.mdView on GitHub

Overview

Provides essential security patterns aligned with the OWASP Top 10 to help developers build secure web apps. It covers input validation, output encoding, authentication, authorization, and secrets management with practical examples and checklists. Following these patterns helps prevent common vulnerabilities like injection, XSS, and misconfigurations.

How This Skill Works

Security patterns are presented in a language-agnostic way, with framework-specific examples in references. The skill demonstrates correct vs. incorrect implementations (e.g., parameterized queries, proper encoding, and secure password handling) and shows how to apply OWASP-aligned controls during development and code reviews.

When to Use It

  • During security reviews or OWASP assessments to spot gaps in code and configurations
  • When validating user input to prevent SQL injections, XSS, and malformed data
  • During output rendering to ensure proper encoding and prevent XSS
  • When implementing authentication and authorization to enforce least privilege
  • When handling secrets and configuration to avoid leakage and ensure rotation

Quick Start

  1. Step 1: Audit your codebase against OWASP Top 10 and identify injection, XSS, and auth gaps
  2. Step 2: Implement secure patterns: validate inputs, apply parameterized queries, encode output, and harden auth/secrets
  3. Step 3: Test, monitor, and iterate: run security tests, rotate secrets, and review headers and configs

Best Practices

  • Validate every input: enforce type, length, range, format, and allowlists; never trust user data
  • Use parameterized queries and bound parameters to prevent SQL injection
  • Encode output by context (HTML, JS, URL) to defend against XSS
  • Strengthen authentication/authorization: hash passwords with bcrypt/Argon2, enable MFA, secure sessions, and rate-limit logins
  • Manage secrets securely: use environment variables or a secrets manager, rotate regularly, and audit access; never hardcode secrets

Example Use Cases

  • Parameterized SQL query in Python to safely search a users table
  • Input validation rules on a signup form (type, length, format)
  • Escaping user input for HTML rendering or using textContent to prevent XSS
  • Hashing passwords with bcrypt and using secure, HttpOnly cookies with SameSite
  • Storing API keys via environment variables or a dedicated secrets manager and auditing access

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers