Tech Recipe Book
My Services
  • Book
    • About the author
    • Architect
      • Algorithms
        • DB index algorithms
          • How does database indexing work
        • Neural network optimization
          • Neural Network Optimization
        • Route search
          • Road network in a database to build a route
          • Traveling Salesman Problem (TSP)
      • Architecture Frameworks
        • DODAF
        • TOGAF
        • Enterprise Architecture (EA) Tools Reviews 2023 | Gartner
      • Zero Trust
      • Billing
        • SHM billing system
      • Bots
        • Discord
        • Telegram
          • Chat GPT Telegram bot
          • Получаем статистику Telegram-канала при помощи api и python или свой tgstat с регистрацией и смс
          • Как хостить телеграм-бота (и другие скрипты на Python) на Repl.it бесплатно 24/7
          • Создание Telegram бота на PHP #1: основные понятия для работы с API
          • Создание Telegram бота на PHP #2: создание первого бота для Telegram
          • Создание Telegram бота на PHP #3: примеры отправки сообщений с кнопками в Telegram
          • Создание Telegram бота на PHP #4: отправка файлов и изображений в Telegram
          • Создание Telegram бота на PHP #5: работа с хуками
      • Business intelligence
      • Cloud Storage
        • Ceph
        • Virtual Distributed File System
      • Cryptography
        • Open Source PKI Software
        • OpenPGP
          • Email Encryption
          • Kleopatra
          • Miscellaneous Tools
          • Server side applications
      • Message broker
        • Kafka
          • Kafka UI-tools
          • Kafka streams ksqlDb
        • RabbitMQ
      • DB
        • MySQL
          • Auto sharding
          • MariaDB Zabbix monitoring
          • MySQL and MariaDB replication with Zabbix monitoring
        • Postgres
          • HA PostgreSQL with Patroni, Haproxy, Keepalived
          • Mass parallel requests - Greenplum
          • PostgreSQL cluster for development and testing
        • Vitess - Scalable. Reliable. MySQL-compatible. Cloud-native. Database.
      • Identity and Access Management (IDM)
        • FreeIPA - Identity, Policy, Audit
        • FreeIPA as an Enterprise solution
        • Keycloak
          • Keycloak HA cluster
        • Open Identity Platform
        • SSO
          • Keycloak for Java app
          • OpenAM
          • OpenIG
      • Firewall
        • nftables
      • Infrastructure As a Code
        • Ansible
        • IaC Packer Ansible Teraform
        • Installing Jenkins using terraform in Kubernetes in Yandex Cloud with letsencypt
        • Teraform Crosplan Pulumi
        • Yandex IaC solutions
      • Kubernetes
        • Installation
          • Install Kubernetes cluster
          • Deploying a Kubespray cluster to OpenStack using Terraform
          • Kube deploy in Yandex cloud
        • Frameworks
          • Deckhouse
            • LDAP authentification
            • On premise Install
            • Yandex Cloud Install
          • K3S
          • OpenShift OKD
          • RKE2
          • Rancher
            • Rancher Install
        • Auth
          • Keycloak in k8s
          • LDAP
        • GUI management Lens
        • Monitoring
          • Monitoring with Falco
          • Network monitoring
          • Nginx ingress
          • Prometheus Graphana for sample Nodejs app
          • Rsource monitoring Avito
        • Exposing services
          • Exposing Kubernetes Services
          • Cilium BGP
        • CNCF
        • Helm
          • Repositories
            • Artifact Hub | official
            • Bitnami | vmware
          • Awesome helm charts and resources
          • Essential Services for Modern Organizations
          • Security and Compliance
          • Additional charts
        • Isolation
          • vcluster - Virtual Kubernetes Clusters
          • Kiosk
          • KubeArmor
          • Control Plane Hardening
          • Hierarchical namespaces
        • Security Center
          • Minesweeper
          • NeuVector by SUSE
          • SOAR in Kubernetes
          • Security Сenter for Kubernetes
        • Terraform CI security
          • Terraform plan analysis with Checkov and Bridgecrew
          • Yandex Terraform scan
        • Vulnerability management
          • Aqua
          • Sysdig
          • Kyverno
          • GitLab
          • NeuVector by SUSE
        • Image scanning
          • Snyk
          • Sysdig
          • Harbor
          • Trivy
        • Signature verification
          • Sigstore
        • Control plane security
          • Gatekeeper
            • Applying OPA Gatekeeper
          • Kyverno
            • Policy as a code. Kyverno
        • Runtime Security
          • Osquery
          • Falco
          • ClamAV
        • Network security
          • Cilium
          • Control Plane Hardening (API restriction)
          • Network policy recipes
          • Service mesh
            • Istio HA, LoadBalance, Rate limit
          • mTLS Autocert
        • Honeypot
          • Building honeypot using vcluster and Falco
        • Backup
          • Kasten K10
        • Secrets
          • Vault CSI Driver
      • Load Balance
        • Nginx
        • HAProxy
          • Proxy methods
          • HAProxy for RDP
          • Payment gateway A/B test with HAProxy
          • HAPRoxy for Percona or Galera
      • Monitoring
        • Zabbix
          • Apache Zabbix
          • Disc Quota
          • Nginx Zabbix
          • SSL certificates Zabix
          • Zabbix notifications
        • Nagios
          • Datacenter monitoring
        • Prometheus and Grafana
      • Windows
        • Sysmon enhanced Windows audit
        • Sysmon to Block Unwanted File
      • Linux
        • Rsync
        • Debian based
          • Apt-Cacher NG
          • Unattended Upgrades in Debian / Ubuntu
        • RedHat basede
          • RPM Server
        • Logs analysis
        • Build armhf qemu
      • NGFW
      • CI/CD
        • DevSecOps
          • DAST
            • Burp
              • Dastardly
            • StackHawk
            • ZAP and GitHub Actions
          • SAST
            • Checkmarx
            • OSV by Google
            • Snyk
            • SonarQube
        • GitLab Runner in Yandex Cloud
        • Dynamic Gitlab Runners in Yandex Cloud
        • GitLab runner in Kubernetes with Werf
        • Kubernetes deploy strategies
        • Kubernetes highload deploy. part 1
        • Kubernetes highload deploy. part 2
        • Kubernetes Argo Rollouts
        • Jenkins in Kubernetes
        • Ansible Semaphore
        • Image storage, scaning and signing
        • Install WireGuard with Gitlab and Terraform
        • CI/CD example fror small web app
        • Threat matrix for CI CD Pipeline
      • SIEM / SOC
        • Datadog
        • Splunk
          • Splunk — general description
        • MaxPatrol
          • MaxPatrol 8 and RedCheck Enterprise
        • QRadar IBM
        • Cloud Native Security Platform (CNAPP) - Aqua
        • OSSIM | AT&T
          • AlienVault (OSSIM) install
        • Wazuh
        • EDR
          • Cortex XDR | Palo Alto Networks
          • Cynet
          • FortiEDR | Fortinet
          • Elastic
        • Elastic
          • Install Elasticsearch, Logstash, and Kibana (Elastic Stack) on Ubuntu 22.04
          • Setting Up Elastic 8 with Kibana, Fleet, Endpoint Security, and Windows Log Collection
        • Threat Intelligence
          • MISP
          • msticpy Microsoft
          • X-Force | IBM
          • Elastic
      • VPN
        • Full-Mesh VPN fastd, tinc, VpnCloud
        • Wireguard
          • WireGuard for Internet access
          • WireGuard on MikroTik and Keenetic
          • WireGuard site to site
        • SoftEther VPN Project
        • Cisco AnyConnect client
        • OpenConnect
        • SSTP python server
      • OS hardening
        • CIS Benchmarks
      • Cloud Providers
      • OpenNebula
        • OpenNebula Edge Cloud - Open Source Cloud & Edge Computing
        • Discover OpenNebula – Open Source Cloud & Edge Computing Platform
        • OpenNebula Multi-Cloud
        • Kubernetes on OpenNebula
        • The Open Source Alternative to Nutanix
        • The Simple Alternative to OpenStack
        • OpenNebula Partner Ecosystem
      • OpenStack
        • Install manual
        • Install with DevStack
      • VM
        • Create a VHD file from a Linux disk
        • Backup / Migration
          • Coriolis
          • Proxmox Backup Server
        • oVirt
        • VMware vCenter
        • Proxmox
      • Docker
        • Container optimization
        • Ubuntu RDP container
      • LXC
        • LXD on Ubuntu 18.04
        • Install, Create and Manage LXC in Ubuntu/Debian
    • Big Data
      • OLAP data qubes
      • Storage and autoscale in Lerua
    • Machine Learning
      • Yandex YaLM 100B. GPT model
      • Kaggle Community Datasts Models
      • AI in video production
      • Image search
      • Chat bots
        • You.com
        • Chat GPT
          • Implementing GPT in NumPy
        • Jailbreak Chat
      • Coding plugins CodeWhisperer
    • Malware
      • Isiaon/Pitraix: Modern Cross-Platform Peer-to-Peer Botnet over TOR
      • theZoo A repository of LIVE malwares
    • Pentest
      • Red Team
        • MITRE ATT&CK matrix
        • C2 Frameworks
          • Brute Ratel C4
          • Cobalt Strike
          • Covenant
          • Havoc Framework
          • Merlin
          • Metasploit
          • Sillenttrinity
          • Sliver
        • Manage and report
          • Dradis Framework
          • Hexway
        • Underground
      • Social engineering
        • Social Engineer Toolkit setoolkit
      • OSINT
        • OSINT for comapny
        • Instagram fishing
      • Forensics
        • Forensics tools
      • Pentesting Methodology
      • Web
      • CI/CD Methodology
      • Cloud Methodology
        • Hacking The Cloud
      • Kubernetes Pentesting
      • Android
        • SSL Unpinning for Android applications
      • iOS
        • SSL unpinning iOS and macOS applications
      • HackBar tool
      • CyberChef Tools
      • Python virtualenv
      • IppSec - YouTube
      • Hacktricks.xyz
    • Compliance
      • 152 ФЗ. Personal data
      • PCI DSS and ГОСТ Р 57580.1-2017
      • Cloud compliance
      • ГОСТ Р 57580.1-2017 для Kubernetes
      • Kubernets as DevSecOps and NIST compliance
      • NIST SP 800-61 cyberincidece control
      • CIS Kubernetes Benchmark v1.6 - RKE2 v1.20
      • CIS Kubernetes Benchmark v1.23 - RKE2
      • Requirements for Russian Banks
      • Tools
        • Chef InSpec
        • Elastic SIEM
    • Asset management
      • CMDBuild
    • Project management
    • Incident management SRE
    • Risk management
      • IT risk management
      • BSI-Standard 200-3
    • Web Dev
      • Cookie security
      • OWASP Top 10 2021
      • Docker nginx php mysql
      • Docker tor hiddenservice nginx
      • Docker Compose wp nginx php mariadb
      • Dependency Checking
        • Nexus Analyzer
        • OWASP dependency-check
      • Yii skeeks cms
      • YiiStudio
    • Art
      • GTK Themes
      • Themes for Xfce Desktop
      • XFCE / Xubuntu Windows 95
      • Moscow events
      • Photo goods
      • Russian style gifts
    • Cryptocurrency
      • News
      • Arbitrage
      • Stocks
      • Exchange aggregators
      • Where to use
      • Prepaid cards
        • BitFree
        • Pyypl Your Money at Your Fingertips
    • IT magazines
      • WIKI and Writeups tools
        • BookStack
        • GitBook
        • MkDocs
        • Wiki.js
        • DokuWiki
    • Languages
    • Learning
      • (ISC)2
        • CISSP
      • Offensive Security
        • OSCP
        • OSEP
        • OSED
      • DevSecOps
        • Certified DevSecOps Professional (CDP)
        • Certified DevSecOps Expert (CDE)
      • Web Security Academy: PortSwigger
    • Relocation
      • London experience
      • IT visas in 2022
      • Remote work
      • Running business in UAE
    • Freenet
      • Independent online services: the philosophy of a free Internet
      • Tor Project Anonymity Online
      • I2P Anonymous Network
    • Services
      • SMS Registration
        • Registering ChatGPT in Russia
      • Local and regional eSIMs for travellers - Airalo
      • Digital busines cards
      • No KYC services and exchanges
Powered by GitBook
On this page
  • What data do you store?
  • Session Cookie vs. Persistent Cookie
  • Secure Flag
  • HTTPOnly Flag
  • SameSite Flag
  • HostOnly Flag
  • Conclusion

Was this helpful?

  1. Book
  2. Web Dev

Cookie security

Last updated 1 year ago

Was this helpful?

— This post is part of a series of blog posts about all kinds of Security topics for Developers —

Cookies are small packets of data which a server can send to your browser to store some configuration or personal data. The browser automatically sends them along with all requests to that same server. The contents are usually very interesting to hackers, so it’s important to know how to secure these cookies. Fortunately there are a lot of things you can do to improve cookie security. So… what do you need to know?

What data do you store?

If you want to store sensitive data, think very hard if you really need to store that particular bit of data in a cookie. By using cookies, you may prevent expensive requests to the server, but the data may also get outdated. Data is typically more secure if it not stored on the client side.

Assuming you decided that you really do need cookies, you need to make sure that you configure them correctly. Cookies have several attributes and flags to do so. Below are the ones you need to know about when considering cookie security.

Session Cookie vs. Persistent Cookie

First of all, decide how long your cookie should be valid. The more sensitive the data, the sooner it should expire. Cookies allow you to specify this through the ‘expires’ and ‘max-age’ attributes. By definition, setting either of these attributes make the cookie persistent. This means that (as long as the expiration is in the future), the cookies survive a browser restart. If both fields are omitted, you get a non-persistent cookie or session-cookie. This means the cookie is automatically removed when your session ends (so when the browser is closed).

  • The more sensitive the data, the sooner you’ll want the cookie to expire, so if you explicitly want to set an expiration or max-age, choose a date in the next few months, weeks or even hours, rather than years.

Secure Flag

If the browser sends cookies over unencrypted connections, it will be possible for hackers to eavesdrop on your connection and read (or even change) the contents of your cookies. To prevent this, send cookies over encrypted connections only.

Setting the secure flag prevents the cookie from ever being sent over an unencrypted connection. It basically tells the browser to never add the cookie to any request to the server that does not use an encrypted channel. The cookie will only be added to connections such as HTTPS (HTTP over Transport Layer Security (TLS)). Note that it is up to the browser to decide what it considers ‘secure’. Typically the browser considers it secure if the protocol makes use of the secure-transport-layer. This also means that a browser may decide to send the cookie when the connection is secured with a self-signed or expired certificate.

  • You should always set the Secure flag in your cookies when they contain sensitive data, unless your website uses an insecure connection, but in that case you have much bigger problems.

You might think that setting this flag is not relevant if your server always uses HTTPS, but that is not true. It means that the server would never send unencrypted data (including cookies) to the browser, but the other direction is not guaranteed. E.g. a network attacker could intercept outbound HTTP requests and redirect them to capture the plaintext cookies.

HTTPOnly Flag

By default the content of cookies can be read via JavaScript. The HTTPOnly flag prevents scripts from reading the cookie. As the name HTTPOnly implies, the browser will only use the cookie in HTTP(S) requests. This prevents hackers from using XSS vulnerabilities to learn the contents of the cookie. E.g. for the sessionId cookie it is never necessary to read the cookie with client-side script, so for sessionId cookies, you can always set the HTTPOnly flag.

  • Set the HTTPOnly flag for all cookies that don’t need to be accessed by script.

It’s good to know that for a hacker there are other techniques to learn the contents of the cookie. Even if the HTTPOnly flag is set, you can use scripts to learn the contents. Ever heard of the HTTP TRACE method? It is a method (like GET and POST) that is intended for debugging. When using the TRACE method in a request, the server just echoes the exact contents of the request back to you (including cookies), so you can see what your browser sent. This is great for debugging! It can however also be used by malicious scripts, because even though your script cannot read the cookie directly, it can read the response of a TRACE request. This is called Cross-Site Tracing (XST).

  • Besides setting the HTTPOnly flag, you should always disable the TRACE method on any non-Development server.

Another thing to keep in mind is that there are other tools that echo HTTP requests. E.g, there are Docker containers that echo the HTTP request, to help you debug your microservices. While very useful in development environments, such services should never end up in Production.

SameSite Flag

  • Set SameSite to ‘strict’ if linking from other sites is not necessary. Set it to ‘lax’ otherwise.

HostOnly Flag

The HostOnly flag specifies whether the cookie is accessible by subdomains or not. It is an implicit flag that the browser sets if the domain attribute is empty. E.g. If the website www.example.com sets a cookie without a Domain attribute, it is a HostOnly cookie. Only if the page domain exactly matches the host that has set the cookie, will it be able to read it. If www.example.com sets a cookie with Domain=example.com, then it is no longer a HostOnly cookie, and all subdomains of example.com will have access to its contents.

  • Leave the Domain attribute empty, unless you explicitly want to share the contents of the cookie with all subdomains and know it’s safe to share the contents with all of them.

Conclusion

So, to summarize:

  • Don’t store sensitive data in cookies, unless you absolutely have to.

  • Use Session cookies if possible. Otherwise set a strict expiration.

  • Use the HttpOnly and the Secure flags of cookies.

  • Set the SameSite flag to avoid other websites to link to your site

  • Leave the Domain empty, to avoid subdomains from using the cookie.

After that, your cookie data should be much safer.

Even if the server uses (HSTS) and includes subdomains and the domain is on the , it’s a good practice to still set the Secure Flag. Not all browsers and user agents use the preload list, so an initial request to your domain could still use an unencrypted channel.

is an experimental flag, which Google added in Chrome 51. It aims to mitigate the risk of CSRF. When the server sets its value to ‘strict’, the browser will not send the cookie to your website if the request comes from a different domain, even when directly clicking a link. For example, a bank doesn’t want financial transactions to be initiated through a link on a different domain. There it makes sense. Facebook on the hand practically lives from letting users click ‘like’ buttons on different domains, so they won’t use this. Setting the SameSite flag to the value ‘lax’ makes the browser a bit more lenient in that it only blocks the cookies with ‘unsafe’ HTTP methods like ‘POST’.

To avoid disappointment, check to see which browsers support this relatively new flag.

Here you can find more information on the cookie specification:

https://techblog.topdesk.com/security/cookie-security/
HTTP Strict Transport Security
preload list
The SameSite flag
https://caniuse.com/#search=samesite
https://tools.ietf.org/html/rfc6265