OWASP Top 10 Mitigation
๐ฅ Vibe Prompt
"Secure a Flask API: fix SQLi, XSS, CSRF, broken auth, insecure deserialization."
from flask import Flask, request, session
import bleach, html
app = Flask(__name__)
# 1. SQL Injection - use parameterized queries
@app.route("/user/<int:user_id>")
def get_user(user_id):
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# 2. XSS - sanitize output
@app.route("/comment")
def show_comment():
raw = request.args.get("text", "")
safe = bleach.clean(raw, tags=["b", "i", "em", "strong"], strip=True)
return html.escape(safe)
# 3. CSRF - token validation
@app.route("/transfer", methods=["POST"])
def transfer():
token = request.form.get("csrf_token")
if not token or token != session.get("csrf_token"):
return "CSRF detected!", 403
# Process transfer
# 4. Broken Auth - rate limiting
from flask_limiter import Limiter
limiter = Limiter(app)
@app.route("/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
pass
# 5. Secure Deserialization
import json
@app.route("/api/data", methods=["POST"])
def api_data():
try:
data = json.loads(request.data) # Safe!
except json.JSONDecodeError:
return "Invalid JSON", 400
OWASP Mitigation Checklist
| Risk | Mitigation | |------|-----------| | SQLi | Parameterized queries / ORM | | XSS | Output encoding / CSP | | CSRF | Anti-CSRF tokens | | Broken Auth | MFA / rate limiting | | Insecure Deserialization | JSON only / validate |
Web Security Course Complete! ๐
- โ HTTP Security Headers
- โ CSP
- โ CORS
- โ CSRF
- โ Full OWASP Mitigation
Key Points
- Understand the core concepts thoroughly
- Practice with hands-on code examples
- Apply knowledge to real-world problems
- Review and reinforce through exercises
Further Learning
- Official documentation
- Open source projects on GitHub
- Community forums and discussions
- Related courses and tutorials
What Is OWASP Mitigation?
OWASP mitigation refers to the security controls and practices that prevent or minimize the impact of the OWASP Top 10 vulnerabilities.
Vulnerability Mitigation Matrix
| OWASP Top 10 | Mitigation Strategy | Key Control | |-------------|--------------------|-------------| | A01: Broken Access Control | Principle of least privilege | Role-based access, deny by default | | A02: Cryptographic Failures | Strong encryption everywhere | TLS 1.3, AES-256, bcrypt | | A03: Injection | Input validation + parameterized queries | Prepared statements, ORM | | A04: Insecure Design | Security by design | Threat modeling, secure architecture | | A05: Security Misconfiguration | Hardened defaults | Automated config scanning | | A06: Vulnerable Components | Dependency management | SCA tools, regular updates | | A07: Auth Failures | Strong authentication | MFA, OAuth 2.0, session management | | A08: Data Integrity Failures | Digital signatures | JWT, HMAC, code signing | | A09: Logging Failures | Comprehensive logging | Centralized logging, alerting | | A10: SSRF | Network segmentation | URL validation, deny private IPs |
Mitigation Implementation
Injection Prevention (SQL)
// โ Vulnerable: string concatenation
const query = `SELECT * FROM users WHERE id = '${userId}'`;
// โ
Safe: parameterized query
const result = await sql`
SELECT * FROM users WHERE id = ${userId}
`;
// โ
Safe: ORM
const user = await prisma.user.findUnique({
where: { id: userId }
});
XSS Prevention
// โ Vulnerable: dangerouslySetInnerHTML with unsanitized input
<div dangerouslySetInnerHTML={{ __html: userInput }} />
// โ
Safe: React auto-escapes by default
<div>{userInput}</div>
// โ
Safe: DOMPurify if HTML is needed
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(userInput)
}} />
CSRF Protection
// Next.js: CSRF token in forms
'use client';
import { useCsrfToken } from '@/lib/csrf';
export function SecureForm() {
const csrfToken = useCsrfToken();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await fetch('/api/action', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
body: JSON.stringify({ /* data */ }),
});
};
return (
<form onSubmit={handleSubmit}>
<input type="hidden" name="csrf_token" value={csrfToken} />
<input type="text" name="data" />
<button type="submit">Submit</button>
</form>
);
}
Security Headers
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:",
},
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()',
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
];
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders,
},
];
},
};
Dependency Scanning
# npm audit
npm audit
# Snyk (free for open source)
npm install -g snyk
snyk test
snyk monitor
# Dependabot (GitHub)
# Enable in: Settings โ Security โ Dependabot
# OWASP Dependency-Check
docker run --rm \
-v $(pwd):/project \
owasp/dependency-check \
--scan /project
Summary
OWASP vulnerability mitigation requires a layered approach: secure coding practices, security headers, input validation, dependency scanning, and proper authentication.
Key takeaways: | Each OWASP Top 10 vulnerability has a specific mitigation strategy | | SQL injection: always use parameterized queries or ORM | | XSS: React auto-escapes; use DOMPurify only when HTML is needed | | CSRF: use anti-CSRF tokens in forms and API requests | | Security headers: CSP, HSTS, X-Frame-Options, Permissions-Policy | | Dependency scanning: npm audit, Snyk, Dependabot, OWASP DC | | Principle of least privilege: deny by default, allow explicitly | | Security by design: threat model early, not as an afterthought |
You've completed this course! You now understand OWASP Top 10 and how to mitigate them.