Web Security Guide: OWASP Top 10, XSS, CSRF, and SQL Injection
Web security is the practice of protecting websites and web applications from attacks. The OWASP Top 10 is the industry-standard awareness document representing the most critical security risks. Understanding these vulnerabilities and their mitigations is essential for any developer building web applications.
This guide covers the most common and dangerous web vulnerabilities: injection attacks, broken authentication, XSS, CSRF, and security misconfiguration.
SQL Injection
SQL injection occurs when untrusted data is sent to the interpreter as part of a query. Attackers craft inputs that alter the SQL query structure, potentially reading, modifying, or deleting data they should not have access to.
-- Vulnerable query
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'anything'
-- The OR '1'='1' makes the WHERE clause always truePrevention
Parameterized queries (prepared statements) are the only reliable defense. They separate SQL code from data, so user input can never be interpreted as SQL:
# Safe with parameterized query
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
(username, password)
)Use an ORM (SQLAlchemy, Prisma, Hibernate) that enforces parameterized queries. Apply the principle of least privilege to database accounts — the application account should not have DROP or TRUNCATE permissions.
Cross-Site Scripting (XSS)
XSS allows attackers to inject client-side scripts into web pages viewed by other users. Stored XSS persists on the server (e.g., in a comment). Reflected XSS comes from the current request (e.g., a search parameter). DOM-based XSS occurs entirely in the browser without server interaction.
Prevention
Context-aware output encoding is the primary defense. Encode data differently depending on where it appears:
- HTML body: encode
<,>,&,",' - HTML attributes: encode besides safe characters
- JavaScript: encode for string literals
- CSS: encode for property values
- URLs: encode for query parameters
from markupsafe import escape
# Flask auto-escapes in Jinja2 templates
return render_template("profile.html", username=escape(username))Content Security Policy (CSP) provides a defense-in-depth layer. CSP restricts which scripts can execute, preventing even injected scripts from running:
Content-Security-Policy: script-src 'self' https://cdn.example.comCross-Site Request Forgery (CSRF)
CSRF tricks an authenticated user into performing actions they did not intend. An attacker crafts a malicious page that submits a form to your application using the victim’s session cookie.
Prevention
Anti-CSRF tokens are unique, unpredictable values embedded in forms and validated by the server. Each session gets a token, and every state-changing request must include it:
<form method="POST" action="/transfer">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<input type="text" name="amount">
<button type="submit">Transfer</button>
</form>SameSite cookies prevent the browser from sending cookies with cross-site requests. Set SameSite=Strict or SameSite=Lax on session cookies. Most modern frameworks (Django, Rails, Spring, Express) include CSRF protection by default.
Broken Authentication
Authentication vulnerabilities allow attackers to impersonate legitimate users. Common issues include weak password policies, credential stuffing, session fixation, and insecure password recovery.
Prevention
- Enforce strong passwords with minimum length requirements (12+ characters)
- Use bcrypt, argon2, or scrypt for password hashing — never MD5, SHA-1, or unsalted hashes
- Implement rate limiting on login endpoints to prevent brute force attacks
- Use multi-factor authentication for sensitive operations
- Rotate session IDs after login to prevent session fixation
- Set secure, HttpOnly, SameSite cookies with appropriate expiration
import bcrypt
# Hashing a password
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
# Verifying a password
if bcrypt.checkpw(password.encode(), stored_hash):
# AuthenticatedSecurity Misconfiguration
Security misconfiguration is the most common OWASP Top 10 issue. It includes default credentials, unpatched software, unnecessary features enabled, directory listing enabled, overly verbose error messages, and improper HTTP headers.
Prevention
- Disable directory listing on web servers
- Remove default accounts and change default passwords
- Disable unnecessary HTTP methods (TRACE, PUT, DELETE if not needed)
- Set secure HTTP headers:
Strict-Transport-Security,X-Frame-Options,X-Content-Type-Options,X-XSS-Protection - Run with the least privilege necessary — do not run your web server as root
- Automate configuration reviews with tools like ScoutSuite, Prowler, or OpenSCAP
Insecure Deserialization
Insecure deserialization occurs when untrusted data is used to instantiate objects. Attackers craft malicious serialized objects that execute arbitrary code when deserialized.
Prevention
- Do not accept serialized objects from untrusted sources
- Use simple data formats (JSON) instead of serialization formats (Java serialization, Python pickle)
- Implement integrity checks like digital signatures on serialized data
- Run deserialization in a sandboxed environment with restricted permissions
Logging and Monitoring
Without adequate logging, you cannot detect or investigate security incidents.
- Log authentication attempts (successful and failed), access control failures, input validation errors, and administrative actions
- Never log passwords, credit card numbers, or other sensitive data
- Centralize logs for analysis with tools like the ELK stack, Splunk, or Datadog
- Set up alerting for anomaly detection — sudden spikes in 403 errors or login failures
- Regularly review logs for suspicious patterns
Summary
Web security requires vigilance across the entire application stack. Validate and parameterize all input, encode output for its context, protect authentication with strong hashing and rate limiting, configure your infrastructure securely, and monitor for suspicious activity. The OWASP Top 10 provides a starting checklist, but security is an ongoing process, not a one-time fix.
FAQ
What is the most common web vulnerability? Security misconfiguration is the most common OWASP Top 10 issue, appearing in nearly every application that has not been deliberately hardened. Broken access control and injection follow closely.
How do I test for XSS? Manual testing involves injecting payloads like <script>alert(1)</script> into input fields. Automated scanning with OWASP ZAP or Burp Suite covers more combinations. Browser developer tools let you inspect how output is rendered.
Does HTTPS protect against injection attacks? No. HTTPS encrypts data in transit but does not validate or sanitize the data itself. SQL injection and XSS work over HTTPS just as well as HTTP.
What is the difference between authentication and authorization? Authentication verifies who you are (login). Authorization determines what you can do (permissions). A user might be authenticated (logged in) but not authorized to access admin features.
Web Security Headers
HTTP security headers provide an additional layer of protection against common web attacks. Modern web applications should implement these headers:
Content-Security-Policy (CSP) — Restricts which resources (scripts, styles, images, fonts) the browser can load and which origins are allowed. CSP is the most effective defense against cross-site scripting (XSS) attacks because even if an attacker injects a script tag, the browser refuses to execute it:
Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' 'unsafe-inline'Strict-Transport-Security (HSTS) — Tells the browser to always connect via HTTPS, preventing downgrade attacks and SSL stripping. Include the preload directive for submission to browser preload lists:
Strict-Transport-Security: max-age=63072000; includeSubDomains; preloadX-Frame-Options — Prevents clickjacking by controlling whether the page can be embedded in frames. Use DENY to block all framing, or SAMEORIGIN to allow framing by same-origin pages.
X-Content-Type-Options — Prevents MIME type sniffing by forcing the browser to use the declared Content-Type. Set to nosniff for all web applications.
Server-Side Request Forgery (SSRF)
SSRF occurs when an attacker tricks a server into making requests to internal resources. Cloud metadata endpoints (169.254.169.254 on AWS/GCP/Azure) are a common target — attackers use SSRF to steal instance credentials. Defenses include:
- Blocking private IP ranges in outbound request code
- Using allow lists of permitted external URLs
- Running services in isolated network segments
- Disabling cloud metadata service when not needed (IMDSv2 with hop limits on AWS)
OWASP Top 10 for 2021
The OWASP Top 10 lists the most critical web application security risks. The 2021 edition introduced significant changes:
A01: Broken Access Control — Moved from #5 to #1. Includes CORS misconfiguration, path traversal, and privilege escalation. Defenses include deny-by-default access policies, centralized access control libraries, and automated access control testing.
A02: Cryptographic Failures — Formerly “Sensitive Data Exposure.” Focuses on weak encryption, missing TLS, and improper certificate validation. Use only modern, audited cryptographic libraries. Never implement custom cryptography.
A03: Injection — SQL, NoSQL, OS command, and LDAP injection remain prevalent. Parameterized queries and prepared statements eliminate injection risks. For NoSQL databases, use the driver’s built-in escaping or object mapping.
Security Checklist for Deployment
Before deploying any web application, verify:
- HTTPS enforced with HSTS header
- CSP header configured appropriately
- No debug or admin endpoints exposed
- Database credentials not in code or config files
- Input validation on all user inputs
- Authentication on all protected routes
- Rate limiting on auth endpoints
- File upload size and type restrictions
- Error messages do not leak stack traces
- Dependencies scanned for known vulnerabilities
Related: API Security Guide | Security Testing
Related Concepts and Further Reading
Understanding web security requires familiarity with several interconnected ideas and principles that together form a complete picture. Exploring these related concepts deepens your knowledge and provides context that makes the core material more meaningful and applicable. Each concept builds on the others, creating a web of understanding that supports deeper learning and practical application. Taking time to explore how these elements connect reveals patterns that accelerate comprehension and retention of new information.
The relationship between web security and adjacent fields is worth particular attention. Many of the most important insights emerge at the boundaries between disciplines, where ideas from different areas combine to create new approaches and solutions that neither field could produce alone. Exploring these connections pays dividends in both breadth and depth of understanding, revealing patterns and principles that might otherwise remain hidden from view. Cross-disciplinary knowledge is increasingly valued as problems become more complex and interconnected.
For those looking to go beyond introductory material, several excellent resources provide deeper treatment of specific aspects of web security. Academic journals, industry publications, authoritative reference works, and online courses each offer different perspectives and levels of detail. The key is to match your reading to your current learning goals and build knowledge progressively, focusing on quality over quantity in your study materials. A well-chosen resource that matches your current level is worth more than dozens of resources that are too basic or too advanced.