Security Best Smart
All-in-one skill covering perform, language, framework, specific. Includes structured workflows, validation checks, and reusable patterns for security.
Security Best Smart
Apply security best practices to codebases by identifying the language and framework in use, then applying language-specific secure coding guidelines. This skill covers input validation, output encoding, authentication patterns, secrets management, dependency auditing, and security header configuration across major web frameworks.
When to Use This Skill
Choose Security Best Smart when you need to:
- Review code for security vulnerabilities aligned with OWASP Top 10
- Apply framework-specific security configurations (Django, Express, Rails, Spring)
- Implement secure coding patterns for authentication, authorization, and data handling
- Audit dependencies for known vulnerabilities and manage secrets securely
Consider alternatives when:
- You need active penetration testing (use ethical hacking / pentest skills)
- You need API-specific security design (use API Security Best Practices)
- You need infrastructure-level security (use cloud security or network security skills)
Quick Start
import ast import re from pathlib import Path from typing import List, Dict class SecurityAuditor: """Scan Python code for common security anti-patterns.""" PATTERNS = { 'sql_injection': { 'pattern': r'(execute|cursor\.execute)\s*\(\s*["\'].*%s.*["\']', 'severity': 'CRITICAL', 'fix': 'Use parameterized queries: cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))', }, 'hardcoded_secret': { 'pattern': r'(password|secret|api_key|token)\s*=\s*["\'][^"\']{8,}["\']', 'severity': 'HIGH', 'fix': 'Use environment variables: os.environ.get("API_KEY")', }, 'eval_usage': { 'pattern': r'\beval\s*\(.*\)', 'severity': 'CRITICAL', 'fix': 'Use ast.literal_eval() for data parsing, avoid eval() entirely', }, 'debug_enabled': { 'pattern': r'DEBUG\s*=\s*True', 'severity': 'HIGH', 'fix': 'Set DEBUG = False in production; use environment variable', }, 'insecure_deserialization': { 'pattern': r'pickle\.loads?\s*\(', 'severity': 'CRITICAL', 'fix': 'Use JSON for untrusted data; pickle is not safe for untrusted input', }, 'weak_hash': { 'pattern': r'hashlib\.(md5|sha1)\s*\(', 'severity': 'MEDIUM', 'fix': 'Use hashlib.sha256() or bcrypt for passwords', }, } def scan_file(self, filepath: str) -> List[Dict]: """Scan a Python file for security issues.""" findings = [] content = Path(filepath).read_text() for name, check in self.PATTERNS.items(): for match in re.finditer(check['pattern'], content, re.IGNORECASE): line_num = content[:match.start()].count('\n') + 1 findings.append({ 'file': filepath, 'line': line_num, 'issue': name, 'severity': check['severity'], 'match': match.group()[:80], 'fix': check['fix'], }) return findings def scan_directory(self, directory: str, pattern="**/*.py") -> List[Dict]: """Scan all matching files in a directory.""" all_findings = [] for path in Path(directory).glob(pattern): findings = self.scan_file(str(path)) all_findings.extend(findings) # Summary by_severity = {} for f in all_findings: by_severity.setdefault(f['severity'], []).append(f) print(f"Scanned: {directory}") print(f"Total findings: {len(all_findings)}") for sev in ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']: count = len(by_severity.get(sev, [])) if count: print(f" {sev}: {count}") return all_findings # auditor = SecurityAuditor() # findings = auditor.scan_directory("./src")
Core Concepts
OWASP Top 10 Quick Reference
| # | Vulnerability | Code-Level Prevention |
|---|---|---|
| A01 | Broken Access Control | Check authorization on every endpoint; deny by default |
| A02 | Cryptographic Failures | Use TLS, strong algorithms (AES-256, SHA-256+), don't roll your own crypto |
| A03 | Injection | Parameterized queries, input validation, output encoding |
| A04 | Insecure Design | Threat modeling, secure design patterns, principle of least privilege |
| A05 | Security Misconfiguration | Disable debug mode, remove defaults, harden headers |
| A06 | Vulnerable Components | Dependency scanning, automated updates, SBOM |
| A07 | Auth Failures | MFA, rate limiting, secure session management |
| A08 | Data Integrity Failures | Verify signatures, validate CI/CD pipelines |
| A09 | Logging Failures | Log security events, protect log integrity |
| A10 | SSRF | URL allowlists, disable redirects, validate schemes |
Configuration
| Parameter | Description | Default |
|---|---|---|
scan_patterns | File patterns to scan | ["**/*.py", "**/*.js", "**/*.ts"] |
severity_threshold | Minimum severity to report | "MEDIUM" |
ignore_paths | Directories to skip | ["node_modules", ".venv", "test"] |
custom_rules | Additional regex patterns to check | [] |
framework | Target framework for specific checks | Auto-detected |
check_dependencies | Scan for vulnerable dependencies | true |
output_format | Report format (json, sarif, text) | "text" |
fix_suggestions | Include remediation guidance | true |
Best Practices
-
Apply defense in depth — never rely on a single security control — Combine input validation, parameterized queries, output encoding, and CSP headers. If one layer fails, others still protect the application. A SQL injection vulnerability is less impactful if the database user has minimal permissions.
-
Use framework-provided security features instead of custom implementations — Django's CSRF protection, Express's helmet middleware, Rails' strong parameters, and Spring Security's authentication all exist because security is hard to implement correctly. Custom security code is more likely to have bugs.
-
Keep dependencies updated and scan for vulnerabilities regularly — Run
npm audit,pip-audit,safety check, orsnyk testin CI/CD pipelines. Known vulnerabilities in dependencies are the easiest attack vector. Set up automated pull requests for security updates. -
Store secrets in environment variables or secret managers, never in code — Use
.envfiles for local development (never committed to git), environment variables in production, and secret managers (AWS Secrets Manager, HashiCorp Vault) for sensitive credentials. Scan git history for accidentally committed secrets. -
Log security-relevant events without logging sensitive data — Log authentication attempts, authorization failures, input validation rejections, and admin actions. Never log passwords, tokens, credit card numbers, or PII. Ensure logs can't be tampered with and are retained for incident investigation.
Common Issues
Security scanner produces too many false positives — Tune the scanner's rules to match your codebase. Suppress false positives with inline comments (# nosec for bandit, // eslint-disable-next-line) rather than disabling rules globally. Review suppressions periodically to ensure they're still valid.
Team doesn't follow secure coding practices consistently — Integrate security checks into the CI/CD pipeline so insecure code can't be merged. Use pre-commit hooks for fast feedback and gate deployments on security scan results. Automated enforcement is more reliable than training alone.
Legacy code has too many vulnerabilities to fix at once — Prioritize by severity and exploitability. Fix critical injection vulnerabilities first, then address authentication and authorization issues. Create a security debt backlog and allocate a percentage of each sprint to security remediation.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.