一键导入
security-review
Security vulnerability detection and secure coding practices
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Security vulnerability detection and secure coding practices
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
This skill should be used when the user wants to validate or run GitHub Actions or GitLab CI workflows locally, test CI before pushing, debug a failing action without burning CI minutes, check ".github/workflows" or ".gitlab-ci.yml" files, or use wrkflw (an `act` alternative). Also triggers before pushing changes that touch workflow files. Provides subcommand selection (validate/run/watch/tui/trigger/list), runtime-mode guidance (docker/podman/emulation), copy-paste recipes, and the tool's known limitations so expectations are set correctly.
Analytical framework for writing style analysis and voice profile construction. Use when analyzing writing samples, building voice profiles, comparing styles, synthesizing metavoice descriptions, or understanding stylistic dimensions. Triggers on "analyze style", "style profile", "voice analysis", "writing fingerprint", "metavoice", "style comparison", "what makes my writing distinctive".
This skill should be used when the user asks to "generate an image", "create a picture", "make an illustration", "edit this image", "upscale", or any request involving AI image generation, nanobanana, nano banana, visual grounding, prompt engineering, or image editing. Provides model selection guidance (Flash/NB2/Pro), prompt engineering techniques, visual grounding best practices, resolution and cost optimization, and multi-image editing workflows for the Nano Banana MCP server (Gemini image models).
This skill should be used when the user asks to "update documentation", "generate README", "audit docs", "add CHANGELOG", "fix outdated docs", "create CONTRIBUTING.md", "add API documentation", "check documentation coverage", or mentions documentation gaps, stale docs, or missing project documentation. Detects project type from manifest files, scores existing documentation quality, generates or updates README, CHANGELOG, CONTRIBUTING, and code documentation for any repository type.
This skill should be used when the user asks about "Android project setup", "new Android app", "MVVM", "Clean Architecture", "Android architecture", "Hilt", "dependency injection", "Room database", "Retrofit", "data layer", "repository pattern", "Android project structure", "Kotlin Android", "Jetpack libraries", or mentions starting a new Android project, choosing an architecture pattern, or setting up dependency injection. Provides opinionated architecture guidance for Kotlin/Compose Android apps.
This skill should be used when the user asks about "Android permissions", "runtime permissions", "camera permission", "storage permission", "notifications", "Photo Picker", "Credential Manager", "Predictive Back", "per-app language", "Baseline Profiles", "Android 16", "adaptive layouts", "Android crash", "Gradle sync fails", "build error", "ANR", "ProGuard", "R8", "Android emulator", or mentions requesting permissions, using platform APIs, troubleshooting Android errors, or dealing with crashes and build failures. Provides permissions guidance, modern platform features, and troubleshooting for Android development.
| name | security-review |
| description | Security vulnerability detection and secure coding practices |
| version | 1.0.0 |
| tags | ["security","vulnerabilities","owasp","secure-coding"] |
This skill provides expert knowledge on identifying security vulnerabilities and implementing secure coding practices.
SQL Injection
# Vulnerable
query = f"SELECT * FROM users WHERE email = '{user_input}'"
# Secure: Use parameterized queries
query = "SELECT * FROM users WHERE email = ?"
cursor.execute(query, (user_input,))
Command Injection
# Vulnerable
os.system(f"ping {user_input}")
# Secure: Validate input and use safe APIs
import subprocess
subprocess.run(["ping", "-c", "1", validated_host], check=True)
NoSQL Injection
// Vulnerable
db.users.find({ email: req.body.email })
// Secure: Validate input type
const email = String(req.body.email);
db.users.find({ email: email })
Password Storage
# Vulnerable: Plain text or MD5
password = "user_password"
# Secure: Use bcrypt, Argon2, or PBKDF2
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
Session Management
# Secure session configuration
SESSION_COOKIE_SECURE = True # HTTPS only
SESSION_COOKIE_HTTPONLY = True # No JavaScript access
SESSION_COOKIE_SAMESITE = 'Strict'
SESSION_TIMEOUT = 30 * 60 # 30 minutes
Encryption in Transit
# Always use HTTPS/TLS
# Enforce HSTS headers
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
Encryption at Rest
from cryptography.fernet import Fernet
# Encrypt sensitive data
cipher = Fernet(encryption_key)
encrypted_data = cipher.encrypt(sensitive_data.encode())
# Never log sensitive information
logger.info(f"User logged in") # Don't log passwords, tokens, etc.
# Vulnerable
import xml.etree.ElementTree as ET
tree = ET.parse(user_file)
# Secure: Disable external entity processing
from defusedxml import ElementTree as ET
tree = ET.parse(user_file)
# Vulnerable: Insecure Direct Object Reference (IDOR)
@app.route('/users/<user_id>')
def get_user(user_id):
return User.get(user_id) # Any user can access any user_id
# Secure: Check authorization
@app.route('/users/<user_id>')
@login_required
def get_user(user_id):
if current_user.id != user_id and not current_user.is_admin:
abort(403)
return User.get(user_id)
Checklist:
# Development
DEBUG = True
SHOW_ERRORS = True
# Production
DEBUG = False
SHOW_ERRORS = False
ALLOWED_HOSTS = ['yourdomain.com']
Stored XSS
# Vulnerable: Direct HTML output
return f"<div>Welcome, {username}</div>"
# Secure: Escape HTML
from html import escape
return f"<div>Welcome, {escape(username)}</div>"
DOM-based XSS
// Vulnerable
element.innerHTML = userInput;
// Secure
element.textContent = userInput;
Content Security Policy (CSP)
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'"
)
# Vulnerable: pickle can execute arbitrary code
import pickle
data = pickle.loads(untrusted_data)
# Secure: Use JSON for untrusted data
import json
data = json.loads(untrusted_data)
Best Practices:
# Regularly update dependencies
pip list --outdated
npm audit
# Use dependency scanning tools
pip-audit
npm audit fix
# Pin versions in production
pip freeze > requirements.txt
npm ci # Instead of npm install
import logging
# Log security events
logger.warning(f"Failed login attempt for user: {email} from IP: {ip_address}")
logger.critical(f"Potential SQL injection detected: {suspicious_input}")
# What to log:
# - Authentication attempts (success/failure)
# - Authorization failures
# - Input validation failures
# - Application errors
# - Administrative actions
# What NOT to log:
# - Passwords, tokens, session IDs
# - Credit card numbers, PII
# - Encryption keys
# Vulnerable: Denylist (easily bypassed)
if '<script>' not in user_input:
process(user_input)
# Secure: Allowlist
import re
if re.match(r'^[a-zA-Z0-9_-]+$', user_input):
process(user_input)
else:
raise ValueError("Invalid input")
from pydantic import BaseModel, EmailStr, constr
class UserInput(BaseModel):
email: EmailStr
age: int = Field(ge=0, le=150)
username: constr(min_length=3, max_length=20, regex=r'^[a-zA-Z0-9_]+$')
# Implement CSRF tokens
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
# For AJAX requests
@app.route('/api/data', methods=['POST'])
@csrf.exempt # Only if using custom token validation
def api_data():
# Validate custom CSRF token from headers
if request.headers.get('X-CSRF-Token') != session['csrf_token']:
abort(403)
from flask_limiter import Limiter
limiter = Limiter(app, key_func=lambda: request.remote_addr)
@app.route('/api/login', methods=['POST'])
@limiter.limit("5 per minute")
def login():
pass
# Use Bearer tokens (JWT)
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
# Implement token expiration
import jwt
from datetime import datetime, timedelta
token = jwt.encode({
'user_id': user.id,
'exp': datetime.utcnow() + timedelta(hours=1)
}, secret_key, algorithm='HS256')
import os
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
# Validate file extension
if not allowed_file(file.filename):
abort(400)
# Use secure filename
filename = secure_filename(file.filename)
# Validate file size
if len(file.read()) > 5 * 1024 * 1024: # 5MB
abort(413)
# Store outside web root
file.save(os.path.join('/var/uploads', filename))
# Essential security headers
@app.after_request
def set_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
response.headers['Content-Security-Policy'] = "default-src 'self'"
return response
# Vulnerable: Hardcoded secrets
API_KEY = "sk_live_123456789"
# Secure: Environment variables
import os
API_KEY = os.environ.get('API_KEY')
# Better: Secret management service
# AWS Secrets Manager, HashiCorp Vault, Azure Key Vault
When this skill is active: