Prepared Statements (Parameterized Queries) are OWASP's primary defense against SQL injection (OWASP Top 10:2025 A03). Parameterized queries force the database to distinguish between code and data, ensuring attackers cannot change query intent. Implementation: Use placeholders for user input instead of string concatenation. Example: SELECT * FROM users WHERE id = ? with parameter binding, NOT 'SELECT * FROM users WHERE id = ' + userInput. Works across all major databases (PostgreSQL $1, MySQL ?, SQL Server @param). Benefits: Complete protection when properly implemented, automatic handling of special characters, no escaping needed. Framework support: All modern ORMs (TypeORM, Sequelize, Prisma) use parameterized queries by default. Defense-in-depth: Combine with principle of least privilege (minimize database permissions), input validation (allowlist for format), and automated security testing (SAST/DAST in CI/CD). OWASP A03:2021-2025 Injection remains critical threat.
Web Security OWASP FAQ & Answers
30 expert Web Security OWASP answers researched from official documentation. Every answer cites authoritative sources you can verify.
unknown
30 questionsUse built-in framework session management (never build custom). Session ID: minimum 128 bits entropy, cryptographically secure random generation (crypto.randomBytes, secrets module, SecureRandom). Most secure cookie configuration (OWASP 2025): Set-Cookie: __Host-SID=
XML External Entity (XXE): CWE-611 injection attack when application parses untrusted XML with external entity references enabled - attacker can access local files, perform SSRF, cause DoS. Ranked A04 in OWASP Top 10 2017 (merged into A03:2021 Injection). Attack vectors: (1) File disclosure: Define external entity ]>, reference &xxe; in XML → server reads /etc/passwd and includes in response. (2) SSRF (Server-Side Request Forgery): Entity references internal service → bypass firewall, access cloud metadata (http://169.254.169.254/latest/meta-data/iam/security-credentials/). (3) Billion Laughs DoS: Recursive entity expansion repeated 9 levels → exponential memory consumption, server crash. (4) Out-of-band data exfiltration: Combine external DTD with parameter entities to send data to attacker server. Real-world impact: CVE-2018-1000613 (Jira XXE), CVE-2019-0227 (Apache Axis), Facebook XXE disclosure (2014). Prevention (2025 best practices): (1) Disable DTDs entirely (safest): Java (DocumentBuilderFactory): factory.setFeature('http://apache.org/xml/features/disallow-doctype-decl', true), Python (lxml): parser = etree.XMLParser(resolve_entities=False, no_network=True), .NET: XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit, PHP 8.0+ (libxml_disable_entity_loader deprecated - external entities disabled by default). (2) Disable external entities if DTDs required: Java: factory.setFeature('http://xml.org/sax/features/external-general-entities', false), Python (defusedxml library recommended over standard xml.etree). (3) Use less complex data formats: Prefer JSON over XML when possible (no entity expansion issues), use Protocol Buffers, MessagePack for binary data. (4) Input validation: Whitelist allowed XML structure, maximum document size (prevent DoS), schema validation (XSD). (5) Least privilege: XML parser runs with minimal file system permissions, network access restricted (no outbound connections). (6) Modern frameworks: Spring Boot (default XXE protection since 5.3.0), ASP.NET Core (safe defaults), Jackson XML (safe by default). Testing for XXE: Burp Suite (XXE detection), OWASP ZAP (active scanner), manual payload injection. Compliance: CWE-611 (Improper Restriction of XML External Entity Reference), OWASP Top 10 A03:2021 (Injection), PCI-DSS 6.5.1 (injection flaws).
Vulnerable and Outdated Components (A06:2021): Using libraries, frameworks, modules with known CVEs - extremely common attack vector. Problems: (1) Unknown inventory: Don't know what versions are deployed (frontend: package.json vs package-lock.json mismatch, backend: nested dependencies). (2) Outdated/unsupported software: Log4j 1.x (EOL 2015), Spring 4 (EOL 2020), Node.js 14 (EOL April 2023). (3) No vulnerability scanning: Not monitoring CVE/NVD for new exploits. (4) Delayed patching: Log4Shell (CVE-2021-44228) took months to patch at many orgs. (5) Component misconfiguration: Secure defaults not enabled (Elasticsearch exposed without auth). Real-world impact: Equifax breach (Apache Struts CVE-2017-5638), Log4Shell (millions affected), Spring4Shell (CVE-2022-22965). Prevention (2025 best practices): (1) Remove unused dependencies: npm prune --production, pip-autoremove, Maven dependency:tree. (2) Maintain SBOM (Software Bill of Materials): CycloneDX, SPDX formats - track all dependencies with versions. (3) Automated scanning: Dependabot (GitHub), Renovate, Snyk, npm audit, pip-audit, OWASP Dependency-Check. (4) CI/CD integration: Fail build if HIGH/CRITICAL CVEs detected (GitHub Advanced Security, GitLab Security Scanning). (5) Continuous monitoring: Subscribe to security advisories (GitHub Security Advisories, NVD Data Feeds). (6) Only use official sources: npm registry (not mirrors), PyPI, Maven Central - verify package signatures. (7) Version pinning: Lock files (package-lock.json, Pipfile.lock, Gemfile.lock) prevent unexpected updates. (8) Monitor unmaintained libraries: Detect abandoned packages (no commits >2 years, unpatched CVEs). SCA tools (2025): Snyk, Sonatype Nexus Lifecycle, WhiteSource, JFrog Xray, GitHub Dependabot, GitLab Security Dashboard. Supply chain attacks increasing: Compromised npm packages (colors, faker, ua-parser-js), malicious PyPI packages - verify before adding dependencies.
Authentication vs Authorization: Fundamental security concepts often confused but serve distinct purposes. Authentication (A07:2021): Verifying identity - answering 'WHO are you?'. Methods: (1) Something you know: Password, PIN, security questions (weakest alone). (2) Something you have: Hardware token, smartphone app (TOTP), smart card, email/SMS code. (3) Something you are: Biometrics (fingerprint, face recognition, iris scan). (4) Somewhere you are: Geolocation, IP address (supplementary). Multi-Factor Authentication (MFA): Combines 2+ methods from different categories (password + TOTP = strong authentication). Examples: Login with username/password proves you are '[email protected]', OAuth login with Google proves you own that Google account, mTLS certificate proves server identity. OWASP category: Identification and Authentication Failures (A07:2021) - broken authentication. Authorization (A01:2021): Verifying permissions - answering 'WHAT can you do?'. Happens AFTER authentication. Access control models: (1) Role-Based Access Control (RBAC): User assigned roles (admin, editor, viewer), roles have permissions (admin: delete users, editor: edit content, viewer: read only). Example: User 'alice' has role 'admin' → can access /admin/users endpoint. (2) Attribute-Based Access Control (ABAC): Permissions based on attributes (user department, resource owner, time of day, IP address). Example: Allow access if user.department == resource.department AND time >= 9am AND time <= 5pm. (3) Access Control Lists (ACL): Permissions attached to each resource. Example: Document 'report.pdf' allows ['alice', 'bob'] to read, ['alice'] to write. (4) Permission-based: Granular permissions (users.create, users.delete, posts.publish). Example: User has permission 'posts.publish' → can publish blog posts. OWASP category: Broken Access Control (A01:2021) - #1 risk, affects 94% of applications. Critical differences: Authentication: Happens ONCE at login (establishes session). Authorization: Checked on EVERY request (continuous verification). Authentication: Binary (you are authenticated or not). Authorization: Granular (different permissions for different resources). Common vulnerabilities: (1) Insecure Direct Object References (IDOR): Authenticated user accesses other users' data by changing ID. Example: GET /api/users/123/profile (attacker changes 123 to 456, accesses victim's profile). Broken authorization - no check if user 123 can access user 456's data. (2) Privilege escalation: Regular user accesses admin functionality. Example: POST /api/admin/delete-user (no check if user has admin role). (3) Missing function-level access control: Admin-only function exposed to all authenticated users. (4) Horizontal privilege escalation: User A accesses User B's resources (same privilege level). (5) Vertical privilege escalation: Regular user gains admin privileges. Best practices (2025): (1) Authenticate first, authorize every request: Never skip authorization checks after authentication. (2) Deny by default: Explicitly allow access, reject everything else. (3) Never trust client-side checks: Validate permissions server-side (client can be manipulated). (4) Use centralized authorization: Single point of enforcement (middleware, decorators, filters). Example: Express.js: requireAuth middleware (authentication), requireRole('admin') middleware (authorization). (5) Principle of least privilege: Grant minimum necessary permissions. (6) Separation of duties: Critical actions require multiple approvers. Framework implementations: Spring Security: @PreAuthorize('hasRole(ADMIN)'), Django: @login_required (auth), @permission_required('app.delete_user') (authz), ASP.NET Core: [Authorize(Roles = 'Admin')], Node.js Passport: passport.authenticate() (auth) + custom middleware (authz). Real-world examples: Facebook Cambridge Analytica (authorization failure - apps accessed excessive user data), Uber 2016 breach (authentication failure - stolen credentials), Capital One 2019 (authorization failure - SSRF + overprivileged IAM role). Testing: Authentication: Test credential validation, MFA bypass, session fixation, brute force. Authorization: Test IDOR, privilege escalation, missing access controls, horizontal/vertical access violations. Compliance: Authentication (A07:2021), Authorization (A01:2021), PCI-DSS (6.5.8 - access control, 8.x - authentication), SOC 2 CC6.1 (logical access controls).
A01 Broken Access Control (remains #1, 3.73% average detection rate across 40 CWEs), A02 Cryptographic Failures, A03 Software Supply Chain Failures (NEW - expands 2021's Vulnerable Components, covers dependencies, build systems, distribution), A04 Injection (includes SQL, NoSQL, OS command, XPath, ORM injection), A05 Insecure Design, A06 Security Misconfiguration, A07 Identification and Authentication Failures, A08 Software and Data Integrity Failures, A09 Security Logging and Monitoring Failures, A10 Mishandling of Exceptional Conditions (NEW - 24 CWEs for error handling, failing open, logical errors). OWASP Top 10:2025 RC1 released Nov 6, 2025, analyzing 2.8M+ applications across 589 CWEs (vs 400 in 2021). Final version expected 2026.
X-Frame-Options: HTTP response header controlling whether browser allows page to be displayed in ,
TLS 1.3 (RFC 8446, finalized 2018) is latest Transport Layer Security protocol. Key improvements over TLS 1.2: (1) Performance - 1-RTT handshake vs 2-RTT (faster connection), 0-RTT resumption for repeat connections (lowest latency). (2) Security - Removed compromised/weak algorithms (RSA key exchange vulnerable to ROBOT attack, CBC mode vulnerable to Lucky13/BEAST/padding oracle, SHA-1, MD5, RC4, DES, 3DES all deprecated), simplified to 5 recommended cipher suites vs dozens in TLS 1.2, uses only Authenticated Encryption with Additional Data (AEAD) - no block ciphers, mandatory Perfect Forward Secrecy (ephemeral keys - DHE/ECDHE required). (3) Privacy - Encrypts more handshake metadata (improved against traffic analysis). NIST mandated TLS 1.3 support for US government systems starting Jan 1, 2024. Critical 2025 update: TLS 1.2 NOT deprecated BUT weak cipher suites being removed (CBC-based like AES_128_CBC, AES_256_CBC dropped by major platforms Nov 2025-Jan 2026). Best practice: Prefer TLS 1.3 exclusively, support TLS 1.2 with GCM-based cipher suites only for legacy compatibility, disable TLS 1.0/1.1 (deprecated RFC 8996). Use Mozilla SSL Configuration Generator for current recommendations.
Insecure Design (A04:2021): New OWASP category distinguishing fundamental design/architectural flaws from implementation bugs - perfect code cannot fix bad design. Key distinction: Missing or ineffective security controls at design phase, not coding errors. Real-world examples: (1) No rate limiting: Authentication endpoint allows unlimited login attempts → credential stuffing succeeds (should design 5 attempts/15 min lockout). (2) Business logic flaws: E-commerce allows negative quantity in cart → refund attack (should validate quantity > 0 at design level). (3) Insufficient tenant separation: Multi-tenant SaaS uses WHERE tenant_id filter in queries → developer forgets filter = data leak (should design database-per-tenant or row-level security). (4) Missing threat modeling: Banking app designed without considering account takeover scenarios. Prevention (shift-left security): (1) Threat modeling: Use STRIDE framework during design (Spoofing, Tampering, Repudiation, Information Disclosure, DoS, Elevation of Privilege). (2) Secure design patterns: OWASP SAMM (Software Assurance Maturity Model), NIST Secure Software Development Framework. (3) Security requirements in user stories: 'As admin, I want rate limiting (max 100 req/min per IP) on all public APIs'. (4) Reference architectures: Cloud provider security blueprints (AWS Well-Architected, Azure Security Benchmark). (5) Paved road approach: Secure-by-default libraries, pre-approved patterns, security guardrails. (6) Security champions: Embed security expertise in development teams. Critical insight: Design flaws cannot be patched - require architectural changes. A04:2021 appeared due to industry shift toward DevSecOps and recognizing design > implementation.
Argon2id is first choice (winner of 2015 Password Hashing Competition, gold standard for 2025 - OWASP recommends minimum 19 MiB memory, 2 iterations, 1 degree parallelism). scrypt as fallback when Argon2id unavailable (minimum CPU/memory cost 2^17, block size 8, parallelization 1). bcrypt only for legacy systems where Argon2/scrypt unavailable (work factor minimum 10, ideally 12+, password limit 72 bytes). PBKDF2 for FIPS-140 compliance requirements only (600,000+ iterations with HMAC-SHA-256). Never use MD5, SHA1, SHA-256, DES, or 3DES for passwords (broken/deprecated). Modern algorithms (Argon2id, bcrypt, PBKDF2) automatically salt passwords - no additional salting required. Security consensus 2025: Argon2 provides unparalleled protection against GPU/ASIC cracking, brute force, rainbow tables.
API Rate Limiting (OWASP API4:2023 - Unrestricted Resource Consumption): Prevents brute force, DoS, credential stuffing, resource exhaustion. Essential for: Authentication endpoints (/login, /reset-password), public APIs, resource-intensive operations. Implementation strategies: (1) Per-user limits: Authenticated requests - track by user ID (100 req/min per user). (2) Per-IP limits: Anonymous requests - track by IP address (20 req/min per IP, watch for distributed attacks). (3) Per-API-key limits: Third-party integrations - track by API key (1000 req/hour per key). (4) Endpoint-specific limits: /login: 5 attempts/15 min (strict), /api/data: 100 req/min (lenient), /search: 20 req/min (moderate). HTTP response (429 Too Many Requests): Headers: X-RateLimit-Limit: 100 (total allowed), X-RateLimit-Remaining: 45 (requests left), X-RateLimit-Reset: 1704974400 (Unix timestamp when limit resets), Retry-After: 60 (seconds until retry allowed). Body: {error: 'rate_limit_exceeded', message: 'Too many requests, retry after 60 seconds', retry_after: 60}. Rate limiting algorithms (2025): (1) Token Bucket (most common): Bucket holds tokens (capacity = limit), each request consumes 1 token, refills at constant rate (e.g., 10 tokens/sec), allows bursts up to bucket capacity. Redis: INCR + EXPIRE, libraries: express-rate-limit, Flask-Limiter. (2) Leaky Bucket: Requests enter queue, processed at steady rate, excess requests dropped, smooths traffic (no bursts). (3) Fixed Window: Count requests per time window (00:00-00:59), resets at window boundary, vulnerable to burst at window edge. (4) Sliding Window Log: Track timestamp of each request, count requests in last N seconds, accurate but memory-intensive. (5) Sliding Window Counter: Hybrid approach - weighted count from current + previous window, balances accuracy and efficiency. Production implementation (2025): Express.js: express-rate-limit with Redis store, Django: django-ratelimit with cache backend, nginx: limit_req_zone, Kong API Gateway: rate-limiting plugin, AWS API Gateway: throttling settings (burst 5000, steady 10000 req/sec), Cloudflare: rate limiting rules (100k req/month free tier). Advanced protections: (1) CAPTCHA integration: Trigger reCAPTCHA after 3 failed login attempts within 5 min. (2) Distributed attack detection: Monitor for coordinated attacks across multiple IPs (>1000 IPs hitting same endpoint). (3) Adaptive rate limiting: Reduce limits during incidents, increase for trusted users. (4) Authentication vs anonymous: Authenticated: 1000 req/hour, Anonymous: 100 req/hour. Monitoring: Track 429 responses, identify legitimate users hitting limits, adjust thresholds based on usage patterns. Compliance: PCI-DSS (6.2 - rate limiting for authentication), OWASP API Security Top 10 (API4:2023), CWE-770 (Allocation of Resources Without Limits).
Injection (A03:2021): 94% of applications tested have injection vulnerabilities - 33 CWEs mapped to this category (most of any OWASP Top 10 risk). Types beyond SQL Injection: (1) NoSQL Injection: MongoDB, CouchDB, Redis injection via unvalidated queries. Example: db.users.find({username: req.body.username}) with body {username: {$ne: null}} → bypasses authentication. Prevention: Use query builders, validate input types, avoid string concatenation in queries. (2) OS Command Injection (CWE-78): Shell commands with unsanitized user input. Example: exec('ping ' + req.query.host) with host=8.8.8.8; rm -rf / → arbitrary command execution. Prevention: Avoid shell commands, use language APIs (Node.js dns.resolve vs ping), input validation, least privilege execution. (3) LDAP Injection: Manipulating LDAP queries. Example: (uid=userInput) with input=)(uid=))(|(uid=* → returns all users. Prevention: Escape LDAP special chars (, (, ), , /, NULL), use parameterized LDAP APIs. (4) XPath Injection: XML query manipulation. Example: //users/user[username='input'] with input=' or '1'='1 → authentication bypass. Prevention: Parameterized XPath queries, input validation, use XPath variables. (5) Expression Language (EL) Injection: Template engines (Freemarker, Velocity, Thymeleaf). Example: ${user.name} with name=${77} → code execution. Prevention: Disable expression evaluation on user input, sandboxing, use safe template modes. (6) Server-Side Template Injection (SSTI): Flask/Jinja2, Django templates. Example: render_template_string(request.args.get('name')) with name={{config}} → leak secrets. Prevention: Never render user input as templates, use template sandboxes. (7) ORM Injection: Bypassing parameterization in ORMs. Example: User.where('email = ' + params[:email]) (Ruby on Rails) → SQL injection. Prevention: Use ORM query builders (User.where(email: params[:email])), never string interpolation. (8) Log Injection (CWE-117): Injecting newlines/ANSI codes into logs. Example: logger.info('User login: ' + username) with username=admin
[CRITICAL] Fake log entry → log forgery. Prevention: Remove newlines/ANSI escape codes, structured logging (JSON). Universal prevention (2025 best practices): (1) Parameterized queries/APIs: Always use prepared statements, never concatenate user input into commands/queries. (2) Allow-list validation: Define allowed characters/patterns (alphanumeric only for IDs), reject anything outside allowlist. (3) Escape special characters: Context-specific escaping (SQL: ', HTML: <>, Shell: ;|&). (4) Least privilege: Database user cannot drop tables, application cannot execute shell commands, limited file system access. (5) Input validation: Type checking (expect integer, reject string), length limits, format validation (email, UUID). (6) Framework protections: Django ORM (auto-parameterized), Hibernate (HQL parameters), sqlalchemy (bound parameters). Testing: OWASP ZAP (injection scanner), Burp Suite Intruder, sqlmap (SQL/NoSQL), commix (command injection). Compliance: OWASP Top 10 A03:2021, CWE-78 (OS Command), CWE-90 (LDAP), CWE-643 (XPath), CWE-917 (Expression Language), PCI-DSS 6.5.1.
CSP is HTTP header providing allowlist-based control over resource loading to defend against Cross-Site Scripting (XSS) attacks. OWASP 2025 recommends Strict CSP using nonces or hashes. Nonce-based (server-rendered pages): Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'. Hash-based (static pages, SPAs): Content-Security-Policy: script-src 'sha256-{HASH}' 'strict-dynamic'; object-src 'none'; base-uri 'none'. strict-dynamic allows nonce/hash-verified scripts to load additional scripts without explicit allowlisting. Critical: Use cryptographically secure random token for nonces (unique per HTTP response), never use unsafe-inline in production. Framework protections + output encoding + CSP provide defense-in-depth. DOMPurify recommended for HTML sanitization. CSP Level 3 supported in modern browsers (2025).
Strict: Cookies sent only in same-site requests (never in cross-site contexts including top-level navigation) - strongest CSRF protection but may break user experience (clicking email link loses session). Lax: Default in Chrome/Edge/Opera as of Dec 2024 (Firefox/Safari still no default) - cookies sent in same-site requests AND top-level GET navigation (link clicks, not POST forms) - balanced CSRF protection. None: Cookies sent in all cross-site requests - requires Secure attribute (HTTPS mandatory), effectively disables SameSite restrictions - use only for embedded content, OAuth, third-party integrations. SameSite provides partial CSRF/cross-site leak protection by controlling cookie transmission. Critical 2025 limitation: CANNOT protect against cross-origin same-site attacks (subdomain takeover, XSS on sibling subdomain bypass SameSite). OWASP recommendation: SameSite is defense-in-depth NOT replacement for CSRF tokens. Best practice: Use SameSite=Strict/Lax + traditional CSRF tokens for layered security.
Essential HTTP security headers (2025 OWASP recommendations): (1) Strict-Transport-Security (HSTS): Force HTTPS connections. Header: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload. Prevents SSL stripping, protocol downgrade attacks. Preload list: hstspreload.org (hardcoded in browsers). (2) Content-Security-Policy (CSP): Control resource loading, primary XSS defense. Example: Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; object-src 'none'; base-uri 'self'. Use nonces for inline scripts (script-src 'nonce-abc123'), report-uri for violation reporting. CSP Level 3 supported in modern browsers (2025). (3) X-Content-Type-Options: Prevent MIME type sniffing. Header: X-Content-Type-Options: nosniff. Blocks browser from interpreting text/plain as text/html (XSS vector). Mandatory for all responses. (4) X-Frame-Options / CSP frame-ancestors: Clickjacking protection. Modern: Content-Security-Policy: frame-ancestors 'self', Legacy: X-Frame-Options: SAMEORIGIN. CSP takes precedence if both present. (5) Referrer-Policy: Control referrer information leakage. Recommended: Referrer-Policy: strict-origin-when-cross-origin (send origin only on HTTPS→HTTP downgrade, full path for same-origin). Alternatives: no-referrer (strictest), same-origin. Prevents token/session ID leakage in URLs. (6) Permissions-Policy: Control browser features (formerly Feature-Policy). Example: Permissions-Policy: geolocation=(), microphone=(), camera=(). Disable unnecessary APIs (prevent malicious iframe access). (7) Set-Cookie attributes: Secure (HTTPS only), HttpOnly (no JavaScript access), SameSite=Strict or Lax (CSRF protection). Cookie prefixes: __Host- (most restrictive), __Secure-. (8) Cache-Control for sensitive pages: Cache-Control: no-store, private (prevent caching of PII/financial data). Pragma: no-cache for HTTP/1.0 compatibility. Deprecated/removed headers (do NOT use): (1) X-XSS-Protection: Deprecated due to bypasses, creates vulnerabilities. Use CSP instead. (2) Public-Key-Pins (HPKP): Deprecated 2020, too risky (self-DoS if misconfigured). Framework implementations (2025): Express.js: helmet() middleware (sets 11 headers automatically), Django: django-csp + SecurityMiddleware, ASP.NET Core: built-in security headers middleware, Spring Boot: SecurityHeadersConfigurer, nginx: add_header directives. Testing tools: SecurityHeaders.com (A+ grade requires all essential headers), Mozilla Observatory, OWASP ZAP. Security scoring: A+ rating requires HSTS preload + CSP + all essential headers. Real-world stats: Only 15% of top 10k websites have proper CSP (2024 study). Compliance: OWASP Top 10 A05:2021 (Security Misconfiguration), PCI-DSS 6.5.10 (security controls), SOC 2 CC6.1 (logical access).
HSTS header forces browsers to access site exclusively via HTTPS, automatically upgrades HTTP requests to HTTPS for specified duration. OWASP 2025 recommended configuration: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload (2 years). Minimum production: max-age=31536000 (1 year). Staging approach for new deployments: start max-age=300 (5 min), then 604800 (1 week), 2592000 (1 month), finally 63072000 (2 years) - verify no breakage before increasing. includeSubDomains: Applies policy to all subdomains (critical for comprehensive protection). preload: Eligible for browser preload list (PERMANENT - requires 1 year minimum max-age, cannot easily undo). Protections: protocol downgrade attacks, SSL stripping, cookie hijacking, man-in-the-middle. Critical: Header MUST be served over HTTPS only (browsers ignore if sent via HTTP). Browsers cache policy for max-age duration. Preload list: hstspreload.org (hardcoded in Chrome, Firefox, Safari, Edge).
Clickjacking (UI Redressing Attack): Attacker overlays transparent iframe of target site on top of decoy site → user thinks they're clicking 'Win Prize' but actually clicking 'Delete Account' or 'Transfer Money'. Attack mechanics: (1) Embed target in
Security Logging and Monitoring Failures (A09:2021): Insufficient visibility allows breaches to persist undetected - average 200+ days (IBM Security 2024). Common failures: (1) Critical events not logged: Failed logins, privilege changes, high-value transactions (>$10k), data exports, admin actions. (2) Inadequate log quality: No user context (IP, session ID, user agent), timestamps not UTC, logs lack correlation IDs. (3) Logs not monitored: Written to disk but never reviewed, no alerting on suspicious patterns. (4) Local-only storage: Logs on compromised server → attacker deletes evidence. (5) No alerting thresholds: 100 failed logins in 5 minutes doesn't trigger alert. (6) Security tools ignored: DAST scans, pentests don't trigger alerts → organization unaware of attacks. Prevention (2025 best practices): (1) Log critical events: All logins (success/failure), authorization failures, input validation failures, privilege escalations, data access (PII, financial), admin actions, API calls (rate limit hits). (2) Structured logging: JSON format with timestamp (ISO 8601 UTC), correlation ID, user ID, IP, action, result, context. Example: {time: '2025-01-15T14:30:00Z', user: 'user@example.com', action: 'login_failed', ip: '203.0.113.1', reason: 'invalid_password'}. (3) Centralized log management: ELK Stack (Elasticsearch, Logstash, Kibana), Splunk, Datadog, AWS CloudWatch, Azure Monitor, Google Cloud Logging. (4) Integrity controls: Write-once storage (S3 Object Lock, immutable volumes), tamper-evident logs (cryptographic hashing). (5) Real-time alerting: SIEM (Security Information and Event Management) - Splunk, Elastic Security, Microsoft Sentinel. Alert on: 5+ failed logins in 5 min, privilege escalation, unusual data export, SQL injection patterns. (6) Incident response plan: NIST 800-61r3 framework - preparation, detection, containment, eradication, recovery, lessons learned. (7) Compliance: PCI-DSS (10.2 - log all user activity), SOC 2 (monitoring controls), GDPR (Article 33 - breach notification within 72 hours). Real-world impact: Equifax breach undetected for 76 days, Target breach detected by external party after 40 days.
XSS is injection attack where malicious scripts execute in victim's browser. Three types: Stored (persistent in database, highest impact), Reflected (in URL/request parameters), DOM-based (client-side JavaScript manipulation, never touches server). OWASP 2025 prevention hierarchy: (1) Framework Security - Use modern frameworks with auto-escaping (React JSX, Vue templates, Angular - avoid dangerouslySetInnerHTML/bypassSecurityTrustHtml without DOMPurify). (2) Output Encoding - Context-specific encoding critical (HTML entity encoding for HTML context, JavaScript encoding for