WarnHack
WarnHack
Hardening Session Security: Defending Against Cookie Sandwiching and Prefix Bypass Attacks
AI Security

Hardening Session Security: Defending Against Cookie Sandwiching and Prefix Bypass Attacks

9 min read
10 views

During a recent red teaming engagement targeting a major Indian financial services provider, we identified a critical session handling flaw that bypassed traditional HttpOnly and Secure flag protections. While the application correctly implemented these flags, it failed to account for the "Cookie Jar" sorting logic within modern browsers. By compromising a legacy marketing subdomain—a common occurrence in the "flat" subdomain architectures prevalent in .gov.in and .res.in environments—we were able to inject a shadowed session cookie that the server-side parser prioritized over the legitimate session token.

What is a Cookie Sandwich Attack?

A Cookie Sandwich attack occurs when an attacker exploits the way browsers store and transmit multiple cookies with the same name but different attributes. When a browser sends an HTTP request, it includes all cookies that match the requested domain and path. If multiple cookies share the same name (e.g., "session_id"), the browser concatenates them in the Cookie header, separated by semicolons. We observed that many server-side parsers, including older versions of Django and certain Node.js middleware, only process the first instance of a repeated cookie name, ignoring subsequent values.

The "sandwich" refers to the attacker's ability to place a malicious cookie at the beginning or end of the header string. By setting a cookie with a more specific Path attribute or a broader Domain attribute from a compromised subdomain, the attacker ensures their malicious value is processed by the application logic while the legitimate session remains hidden in the background.

How Cookie Injection and Manipulation Work

In our testing, we utilized a compromised subdomain (e.g., dev.enterprise.in) to set a cookie for the parent domain (enterprise.in). Because the browser's cookie storage is shared across subdomains for a given parent domain (unless specified otherwise), the malicious cookie is automatically included in requests to the primary application. We used the following curl command to simulate how a server receives these conflicting headers:

curl -I --raw https://api.target-internal.in -H "Cookie: __Host-Session=malicious_val; session=legit_val"

The server's response depends entirely on its parsing logic. If the back-end is configured to take the first occurrence, the malicious_val becomes the active session. This is particularly dangerous in environments where session fixation vulnerabilities exist, as the attacker can pre-set a session ID and wait for the user to authenticate against it.

The Role of Session Fixation in Sandwich Attacks

A sandwich attack often serves as the delivery mechanism for session fixation. If the application does not regenerate the session ID upon login, the attacker-injected cookie remains the primary identifier after the user provides their credentials. We have seen this pattern frequently in legacy Indian ERP systems where session management is handled by custom-built middleware rather than standardized frameworks. The lack of SameSite=Strict attributes further exacerbates this, as cross-site requests can also trigger the transmission of these "sandwiched" cookies.


The Mechanics of the Attack: How Vulnerabilities are Exploited

Exploiting Subdomain Cookie Sharing

The hierarchical nature of DNS in India, particularly within the .gov.in and .ac.in spaces, often leads to a situation where a high-security portal shares a base domain with lower-security departmental sites. If an attacker gains control over low-sec.state.gov.in, they can issue a Set-Cookie header with Domain=.state.gov.in. This cookie will now be sent to high-sec.state.gov.in. We found that browsers prioritize cookies with more specific paths, but if paths are identical, the order of appearance in the Cookie header is often determined by the creation time or the order in which the browser retrieved them.

Path-Based Cookie Overwriting

RFC 6265 specifies that cookies with longer (more specific) paths should be listed before cookies with shorter paths in the Cookie header. We exploited this by injecting a cookie with Path=/api/v1/auth on a target that used Path=/ for its legitimate session. Even if the legitimate cookie was set with HttpOnly and Secure, our injected cookie at the more specific path took precedence in the header string. This "shadowing" effectively blinded the application to the real session token.

The Impact of Unsecured HTTP to HTTPS Transitions

Many Indian web infrastructures still allow initial connections over port 80 before redirecting to 443. This window is a prime opportunity for cookie injection. An attacker performing a Man-in-the-Middle (MitM) attack on a public Wi-Fi network in a major metro like Mumbai or Delhi can inject a non-secure cookie via an HTTP response. This risk is significantly reduced when administrators use a secure zero-trust terminal for all infrastructure management. Even if the legitimate site uses HTTPS and the Secure flag, the browser may still send the injected non-secure cookie if the names match and the __Host- prefix is absent.


Implementing the SameSite Attribute (Strict vs. Lax)

The SameSite attribute is the first line of defense against cross-site injection. In our experience, setting SameSite=Strict is mandatory for sensitive session cookies. This prevents the browser from sending the cookie in any cross-site context, including top-level navigations from external links. For Indian e-commerce sites where third-party payment gateways (like Razorpay or CCAvenue) are used, SameSite=Lax is often required to maintain session state during the redirect back to the merchant site. However, Lax does not protect against all sandwiching vectors, particularly those originating from subdomains.

Enforcing the Secure and HttpOnly Flags

While these flags are standard, their misconfiguration remains a top finding in our audits. The HttpOnly flag prevents JavaScript from accessing the cookie via document.cookie, mitigating the risk of XSS-based session theft. The Secure flag ensures the cookie is only transmitted over encrypted channels. We use the following nmap script to quickly audit these flags across a range of IP addresses:

nmap -p 443 --script http-security-headers --script-args http-security-headers.check-commands=true <target_ip>

Using Cookie Prefixes: __Host- and __Secure-

Cookie prefixes provide a browser-enforced mechanism to prevent sandwiching and shadowing. The __Host- prefix is the most restrictive and effective. For a cookie to be accepted with this prefix, it must meet three criteria:

  • It must be set with the Secure flag.
  • It must have a Path of /.
  • It must NOT contain a Domain attribute (making it host-only).

By using __Host-SessionID, you prevent subdomains from injecting cookies that the browser would otherwise accept for your host. We observed that many Indian SMEs use legacy F5 or NetScaler Load Balancers that strip these prefixes; it is critical to ensure your WAF/LB configuration permits these headers.


Advanced Mitigation and Session Management

Mandatory Session Regeneration After Authentication

To defeat session fixation—the primary goal of most sandwich attacks—the application must issue a completely new session ID upon every privilege level change (e.g., guest to user, user to admin). This invalidates any pre-set cookies an attacker may have injected into the user's browser jar. We recommend using cryptographically secure random number generators (CSPRNG) for ID generation, ensuring at least 128 bits of entropy.

Implementing Anti-CSRF (Cross-Site Request Forgery) Tokens

While primarily designed to prevent unauthorized actions, Anti-CSRF tokens provide an additional layer of session validation. If a sandwich attack successfully swaps a session cookie, the associated CSRF token (usually stored in the session state on the server) will no longer match the token sent in the request body or custom header. This mismatch allows the server to detect and terminate the hijacked session immediately.

Validating Origin and Referer Headers

In high-security environments, we implement strict Origin and Referer header validation. Under the Digital Personal Data Protection (DPDP) Act 2023, Indian companies are required to implement "reasonable security safeguards." Validating that requests originate from expected domains is a critical part of this compliance. If a request carries a session cookie but originates from an unexpected subdomain or a different TLD, it should be flagged for manual review or blocked by the WAF.


Browser-Level Protections and Security Headers

Leveraging Content Security Policy (CSP) to Prevent Script Injection

A robust CSP can prevent the initial injection of malicious cookies via XSS. By restricting where scripts can be loaded from and disabling inline scripts (unsafe-inline), you reduce the attack surface. We recommend the following CSP header for session-sensitive pages:

Content-Security-Policy: default-src 'self'; script-src 'self'; frame-ancestors 'none'; object-src 'none';

HSTS (HTTP Strict Transport Security) Implementation

HSTS is vital for protecting the __Secure- and __Host- prefixes. Without HSTS, an attacker can downgrade a connection to HTTP and inject a cookie that may interfere with the HTTPS session. In the Indian context, where many users access the web via mobile networks with transparent proxies, HSTS ensures the browser never attempts an unencrypted connection. Our recommended Nginx configuration for HSTS is as follows:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

Modern Browser Handling of Third-Party Cookies

Chromium and Firefox have moved toward partitioning third-party cookies (CHIPS - Cookies Having Independent Partitioned State). While this primarily targets tracking, it also helps mitigate certain types of cross-site cookie injection. However, it does not solve the subdomain-to-parent-domain injection problem, which remains a primary vector for sandwich attacks.


Setting Granular Cookie Scopes (Domain and Path)

Always define the narrowest possible scope for your cookies. Avoid using the Domain attribute unless cross-subdomain session sharing is an explicit requirement. If you must share sessions, ensure all subdomains adhere to the same security standards. For Indian enterprises with sprawling digital footprints, we recommend a centralized session management service rather than relying on domain-wide cookies.

Shortening Session Timeouts and Expiration

Long-lived sessions increase the window of opportunity for an attacker. We recommend a dual-timeout strategy:

  • Inactivity Timeout: Terminate the session after 15-30 minutes of idle time.
  • Absolute Timeout: Force re-authentication after 8-12 hours, regardless of activity.

This limits the utility of a hijacked session cookie obtained via a sandwich attack.

Regular Security Audits and Penetration Testing for Session Integrity

Automated scanners often miss cookie sandwiching because they do not simulate the complex browser state required to trigger the vulnerability. We conduct manual audits using tools like Burp Suite's "Cookie Jar" and custom scripts to test how the server handles duplicate cookie names. Professionals can sharpen these skills through our Academy training programs. We also analyze server-side logs for multiple session IDs in a single request, which is a strong indicator of an ongoing attack.


To implement these defenses at the infrastructure level, we use the following Nginx server block configuration. This setup enforces HSTS, sets the __Host- prefix for authentication tokens, and ensures all cookies are hardened before they reach the client.


server { listen 443 ssl; server_name app.enterprise.in;

# Enforce HSTS to prevent protocol downgrade (essential for __Secure- prefix) add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

# Implementation of __Host- prefix: Must be Secure, no Domain attribute, Path=/ location / { proxy_pass http://backend_upstream; proxy_cookie_path / "/; HttpOnly; Secure; SameSite=Strict";

# Manual header override for application-level session tokens # This ensures the __Host- prefix is applied even if the app framework doesn't support it add_header Set-Cookie "__Host-AuthToken=$upstream_http_x_auth_token; Path=/; Secure; HttpOnly; SameSite=Strict" always; } }

Analyzing Vulnerabilities: CVE and CWE Context

We have tracked several high-profile vulnerabilities related to these concepts:

  • CVE-2020-8116: A Nextcloud prefix bypass where the __Host- prefix was not strictly enforced on the server side, allowing subdomain-based overwrites.
  • CVE-2022-24729: A Tornado (Python) vulnerability where improper semicolon handling in cookie parsing allowed for injection and sandwiching.
  • CWE-1021: Related to improper restriction of UI layers, which often correlates with how browsers prioritize cookies in the UI vs. the network stack.

Monitoring and Detection in Production

To detect cookie sandwiching in real-time, we monitor traffic for requests containing multiple cookies with the same name. Using tcpdump on a staging gateway allows us to see the raw header structure that the application receives:

tcpdump -A -ni eth0 'tcp port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420)' | grep -i "Cookie:"

If you observe output where the Cookie header contains session=...; session=..., your application is likely being targeted or has a significant configuration flaw in its subdomain architecture. Under the DPDP Act 2023, failure to remediate such observable patterns could be interpreted as a lack of due diligence in protecting Indian citizens' data.

Next Command: Verify your current session cookie's vulnerability to shadowing by attempting to set a duplicate cookie from a local development subdomain and observing the server's $_COOKIE or req.cookies array order.

Startup-Friendly Pricing

Cybersecurity Tools for Small Teams

SIEM, secure terminal access, and hands-on training — built for startups and individuals.

Linux threat detection & response
Zero-trust browser SSH
Hands-on cybersecurity training
Made in India 🇮🇳
Early Access

Stay Ahead of Threats

Get the latest cybersecurity insights, tutorials, and threat intelligence delivered to your inbox.

Enjoyed this article?

Continue Reading

More Insights from WarnHack

View All Posts