Application Security
What I Do
I provide guidance on securing applications throughout the software development lifecycle. This includes identifying and mitigating common vulnerabilities (OWASP Top 10), implementing secure coding patterns, integrating security testing into CI/CD pipelines, and establishing defense-in-depth strategies that protect applications from injection attacks, broken authentication, data exposure, and other threats.
When to Use Me
- Designing a new application and need security architecture guidance
- Reviewing code for common vulnerability patterns
- Implementing input validation, output encoding, or authentication flows
- Integrating SAST/DAST/SCA tools into your build pipeline
- Remediating findings from a penetration test or vulnerability scan
- Building middleware for security headers, CSRF protection, or rate limiting
Core Concepts
- OWASP Top 10: The most critical web application security risks including injection, broken authentication, sensitive data exposure, XXE, broken access control, misconfigurations, XSS, insecure deserialization, vulnerable components, and insufficient logging.
- Input Validation: Verify all input on the server side using allowlists, type checks, length constraints, and range checks before processing.
- Output Encoding: Context-aware encoding (HTML, JavaScript, URL, CSS) to prevent injection when rendering user-controlled data.
- Defense in Depth: Layered security controls so that failure of one control does not compromise the entire system.
- Least Privilege: Grant only the minimum permissions required for a function, user, or process to operate.
- Secure Session Management: Use strong session IDs, enforce timeouts, regenerate tokens after authentication, and bind sessions to client attributes.
- Security Headers: HTTP response headers (CSP, HSTS, X-Content-Type-Options, X-Frame-Options) that instruct browsers to enable built-in protections.
- Dependency Management: Track and update third-party libraries to avoid inheriting known vulnerabilities (CVEs).
- Error Handling: Return generic error messages to users while logging detailed diagnostics server-side to avoid information leakage.
- Security Testing Integration: Embed SAST, DAST, and SCA scans in CI/CD to catch vulnerabilities before deployment.
Code Examples
1. Parameterized Queries to Prevent SQL Injection (Python)
import sqlite3
from typing import Optional, Dict, Any
def get_user_by_id(db_path: str, user_id: int) -> Optional[Dict[str, Any]]:
"""Fetch user with parameterized query to prevent SQL injection."""
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT id, username, email FROM users WHERE id = ?", (user_id,))
row = cursor.fetchone()
conn.close()
if row:
return dict(row)
return None
2. Content Security Policy Middleware (Node.js/Express)
const helmet = require('helmet');
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'nonce-{{nonce}}'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https://cdn.example.com"],
connectSrc: ["'self'", "https://api.example.com"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
upgradeInsecureRequests: [],
},
})
);
app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true, preload: true }));
app.use(helmet.noSniff());
app.use(helmet.frameguard({ action: 'deny' }));
3. CSRF Token Validation (Python/Flask)
import secrets
from functools import wraps
from flask import Flask, session, request, abort
def generate_csrf_token() -> str:
if "_csrf_token" not in session:
session["_csrf_token"] = secrets.token_hex(32)
return session["_csrf_token"]
def csrf_protect(f):
@wraps(f)
def decorated(*args, **kwargs):
if request.method in ("POST", "PUT", "DELETE", "PATCH"):
token = request.form.get("_csrf_token") or request.headers.get("X-CSRF-Token")
if not token or token != session.get("_csrf_token"):
abort(403, description="CSRF token missing or invalid")
return f(*args, **kwargs)
return decorated
4. Input Validation with Allowlists (Python)
import re
from typing import Optional
ALLOWED_USERNAME_PATTERN = re.compile(r"^[a-zA-Z0-9_]{3,30}$")
ALLOWED_SORT_FIELDS = {"created_at", "updated_at", "username", "email"}
def validate_username(username: str) -> Optional[str]:
if not ALLOWED_USERNAME_PATTERN.match(username):
return None
return username
def validate_sort_field(field: str) -> str:
if field not in ALLOWED_SORT_FIELDS:
return "created_at"
return field
5. Secure Password Hashing (Python)
import hashlib
import secrets
from typing import Tuple
def hash_password(password: str) -> Tuple[str, str]:
salt = secrets.token_hex(32)
pwd_hash = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt.encode("utf-8"), iterations=600_000
)
return pwd_hash.hex(), salt
def verify_password(password: str, stored_hash: str, salt: str) -> bool:
pwd_hash = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt.encode("utf-8"), iterations=600_000
)
return secrets.compare_digest(pwd_hash.hex(), stored_hash)
Best Practices
- Validate all input server-side using allowlists and strict type/length/range checks regardless of client-side validation.
- Use parameterized queries or ORMs for all database interactions to prevent SQL injection.
- Encode output contextually (HTML, JS, URL, CSS) when rendering user-controlled data.
- Set security headers (CSP, HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy) on every response.
- Hash passwords with strong algorithms (bcrypt, scrypt, Argon2, or PBKDF2 with high iteration counts) and unique salts.
- Implement CSRF protection for all state-changing operations using synchronizer tokens or SameSite cookies.
- Keep dependencies updated and run SCA scans to detect known vulnerabilities in third-party libraries.
- Log security events (authentication failures, access denials, input validation failures) with enough context for investigation but without sensitive data.
- Fail securely by denying access by default when errors occur rather than allowing access.
- Enforce HTTPS everywhere and redirect HTTP to HTTPS with HSTS headers.
1---2name: application-security-23description: Securing applications through design, development, and deployment practices to prevent vulnerabilities and protect against attacks4---56# Application Security78## What I Do910I provide guidance on securing applications throughout the software development lifecycle. This includes identifying and mitigating common vulnerabilities (OWASP Top 10), implementing secure coding patterns, integrating security testing into CI/CD pipelines, and establishing defense-in-depth strategies that protect applications from injection attacks, broken authentication, data exposure, and other threats.1112## When to Use Me1314- Designing a new application and need security architecture guidance15- Reviewing code for common vulnerability patterns16- Implementing input validation, output encoding, or authentication flows17- Integrating SAST/DAST/SCA tools into your build pipeline18- Remediating findings from a penetration test or vulnerability scan19- Building middleware for security headers, CSRF protection, or rate limiting2021## Core Concepts22231. **OWASP Top 10**: The most critical web application security risks including injection, broken authentication, sensitive data exposure, XXE, broken access control, misconfigurations, XSS, insecure deserialization, vulnerable components, and insufficient logging.242. **Input Validation**: Verify all input on the server side using allowlists, type checks, length constraints, and range checks before processing.253. **Output Encoding**: Context-aware encoding (HTML, JavaScript, URL, CSS) to prevent injection when rendering user-controlled data.264. **Defense in Depth**: Layered security controls so that failure of one control does not compromise the entire system.275. **Least Privilege**: Grant only the minimum permissions required for a function, user, or process to operate.286. **Secure Session Management**: Use strong session IDs, enforce timeouts, regenerate tokens after authentication, and bind sessions to client attributes.297. **Security Headers**: HTTP response headers (CSP, HSTS, X-Content-Type-Options, X-Frame-Options) that instruct browsers to enable built-in protections.308. **Dependency Management**: Track and update third-party libraries to avoid inheriting known vulnerabilities (CVEs).319. **Error Handling**: Return generic error messages to users while logging detailed diagnostics server-side to avoid information leakage.3210. **Security Testing Integration**: Embed SAST, DAST, and SCA scans in CI/CD to catch vulnerabilities before deployment.3334## Code Examples3536### 1. Parameterized Queries to Prevent SQL Injection (Python)3738```python39import sqlite340from typing import Optional, Dict, Any4142def get_user_by_id(db_path: str, user_id: int) -> Optional[Dict[str, Any]]:43 """Fetch user with parameterized query to prevent SQL injection."""44 conn = sqlite3.connect(db_path)45 conn.row_factory = sqlite3.Row46 cursor = conn.cursor()47 cursor.execute("SELECT id, username, email FROM users WHERE id = ?", (user_id,))48 row = cursor.fetchone()49 conn.close()50 if row:51 return dict(row)52 return None53```5455### 2. Content Security Policy Middleware (Node.js/Express)5657```javascript58const helmet = require('helmet');5960app.use(61 helmet.contentSecurityPolicy({62 directives: {63 defaultSrc: ["'self'"],64 scriptSrc: ["'self'", "'nonce-{{nonce}}'"],65 styleSrc: ["'self'", "'unsafe-inline'"],66 imgSrc: ["'self'", "data:", "https://cdn.example.com"],67 connectSrc: ["'self'", "https://api.example.com"],68 fontSrc: ["'self'"],69 objectSrc: ["'none'"],70 frameAncestors: ["'none'"],71 upgradeInsecureRequests: [],72 },73 })74);7576app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true, preload: true }));77app.use(helmet.noSniff());78app.use(helmet.frameguard({ action: 'deny' }));79```8081### 3. CSRF Token Validation (Python/Flask)8283```python84import secrets85from functools import wraps86from flask import Flask, session, request, abort8788def generate_csrf_token() -> str:89 if "_csrf_token" not in session:90 session["_csrf_token"] = secrets.token_hex(32)91 return session["_csrf_token"]9293def csrf_protect(f):94 @wraps(f)95 def decorated(*args, **kwargs):96 if request.method in ("POST", "PUT", "DELETE", "PATCH"):97 token = request.form.get("_csrf_token") or request.headers.get("X-CSRF-Token")98 if not token or token != session.get("_csrf_token"):99 abort(403, description="CSRF token missing or invalid")100 return f(*args, **kwargs)101 return decorated102```103104### 4. Input Validation with Allowlists (Python)105106```python107import re108from typing import Optional109110ALLOWED_USERNAME_PATTERN = re.compile(r"^[a-zA-Z0-9_]{3,30}$")111ALLOWED_SORT_FIELDS = {"created_at", "updated_at", "username", "email"}112113def validate_username(username: str) -> Optional[str]:114 if not ALLOWED_USERNAME_PATTERN.match(username):115 return None116 return username117118def validate_sort_field(field: str) -> str:119 if field not in ALLOWED_SORT_FIELDS:120 return "created_at"121 return field122```123124### 5. Secure Password Hashing (Python)125126```python127import hashlib128import secrets129from typing import Tuple130131def hash_password(password: str) -> Tuple[str, str]:132 salt = secrets.token_hex(32)133 pwd_hash = hashlib.pbkdf2_hmac(134 "sha256", password.encode("utf-8"), salt.encode("utf-8"), iterations=600_000135 )136 return pwd_hash.hex(), salt137138def verify_password(password: str, stored_hash: str, salt: str) -> bool:139 pwd_hash = hashlib.pbkdf2_hmac(140 "sha256", password.encode("utf-8"), salt.encode("utf-8"), iterations=600_000141 )142 return secrets.compare_digest(pwd_hash.hex(), stored_hash)143```144145## Best Practices1461471. **Validate all input server-side** using allowlists and strict type/length/range checks regardless of client-side validation.1482. **Use parameterized queries or ORMs** for all database interactions to prevent SQL injection.1493. **Encode output contextually** (HTML, JS, URL, CSS) when rendering user-controlled data.1504. **Set security headers** (CSP, HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy) on every response.1515. **Hash passwords with strong algorithms** (bcrypt, scrypt, Argon2, or PBKDF2 with high iteration counts) and unique salts.1526. **Implement CSRF protection** for all state-changing operations using synchronizer tokens or SameSite cookies.1537. **Keep dependencies updated** and run SCA scans to detect known vulnerabilities in third-party libraries.1548. **Log security events** (authentication failures, access denials, input validation failures) with enough context for investigation but without sensitive data.1559. **Fail securely** by denying access by default when errors occur rather than allowing access.15610. **Enforce HTTPS everywhere** and redirect HTTP to HTTPS with HSTS headers.