SE

secure-coding-cybersecurity

Provides security guardrails and audit checklists to secure AI-generated code against common vulnerabilities.

Install

mkdir -p .claude/skills/secure-coding-cybersecurity && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/15555" && unzip -o skill.zip -d .claude/skills/secure-coding-cybersecurity && rm skill.zip

Installs to .claude/skills/secure-coding-cybersecurity

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Expert guidance on secure coding practices, focusing on preventing common security errors made by AI during code generation. Use for: auditing AI-generated code, implementing secure design patterns, and ensuring code follows OWASP Top 10 standards. Covers input validation, authentication, cryptography, file handling, secure configuration, and business logic security.
369 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • Audit AI-generated code for security flaws
  • Implement secure design patterns
  • Ensure code follows OWASP Top 10 standards
  • Validate and normalize user input
  • Prevent SQL, XSS, and OS command injections
  • Manage secrets securely using environment variables or vaults

How it works

This skill provides guardrails, checklists, and verification steps to ensure code is secure. It identifies common AI security failures and outlines non-negotiable security rules.

Inputs & outputs

You give it
AI-generated code snippets or existing code
You get back
Audited code with identified vulnerabilities and recommendations

When to use secure-coding-cybersecurity

  • Auditing AI-generated code
  • Ensuring OWASP compliance
  • Implementing secure file handling
  • Validating authentication logic

About this skill

Secure Coding & Cybersecurity Skill

Vision and Purpose

This skill establishes security as a first-class citizen in code generation and review. It recognizes that AI-generated code often prioritizes functionality over security, inheriting and propagating vulnerabilities from training data. This skill provides comprehensive guardrails, checklists, and verification steps to ensure all code—especially AI-generated—is robust, secure, and follows industry best practices.

Critical Understanding: Why AI Code is Often Insecure

AI models optimize for "working code" and "correct-looking output" before "secure and robust code." This introduces classic vulnerabilities at concerning rates:

Root Causes of AI Security Failures

  1. Functionality over Security: If the prompt doesn't explicitly demand security, the model prioritizes the shortest solution even if it uses eval(), SQL string concatenation, or hardcoded keys.

  2. Learning from Insecure Examples: A significant portion of publicly available code contains bad practices (hardcoded secrets, weak encryption, missing validation), and models reproduce these patterns.

  3. Lack of Context Awareness: AI doesn't understand your business rules, threat model, or compliance requirements (PCI-DSS, HIPAA, GDPR), filling gaps with dangerous assumptions.

  4. High CWE Rates in Studies: Empirical research consistently finds serious vulnerabilities (SQLi, XSS, buffer overflows, crypto misuse, hardcoded credentials) in AI-generated code samples.

The Security Non-Negotiables

These rules must NEVER be violated, regardless of convenience or "example purposes":

  1. Never Prioritize Simplicity Over Security: Do not provide "clean" examples that omit input validation or use insecure defaults, even with disclaimers.

  2. Treat AI Output as Untrusted: Always audit AI-generated snippets for hallucinated libraries, outdated patterns, and missing security controls.

  3. Fail Closed: All logic must default to "Access Denied" if an exception occurs, validation fails, or state is unclear.

  4. No Hardcoded Secrets: Never suggest code with hardcoded API keys, passwords, tokens, or cryptographic keys. Always use environment variables, secret managers, or secure vaults.

  5. Parameterized Everything: Never use string concatenation or formatting for SQL queries, OS commands, HTML rendering, or LDAP filters.

  6. Validate All Inputs: Every piece of external data must be validated and sanitized before use.

  7. Defense in Depth: Never rely on a single security control; implement multiple layers of protection.

Comprehensive Security Checklist

1. Input Validation and Injection Prevention

The Problem: AI frequently omits input validation and sanitization unless explicitly requested, leading to CWE-20 (Improper Input Validation) and the entire injection vulnerability family (SQLi, XSS, OS Command Injection, LDAP Injection).

Research Finding: Multiple studies identify SQL injection, XSS, and OS command injection as recurrent vulnerabilities in LLM-generated code.

Checklist

  • Validate and normalize ALL user input before use, including:

    • Query parameters (URL parameters)
    • Request body (JSON, form data)
    • Headers (including custom headers)
    • Path parameters
    • File uploads
    • WebSocket messages
    • GraphQL inputs
  • Use allowlists over denylists: Define what is permitted rather than trying to block what is malicious. Use strict type checking, enum validation, and schema validation.

  • Parameterized queries ONLY: Never concatenate strings to build SQL queries, shell commands, LDAP filters, XPath expressions, or NoSQL queries. Always use:

    • Prepared statements with bound parameters
    • ORM query builders with parameterized methods
    • Safe API abstractions that prevent injection
  • XSS Prevention: Escape or sanitize all data before rendering in HTML contexts:

    • Use auto-escaping template engines
    • Apply context-appropriate encoding (HTML, JavaScript, CSS, URL)
    • Avoid innerHTML, document.write, and similar dangerous APIs
    • Implement Content Security Policy (CSP) headers
  • Disable dangerous evaluation: Never use eval(), Function(), exec(), child_process.exec(), Runtime.exec(), os.system(), or similar on user-controlled data. If dynamic execution is absolutely necessary, use strict sandboxing and allowlists.

  • Strict regex validation: When using regular expressions for validation:

    • Prefer exact match patterns (^pattern$) over partial matches
    • Avoid overly permissive patterns
    • Be aware of ReDoS (Regular Expression Denial of Service) vulnerabilities

Verification Steps

Before considering input handling complete:

  1. Fuzz Test: Test with unexpected inputs (null, empty strings, very long strings, special characters, Unicode, binary data)
  2. Injection Test: Attempt SQL, NoSQL, command, and XSS injection payloads
  3. Boundary Test: Test at and beyond length limits, type boundaries, and range limits
  4. Negative Test: Ensure invalid inputs are rejected with appropriate errors

Common AI Mistakes to Avoid

# ❌ NEVER DO THIS - SQL Injection vulnerability
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)

# ✅ DO THIS INSTEAD - Parameterized query
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))

# ❌ NEVER DO THIS - XSS vulnerability
element.innerHTML = userInput

// ❌ NEVER DO THIS - Command Injection
const output = exec(`ls ${userInput}`);

// ✅ DO THIS INSTEAD - Safe command execution with allowlist
const allowedCommands = ['list', 'status'];
if (allowedCommands.includes(userInput)) {
  const output = execFile('ls', [safePath]);
}

2. Authentication, Authorization, and Session Management

The Problem: AI generates authentication flows that "pass happy path tests" but ignore critical security details like rate limiting, constant-time comparison, or fine-grained authorization controls. This enables brute-force attacks, privilege escalation, and API abuse.

Checklist

  • Secure password storage:

    • Use modern, memory-hard algorithms: Argon2id (recommended), bcrypt, or scrypt
    • Never use MD5, SHA1, SHA256 for password hashing (they're too fast)
    • Always use unique salts per password
    • Configure appropriate cost factors/work factors
  • Constant-time comparisons: Compare tokens, passwords, and API keys using constant-time comparison functions to prevent timing attacks:

    • Python: hmac.compare_digest()
    • Node.js: crypto.timingSafeEqual()
    • Java: MessageDigest.isEqual()
  • Rate limiting and brute-force protection:

    • Implement rate limiting on login endpoints, password reset, OTP verification, and sensitive APIs
    • Use progressive delays for failed attempts
    • Consider CAPTCHA after multiple failures
    • Implement account lockout policies (with unlock mechanisms)
  • Authorization on every endpoint:

    • Verify ownership and permissions on every request, not just authentication
    • Check for IDOR (Insecure Direct Object Reference) vulnerabilities
    • Validate that users can only access their own resources
    • Implement attribute-based access control (ABAC) where appropriate
  • Secure session management:

    • Use cryptographically secure random session IDs
    • Implement reasonable session timeouts
    • Support session revocation and rotation
    • Regenerate session IDs on privilege changes (login, password change, role change)
  • Secure cookie configuration:

    • Set HttpOnly flag (prevents JavaScript access)
    • Set Secure flag (HTTPS only)
    • Set SameSite attribute (Strict or Lax)
    • Use appropriate Max-Age or Expires
    • Consider __Host- prefix for additional protection
  • JWT security:

    • Use strong signing algorithms (RS256, ES256, HS256 with strong secrets)
    • Never use "none" algorithm or weak secrets
    • Set short expiration times
    • Include token rotation and revocation mechanisms
    • Store tokens securely (not in localStorage for sensitive apps)
  • Password reset security:

    • Use cryptographically secure random tokens with high entropy
    • Implement single-use tokens with short expiration
    • Do not reveal whether an email exists in the system (privacy protection)
    • Invalidate existing tokens when new ones are requested
    • Require re-authentication after password reset
  • Multi-factor authentication (MFA):

    • Support TOTP (Time-based One-Time Password)
    • Support WebAuthn/FIDO2 for strong authentication
    • Enforce MFA for privileged accounts
    • Implement backup codes securely

Verification Steps

  1. Brute Force Test: Attempt to guess passwords, session IDs, and tokens
  2. Timing Attack Test: Measure response times for different inputs
  3. Authorization Test: Try to access other users' resources
  4. Session Fixation Test: Verify session ID changes on login
  5. Token Analysis: Check JWT headers and payloads for security issues

Common AI Mistakes to Avoid

# ❌ NEVER DO THIS - Insecure password hashing
hashed = hashlib.md5(password.encode()).hexdigest()

# ✅ DO THIS INSTEAD - Secure password hashing
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

# ❌ NEVER DO THIS - Timing attack vulnerability
if token == stored_token:
    # authenticate

# ✅ DO THIS INSTEAD - Constant-time comparison
if hmac.compare_digest(token, stored_token):
    # authenticate

# ❌ NEVER DO THIS - No rate limiting
@app.route('/login', methods=['POST'])
def login():
    # authenticate

# ✅ DO THIS INSTEAD - Rate limiting
@limiter.limit("5 per minute")
@app.route('/login', methods=['POST'])
def login():
    # authenticate

# ❌ NEVER DO THIS - Missing authorization check
@app.route('/api/documents/<doc_id>')
def get_document(doc_id):
    return Document.query.get(doc_id)  # No ownership check!

# ✅ DO THI

---

*Content truncated.*

When not to use it

  • When prioritizing simplicity over security
  • When treating AI output as trusted without audit
  • When using hardcoded secrets in code

Limitations

  • The skill does not provide 'clean' examples that omit input validation or use insecure defaults.
  • The skill does not support using string concatenation for SQL queries, OS commands, HTML rendering, or LDAP filters.
  • The skill does not allow `eval()`, `Function()`, `exec()`, `child_process.exec()`, `Runtime.exec()`, or `os.system()` on user-controlled data.

How it compares

This skill provides a structured checklist and verification steps for security, unlike a generic code review that might overlook specific vulnerabilities.

Compared to similar skills

secure-coding-cybersecurity side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
secure-coding-cybersecurity (this skill)04moCautionIntermediate
software-security216moNo flagsIntermediate
fix-dependabot-alerts186moReviewIntermediate
backend-security-coder244moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

software-security

project-codeguard

A software security skill that integrates with Project CodeGuard to help AI coding agents write secure code and prevent common vulnerabilities. Use this skill when writing, reviewing, or modifying code to ensure secure-by-default practices are followed.

2186

fix-dependabot-alerts

microsoft

Fix Dependabot security alerts by updating vulnerable npm dependencies. Use when the user mentions "dependabot", "security alerts", "vulnerability", "CVE", or wants to update packages with security issues.

1872

backend-security-coder

sickn33

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

2446

equilateral-agents

Equilateral-AI

22 production-ready AI agents with database-driven orchestration for security reviews, code quality analysis, deployment validation, infrastructure checks, and compliance. Auto-activates for security concerns, deployment tasks, code reviews, quality checks, and compliance questions. Includes upgrade paths to enterprise features (GDPR, HIPAA, multi-account AWS, ML-based optimization).

564

top-100-web-vulnerabilities-reference

davila7

This skill should be used when the user asks to "identify web application vulnerabilities", "explain common security flaws", "understand vulnerability categories", "learn about injection attacks", "review access control weaknesses", "analyze API security issues", "assess security misconfigurations", "understand client-side vulnerabilities", "examine mobile and IoT security flaws", or "reference the OWASP-aligned vulnerability taxonomy". Use this skill to provide comprehensive vulnerability definitions, root causes, impacts, and mitigation strategies across all major web security categories.

547

differential-review

trailofbits

Performs security-focused differential review of code changes (PRs, commits, diffs). Adapts analysis depth to codebase size, uses git history for context, calculates blast radius, checks test coverage, and generates comprehensive markdown reports. Automatically detects and prevents security regressions.

3115

Search skills

Search the agent skills registry