# Insecure Cookie Vulnerabilities

#### Tools recognizing this:

<kbd>Opengrep</kbd> <kbd>Fortify</kbd> <kbd>Checkmarx</kbd> <kbd>SonarQube</kbd> <kbd>Snyk</kbd> <kbd>Semgrep</kbd> <kbd>CodeQL</kbd>

## What are Insecure Cookies and How Do They Work?

Insecure cookies are a significant web security vulnerability that occurs when cookies containing sensitive information are transmitted without proper security attributes. When cookies are set without security flags, they become vulnerable to various attacks, including:

* Man-in-the-middle attacks
* Cookie theft through XSS
* Session hijacking
* Cookie sniffing over unsecured networks
* Cross-site request forgery (CSRF)

This guide covers insecure cookie vulnerabilities, examples, prevention methods, and how to implement secure cookies using real-world techniques.

## One Simple Insecure Cookie Example

Consider this basic example of setting a cookie:

{% code overflow="wrap" %}

```
Cookie cookie = new Cookie("sessionId", sessionValue);
response.addCookie(cookie);
```

{% endcode %}

This cookie is vulnerable because it:

<mark style="color:red;">- Lacks the Secure flag (can be transmitted over HTTP)</mark> <mark style="color:red;">- Lacks the HttpOnly flag (can be accessed via JavaScript)</mark> <mark style="color:red;">- Doesn't specify SameSite attribute (vulnerable to CSRF)</mark>

## Insecure Cookie Prevention Methods: How to Fix Your Code

The most effective way to fix insecure cookie issues is to set appropriate security attributes when creating cookies. Essential security attributes include:

* Secure flag: Ensures cookies are only transmitted over HTTPS
* HttpOnly flag: Prevents JavaScript access to cookies
* SameSite attribute: Controls how cookies are sent in cross-site requests
* Appropriate expiration time
* Path and domain restrictions

### Code Samples

{% tabs %}
{% tab title="Java" %}
**Vulnerable Code**

<pre class="language-java"><code class="lang-java">Cookie cookie = new Cookie("sessionId", sessionValue);
<a data-footnote-ref href="#user-content-fn-1">response.addCookie(cookie);</a>
</code></pre>

**Fixed Code**

```java
Cookie cookie = new Cookie("sessionId", sessionValue);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie);
```

**Fix Explanation**

The vulnerable code creates a cookie without any security attributes.The fix adds essential security flags: Secure and HttpOnly.Sets appropriate expiration time and path restrictions.Modern frameworks may also support SameSite attribute configuration.
{% endtab %}

{% tab title="JavaScript" %}
**Vulnerable Code**

```javascript
res.cookie('sessionId', sessionValue);
```

**Fixed Code**

```javascript
res.cookie('sessionId', sessionValue, {
    secure: true,
    httpOnly: true,
    sameSite: 'strict',
    maxAge: 3600000,
    path: '/'
});
```

**Fix Explanation**

The vulnerable code sets a cookie without security options.The fix includes all necessary security attributes.Uses secure, httpOnly, and sameSite flags.Sets appropriate maxAge and path restrictions.
{% endtab %}

{% tab title="Python" %}
**Vulnerable Code**

```python
response.set_cookie('sessionId', session_value)
```

**Fixed Code**

```python
response.set_cookie(
    'sessionId',
    session_value,
    secure=True,
    httponly=True,
    samesite='Strict',
    max_age=3600,
    path='/'
)
```

**Fix Explanation**

The vulnerable code sets a cookie without security parameters.The fix adds all necessary security attributes.Includes secure, httponly, and samesite flags.Sets appropriate max\_age and path restrictions.
{% endtab %}

{% tab title="C#" %}
**Vulnerable Code**

```csharp
Response.Cookies.Append("sessionId", sessionValue);
```

**Fixed Code**

```csharp
var options = new CookieOptions
{
    Secure = true,
    HttpOnly = true,
    SameSite = SameSiteMode.Strict,
    MaxAge = TimeSpan.FromHours(1),
    Path = "/"
};
Response.Cookies.Append("sessionId", sessionValue, options);
```

**Fix Explanation**

The vulnerable code creates a cookie without security options.The fix uses CookieOptions to set security attributes.Includes Secure, HttpOnly, and SameSite flags.Sets appropriate MaxAge and Path restrictions.
{% endtab %}

{% tab title="PHP" %}
**Vulnerable Code**

```php
setcookie("sessionId", $sessionValue);
```

**Fixed Code**

```php
setcookie(
    "sessionId",
    $sessionValue,
    [
        'expires' => time() + 3600,
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict'
    ]
);
```

**Fix Explanation**

The vulnerable code sets a cookie without security options.The fix includes an array of security attributes.Sets secure, httponly, and samesite flags.Includes appropriate expiration time and path restrictions.
{% endtab %}

{% tab title="Ruby" %}
**Vulnerable Code**

```ruby
cookies[:session_id] = session_value
```

**Fixed Code**

```ruby
cookies[:session_id] = {
  value: session_value,
  secure: true,
  httponly: true,
  same_site: :strict,
  expires: 1.hour.from_now,
  path: '/'
}
```

**Fix Explanation**

The vulnerable code sets a cookie without security options.The fix includes a hash of security attributes.Uses secure, httponly, and same\_site flags.Sets appropriate expiration time and path restrictions.
{% endtab %}
{% endtabs %}

## Need more help in preventing Insecure Cookies?

[Mobb](https://mobb.ai) supports fixing many forms of Insecure Cookie vulnerabilities, and can mitigate your issues in batch.

Start now for free at [app.mobb.ai](https://app.mobb.ai)

### We'd love your feedback!

We're excited to hear your thoughts and ideas about fixing vulnerabilities.

[Book a meeting](https://calendly.com/mobbai/demo) or [Contact us](https://content.mobb.ai/contact) if you have any corrections, questions or suggestions. Start now for free at <https://app.mobb.ai>

[^1]: This is the vulnerable part


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/fixing-guides/insecure-cookie-fix-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
