Files
skills/public/security-input-validation.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
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]>
2026-09-11 00:27:59 -07:00

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">&quot;&quot;&quot;
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
&quot;&quot;&quot;
from pydantic import BaseModel, validator, Field
class UserInput(BaseModel):
&quot;&quot;&quot;Layer 1: Schema validation&quot;&quot;&quot;
username: str = Field(min_length=3, max_length=32)
email: str
age: int = Field(ge=18, le=120)
@validator(&#x27;username&#x27;)
def validate_username(cls, v):
&quot;&quot;&quot;Layer 2: Business logic validation&quot;&quot;&quot;
if not v.isalnum():
raise ValueError(&#x27;Username must be alphanumeric&#x27;)
return v
@validator(&#x27;email&#x27;)
def validate_email(cls, v):
&quot;&quot;&quot;Layer 2: Email format validation&quot;&quot;&quot;
import re
pattern = r&#x27;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$&#x27;
if not re.match(pattern, v):
raise ValueError(&#x27;Invalid email format&#x27;)
return v
def process_user_input(data: dict):
&quot;&quot;&quot;Layer 3: Sanitization before use&quot;&quot;&quot;
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(&#x27;users.db&#x27;)
cursor = conn.cursor()
# Attacker input: &quot;admin&#x27; OR &#x27;1&#x27;=&#x27;1&quot;
query = f&quot;SELECT * FROM users WHERE username = &#x27;{username}&#x27;&quot;
cursor.execute(query)
return cursor.fetchone()
# Attack payload: username = &quot;admin&#x27; OR &#x27;1&#x27;=&#x27;1&quot;
# Result: Returns all users (bypasses authentication)
# ❌ ALSO VULNERABLE - String concatenation
def delete_user_vulnerable(user_id: str):
query = &quot;DELETE FROM users WHERE id = &quot; + user_id
cursor.execute(query)
# Attack payload: user_id = &quot;1 OR 1=1&quot;
# 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(&#x27;users.db&#x27;)
cursor = conn.cursor()
# Database driver handles escaping
query = &quot;SELECT * FROM users WHERE username = ?&quot;
cursor.execute(query, (username,))
return cursor.fetchone()
# ✅ CORRECT - Named parameters
def get_user_by_email(email: str):
query = &quot;SELECT * FROM users WHERE email = :email&quot;
cursor.execute(query, {&quot;email&quot;: email})
return cursor.fetchone()
# ✅ CORRECT - Multiple parameters
def create_user(username: str, email: str, age: int):
query = &quot;&quot;&quot;
INSERT INTO users (username, email, age)
VALUES (?, ?, ?)
&quot;&quot;&quot;
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__ = &#x27;users&#x27;
id = Column(Integer, primary_key=True)
username = Column(String(50))
email = Column(String(100))
engine = create_engine(&#x27;sqlite:///users.db&#x27;)
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&quot;%{search_term}%&quot;)
).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):
&quot;&quot;&quot;Safe dynamic query construction&quot;&quot;&quot;
query = &quot;SELECT * FROM users WHERE 1=1&quot;
params = []
# Whitelist allowed columns
ALLOWED_COLUMNS = {&#x27;username&#x27;, &#x27;email&#x27;, &#x27;age&#x27;, &#x27;created_at&#x27;}
for column, value in filters.items():
# Validate column name against whitelist
if column not in ALLOWED_COLUMNS:
raise ValueError(f&quot;Invalid column: {column}&quot;)
# Use parameterized queries for values
query += f&quot; AND {column} = ?&quot; # 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(&quot;/search&quot;)
def search(q: str):
# ❌ VULNERABLE
return f&quot;&lt;h1&gt;Search results for: {q}&lt;/h1&gt;&quot;
# Attack: q = &quot;&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;&quot;
# Result: Script executes in user&#x27;s browser
# Stored XSS - Malicious input stored in database
@app.post(&quot;/comments&quot;)
def create_comment(content: str):
# ❌ VULNERABLE - Stores unsanitized input
db.execute(&quot;INSERT INTO comments (content) VALUES (?)&quot;, (content,))
# Later, when displayed:
# return f&quot;&lt;p&gt;{comment.content}&lt;/p&gt;&quot; # Script executes
# DOM-based XSS - Client-side JavaScript manipulation
# ❌ VULNERABLE JavaScript
document.getElementById(&#x27;output&#x27;).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) -&gt; str:
&quot;&quot;&quot;✅ Escape HTML entities&quot;&quot;&quot;
return html.escape(content)
# Input: &quot;&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;&quot;
# Output: &quot;&amp;lt;script&amp;gt;alert(&#x27;XSS&#x27;)&amp;lt;/script&amp;gt;&quot;
# Displayed as text, not executed
# Strategy 2: Allowlist-based Sanitization (for rich text)
def sanitize_html(content: str) -&gt; str:
&quot;&quot;&quot;✅ Allow only safe HTML tags&quot;&quot;&quot;
allowed_tags = [&#x27;p&#x27;, &#x27;br&#x27;, &#x27;strong&#x27;, &#x27;em&#x27;, &#x27;u&#x27;, &#x27;a&#x27;, &#x27;ul&#x27;, &#x27;ol&#x27;, &#x27;li&#x27;]
allowed_attrs = {&#x27;a&#x27;: [&#x27;href&#x27;, &#x27;title&#x27;]}
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):
&quot;&quot;&quot;✅ Add CSP header&quot;&quot;&quot;
response.headers[&#x27;Content-Security-Policy&#x27;] = (
&quot;default-src &#x27;self&#x27;; &quot;
&quot;script-src &#x27;self&#x27; &#x27;unsafe-inline&#x27; https://cdn.example.com; &quot;
&quot;style-src &#x27;self&#x27; &#x27;unsafe-inline&#x27;;&quot;
)
return response
# Strategy 4: Template Auto-escaping
from jinja2 import Environment, select_autoescape
env = Environment(autoescape=select_autoescape([&#x27;html&#x27;, &#x27;xml&#x27;]))
# ✅ Jinja2 automatically escapes variables
template = env.from_string(&quot;&lt;p&gt;{{ user_input }}&lt;/p&gt;&quot;)
safe_html = template.render(user_input=&quot;&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;&quot;)
# Output: &quot;&lt;p&gt;&amp;lt;script&amp;gt;alert(&#x27;XSS&#x27;)&amp;lt;/script&amp;gt;&lt;/p&gt;&quot;</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=&quot;templates&quot;, autoescape=True)
@app.get(&quot;/profile&quot;)
def profile(request: Request, user_id: int):
user = get_user(user_id)
# ✅ Template auto-escapes user.bio
return templates.TemplateResponse(&quot;profile.html&quot;, {
&quot;request&quot;: request,
&quot;user&quot;: user
})
# React (auto-escaping)
# ✅ React escapes by default
function UserProfile({ username }) {
return &lt;div&gt;{username}&lt;/div&gt;; // Automatically escaped
}
# ❌ Dangerous - dangerouslySetInnerHTML
function VulnerableComponent({ html }) {
return &lt;div dangerouslySetInnerHTML={{ __html: html }} /&gt;; // XSS risk
}
# ✅ Use sanitization library
import DOMPurify from &#x27;dompurify&#x27;;
function SafeComponent({ html }) {
const clean = DOMPurify.sanitize(html);
return &lt;div dangerouslySetInnerHTML={{ __html: clean }} /&gt;;
}</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&quot;ping -c 4 {hostname}&quot;
os.system(command)
# Attack: hostname = &quot;google.com; rm -rf /&quot;
# Result: Deletes files after ping
# ❌ ALSO VULNERABLE - shell=True
def backup_file_vulnerable(filename: str):
subprocess.call(f&quot;tar -czf backup.tar.gz {filename}&quot;, shell=True)
# Attack: filename = &quot;data.txt; cat /etc/passwd&quot;
# 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):
&quot;&quot;&quot;Safe command execution&quot;&quot;&quot;
# Validate hostname format
if not is_valid_hostname(hostname):
raise ValueError(&quot;Invalid hostname&quot;)
# Use list of arguments (no shell interpretation)
result = subprocess.run(
[&quot;ping&quot;, &quot;-c&quot;, &quot;4&quot;, hostname],
shell=False, # Critical: Don&#x27;t use shell
capture_output=True,
text=True,
timeout=5
)
return result.stdout
def is_valid_hostname(hostname: str) -&gt; bool:
&quot;&quot;&quot;Validate hostname format&quot;&quot;&quot;
import re
pattern = r&#x27;^[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])?)*$&#x27;
return re.match(pattern, hostname) is not None
# ✅ CORRECT - Avoid shell entirely
def compress_file_safe(filename: str):
&quot;&quot;&quot;Safe file compression&quot;&quot;&quot;
# Validate filename (no path traversal)
safe_filename = Path(filename).name
if not safe_filename or safe_filename.startswith(&#x27;.&#x27;):
raise ValueError(&quot;Invalid filename&quot;)
# Use Python libraries instead of shell commands
import tarfile
with tarfile.open(&quot;backup.tar.gz&quot;, &quot;w:gz&quot;) as tar:
tar.add(safe_filename)
# ✅ If shell is unavoidable, use shlex.quote()
def run_with_shell_safe(user_input: str):
&quot;&quot;&quot;Escape shell metacharacters&quot;&quot;&quot;
safe_input = shlex.quote(user_input)
command = f&quot;echo {safe_input}&quot;
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(&quot;/download&quot;)
def download_file(filename: str):
return send_file(f&quot;/uploads/{filename}&quot;)
# Attack: filename = &quot;../../etc/passwd&quot;
# 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(&quot;/var/app/uploads&quot;).resolve()
@app.get(&quot;/download&quot;)
def download_file_safe(filename: str):
&quot;&quot;&quot;✅ Prevent path traversal&quot;&quot;&quot;
# 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, &quot;Forbidden&quot;)
# Check if file exists
if not requested_path.is_file():
abort(404, &quot;File not found&quot;)
# Whitelist allowed extensions
ALLOWED_EXTENSIONS = {&#x27;.pdf&#x27;, &#x27;.jpg&#x27;, &#x27;.png&#x27;, &#x27;.txt&#x27;}
if requested_path.suffix.lower() not in ALLOWED_EXTENSIONS:
abort(403, &quot;File type not allowed&quot;)
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(&quot;/var/app/uploads&quot;)
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB
ALLOWED_EXTENSIONS = {&#x27;pdf&#x27;, &#x27;png&#x27;, &#x27;jpg&#x27;, &#x27;jpeg&#x27;, &#x27;gif&#x27;}
ALLOWED_MIME_TYPES = {
&#x27;application/pdf&#x27;,
&#x27;image/png&#x27;,
&#x27;image/jpeg&#x27;,
&#x27;image/gif&#x27;
}
def validate_file_upload(file) -&gt; Path:
&quot;&quot;&quot;Comprehensive file upload validation&quot;&quot;&quot;
# Check file size
file.seek(0, 2) # Seek to end
size = file.tell()
file.seek(0) # Reset
if size &gt; MAX_FILE_SIZE:
raise ValueError(&quot;File too large&quot;)
# Sanitize filename
original_filename = secure_filename(file.filename)
if not original_filename:
raise ValueError(&quot;Invalid filename&quot;)
# Validate extension
extension = Path(original_filename).suffix.lower()[1:]
if extension not in ALLOWED_EXTENSIONS:
raise ValueError(f&quot;File type not allowed: {extension}&quot;)
# Verify MIME type (don&#x27;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&quot;Invalid file content: {mime_type}&quot;)
# Generate unique filename (prevent overwrites)
unique_filename = f&quot;{uuid.uuid4()}.{extension}&quot;
save_path = UPLOAD_FOLDER / unique_filename
# Save file
file.save(save_path)
# Set restrictive permissions
save_path.chmod(0o644)
return save_path
@app.post(&quot;/upload&quot;)
def upload_file():
&quot;&quot;&quot;✅ Secure file upload endpoint&quot;&quot;&quot;
if &#x27;file&#x27; not in request.files:
return {&quot;error&quot;: &quot;No file provided&quot;}, 400
file = request.files[&#x27;file&#x27;]
try:
save_path = validate_file_upload(file)
return {&quot;filename&quot;: save_path.name}, 200
except ValueError as e:
return {&quot;error&quot;: 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(&#x27;username&#x27;)
def validate_username(cls, v):
&quot;&quot;&quot;Alphanumeric and underscore only&quot;&quot;&quot;
if not re.match(r&#x27;^[a-zA-Z0-9_]+$&#x27;, v):
raise ValueError(&#x27;Username must be alphanumeric&#x27;)
return v
@validator(&#x27;email&#x27;)
def validate_email(cls, v):
&quot;&quot;&quot;Email format validation&quot;&quot;&quot;
pattern = r&#x27;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$&#x27;
if not re.match(pattern, v):
raise ValueError(&#x27;Invalid email&#x27;)
return v.lower()
@validator(&#x27;password&#x27;)
def validate_password(cls, v):
&quot;&quot;&quot;Password complexity&quot;&quot;&quot;
if not re.search(r&#x27;[A-Z]&#x27;, v):
raise ValueError(&#x27;Password must contain uppercase&#x27;)
if not re.search(r&#x27;[a-z]&#x27;, v):
raise ValueError(&#x27;Password must contain lowercase&#x27;)
if not re.search(r&#x27;\d&#x27;, v):
raise ValueError(&#x27;Password must contain digit&#x27;)
if not re.search(r&#x27;[^A-Za-z0-9]&#x27;, v):
raise ValueError(&#x27;Password must contain special character&#x27;)
return v
@validator(&#x27;website&#x27;)
def validate_website(cls, v):
&quot;&quot;&quot;URL validation&quot;&quot;&quot;
if v is None:
return v
url_pattern = r&#x27;^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$&#x27;
if not re.match(url_pattern, v):
raise ValueError(&#x27;Invalid URL&#x27;)
return v
# Usage
@app.post(&quot;/users&quot;)
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 = &quot;asc&quot;
DESC = &quot;desc&quot;
class SortField(Enum):
NAME = &quot;name&quot;
EMAIL = &quot;email&quot;
CREATED_AT = &quot;created_at&quot;
@app.get(&quot;/users&quot;)
def list_users(
sort_by: SortField = SortField.CREATED_AT,
order: SortOrder = SortOrder.DESC,
limit: int = Field(10, ge=1, le=100)
):
&quot;&quot;&quot;✅ Enum validation prevents SQL injection&quot;&quot;&quot;
# Enums ensure only valid values
query = f&quot;&quot;&quot;
SELECT * FROM users
ORDER BY {sort_by.value} {order.value}
LIMIT {limit}
&quot;&quot;&quot;
# 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>