01642 06 11 11 Arrange Call

How to set Secure Cookie flags using Apache or nginx

What are Cookie flags?

The Secure flag is flag that can be included in a Set-Cookie header which tells the browser that the cookie must only ever be sent over a secure connection.

Why should I implement Secure Cookie flags?

When our pen-test team undertake a web application pen test, a common issue is Cookie configuration. Imagine, a user who types in the HTTP version of a website instead of the HTTPS, their session is valid, and their browser pre-fills their session cookie in their request headers. Now imagine that user is sat in a cafĂ© with connected to an open WIFI network, and you’re sat watching the WIFI traffic using Wireshark. You’ll be able to see the HTTP request, even if the website then diverts the user to the HTTPS port. This request will contain the cookie and its content, which you can replicate and hi-jack their session!

How to implement secure cookies using Apache:

Edit Apache Configuration

Edit your Apache configuration file, which is typically located at /etc/apache2/apache2.conf or /etc/httpd/conf/httpd.conf.sudo nano /etc/apache2/apache2.conf

Add Cookie Attributes

Insert the following lines at the appropriate location in your Apache configuration file to set secure cookie attributes:Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

This configuration adds the ‘HttpOnly’ attribute, preventing JavaScript access to the cookie, and the ‘Secure’ attribute, ensuring the cookie is only sent over HTTPS connections.

Save and Restart Apache

Save your changes and restart Apache to apply the new configuration:sudo systemctl restart apache2

How to implement secure cookies using nginx:

Edit Nginx Configuration

Edit your Nginx configuration file, which is typically located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.sudo nano /etc/nginx/nginx.conf

Add Cookie Attributes

Insert the following lines at the appropriate location in your Nginx configuration file to set secure cookie attributes:server { # Other server configurations... location / { # Other location configurations... # Set secure cookie attributes add_header Set-Cookie "HttpOnly;Secure"; } }

This configuration adds the ‘HttpOnly’ attribute, preventing JavaScript access to the cookie, and the ‘Secure’ attribute, ensuring the cookie is only sent over HTTPS connections.

Save and Reload Nginx

Save your changes and reload Nginx to apply the new configuration:sudo systemctl reload nginx

Are there any other ways to protect against session hijacking attacks?

Look at our article on Security Headers, and how you can implement HTTP Strict Transport Security (HSTS) to protect visitors by ensuring that their browsers always connect to your website over HTTPS.

You can check your security headers by using our security header checking tool.