GO KALI FREE
IntermediateWeb Security

Web Security Fundamentals: OWASP Top 10 and Beyond

A comprehensive guide to web application security covering the OWASP Top 10 vulnerabilities, defense in depth strategies, and secure development lifecycle practices.

#OWASP Top 10#web security#penetration testing#secure coding#vulnerabilities

Why Web Security Matters

Web applications are the primary interface between organizations and their users. They handle sensitive data — personal information, payment details, medical records — and they run on complex technology stacks that span client browsers, application servers, databases, APIs, third-party services, and cloud infrastructure. Each component introduces potential vulnerabilities.

In 2026, web applications remain the most targeted attack vector. Understanding the OWASP Top 10 and implementing defense in depth is essential for anyone building or securing modern web applications.

How the Web Works

Before you can secure a web application, you need to understand how the web works at a fundamental level.

The HTTP Request Lifecycle

Every time you visit a web page, your browser goes through this sequence:

  • **DNS Resolution** — The browser looks up the domain name to find the server's IP address
  • **TCP Connection** — A TCP connection is established to the server on port 80 (HTTP) or 443 (HTTPS)
  • **TLS Handshake** — For HTTPS, a TLS handshake negotiates encryption parameters and verifies the server certificate
  • **HTTP Request** — The browser sends an HTTP request (GET, POST, etc.) to the server
  • **Server Processing** — The server processes the request, queries databases if needed, and prepares a response
  • **HTTP Response** — The server sends back an HTTP response with headers and body content
  • **Browser Rendering** — The browser parses the HTML, loads additional resources (CSS, JS, images), and renders the page
  • This entire process typically completes in under one second for a well-optimized site.

    {@visual http-request-flow}

    Client-Side vs Server-Side

    Understanding where code executes is critical for security:

    Client-Side (browser):

  • HTML, CSS, JavaScript
  • Can be viewed and modified by users
  • Never trust client-side validation for security
  • XSS attacks execute here
  • Server-Side (web server, application server):

  • Backend languages (PHP, Python, Java, Node.js, Go)
  • Database access, file operations, authentication logic
  • Hidden from users, but vulnerable to injection attacks
  • SSRF, SQL injection, and command injection target server-side code
  • {@visual web-app-stack}

    HTTP Protocol Deep Dive

    HTTP Methods

    | Method | Purpose | Safe | Idempotent | Body |

    |--------|---------|------|------------|------|

    | GET | Retrieve a resource | Yes | Yes | No |

    | POST | Create a resource | No | No | Yes |

    | PUT | Update/replace a resource | No | Yes | Yes |

    | PATCH | Partial update | No | No | Yes |

    | DELETE | Remove a resource | No | Yes | No |

    | HEAD | Get headers only | Yes | Yes | No |

    | OPTIONS | Discover allowed methods | Yes | Yes | No |

    Safe means the request does not modify server state. Idempotent means multiple identical requests produce the same result.

    HTTP Request Structure

    GET /api/users HTTP/1.1
    Host: example.com
    User-Agent: Mozilla/5.0 (X11; Linux x86_64)
    Authorization: Bearer eyJhbGciOiJI...
    Accept: application/json
    Content-Type: application/json
    

    HTTP Response Structure

    HTTP/1.1 200 OK
    Content-Type: application/json
    Content-Length: 342
    X-Content-Type-Options: nosniff
    Strict-Transport-Security: max-age=31536000
    
    {"users":[{"id":1,"name":"Alice"}]}
    

    HTTP Status Code Classes

    | Code Range | Class | Meaning |

    |-----------|-------|---------|

    | 1xx | Informational | Request received, continuing |

    | 2xx | Success | Request received, understood, accepted |

    | 3xx | Redirection | Further action needed |

    | 4xx | Client Error | Request has bad syntax or cannot be fulfilled |

    | 5xx | Server Error | Server failed to fulfill a valid request |

    Key Status Codes

    | Code | Meaning | Typical Cause |

    |------|---------|---------------|

    | 200 | OK | Request succeeded |

    | 201 | Created | Resource created via POST |

    | 301 | Moved Permanently | URL changed permanently |

    | 302 | Found (Temporary Redirect) | URL changed temporarily |

    | 304 | Not Modified | Cache is valid |

    | 400 | Bad Request | Malformed request syntax |

    | 401 | Unauthorized | Missing or invalid authentication |

    | 403 | Forbidden | Authenticated but not authorized |

    | 404 | Not Found | Resource does not exist |

    | 405 | Method Not Allowed | Wrong HTTP method |

    | 429 | Too Many Requests | Rate limit exceeded |

    | 500 | Internal Server Error | Server-side error |

    | 502 | Bad Gateway | Upstream server error |

    | 503 | Service Unavailable | Server overloaded or down |

    HTTPS and TLS

    Why HTTPS Matters

    HTTP sends all data in plaintext. Anyone on the network path — Wi-Fi hotspot, ISP, corporate proxy, attacker on the same network — can read every request and response. HTTPS encrypts the entire communication using TLS (Transport Layer Security).

    The TLS Handshake

    The TLS handshake establishes an encrypted connection between client and server:

  • **Client Hello** — Browser sends supported TLS versions, cipher suites, and a random number
  • **Server Hello** — Server selects the highest mutually supported TLS version and cipher suite, sends its certificate and a random number
  • **Certificate Verification** — Browser verifies the server certificate against trusted Certificate Authorities (CAs)
  • **Key Exchange** — Client and server derive session keys using asymmetric cryptography
  • **Secure Connection** — All subsequent data is encrypted with the session keys
  • In TLS 1.3, this completes in a single round trip (1-RTT), making it faster than previous versions.

    {@visual https-tls-handshake}

    Comparison: HTTP vs HTTPS

    | Feature | HTTP | HTTPS |

    |---------|------|-------|

    | Encryption | None (plaintext) | TLS encryption |

    | Default Port | 80 | 443 |

    | Authentication | None | Server certificate verified by CA |

    | Data Integrity | None (can be modified in transit) | Cryptographic integrity verification |

    | SEO Impact | Negative (Chrome marks as "Not Secure") | Positive (Google ranking signal) |

    | Performance | Slightly faster (no TLS overhead) | Minimal overhead with modern hardware |

    | Required For | Nothing modern | HTTP/2, HTTP/3, Service Workers, Geolocation API |

    | Certificate | Not needed | Required from a trusted CA |

    How Browsers Use the Network Tab

    Browser Developer Tools are essential for understanding web security. Open them with F12 or Ctrl+Shift+I.

    Network Tab Walkthrough

    Open the Network tab, visit any website, and observe:

  • **Request List** — Every resource loaded (HTML, CSS, JS, images, API calls)
  • **Headers** — Request and response headers for each resource
  • **Payload** — Data sent in POST/PUT bodies
  • **Cookies** — Cookies sent with the request
  • **Timing** — DNS lookup, TCP connection, TLS handshake, server processing, content download
  • **Status** — HTTP status codes for each request
  • Practical Example

    # Using curl to inspect headers (same as browser Network tab)
    curl -I https://example.com
    HTTP/2 200
    content-encoding: br
    content-type: text/html; charset=UTF-8
    server: Apache
    strict-transport-security: max-age=63072000
    x-content-type-options: nosniff
    x-frame-options: DENY
    

    {@visual devtools-network-tab}

    Cookies, Sessions, and Authentication

    How Cookies Work

    Cookies are small pieces of data that the server sends to the browser, which the browser stores and sends back with every subsequent request to the same domain.

    Cookie Attributes:

    | Attribute | Purpose | Security Implication |

    |-----------|---------|---------------------|

    | HttpOnly | Prevents JavaScript access to the cookie | Prevents XSS from stealing cookies |

    | Secure | Cookie only sent over HTTPS | Prevents exposure on HTTP connections |

    | SameSite | Controls when cookies are sent cross-site | Prevents CSRF attacks |

    | Domain | Which domain receives the cookie | Overly broad domains leak cookies |

    | Path | Which URL path receives the cookie | Narrow paths reduce exposure |

    | Expires/Max-Age | Cookie lifetime | Shorter lifetimes reduce window of attack |

    Sessions vs Cookies

    | Feature | Cookies | Sessions |

    |---------|---------|----------|

    | Storage Location | Browser (client-side) | Server (in memory, database, or Redis) |

    | Data Exposure | Visible to user, can be modified | Hidden on server, user cannot modify |

    | Size Limit | 4KB per cookie | Limited by server memory/storage |

    | Expiration | Set by Expires/Max-Age | Server-controlled, can be invalidated immediately |

    | Security | Must use HttpOnly + Secure + SameSite | Server controls the data, only session ID in cookie |

    Best Practice: Store only a session identifier in the cookie. Store all sensitive data on the server side, keyed by that session ID.

    {@visual cookie-session-lifecycle}

    Authentication vs Authorization

    | Concept | Authentication (AuthN) | Authorization (AuthZ) |

    |---------|----------------------|----------------------|

    | Question | "Who are you?" | "What can you do?" |

    | Mechanism | Username/password, MFA, OAuth | Roles, permissions, policies |

    | Failure | Login denied | 403 Forbidden |

    | Token | ID Token (JWT) | Access Token (JWT) with claims |

    | OWASP Category | A07: Identification and Authentication Failures | A01: Broken Access Control |

    {@visual auth-flow}

    JWT (JSON Web Tokens)

    JWTs are self-contained tokens that encode claims in a base64-encoded JSON payload, signed with a secret or public/private key pair.

    # A JWT consists of three parts separated by dots:
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGUiOiJhZG1pbiJ9.dQw4w9WgXcQ
    
    # Header: {"alg":"HS256","typ":"JWT"}
    # Payload: {"userId":1,"role":"admin"}
    # Signature: HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload), secret)
    

    JWT Security Checklist:

  • Use a strong signing algorithm (HS256 or RS256)
  • Never use "none" algorithm
  • Set short expiration times (15-60 minutes)
  • Validate the signature on every request
  • Store JWTs in HttpOnly+Secure cookies, not localStorage
  • Include issuer (iss) and audience (aud) claims
  • Same-Origin Policy and CORS

    Same-Origin Policy (SOP)

    SOP is a fundamental browser security mechanism that restricts how a document or script loaded from one origin can interact with resources from another origin. Two URLs have the same origin if they share the same protocol, host, and port.

    https://example.com/page1
    https://example.com/page2      # Same origin
    https://api.example.com         # Different origin (subdomain)
    http://example.com              # Different origin (protocol)
    https://example.com:8080        # Different origin (port)
    

    Cross-Origin Resource Sharing (CORS)

    CORS is a mechanism that allows servers to relax SOP restrictions for specific cross-origin requests. The server includes HTTP headers that tell the browser which origins are permitted.

    # Server response allowing cross-origin requests
    Access-Control-Allow-Origin: https://myapp.com
    Access-Control-Allow-Methods: GET, POST, PUT, DELETE
    Access-Control-Allow-Headers: Content-Type, Authorization
    Access-Control-Allow-Credentials: true
    Access-Control-Max-Age: 3600
    

    Common CORS Mistakes:

  • Setting `Access-Control-Allow-Origin: *` with credentials enabled (incompatible by spec)
  • Reflecting the Origin header without validation (allows any site)
  • Overly permissive methods or headers
  • Missing validation in preflight responses
  • Terminal Sessions for Web Security

    curl Examples

    # Basic GET request
    curl https://example.com
    
    # View response headers only
    curl -I https://example.com
    
    # POST request with JSON data
    curl -X POST https://api.example.com/login \
      -H "Content-Type: application/json" \
      -d '{"username":"admin","password":"secret"}'
    
    # Include cookies
    curl -b "sessionid=abc123" https://example.com/dashboard
    
    # Follow redirects
    curl -L http://example.com
    
    # Show full request and response details
    curl -v https://example.com
    
    # Use a specific HTTP method
    curl -X PUT -d '{"name":"updated"}' https://api.example.com/resource/1
    

    openssl s_client (Inspect TLS)

    # Connect to a server and show the TLS handshake details
    openssl s_client -connect example.com:443 -servername example.com
    
    # Show certificate chain
    openssl s_client -connect example.com:443 -showcerts
    
    # Check if a server supports TLS 1.3
    openssl s_client -connect example.com:443 -tls1_3
    

    DNS Tools

    # dig — Detailed DNS lookup
    dig example.com
    dig example.com MX
    dig +trace example.com
    
    # host — Simple DNS lookup
    host example.com
    host -t MX example.com
    
    # nslookup — Interactive DNS tool
    nslookup example.com
    nslookup -type=any example.com
    

    Network Diagnostics

    # ping — Test basic connectivity
    ping -c 4 example.com
    
    # traceroute — Map network path
    traceroute example.com
    
    # Test specific port connectivity
    nc -zv example.com 443
    timeout 2 bash -c "echo >/dev/tcp/example.com/80" && echo "Port 80 open"
    

    Python HTTP Server

    # Serve the current directory on port 8000
    python3 -m http.server 8000
    
    # This is useful for:
    # - Testing local files in a browser-like environment
    # - Creating a quick file sharing endpoint
    # - Testing webhooks locally with ngrok
    
    # WARNING: Do not use this in production — no security features
    

    Burp Suite Walkthrough

    Burp Suite is the industry-standard tool for web application security testing. The Community Edition is free and sufficient for learning.

    Setting Up Burp Suite

  • Launch Burp Suite from Kali: `burpsuite` (or find it in Applications → Web Application Analysis)
  • Choose "Temporary Project" and use the default configuration
  • Go to the **Proxy** tab, then **Intercept** sub-tab
  • Ensure "Intercept is on" is displayed
  • Configuring Your Browser

    To route browser traffic through Burp's proxy:

  • In Firefox, go to Settings → Network Settings → Manual proxy configuration
  • Set HTTP Proxy to 127.0.0.1, Port 8080
  • Check "Also use this proxy for HTTPS"
  • Visit http://burpsuite to download the CA certificate
  • Import the certificate into Firefox's certificate store (Trust this CA to identify websites)
  • Proxy Tab

    The Proxy tab shows all requests passing through Burp:

  • **Intercept** — Pause requests to modify them before forwarding
  • **HTTP History** — Complete log of all requests and responses
  • **WebSockets History** — WebSocket communication logs
  • Intercepting and Modifying Requests

    When Intercept is on, every request pauses in Burp:

    # Example intercepted request
    GET /login HTTP/1.1
    Host: example.com
    User-Agent: Mozilla/5.0
    Cookie: sessionid=abc123
    
    username=admin&password=secret
    

    You can modify any part — URL, headers, body — before clicking "Forward" to send it to the server. This is how you test for vulnerabilities like parameter tampering, SQL injection, and access control bypasses.

    Repeater

    The Repeater tab lets you resend individual requests and observe responses. Use it to:

  • Test parameter variations on a single endpoint
  • Compare responses with different payloads
  • Manually verify vulnerability findings
  • Right-click any request in Proxy → HTTP History
  • Select "Send to Repeater"
  • Modify the request and click "Send"
  • Compare responses side by side
  • {@visual burp-proxy-intercept}

    Decoder

    The Decoder tab converts between encodings:

  • Base64 encode/decode
  • URL encode/decode
  • HTML entity encode/decode
  • Hex encode/decode
  • ASCII/hex/octal/binary conversion
  • Comparer

    The Comparer tab highlights differences between two requests or responses. Use it to:

  • Compare successful vs failed login responses
  • Compare responses with and without a parameter
  • Detect differences in error messages (useful for blind injection testing)
  • Target

    The Target tab shows a site map of discovered endpoints, parameters, and content. It automatically builds this from proxied traffic and is useful for understanding the application's attack surface.

    {@visual burp-proxy-intercept}

    OWASP Top 10 2021

    The Open Web Application Security Project (OWASP) Top 10 is the definitive guide to the most critical web application security risks. Updated periodically, it represents a broad consensus among security experts about the most important vulnerabilities.

    A01: Broken Access Control

    Access control enforces what users can do within an application. Broken access control occurs when these restrictions are not properly implemented.

    Common examples include privilege escalation (a regular user accessing admin functions), insecure direct object references (IDOR — changing a URL parameter like /user/123 to /user/456 to access another user's data), and missing restrictions on API endpoints.

    Prevention: Implement role-based access control (RBAC) with server-side enforcement, deny access by default, validate permissions on every request, and use random or hashed identifiers instead of sequential IDs.

    Real-World Impact: The 2021 T-Mobile breach exposed data of 40 million people through an insecure API endpoint with broken access control.

    A02: Cryptographic Failures

    Previously titled "Sensitive Data Exposure," this category focuses on failures related to cryptography. Examples include transmitting data without TLS, storing passwords with weak hashing algorithms (MD5, SHA1), using outdated ciphers, and hardcoding cryptographic keys.

    Prevention: Use TLS 1.3 everywhere, hash passwords with bcrypt/argon2, encrypt sensitive data at rest, never hardcode secrets, and use established cryptographic libraries rather than implementing your own.

    A03: Injection

    Injection attacks occur when untrusted data is sent to an interpreter as part of a command or query. SQL injection is the most well-known, but command injection, LDAP injection, and NoSQL injection are also common.

    -- Vulnerable SQL query (concatenation)
    SELECT * FROM users WHERE username = '" + userInput + "' AND password = '" + passInput + "'
    
    -- If userInput = admin' --, the query becomes:
    SELECT * FROM users WHERE username = 'admin' --' AND password = ''
    
    -- This bypasses authentication entirely!
    

    Prevention: Use parameterized queries (prepared statements) for database access, employ input validation and parameterization for all interpreters, escape special characters, and use ORM frameworks that handle query construction safely.

    A04: Insecure Design

    This newer category highlights the importance of security-by-design — building security into the application architecture from the start rather than bolting it on later. Issues include missing threat modeling, inadequate rate limiting, and lack of secure defaults.

    Prevention: Integrate security into the design phase using threat modeling (STRIDE, PASTA), establish secure design patterns, and require security reviews for architectural changes.

    A05: Security Misconfiguration

    Applications often ship with insecure default configurations. Common problems include enabling unnecessary services, using default credentials, exposing directory listings, verbose error messages revealing stack traces, and failing to patch or update components.

    Prevention: Automate configuration management with infrastructure-as-code, disable unnecessary features, enforce secure defaults, and regularly scan for misconfigurations.

    A06: Vulnerable and Outdated Components

    Modern applications depend heavily on third-party libraries and frameworks. These dependencies can introduce known vulnerabilities that attackers can exploit.

    Prevention: Maintain an inventory of all components and their versions (software bill of materials — SBOM), regularly scan for known vulnerabilities (CVE databases, Snyk, OWASP Dependency-Check), update dependencies promptly, and remove unused dependencies.

    A07: Identification and Authentication Failures

    Weak authentication mechanisms include allowing weak passwords, not implementing MFA, exposing session identifiers in URLs, and failing to invalidate sessions on logout.

    Prevention: Enforce strong password policies, implement MFA, use secure session management (HttpOnly, Secure, SameSite cookies), limit login attempts, and implement proper session expiration.

    A08: Software and Data Integrity Failures

    This category covers failures related to integrity verification. Examples include using untrusted third-party CDNs, accepting deserialized data without validation, and failing to verify software update signatures.

    Prevention: Use subresource integrity (SRI) for CDN resources, sign and verify software updates, validate serialized data, and verify the integrity of CI/CD pipeline artifacts.

    A09: Security Logging and Monitoring Failures

    Without adequate logging and monitoring, breaches go undetected for months. The average dwell time (time between intrusion and detection) is over 200 days.

    Prevention: Log all authentication attempts (successful and failed), access control failures, input validation errors, and administrative actions. Use centralized logging with SIEM integration, protect logs from tampering, and establish alerting thresholds.

    A10: Server-Side Request Forgery (SSRF)

    SSRF occurs when an attacker can trick the server into making requests to internal resources. This can expose internal services, cloud metadata endpoints, and other sensitive infrastructure.

    Prevention: Validate and sanitize all URLs provided by users, restrict outbound traffic from application servers, block access to private IP ranges, and avoid passing raw URLs to network functions.

    Defense in Depth

    No single security control is sufficient. Defense in depth layers multiple controls so that if one fails, others still provide protection.

    Web Application Firewall (WAF)

    A WAF filters HTTP traffic between the client and the application, blocking common attack patterns like SQL injection and XSS. Cloud WAF services (Cloudflare, AWS WAF, ModSecurity) offer managed rule sets and are easy to deploy.

    Content Security Policy (CSP)

    CSP is an HTTP header that tells the browser which sources of content are allowed to load:

    # Restrictive CSP
    Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'none'
    

    A well-crafted CSP prevents XSS by blocking inline scripts and restricting script sources, and can eliminate data exfiltration by restricting connection destinations.

    Input Validation

    Validate all input on the server side (client-side validation is for user experience, not security). Use allow lists of acceptable values rather than deny lists of dangerous patterns. Validate type, length, format, and range.

    Output Encoding

    Encode dynamic content before rendering it in the browser to prevent XSS attacks. Use contextual encoding — HTML encoding for HTML contexts (<), URL encoding for URLs (%3C), JavaScript encoding for script contexts.

    Security Headers

    Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
    X-Content-Type-Options: nosniff
    X-Frame-Options: DENY
    Content-Security-Policy: default-src 'self'
    Referrer-Policy: strict-origin-when-cross-origin
    Permissions-Policy: camera=(), microphone=(), geolocation=()
    

    These headers add additional protection layers with minimal performance cost.

    Practical Labs

    Lab 1: Inspecting a Real Website

    Objective: Use browser Developer Tools to inspect HTTP traffic.

    Setup: Open Chrome/Firefox Developer Tools (F12), click the Network tab, visit any website.

    Commands: Filter by "XHR" to see API calls, click any request to view headers and response.

    Expected Observations: See DNS timings, TLS handshake duration, request and response headers, cookie exchange, and status codes.

    Safety Notes: You are only observing traffic to a public website you have deliberately visited. This is safe and legal.

    Lab 2: Testing with Burp Suite

    Objective: Intercept and modify HTTP requests using Burp Suite.

    Setup: Install Burp Suite (comes pre-installed on Kali), configure Firefox proxy to 127.0.0.1:8080, install Burp CA certificate.

    Steps:

  • Open Burp Suite and confirm Intercept is on
  • In Firefox, visit an HTTP test site (like http://testasp.vulnweb.com)
  • Watch the request pause in Burp's Intercept tab
  • Modify a parameter value (e.g., change a form field value)
  • Click Forward to send the modified request
  • Observe the modified response
  • Safety Notes: Only practice on sites you own or have explicit permission to test.

    Lab 3: SQL Injection on DVWA

    Objective: Perform a basic SQL injection attack on DVWA in a safe local environment.

    Setup: Install and run DVWA locally using Docker or XAMPP. Set security level to Low.

    Steps:

  • Open DVWA in your browser
  • Navigate to SQL Injection page
  • Enter `' OR '1'='1` in the User ID field
  • Observe how the query returns all users instead of one
  • Cleanup: Reset DVWA to high security level.

    Safety Notes: Only run DVWA on a local, isolated environment. Never test against external systems.

    Common Beginner Mistakes

    1. Ignoring HTTPS

  • **Problem**: Assuming HTTP is acceptable for any functionality
  • **Fix**: Enforce HTTPS everywhere, including all API endpoints
  • **Prevention**: Use HSTS preloading and redirect HTTP to HTTPS at the server level
  • 2. Trusting Client-Side Validation

  • **Problem**: Relying on JavaScript validation in the browser for security
  • **Fix**: Always validate input on the server side
  • **Why**: Client-side validation is bypassed instantly with curl or Burp Suite
  • 3. Using GET Requests for Sensitive Data

  • **Problem**: Sending passwords, tokens, or API keys in URL query parameters
  • **Fix**: Use POST/PUT with an HTTPS request body
  • **Risk**: URLs are logged by servers, proxies, and stored in browser history
  • 4. Weak Session Management

  • **Problem**: Predictable session IDs (sequential numbers, timestamps), long session timeouts
  • **Fix**: Use cryptographically random session IDs, implement idle and absolute timeouts
  • **Risk**: Session hijacking through prediction or fixation
  • 5. Insecure Cookie Configuration

  • **Problem**: Missing HttpOnly, Secure, and SameSite attributes
  • **Fix**: Set `Set-Cookie: sessionid=...; HttpOnly; Secure; SameSite=Lax`
  • **Risk**: XSS can steal HttpOnly-less cookies; missing Secure leaks over HTTP
  • 6. Poor CORS Configuration

  • **Problem**: Setting `Access-Control-Allow-Origin: *` or reflecting the Origin header without validation
  • **Fix**: Whitelist specific origins, validate on the server side
  • **Risk**: Any malicious site can make authenticated API calls from the victim's browser
  • 7. Storing Secrets in Code

  • **Problem**: Hardcoding API keys, database passwords, or JWT secrets in source code
  • **Fix**: Use environment variables, vault services, or secret management tools
  • **Risk**: Secrets exposed in version control, CI/CD logs, and decompiled code
  • 8. Not Validating Content Types

  • **Problem**: Accepting any Content-Type in API endpoints
  • **Fix**: Validate `Content-Type` header matches expected format (`application/json`)
  • **Risk**: Cached JSON responses can be executed as JavaScript (JSON hijacking)
  • 9. Exposing Stack Traces

  • **Problem**: Returning detailed error messages with stack traces, SQL queries, and file paths
  • **Fix**: Return generic error messages in production, log details server-side
  • **Risk**: Information leakage helps attackers refine their approach
  • 10. Ignoring Subresource Integrity (SRI)

  • **Problem**: Loading third-party JavaScript from CDNs without SRI attributes
  • **Fix**: Add `integrity="sha384-..."` and `crossorigin="anonymous"` to script tags
  • **Risk**: Compromised CDN can inject malicious code into your application
  • 11. Missing Rate Limiting

  • **Problem**: Allowing unlimited login attempts, API calls, or form submissions
  • **Fix**: Implement rate limiting per IP, per user, and per endpoint
  • **Risk**: Brute force attacks, credential stuffing, and DoS
  • 12. Weak Password Policies

  • **Problem**: Allowing short passwords, common passwords, no complexity requirements
  • **Fix**: Enforce minimum length (12+ characters), use password strength meters, check against breach databases
  • **Risk**: Credential compromise through brute force or dictionary attacks
  • 13. Not Implementing Account Lockout

  • **Problem**: Allowing unlimited login attempts without lockout delays
  • **Fix**: Lock accounts after 5-10 failed attempts for 15-30 minutes
  • **Risk**: Automated brute force succeeds eventually without lockout
  • 14. Using Unvalidated Redirects

  • **Problem**: Redirecting users to URLs based on user-supplied parameters
  • **Fix**: Maintain a whitelist of allowed redirect destinations
  • **Risk**: Phishing attacks — an attacker crafts a redirect to a malicious site
  • 15. Forgetting to Invalidate Sessions on Logout

  • **Problem**: Server-side session persists after user clicks "Logout"
  • **Fix**: Delete the session from the server on logout
  • **Risk**: Previous session can be reused if cookies are not cleared
  • Troubleshooting

    Mixed Content

  • **Problem**: HTTPS page loads HTTP resources (images, scripts, stylesheets)
  • **Browser Message**: "Mixed Content: The page was loaded over HTTPS, but requested an insecure resource"
  • **Solution**: Update all resource URLs to use HTTPS. Use scheme-relative URLs (`//cdn.example.com/file.js`)
  • **Prevention**: Enable CSP with `upgrade-insecure-requests` directive
  • Certificate Errors

  • **Problem**: Browser displays "Your connection is not private" warning
  • **Common Causes**: Expired certificate, mismatched domain name, self-signed certificate, untrusted CA
  • **Solution**: Renew the certificate, verify the domain name matches, use Let's Encrypt for free valid certificates
  • **Verification**: `openssl s_client -connect example.com:443 -servername example.com | openssl x509 -noout -dates`
  • CORS Failures

  • **Problem**: Browser console shows "Cross-Origin Request Blocked" error
  • **Common Causes**: Missing `Access-Control-Allow-Origin` header, using `*` with credentials, mismatched Origin
  • **Debugging**: Check the browser Network tab to see the preflight (OPTIONS) request and its response headers
  • **Solution**: Configure the server to send proper CORS headers for the specific origin
  • 403 Forbidden

  • **Problem**: Server returns 403 for valid requests
  • **Common Causes**: WAF blocking, missing permissions, IP blacklisting, expired session
  • **Debugging**: Check WAF logs, verify session validity, test with different IPs
  • **Solution**: Review access control configuration, whitelist legitimate traffic
  • 404 Not Found

  • **Problem**: Resource does not exist
  • **Security Implications**: Directory brute forcing revealed; verbose 404 messages aid recon
  • **Best Practice**: Return generic 404 pages (no "admin" vs "user" distinction to avoid information leakage)
  • 500 Internal Server Error

  • **Problem**: Server encountered an unexpected condition
  • **Debugging**: Check server logs (`/var/log/apache2/error.log`, `journalctl -u nginx`)
  • **Security Risk**: Stack traces in responses expose code structure. Never display them in production
  • **Solution**: Fix the underlying error; ensure error logging captures details without exposing them to users
  • CSRF Token Mismatch

  • **Problem**: Form submissions fail with CSRF validation errors
  • **Common Causes**: Expired token, mismatched origin, missing token field
  • **Solution**: Regenerate the form with a valid CSRF token, ensure SameSite cookie configuration is correct
  • **Debugging**: Check that the CSRF token in the form matches the session-stored token
  • Cookie Not Set

  • **Problem**: Browser does not store cookies from the server response
  • **Common Causes**: Missing `Domain` attribute mismatch, `SameSite` restrictions, Secure flag on HTTP
  • **Solution**: Ensure Domain matches the request URL, use SameSite=Lax for most cases, only set Secure over HTTPS
  • **Debugging**: Check the response headers in Network tab and browser DevTools Application → Storage → Cookies
  • DNS Resolution Failure

  • **Problem**: "Server not found" or "DNS_PROBE_FINISHED_NXDOMAIN"
  • **Solution**: Verify the domain exists with `dig example.com`, check DNS configuration with `nslookup`
  • **Common Causes**: Domain expired, DNS propagation delay, misconfigured nameservers, local DNS cache corrupted
  • Connection Refused

  • **Problem**: Browser shows "Connection refused" error
  • **Solution**: Verify the server is running with `nc -zv example.com 443` or `curl -v https://example.com`
  • **Common Causes**: Service not started, firewall blocking port, wrong port number, server crash
  • Detection & Defense

    Web Application Firewall (WAF)

    WAFs examine HTTP traffic at the application layer and block malicious requests before they reach the application.

  • **Cloud WAF**: Cloudflare, AWS WAF, Fastly — easy to deploy, constantly updated rule sets
  • **Open Source WAF**: ModSecurity with OWASP Core Rule Set — flexible but requires configuration
  • **Behavioral WAF**: Signals Sciences, DataDome — use ML to detect anomalous traffic patterns
  • Content Security Policy (CSP)

    CSP is your strongest defense against XSS. A strict CSP:

    # Strict CSP that allows only same-origin resources and blocks inline scripts
    Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'
    

    Secure Headers Checklist

  • [ ] Strict-Transport-Security (HSTS)
  • [ ] X-Content-Type-Options: nosniff
  • [ ] X-Frame-Options: DENY
  • [ ] Content-Security-Policy
  • [ ] Referrer-Policy: strict-origin-when-cross-origin
  • [ ] Permissions-Policy (Feature-Policy legacy)
  • [ ] Cache-Control: no-store (for sensitive pages)
  • [ ] Set-Cookie with HttpOnly, Secure, SameSite
  • Input Validation Rules

  • Validate on the server side only — never trust client-side validation
  • Use allow lists (`^[a-zA-Z0-9]+ Cybersecurity Education | GO KALI FREE
    GO KALI FREE
    ) instead of deny lists
  • Validate type (string, number, email, URL), length (min/max), format (regex), and range
  • Sanitize by encoding, not by stripping — stripping can be bypassed
  • Output Encoding by Context

    | Context | Encoding | Example |

    |---------|----------|---------|

    | HTML body | HTML entity encode | <script> |

    | HTML attribute | HTML attribute encode | " |

    | JavaScript string | JavaScript string encode | \x3Cscript\x3E |

    | URL parameter | URL encode | %3Cscript%3E |

    | CSS string | CSS escape | \3C script\3E |

    Rate Limiting

  • Per IP: 100 requests per minute per IP
  • Per user: 10 login attempts per 15 minutes
  • Per endpoint: 1000 requests per minute for read, 100 for write
  • Response: 429 Too Many Requests with Retry-After header
  • Logging Requirements

  • Log all authentication events (successful login, failed login, password reset)
  • Log access control failures (403 responses)
  • Log input validation failures
  • Log administrative actions
  • Include timestamp, source IP, user ID, action, and result
  • Protect logs from tampering (immutable storage, append-only)
  • Integrate with SIEM for real-time alerting
  • Monitoring

  • Monitor for abnormal traffic patterns (spikes, unusual geolocations)
  • Alert on multiple failed logins from the same IP
  • Alert on known attack patterns (SQL injection, XSS attempts in logs)
  • Track dwell time — the average breach detection time is still over 200 days
  • Conduct regular security reviews using OWASP ASVS as a checklist
  • Secure Development Lifecycle (SDL)

    Integrate security into every phase of development:

  • **Training** — Educate developers on secure coding practices specific to their tech stack
  • **Requirements** — Define security requirements alongside functional requirements (use OWASP ASVS for standard guidance)
  • **Design** — Perform threat modeling (STRIDE, PASTA), security architecture review, and design review against OWASP ASVS controls
  • **Implementation** — Use secure coding standards (OWASP Cheat Sheets), peer reviews, and pre-commit security hooks
  • **Testing** — Automate security testing: SAST (static analysis), DAST (dynamic analysis), dependency scanning, and integration testing in CI/CD
  • **Deployment** — Configure production securely (security headers, CSP, TLS), manage secrets via vault services, automate infrastructure-as-code scanning
  • **Response** — Have an incident response plan, practice tabletop exercises, and learn from post-incident reviews
  • Web security is not a one-time checklist — it is an ongoing practice. The OWASP Top 10 provides the starting point, but defense in depth and a secure development lifecycle are what truly protect applications in production.

    {@visual attack-chain-web}

    Glossary

    | Term | Definition |

    |------|-----------|

    | Authentication (AuthN) | The process of verifying who a user is (e.g., username/password, MFA) |

    | Authorization (AuthZ) | The process of determining what a user can do after authentication |

    | CORS | Cross-Origin Resource Sharing — a mechanism that allows controlled cross-origin requests |

    | CSP | Content Security Policy — an HTTP header that restricts which resources a browser can load |

    | CSRF | Cross-Site Request Forgery — an attack that tricks a user into performing unwanted actions |

    | Cookie | A small piece of data stored by the browser and sent with each request to the originating domain |

    | DNS | Domain Name System — translates domain names to IP addresses |

    | HSTS | HTTP Strict Transport Security — instructs browsers to always use HTTPS |

    | HTTP | Hypertext Transfer Protocol — the foundation protocol for web communication |

    | HTTPS | HTTP over TLS — encrypted HTTP communication |

    | Injection | An attack where untrusted data is sent to an interpreter as part of a command or query |

    | JWT | JSON Web Token — a self-contained token format for transmitting claims securely |

    | MFA | Multi-Factor Authentication — requiring two or more verification factors |

    | MITM | Man-in-the-Middle — an attack where the attacker intercepts communication between two parties |

    | ORM | Object-Relational Mapping — a technique for converting data between incompatible type systems |

    | OWASP | Open Web Application Security Project — a nonprofit focused on improving software security |

    | RBAC | Role-Based Access Control — restricting access based on user roles |

    | SIEM | Security Information and Event Management — centralized logging and analysis system |

    | SOP | Same-Origin Policy — a browser security mechanism restricting cross-origin interactions |

    | SSRF | Server-Side Request Forgery — an attack that tricks the server into making internal requests |

    | TLS | Transport Layer Security — cryptographic protocol for secure communication |

    | WAF | Web Application Firewall — filters HTTP traffic to block common attack patterns |

    | XSS | Cross-Site Scripting — injection of malicious scripts into web pages viewed by others |

    | SQLi | SQL Injection — injection attack targeting database queries |

    References

    {@ref owasp-top10}

    {@ref owasp-testing-guide}

    {@ref owasp-cheatsheet}

    {@ref owasp-asvs}

    {@ref mdn-http}

    {@ref mdn-cors}

    {@ref burpsuite-docs}

    {@ref rfc2616}

    {@ref rfc7230}

    {@ref rfc8446}

    {@ref rfc6265}

    {@ref rfc7519}

    {@ref nist-sp800-115}

    {@ref nist-csf}

    Frequently Asked Questions

    What is the OWASP Top 10?

    The OWASP Top 10 is a regularly updated list of the most critical web application security risks, maintained by the Open Web Application Security Project. It includes vulnerabilities like Broken Access Control, Cryptographic Failures, and Injection attacks.

    What is SQL injection and how do I prevent it?

    SQL injection (SQLi) occurs when user input is directly included in SQL queries, allowing attackers to manipulate the database. Prevent it by using parameterized queries (prepared statements), input validation, and least privilege database permissions. See our [SQL injection guide](/learn/sql-injection-basics) for details.

    What is Cross-Site Scripting (XSS)?

    XSS is a client-side code injection vulnerability where attackers inject malicious scripts into web pages viewed by other users. Prevent it with output encoding, Content Security Policy (CSP), and input validation. Learn more in our [XSS guide](/learn/xss-basics).

    What is Broken Access Control?

    Broken Access Control (A01 in OWASP) occurs when restrictions on what users can do are not properly implemented. Examples include privilege escalation and insecure direct object references (IDOR). Implement role-based access control with server-side enforcement.

    What is a Content Security Policy (CSP)?

    CSP is an HTTP header that tells the browser which content sources are allowed to load. It prevents XSS by blocking inline scripts and restricting script sources, and can eliminate data exfiltration by restricting connection destinations.

    What is defense in depth?

    Defense in depth layers multiple security controls so that if one fails, others still provide protection. It combines WAFs, CSP, input validation, output encoding, security headers, and secure development practices for comprehensive protection.

    How do I secure API endpoints?

    Validate all input, use rate limiting, implement proper authentication and authorization (OAuth 2.0/JWT), enforce HTTPS, validate Content-Type headers, and use API gateways. OWASP API Security Top 10 provides specific guidance.

    What is Server-Side Request Forgery (SSRF)?

    SSRF occurs when an attacker tricks the server into making requests to internal resources, exposing internal services and cloud metadata endpoints. Prevent it by validating and sanitizing URLs, restricting outbound traffic, and blocking private IP ranges.

    What tools can I use to test web security?

    [Burp Suite](/tools/burp-suite) is the industry standard for web application testing. OWASP ZAP is a free alternative. Both provide intercepting proxies, vulnerability scanners, and automated testing capabilities. Use [Nikto](/tools/nikto) for server misconfiguration scanning.

    What is a Web Application Firewall (WAF)?

    A WAF filters HTTP traffic between clients and applications, blocking common attack patterns like SQL injection and XSS. Cloud WAF services like Cloudflare and AWS WAF offer managed rule sets that are easy to deploy and maintain.