mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
757 lines
33 KiB
HTML
757 lines
33 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>security-input-validation</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/security-input-validation.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/security-input-validation">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/security-input-validation.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>security-input-validation</h1><p class="lede">Input validation and sanitization patterns to prevent SQL injection, XSS, command injection, and other input-based attacks</p><h1>Security: Input Validation</h1>
|
|
<p><strong>Scope</strong>: Input validation, sanitization, SQL injection prevention, XSS protection, command injection <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Processing user input in web applications or APIs</li><li>Preventing SQL injection, XSS, or command injection attacks</li><li>Validating and sanitizing form data</li><li>Building input validation schemas</li><li>Implementing file upload security</li><li>Preventing path traversal attacks</li><li>Designing secure data processing pipelines</li></ul>
|
|
<h2>Input Validation Fundamentals</h2>
|
|
<h3>Defense in Depth</h3>
|
|
<pre><code class="lang-python">"""
|
|
Multi-layer validation strategy:
|
|
1. Client-side: UX feedback (not security)
|
|
2. Schema validation: Type and format checking
|
|
3. Business logic: Domain-specific rules
|
|
4. Sanitization: Clean dangerous content
|
|
5. Encoding: Context-specific output encoding
|
|
"""
|
|
|
|
from pydantic import BaseModel, validator, Field
|
|
|
|
class UserInput(BaseModel):
|
|
"""Layer 1: Schema validation"""
|
|
username: str = Field(min_length=3, max_length=32)
|
|
email: str
|
|
age: int = Field(ge=18, le=120)
|
|
|
|
@validator('username')
|
|
def validate_username(cls, v):
|
|
"""Layer 2: Business logic validation"""
|
|
if not v.isalnum():
|
|
raise ValueError('Username must be alphanumeric')
|
|
return v
|
|
|
|
@validator('email')
|
|
def validate_email(cls, v):
|
|
"""Layer 2: Email format validation"""
|
|
import re
|
|
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
if not re.match(pattern, v):
|
|
raise ValueError('Invalid email format')
|
|
return v
|
|
|
|
def process_user_input(data: dict):
|
|
"""Layer 3: Sanitization before use"""
|
|
validated = UserInput(**data)
|
|
|
|
# Layer 4: Context-specific encoding (when outputting)
|
|
safe_username = html.escape(validated.username)
|
|
|
|
return validated</code></pre>
|
|
<h2>SQL Injection Prevention</h2>
|
|
<h3>Vulnerable Code Examples</h3>
|
|
<pre><code class="lang-python">import sqlite3
|
|
|
|
# ❌ NEVER DO THIS - SQL Injection vulnerable
|
|
def get_user_vulnerable(username: str):
|
|
conn = sqlite3.connect('users.db')
|
|
cursor = conn.cursor()
|
|
|
|
# Attacker input: "admin' OR '1'='1"
|
|
query = f"SELECT * FROM users WHERE username = '{username}'"
|
|
cursor.execute(query)
|
|
|
|
return cursor.fetchone()
|
|
|
|
# Attack payload: username = "admin' OR '1'='1"
|
|
# Result: Returns all users (bypasses authentication)
|
|
|
|
# ❌ ALSO VULNERABLE - String concatenation
|
|
def delete_user_vulnerable(user_id: str):
|
|
query = "DELETE FROM users WHERE id = " + user_id
|
|
cursor.execute(query)
|
|
|
|
# Attack payload: user_id = "1 OR 1=1"
|
|
# Result: Deletes all users</code></pre>
|
|
<h3>Secure Code (Parameterized Queries)</h3>
|
|
<pre><code class="lang-python"># ✅ CORRECT - Parameterized queries (prepared statements)
|
|
def get_user_safe(username: str):
|
|
conn = sqlite3.connect('users.db')
|
|
cursor = conn.cursor()
|
|
|
|
# Database driver handles escaping
|
|
query = "SELECT * FROM users WHERE username = ?"
|
|
cursor.execute(query, (username,))
|
|
|
|
return cursor.fetchone()
|
|
|
|
# ✅ CORRECT - Named parameters
|
|
def get_user_by_email(email: str):
|
|
query = "SELECT * FROM users WHERE email = :email"
|
|
cursor.execute(query, {"email": email})
|
|
return cursor.fetchone()
|
|
|
|
# ✅ CORRECT - Multiple parameters
|
|
def create_user(username: str, email: str, age: int):
|
|
query = """
|
|
INSERT INTO users (username, email, age)
|
|
VALUES (?, ?, ?)
|
|
"""
|
|
cursor.execute(query, (username, email, age))
|
|
conn.commit()</code></pre>
|
|
<h3>ORM Usage (Automatically Safe)</h3>
|
|
<pre><code class="lang-python">from sqlalchemy import create_engine, Column, Integer, String
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
Base = declarative_base()
|
|
|
|
class User(Base):
|
|
__tablename__ = 'users'
|
|
id = Column(Integer, primary_key=True)
|
|
username = Column(String(50))
|
|
email = Column(String(100))
|
|
|
|
engine = create_engine('sqlite:///users.db')
|
|
Session = sessionmaker(bind=engine)
|
|
session = Session()
|
|
|
|
# ✅ ORM automatically uses parameterized queries
|
|
def get_user_by_username(username: str):
|
|
return session.query(User).filter(User.username == username).first()
|
|
|
|
# ✅ Safe even with complex queries
|
|
def search_users(search_term: str):
|
|
return session.query(User).filter(
|
|
User.username.like(f"%{search_term}%")
|
|
).all() # ORM handles escaping</code></pre>
|
|
<h3>Dynamic Queries (Be Careful)</h3>
|
|
<pre><code class="lang-python"># ⚠️ When you must build dynamic queries
|
|
def search_with_filters(filters: dict):
|
|
"""Safe dynamic query construction"""
|
|
query = "SELECT * FROM users WHERE 1=1"
|
|
params = []
|
|
|
|
# Whitelist allowed columns
|
|
ALLOWED_COLUMNS = {'username', 'email', 'age', 'created_at'}
|
|
|
|
for column, value in filters.items():
|
|
# Validate column name against whitelist
|
|
if column not in ALLOWED_COLUMNS:
|
|
raise ValueError(f"Invalid column: {column}")
|
|
|
|
# Use parameterized queries for values
|
|
query += f" AND {column} = ?" # Column name is whitelisted
|
|
params.append(value) # Value is parameterized
|
|
|
|
cursor.execute(query, tuple(params))
|
|
return cursor.fetchall()</code></pre>
|
|
<h2>Cross-Site Scripting (XSS) Prevention</h2>
|
|
<h3>Types of XSS</h3>
|
|
<pre><code class="lang-python"># Reflected XSS - Input immediately reflected in response
|
|
@app.get("/search")
|
|
def search(q: str):
|
|
# ❌ VULNERABLE
|
|
return f"<h1>Search results for: {q}</h1>"
|
|
|
|
# Attack: q = "<script>alert('XSS')</script>"
|
|
# Result: Script executes in user's browser
|
|
|
|
# Stored XSS - Malicious input stored in database
|
|
@app.post("/comments")
|
|
def create_comment(content: str):
|
|
# ❌ VULNERABLE - Stores unsanitized input
|
|
db.execute("INSERT INTO comments (content) VALUES (?)", (content,))
|
|
|
|
# Later, when displayed:
|
|
# return f"<p>{comment.content}</p>" # Script executes
|
|
|
|
# DOM-based XSS - Client-side JavaScript manipulation
|
|
# ❌ VULNERABLE JavaScript
|
|
document.getElementById('output').innerHTML = userInput;</code></pre>
|
|
<h3>XSS Prevention Strategies</h3>
|
|
<pre><code class="lang-python">import html
|
|
from markupsafe import escape
|
|
from bleach import clean
|
|
|
|
# Strategy 1: HTML Escaping (for text content)
|
|
def display_user_content_safe(content: str) -> str:
|
|
"""✅ Escape HTML entities"""
|
|
return html.escape(content)
|
|
|
|
# Input: "<script>alert('XSS')</script>"
|
|
# Output: "&lt;script&gt;alert('XSS')&lt;/script&gt;"
|
|
# Displayed as text, not executed
|
|
|
|
# Strategy 2: Allowlist-based Sanitization (for rich text)
|
|
def sanitize_html(content: str) -> str:
|
|
"""✅ Allow only safe HTML tags"""
|
|
allowed_tags = ['p', 'br', 'strong', 'em', 'u', 'a', 'ul', 'ol', 'li']
|
|
allowed_attrs = {'a': ['href', 'title']}
|
|
|
|
return clean(
|
|
content,
|
|
tags=allowed_tags,
|
|
attributes=allowed_attrs,
|
|
strip=True # Remove disallowed tags
|
|
)
|
|
|
|
# Strategy 3: Content Security Policy (CSP)
|
|
from flask import Flask, make_response
|
|
|
|
app = Flask(__name__)
|
|
|
|
@app.after_request
|
|
def add_security_headers(response):
|
|
"""✅ Add CSP header"""
|
|
response.headers['Content-Security-Policy'] = (
|
|
"default-src 'self'; "
|
|
"script-src 'self' 'unsafe-inline' https://cdn.example.com; "
|
|
"style-src 'self' 'unsafe-inline';"
|
|
)
|
|
return response
|
|
|
|
# Strategy 4: Template Auto-escaping
|
|
from jinja2 import Environment, select_autoescape
|
|
|
|
env = Environment(autoescape=select_autoescape(['html', 'xml']))
|
|
|
|
# ✅ Jinja2 automatically escapes variables
|
|
template = env.from_string("<p>{{ user_input }}</p>")
|
|
safe_html = template.render(user_input="<script>alert('XSS')</script>")
|
|
# Output: "<p>&lt;script&gt;alert('XSS')&lt;/script&gt;</p>"</code></pre>
|
|
<h3>Framework-Specific XSS Prevention</h3>
|
|
<pre><code class="lang-python"># FastAPI with Jinja2 (auto-escaping enabled)
|
|
from fastapi import FastAPI
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
app = FastAPI()
|
|
templates = Jinja2Templates(directory="templates", autoescape=True)
|
|
|
|
@app.get("/profile")
|
|
def profile(request: Request, user_id: int):
|
|
user = get_user(user_id)
|
|
|
|
# ✅ Template auto-escapes user.bio
|
|
return templates.TemplateResponse("profile.html", {
|
|
"request": request,
|
|
"user": user
|
|
})
|
|
|
|
# React (auto-escaping)
|
|
# ✅ React escapes by default
|
|
function UserProfile({ username }) {
|
|
return <div>{username}</div>; // Automatically escaped
|
|
}
|
|
|
|
# ❌ Dangerous - dangerouslySetInnerHTML
|
|
function VulnerableComponent({ html }) {
|
|
return <div dangerouslySetInnerHTML={{ __html: html }} />; // XSS risk
|
|
}
|
|
|
|
# ✅ Use sanitization library
|
|
import DOMPurify from 'dompurify';
|
|
|
|
function SafeComponent({ html }) {
|
|
const clean = DOMPurify.sanitize(html);
|
|
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
|
|
}</code></pre>
|
|
<h2>Command Injection Prevention</h2>
|
|
<h3>Vulnerable Code</h3>
|
|
<pre><code class="lang-python">import os
|
|
import subprocess
|
|
|
|
# ❌ NEVER DO THIS - Command injection vulnerable
|
|
def ping_host_vulnerable(hostname: str):
|
|
command = f"ping -c 4 {hostname}"
|
|
os.system(command)
|
|
|
|
# Attack: hostname = "google.com; rm -rf /"
|
|
# Result: Deletes files after ping
|
|
|
|
# ❌ ALSO VULNERABLE - shell=True
|
|
def backup_file_vulnerable(filename: str):
|
|
subprocess.call(f"tar -czf backup.tar.gz {filename}", shell=True)
|
|
|
|
# Attack: filename = "data.txt; cat /etc/passwd"
|
|
# Result: Leaks sensitive files</code></pre>
|
|
<h3>Safe Code</h3>
|
|
<pre><code class="lang-python">import subprocess
|
|
import shlex
|
|
from pathlib import Path
|
|
|
|
# ✅ CORRECT - Use list arguments (no shell)
|
|
def ping_host_safe(hostname: str):
|
|
"""Safe command execution"""
|
|
# Validate hostname format
|
|
if not is_valid_hostname(hostname):
|
|
raise ValueError("Invalid hostname")
|
|
|
|
# Use list of arguments (no shell interpretation)
|
|
result = subprocess.run(
|
|
["ping", "-c", "4", hostname],
|
|
shell=False, # Critical: Don't use shell
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=5
|
|
)
|
|
|
|
return result.stdout
|
|
|
|
def is_valid_hostname(hostname: str) -> bool:
|
|
"""Validate hostname format"""
|
|
import re
|
|
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$'
|
|
return re.match(pattern, hostname) is not None
|
|
|
|
# ✅ CORRECT - Avoid shell entirely
|
|
def compress_file_safe(filename: str):
|
|
"""Safe file compression"""
|
|
# Validate filename (no path traversal)
|
|
safe_filename = Path(filename).name
|
|
|
|
if not safe_filename or safe_filename.startswith('.'):
|
|
raise ValueError("Invalid filename")
|
|
|
|
# Use Python libraries instead of shell commands
|
|
import tarfile
|
|
|
|
with tarfile.open("backup.tar.gz", "w:gz") as tar:
|
|
tar.add(safe_filename)
|
|
|
|
# ✅ If shell is unavoidable, use shlex.quote()
|
|
def run_with_shell_safe(user_input: str):
|
|
"""Escape shell metacharacters"""
|
|
safe_input = shlex.quote(user_input)
|
|
command = f"echo {safe_input}"
|
|
|
|
subprocess.run(command, shell=True) # Now safe (but avoid if possible)</code></pre>
|
|
<h2>Path Traversal Prevention</h2>
|
|
<h3>Vulnerable Code</h3>
|
|
<pre><code class="lang-python">from flask import send_file
|
|
|
|
# ❌ VULNERABLE - Path traversal
|
|
@app.get("/download")
|
|
def download_file(filename: str):
|
|
return send_file(f"/uploads/{filename}")
|
|
|
|
# Attack: filename = "../../etc/passwd"
|
|
# Result: Leaks system files</code></pre>
|
|
<h3>Safe Code</h3>
|
|
<pre><code class="lang-python">from pathlib import Path
|
|
from flask import send_file, abort
|
|
|
|
UPLOAD_DIR = Path("/var/app/uploads").resolve()
|
|
|
|
@app.get("/download")
|
|
def download_file_safe(filename: str):
|
|
"""✅ Prevent path traversal"""
|
|
|
|
# Resolve full path
|
|
requested_path = (UPLOAD_DIR / filename).resolve()
|
|
|
|
# Check if path is within allowed directory
|
|
if not str(requested_path).startswith(str(UPLOAD_DIR)):
|
|
abort(403, "Forbidden")
|
|
|
|
# Check if file exists
|
|
if not requested_path.is_file():
|
|
abort(404, "File not found")
|
|
|
|
# Whitelist allowed extensions
|
|
ALLOWED_EXTENSIONS = {'.pdf', '.jpg', '.png', '.txt'}
|
|
if requested_path.suffix.lower() not in ALLOWED_EXTENSIONS:
|
|
abort(403, "File type not allowed")
|
|
|
|
return send_file(requested_path)</code></pre>
|
|
<h2>File Upload Security</h2>
|
|
<h3>Secure File Upload Implementation</h3>
|
|
<pre><code class="lang-python">from werkzeug.utils import secure_filename
|
|
import magic # python-magic library
|
|
from pathlib import Path
|
|
import uuid
|
|
|
|
UPLOAD_FOLDER = Path("/var/app/uploads")
|
|
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB
|
|
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif'}
|
|
ALLOWED_MIME_TYPES = {
|
|
'application/pdf',
|
|
'image/png',
|
|
'image/jpeg',
|
|
'image/gif'
|
|
}
|
|
|
|
def validate_file_upload(file) -> Path:
|
|
"""Comprehensive file upload validation"""
|
|
|
|
# Check file size
|
|
file.seek(0, 2) # Seek to end
|
|
size = file.tell()
|
|
file.seek(0) # Reset
|
|
|
|
if size > MAX_FILE_SIZE:
|
|
raise ValueError("File too large")
|
|
|
|
# Sanitize filename
|
|
original_filename = secure_filename(file.filename)
|
|
|
|
if not original_filename:
|
|
raise ValueError("Invalid filename")
|
|
|
|
# Validate extension
|
|
extension = Path(original_filename).suffix.lower()[1:]
|
|
if extension not in ALLOWED_EXTENSIONS:
|
|
raise ValueError(f"File type not allowed: {extension}")
|
|
|
|
# Verify MIME type (don't trust extension)
|
|
file_content = file.read(2048) # Read first 2KB
|
|
file.seek(0) # Reset
|
|
|
|
mime_type = magic.from_buffer(file_content, mime=True)
|
|
if mime_type not in ALLOWED_MIME_TYPES:
|
|
raise ValueError(f"Invalid file content: {mime_type}")
|
|
|
|
# Generate unique filename (prevent overwrites)
|
|
unique_filename = f"{uuid.uuid4()}.{extension}"
|
|
save_path = UPLOAD_FOLDER / unique_filename
|
|
|
|
# Save file
|
|
file.save(save_path)
|
|
|
|
# Set restrictive permissions
|
|
save_path.chmod(0o644)
|
|
|
|
return save_path
|
|
|
|
@app.post("/upload")
|
|
def upload_file():
|
|
"""✅ Secure file upload endpoint"""
|
|
if 'file' not in request.files:
|
|
return {"error": "No file provided"}, 400
|
|
|
|
file = request.files['file']
|
|
|
|
try:
|
|
save_path = validate_file_upload(file)
|
|
return {"filename": save_path.name}, 200
|
|
except ValueError as e:
|
|
return {"error": str(e)}, 400</code></pre>
|
|
<h2>Input Validation Patterns</h2>
|
|
<h3>Schema Validation (Pydantic)</h3>
|
|
<pre><code class="lang-python">from pydantic import BaseModel, Field, validator
|
|
from typing import Optional
|
|
import re
|
|
|
|
class CreateUserRequest(BaseModel):
|
|
username: str = Field(min_length=3, max_length=32)
|
|
email: str
|
|
password: str = Field(min_length=12)
|
|
age: Optional[int] = Field(None, ge=18, le=120)
|
|
website: Optional[str] = None
|
|
|
|
@validator('username')
|
|
def validate_username(cls, v):
|
|
"""Alphanumeric and underscore only"""
|
|
if not re.match(r'^[a-zA-Z0-9_]+$', v):
|
|
raise ValueError('Username must be alphanumeric')
|
|
return v
|
|
|
|
@validator('email')
|
|
def validate_email(cls, v):
|
|
"""Email format validation"""
|
|
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
if not re.match(pattern, v):
|
|
raise ValueError('Invalid email')
|
|
return v.lower()
|
|
|
|
@validator('password')
|
|
def validate_password(cls, v):
|
|
"""Password complexity"""
|
|
if not re.search(r'[A-Z]', v):
|
|
raise ValueError('Password must contain uppercase')
|
|
if not re.search(r'[a-z]', v):
|
|
raise ValueError('Password must contain lowercase')
|
|
if not re.search(r'\d', v):
|
|
raise ValueError('Password must contain digit')
|
|
if not re.search(r'[^A-Za-z0-9]', v):
|
|
raise ValueError('Password must contain special character')
|
|
return v
|
|
|
|
@validator('website')
|
|
def validate_website(cls, v):
|
|
"""URL validation"""
|
|
if v is None:
|
|
return v
|
|
|
|
url_pattern = r'^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$'
|
|
if not re.match(url_pattern, v):
|
|
raise ValueError('Invalid URL')
|
|
return v
|
|
|
|
# Usage
|
|
@app.post("/users")
|
|
def create_user(user: CreateUserRequest):
|
|
# Pydantic automatically validates
|
|
# If validation fails, returns 422 Unprocessable Entity
|
|
return create_user_in_db(user)</code></pre>
|
|
<h3>Whitelist Validation</h3>
|
|
<pre><code class="lang-python">from enum import Enum
|
|
|
|
class SortOrder(Enum):
|
|
ASC = "asc"
|
|
DESC = "desc"
|
|
|
|
class SortField(Enum):
|
|
NAME = "name"
|
|
EMAIL = "email"
|
|
CREATED_AT = "created_at"
|
|
|
|
@app.get("/users")
|
|
def list_users(
|
|
sort_by: SortField = SortField.CREATED_AT,
|
|
order: SortOrder = SortOrder.DESC,
|
|
limit: int = Field(10, ge=1, le=100)
|
|
):
|
|
"""✅ Enum validation prevents SQL injection"""
|
|
|
|
# Enums ensure only valid values
|
|
query = f"""
|
|
SELECT * FROM users
|
|
ORDER BY {sort_by.value} {order.value}
|
|
LIMIT {limit}
|
|
"""
|
|
|
|
# Safe because sort_by and order are validated enums
|
|
return db.execute(query)</code></pre>
|
|
<h2>Security Best Practices</h2>
|
|
<h3>Input Validation Checklist</h3>
|
|
<p><strong>General</strong>:</p>
|
|
<ul><li>[ ] Validate all inputs (including headers, cookies, query params)</li><li>[ ] Use allowlists over blocklists</li><li>[ ] Validate on server-side (never trust client)</li><li>[ ] Fail securely (reject invalid input)</li><li>[ ] Log validation failures</li></ul>
|
|
<p><strong>SQL Injection Prevention</strong>:</p>
|
|
<ul><li>[ ] Always use parameterized queries</li><li>[ ] Use ORM when possible</li><li>[ ] Validate column/table names with whitelist</li><li>[ ] Escape dynamic SQL (last resort)</li><li>[ ] Use least-privilege database accounts</li></ul>
|
|
<p><strong>XSS Prevention</strong>:</p>
|
|
<ul><li>[ ] Enable template auto-escaping</li><li>[ ] Use Content Security Policy (CSP)</li><li>[ ] Sanitize rich text with allowlist</li><li>[ ] Set X-XSS-Protection header</li><li>[ ] Use httpOnly and secure cookies</li></ul>
|
|
<p><strong>Command Injection Prevention</strong>:</p>
|
|
<ul><li>[ ] Avoid shell execution (use libraries)</li><li>[ ] Never use shell=True with user input</li><li>[ ] Use subprocess with list arguments</li><li>[ ] Validate all arguments</li><li>[ ] Use shlex.quote() as last resort</li></ul>
|
|
<p><strong>File Upload Security</strong>:</p>
|
|
<ul><li>[ ] Validate file size</li><li>[ ] Verify MIME type (not just extension)</li><li>[ ] Use secure_filename()</li><li>[ ] Generate unique filenames</li><li>[ ] Store outside web root</li><li>[ ] Set restrictive permissions</li></ul>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>security-authentication.md</code> - Validating authentication credentials</li><li><code>security-authorization.md</code> - Validating authorization inputs</li><li><code>security-headers.md</code> - CSP and other protective headers</li><li><code>api-error-handling.md</code> - Handling validation errors</li></ul>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/security-input-validation.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |