Cookies in Tech world…

Yes we are going to talk about cookies used in computers and not of cookies in bakery :)

Pratham Mittal
12 min readJul 7, 2023

What are cookies?

Cookies are small pieces of data stored on a user’s computer by websites they visit. They play a crucial role in enhancing the functionality and efficiency of stateless protocols like HTTP/HTTPS. Here’s a detailed explanation of cookies and their significance.

Cookies are primarily used to track and maintain stateful information between a web server and a client’s web browser. They enable websites to remember specific user preferences, login sessions, shopping cart items, and other relevant data.

HTTP is inherently stateless protocol, meaning that it doesn’t retain information about previous requests. However, cookies provide a mechanism to maintain stateful interactions. By storing relevant data on the client side and sending it with each request, cookies enable stateful behavior within the stateless HTTP protocol.

When a user visits a website, the server can send a “Set-Cookie” header in the HTTP response as shown below (pardon for the mess i created in hiding cookies value). This header contains a unique identifier (cookie name) and a value associated with it. The web browser then stores this information as a cookie on the user’s device/browser.

Cookies set by Web server
Cookies stored in user’s browser

But yes, cookies are used for various purposes by web servers and not only to maintain HTTP’s stateless behaviour.

Various types/purposes of cookies.

1.Session cookies, also known as ‘temporary cookies’, are used by websites in recognising users and the information provided when they navigate through a website. Session cookies only retain information about a user’s activities for as long as they are on the website. Once the web browser is closed or user logs out, the cookies are deleted from user’s browser. These are commonly used on shopping websites/e-commerce websites.

2. Permanent cookies, also known as ‘persistent cookies’, remains with user even after the web browser is closed or user logs out so web users don’t need to re-enter credentials every time they use a site. The law states that permanent cookies must be deleted after 12 months (1 year) as permanent cookies can lead to various attack surfaces for attackers which we will discuss afterwards.

Permanent cookies have an expiration date set by the server, and they remain on the user’s device until that expiration date is reached or until manually cleared by the user or browser settings. They are commonly used to remember user preferences, customisation settings, or persistent identifiers for tracking purposes.

NOTE: Never use Permanent cookies to maintain user’s session and moreover in Fintech/Banking applications session cookies expire after 10–20 minutes and not more than that and user is prompted to log in again after expiry time of session cookie.

3. First-party cookies are installed directly by the website (ie domain) the user is visiting (ie the URL shown in the browser’s address bar). These cookies enable website owners to collect analytics data, remember language settings, and perform other useful functions so as to provide a good user experience.

4. Third-party cookies are installed by third parties with the aim of collecting certain information from web users to carry out research into, for example, behaviour, demographics or spending habits, likes/dislikes etc. They are commonly used by advertisers who want to ensure that products and services are marketed towards the right target audience.

If you might have surprised how Instagram/Facebook advertisements shown you the same dress/shoes/hotel/destination etc. that you searched some time ago on Myntra/MakeMyTrip/Nike then Third-party cookies is your answer. Taking example of Myntra & Instagram to explain in details (Just taking example, no purpose to promote any of them)

In the context of Myntra wanting to show advertisements on Instagram using third-party cookies, here’s an overview of the process:

a) User Interaction: A user visits the Myntra website and interacts with it, such as browsing products, adding items to their cart, or making purchases etc.

b) Setting Third-Party Cookies: While the user is on the Myntra website, Myntra may utilize third-party advertising partners or tracking providers such as Instagram. These partners can set third-party cookies on the user’s browser, storing information related to the user’s interaction with Myntra.

c) Advertiser Integration: Myntra integrates with advertising platforms like Instagram, which allow advertisers to display targeted ads to users. Myntra establishes a partnership or advertising agreement with Instagram to facilitate this.

d) Sharing Data via Cookies: Myntra, as part of its advertising agreement with Instagram, may share certain information stored in the third-party cookies with Instagram. This data could include details about the user’s browsing history, preferences, or items they have shown interest in on the Myntra website.

e) Instagram Ad Targeting: Based on the data shared by Myntra, Instagram can leverage this information to target ads to the user. Instagram’s advertising algorithms and targeting mechanisms analyse the user’s interests and preferences to display relevant ads from Myntra on the user’s Instagram feed or in other advertising spaces.

f) User Experience: As the user continues to browse Instagram, they may encounter ads from Myntra that align with their previous interactions on the Myntra website. These ads can be personalised and tailored based on the shared information.

It’s important to note that cookie usage and third-party tracking practices are subject to privacy regulations and user consent requirements in different jurisdictions. Users typically have control over cookie settings and can manage their preferences regarding third-party tracking and personalised ads through browser settings or specific platform settings.

Additionally, both Myntra and Instagram are responsible for adhering to applicable privacy policies and ensuring that user data is handled securely and in compliance with relevant regulations.

5. Flash cookies, also known as ‘super cookies’, are independent of the web browser. They are designed to be permanently stored on a user’s computer. These types of cookies remain on a user’s device even after all cookies have been deleted from their web browser.

6. Zombie cookies are a type of flash cookie that is automatically re-created after a user has deleted them. This means they are difficult to detect or manage. They are often used in online games to prevent users from cheating but have also been used to install malicious software onto a user’s device.

Till now, I hope it is cleared what is exactly meant by cookies, why they were introduced and it’s different types. Let’s now see how websites control these cookies’ behaviour and storage.

Cookie attributes/Flags

Cookie attributes/flags are additional settings that can be applied to cookies to specify their behavior, scope, and security. These attributes provide more control over how cookies are stored, transmitted, and accessed. Here are the commonly used cookie attributes:

1.Secure: The “Secure” attribute ensures that the cookie is only transmitted over a secure HTTPS connection. It helps protect sensitive information by preventing the cookie from being sent over an unencrypted connection. If Secure flag is set and website is using http protocol then cookie won’t be sent in the request thus preventing stealing of cookies from MITM (Man in the Middle) attacks.

2. HttpOnly: The “HttpOnly” attribute restricts access to the cookie from client-side scripts (such as JavaScript). This measure helps mitigate cross-site scripting (XSS) attacks by preventing malicious scripts from accessing sensitive cookies.

3. SameSite: The “SameSite” attribute defines the cookie’s same-site policy, which determines if the cookie should be sent in cross-site requests. It helps protect against cross-site request forgery (CSRF) attacks. In the context of SameSite cookie restrictions, a site is defined as the top-level domain (TLD), usually something like .com or .net, plus one additional level of the domain name. This is often referred to as the TLD+1.

When determining whether a request is same-site or not, the URL scheme/protocol is also taken into consideration. This means that a link from http://app.example.com to https://app.example.com is treated as cross-site by most browsers.

The possible values of SameSite attribute can be:

Strict”: The cookie is only sent in requests originating from the same site (including subdomains). It provides the highest level of protection against CSRF attacks.

“Lax”: The cookie is sent in cross-site requests if they result from a top-level navigation (such as clicking a link) or if they are “safe” HTTP methods (GET, HEAD, OPTIONS) and not if the request is initiated by third party site. This is the default behavior of cookie if the attribute is not specified.

“None”: The cookie is sent in all cross-site requests. However, it requires the “Secure” attribute to ensure it is sent only over secure HTTPS connections.

4. Domain: The “Domain” attribute specifies the domain(s) to which the cookie should be sent. By default, cookies are only sent to the exact domain that set them. However, by specifying a domain attribute, cookies can be shared across subdomains or across multiple related domains.

5. Path: The “Path” attribute defines the URL path on the server to which the cookie should be sent. It restricts the cookie’s availability to specific directories or pages within a website.

6. Expires/Max-Age: The “Expires” attribute or “Max-Age” attribute sets an expiration date or time for the cookie. Once the expiration is reached, the browser will delete the cookie. These attributes allow cookies to be persistent (e.g., last for a specific time period) or session-based (e.g., expire when the browser is closed).

These attributes, used individually or in combination, help define the behavior and security of cookies. They offer control over cookie transmission, access restrictions, secure connections, and lifespan. Implementing appropriate cookie attributes enhances privacy, security, and compliance with relevant regulations.

Example Time…

Set-Cookie: TestCookie=Demonstrate; Expires=Wed, 21 Jul 2023 10:00:00 GMT; Max-Age=3600; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Strict

Let’s break down the attributes and their meanings:

Attribute 1. Cookie Name and Value: “TestCookie” is the name of the cookie, and “Demonstrate” is the corresponding value.

Attribute 2 Expires: Specifies the expiration date and time for the cookie. In this example, the cookie will expire on Wednesday, 21st July 2023, at 10:00:00 GMT (2 weeks after this is created as i am writing this on 7 July 2023).

Attribute 3 Max-Age: Indicates the maximum age of the cookie in seconds. Here, the cookie will be valid for 3600 seconds (1 hour) from the time it was set.

NOTE: Max-Age attribute is recommended over the Expires attribute because it provides a simpler and more flexible way to specify cookie expiration. The Max-Age attribute is supported by most modern browsers, whereas the Expires attribute has been gradually phased out. If both attributes are present, the Max-Age attribute takes precedence.

Attribute 4 Domain: Specifies the domain to which the cookie belongs. In this case, the cookie is associated with the domain “example.com” and can be accessed by any subdomains of “example.com” as well (app.example.com).

Attribute 5 Path: Defines the URL path on the server for which the cookie is valid. The cookie will be sent with requests that match this path. In this example, the cookie is valid for all paths under the root (“/”) directory (It will be valid for /users or /admin etc).

NOTE: It is always a good practice to have proper check on path and domain attribute.Consider a website called “example.com” with different subdomains and paths:

Scenario 1: Improper Domain Attribute

  • Cookie: Set-Cookie: TestCookie=exampleValue; Domain=example.com
  • Subdomains: www.example.com, store.example.com, blog.example.com
  • Paths: /home, /store, /blog

In this scenario, the cookie’s Domain attribute is set as “example.com”. As a result:

  • The cookie will be accessible across all subdomains of “example.com” (www.example.com, store.example.com, blog.example.com).
  • The cookie will also be accessible on all paths under each subdomain (/home, /store, /blog).

Impact: If the Domain attribute is not set properly, such as being too broad or not matching the actual domain structure, it can lead to unintended cookie sharing across unrelated subdomains or misinterpretation of the cookie’s intended scope. This can result in unexpected behavior and potential security vulnerabilities.

Scenario 2: Improper Path Attribute

  • Cookie: Set-Cookie: myCookie=exampleValue; Path=/store Domain=example.com
  • Subdomains: www.example.com, store.example.com, blog.example.com
  • Paths: /store

In this scenario, the cookie’s Path attribute is set as “/store”. As a result:

The cookie will only be accessible on the “/store” path.

The cookie will not be accessible on other paths, such as “/home” or “/blog”.

Impact: If the Path attribute is not set properly, such as being too restrictive or not aligned with the intended functionality, it can prevent the cookie from being accessible in the desired context. This can lead to issues like loss of session data, inability to maintain user preferences across different paths, or unnecessary duplication of cookies for different paths.

Attribute 6 Secure: Indicates that the cookie should only be transmitted over a secure HTTPS connection. This attribute ensures that the cookie is sent securely to prevent interception or tampering.

Attribute 7 HttpOnly: Restricts access to the cookie from client-side scripts, such as JavaScript. It helps protect against cross-site scripting (XSS) attacks by preventing malicious scripts from accessing the cookie.

Attribute 8 SameSite: Sets the SameSite policy for the cookie. In this case, the SameSite attribute is set to Strict, meaning the cookie will only be sent in requests originating from the same site (including subdomains). Cross-site requests won’t include this cookie.

Note that not all cookies will have all attributes set, and the attribute values may vary based on the specific requirements of a website or application.

Session Management

Session management refers to the process of securely managing user sessions in web applications. A session is a period of interaction between a user and a web application, typically starting when the user logs in and ending when the user logs out or the session times out. During a session, the web application maintains stateful information about the user’s activities and data.

While session management is crucial for maintaining user authentication, authorization, and personalised experiences, it can be susceptible to various attacks. Here are some common attacks associated with session management.

Session Hijacking: Session Hijacking, also known as session stealing or session sidejacking, involves an attacker intercepting or stealing a valid session ID of an authenticated user. The attacker may use various techniques to obtain the session ID, such as network sniffing, session prediction, or session theft through malicious software. Once the attacker possesses a valid session ID, they can impersonate the user and perform actions on their behalf without requiring the user’s credentials. Session Hijacking attacks are a serious threat to session security and can lead to unauthorized access, data theft, or malicious activities.

Session Replay: Session Replay refers to the unauthorized capture and playback of a user’s session data, including interactions and actions performed on a website. This attack involves an attacker recording or intercepting a user’s session and then replaying it later to gain unauthorized access or perform malicious activities. The attacker can use tools or techniques to capture the session data, including network sniffing or key-logging. Session Replay attacks are a significant concern when sensitive actions or transactions occur during a session, such as financial transactions or privileged operations.

Session Fixation: Session Fixation is an attack where an attacker forces a user’s session identifier (session ID) to a predefined value of their choice. This attack typically occurs before the user logs in or establishes a session. The attacker may trick the user into using a specific session ID (e.g., by providing a malicious link or through social engineering). Once the user logs in, the attacker can exploit the fixed session ID to gain unauthorized access to the user’s session. The attack relies on the application’s failure to generate a new session ID upon authentication i.e. the session ID remains same before and after log in due to which session ID set by attacker remains same after victim’s login and attacker has no control over victim’s session.

Session Timeout/Browser Session Management: Improper session timeout or browser session management can leave sessions open for an extended period, increasing the risk of unauthorized access if an attacker gains physical or digital access to the user’s device.

To mitigate these attacks, web applications should implement secure session management practices, including:

  • Generating secure and unpredictable session IDs with very entropy.
  • Regenerating session IDs upon authentication and session state changes.
  • Encrypting session data to prevent tampering.
  • Implementing mechanisms to detect and prevent session fixation and hijacking.
  • Employing secure communication channels, such as HTTPS, to protect session data.
  • Implementing httpOnly flag to prevent XSS attacks.
  • Implementing CSRF protection mechanisms, such as same-site flag to strict.
  • Configuring appropriate session timeout and idle timeout settings.

By following these best practices, organizations can enhance the security of session management and protect user sessions from potential attacks.

--

--

Pratham Mittal
Pratham Mittal

Written by Pratham Mittal

Ethical hacker || Security Engineer || Amazon, Ex - Razorpay, MakeMyTrip, Synopsys