Websikkerhed: Sådan hærdes dine HTTP-cookies

Bemærk: dette er del 4 af en serie om websikkerhed. Del 3 var Sikre din webapplikation med disse HTTP-headere.

Forestil dig at være en backend-udvikler, der har brug for at implementere sessioner i en applikation: det første, du kommer til at tænke på, er at udstede et token til klienter og bede dem om at sende dette token med deres efterfølgende anmodninger. Derefter vil du kunne identificere klienter baseret på det token, der er inkluderet i deres anmodning.

HTTP-cookies blev født for at standardisere denne form for mekanisme på tværs af browsere. De er intet andet end en måde at gemme data sendt af serveren og sende dem sammen med fremtidige anmodninger. Serveren sender en cookie, som indeholder små data. Browseren gemmer den og sender den sammen med fremtidige anmodninger til den samme server.

Hvorfor skulle vi bekymre os om cookies ud fra et sikkerhedsperspektiv? Fordi de data, de indeholder, oftere end ikke er ekstremt følsomme. Cookies bruges generelt til at gemme session-id'er eller få adgang til tokens, en angribers hellige gral. Når de er udsat for eller kompromitteret, kan angribere efterligne brugere eller eskalere deres privilegier i din applikation.

Sikring af cookies er et af de vigtigste aspekter ved implementering af sessioner på nettet. Dette kapitel vil derfor give dig en bedre forståelse af cookies, hvordan du sikrer dem, og hvilke alternativer der kan bruges.

Hvad ligger bag en cookie?

En server kan indstille en cookie ved hjælp af Set-Cookieoverskriften:

HTTP/1.1 200 OkSet-Cookie: access_token=1234...

En klient gemmer derefter disse data og sender dem i efterfølgende anmodninger gennem Cookieoverskriften:

GET / HTTP/1.1Host: example.comCookie: access_token=1234...

Bemærk, at servere kan indstille flere cookies på én gang:

HTTP/1.1 200 OkSet-Cookie: access_token=1234Set-Cookie: user_id=10...

og klienter kan gemme flere cookies og sende dem i deres anmodning:

GET / HTTP/1.1Host: example.comCookie: access_token=1234; user_id=10...

Ud over den almindelige nøgle og værdi kan cookies indeholde yderligere direktiver, der begrænser deres levetid og omfang.

Udløber

Angiver, hvornår en cookie skal udløbe, så browsere ikke gemmer og sender den på ubestemt tid. Et klart eksempel er et session-id, som normalt udløber efter nogen tid. Dette direktiv udtrykkes som en dato i form af Date: , <time> ;:: GMT, som Dato: Fre, 24 Aug 2018 04:33:00 GMT. Her er et komplet eksempel på en cookie, der udløber den 1. januar 2018:

access_token=1234;Expires=Mon, 1st Jan 2018 00:00:00 GMT

Max-Age

Svarende til Expiresdirektivet Max-Ageangiver antallet af sekunder, indtil cookien skal udløbe. En cookie, der skal vare 1 time, ser ud som følger:

access_token=1234;Max-Age=3600

Domæne

Dette direktiv definerer, hvilke værter cookien skal sendes til. Husk, cookies indeholder generelt følsomme data, så det er vigtigt for browsere, at de ikke lækker dem til ikke-tillid til værter. En cookie med direktivet Domain=trusted.example.comsendes ikke sammen med anmodninger til noget andet domæne end trusted.example.comikke engang roddomænet example.com. Her er et gyldigt eksempel på en cookie begrænset til et bestemt underdomæne:

access_token=1234;Domain=trusted.example.com

Sti

Svarende til Domaindirektivet, men gælder URL-stien ( /some/path). Dette direktiv forhindrer en cookie i at blive delt med ikke-tillid til stier, som i følgende eksempel:

access_token=1234;Path=/trusted/path

Session og vedvarende cookies

Når en server sender en cookie uden at indstille sin Expireseller Max-Age, behandler browsere den som en session-cookie : snarere end at gætte dens levetid eller anvende sjove heuristikker, sletter browseren den, når den lukker ned.

Tværtimod opbevares en vedvarende cookie hos klienten indtil den frist, der er fastsat af dens Expireseller Max-Agedirektiver.

Det er værd at bemærke, at browsere muligvis anvender en mekanisme kendt som gendannelse af sessioner , hvor sessionscookies kan gendannes, når klienten lukker ned. Browsere har implementeret denne form for mekanisme til bekvemt at lade brugerne genoptage en session efter for eksempel et nedbrud. Gendannelse af session kan føre til uventede problemer, hvis vi forventer, at sessionscookies udløber inden for en bestemt tidsramme (for eksempel er vi absolut positive, at en session ikke varer mere end X tid).

Fra en browsers perspektiv er gendannelse af sessioner en perfekt gyldig funktion, da disse cookies er i klientens hænder uden en udløbsdato. Hvad klienten gør med disse cookies påvirker ikke serveren, som ikke er i stand til at opdage, om klienten lukker ned på et hvilket som helst tidspunkt. Hvis klienten ønsker at holde session-cookies i live for evigt, er det ikke noget, der bekymrer serveren. Det ville helt sikkert være en tvivlsom implementering, men serveren kan ikke gøre noget ved det.

Jeg tror ikke, der er en klar vinder mellem session og vedvarende cookies, da begge tjener forskellige formål meget godt. Hvad jeg dog har observeret er, at Facebook, Google og lignende tjenester bruger vedvarende cookies. Fra personlig erfaring har jeg generelt altid brugt vedvarende cookies, men aldrig været nødt til at binde vigtige oplysninger, såsom et socialsikringsnummer eller en bankkontos saldo til en session.

I nogle sammenhænge skal du muligvis bruge sessioncookies på grund af overholdelseskrav. Jeg har set revisorer bede om at konvertere alle vedvarende cookies til sessioner. Når folk spørger mig ” skal jeg bruge X eller Y? ”Mit svar er“ det afhænger af sammenhængen ”. At opbygge en gæstebog til din blog bærer forskellige sikkerhedsforklaringer end at opbygge et banksystem. Som vi vil se senere i denne serie, vil jeg anbefale at forstå din kontekst og forsøge at opbygge et system, der er sikkert nok : absolut sikkerhed er utopi, ligesom en 100% SLA.

Kun vært

Når en server ikke inkluderer et Domaindirektiv, skal cookien betragtes som host-onlyen, hvilket betyder, at dens gyldighed kun er begrænset til det aktuelle domæne.

Dette er en slags "standard" -adfærd fra browsere, når de modtager en cookie, der ikke har et Domainsæt. Du kan finde et lille eksempel, jeg skrev på github.com/odino/wasec/tree/master/cookies. Det er en simpel webapp, der indstiller cookies baseret på URL-parametre og udskriver cookies på siden gennem en JavaScript-kode:

 let content = "none";
if (document.cookie) { let cookies = document.cookie.split(';') content = ''
cookies.forEach(c => { content += "

" + c + "

" }) }
document.getElementById('output').innerHTML = "Cookies on this document: " + content + " " 

Hvis du følger instruktionerne i, vil READMEdu få adgang til en webserver på wasec.local: 7888, som illustrerer, hvordan host-onlycookies fungerer:

Hvis vi derefter prøver at besøge et underdomæne, vil de cookies, vi sætter på hoveddomænet, ikke være synlige - prøv at navigere til sub.wasec.local: 7888:

En måde at omgå denne begrænsning er, som vi har set tidligere, at specificere Domaincookiens direktiv, noget vi kan gøre ved at besøge wasec.local: 7888 /? Domain = on:

If we have a look at the application running on the subdomain, we will now be able to see cookies set on the parent domain, as they use Domain=wasec.local, which allows any domain “under” wasec.local to access the cookies:

In HTTP terms, this is how the responses sent from the server look like:

~ ᐅ curl -I //wasec.local:7888HTTP/1.1 200 OKSet-Cookie: example=test_cookieDate: Fri, 24 Aug 2018 09:34:08 GMTConnection: keep-alive
~ ᐅ curl -I "//wasec.local:7888/?domain=on"HTTP/1.1 200 OKSet-Cookie: example=test_cookieSet-Cookie: example_with_domain=test_domain_cookie;Domain=wasec.localDate: Fri, 24 Aug 2018 09:34:11 GMTConnection: keep-alive

Supercookies

What if we were able to set a cookie on a top-level domain (TLD) such as .com or .org? That would definitely be a huge security concern, for two main reasons:

  • user privacy: every website running on that specific TLD would be able to track information about the user in a shared storage
  • information leakage: a server could mistakenly store a sensitive piece of data in a cookie available to other sites

Luckily, TLD-cookies, otherwise known as supercookies, are disabled by web browsers for the reasons I mentioned above. If you try to set a supercookie, the browser will simply refuse to do so. If we append the parameter super=on in our example, we will see the server trying to set a supercookie, while the browser ignores it:

In today’s web, though, there are other ways to keep track of users, ETag tracking being an example of this. Since cookies are usually associated with tracking, these techniques are often referred to as supercookies as well, even though they do not rely on HTTP cookies. Other terms that may refer to the same set of technologies and practices are permacookies (permanent cookies) or zombiecookies (cookies that never die).

Unwanted Verizon Ads Companies love to make money out of ads, that’s no news. But when ISPs start to aggressively track their customers in order to serve unwanted ads, well, that’s a different story. In 2016, Verizon was found guilty of tracking users without their consent, and sharing their information with advertisers. This resulted in a fine of $1.35 million and the inability, for the company, to continue with their questionable tracking policy. Another interesting example was Comcast, who used to include custom JavaScript code in web pages served through its network. Needless to say, if all web traffic would be served through HTTPS we wouldn’t have this problem, as ISPs wouldn’t be able to decrypt and manipulate traffic on-the-fly.

Cookie flags that matter

Until now we’ve barely scratched the surface of HTTP cookies. It’s now time for us to taste the real juice.

There are 3 very important directives (Secure, HttpOnly, and SameSite) that should be understood before using cookies, as they heavily impact how cookies are stored and secured.

Encrypt it or forget it

Cookies contain very sensitive information. If attackers get hold of a session ID, they can impersonate users by hijacking their sessions.

Most session hijacking attacks usually happen through a man-in-the-middle who can listen to the unencrypted traffic between the client and server, and steal any information that’s been exchanged. If a cookie is exchanged via HTTP, then it’s vulnerable to MITM attacks and session hijacking.

To overcome the issue, we can use HTTPS when issuing the cookie and add the Secure flag to it. This instructs browsers to never send the cookie in plain HTTP requests.

Going back to our practical example, we can test this out by navigating to //wasec.local:7889/?secure=on. The server sets 2 additional cookies, one with the Secure flag and one without:

When we go back and navigate to the HTTP version of the site, we can clearly see that the Secure cookie is not available in the page. Try navigating to wasec.local:7888.

We can clearly see that the HTTPS version of our app set a cookie that’s available to the HTTP one (the not_secure one), but the other cookie, flagged as Secure, is nowhere to be seen.

Marking sensitive cookies as Secure is an incredibly important aspect of cookie security. Even if you serve all of your traffic over HTTPS, attackers can find a way to set up a plain old HTTP page under your domain and redirect users there. Unless your cookies are Secure, they will then have access to a very delicious meal.

JavaScript can’t touch this

As we’ve seen earlier in this series, XSS attacks allow a malicious user to execute arbitrary JavaScript on a page. Considering that you could read the contents of the cookie jar with a simple document.cookie, protecting our cookies from untrusted JavaScript access is a very important aspect of hardening cookies from a security standpoint.

Luckily, the HTTP spec took care of this with the HttpOnly flag. By using this directive we can instruct the browser not to share the cookie with JavaScript. The browser then removes the cookie from the window.cookie variable, making it impossible to access the cookie via JavaScript.

If we look at the example at wasec.local:7888/?httponly=on, we can clearly see how this works. The browser has stored the cookie (as seen in the DevTools screenshot below) but won’t share it with JavaScript:

The browser will then keep sending the cookie to the server in subsequent requests, so the server can still keep track of the client through the cookie. The trick, in this case, is that the cookie is never exposed to the end-user, and remains “private” between the browser and the server.

The HttpOnly flag helps mitigate XSS attacks by denying access to critical information stored in a cookie. Using it makes it harder for an attacker to hijack a session.

In 2003, researchers found an interesting vulnerability around the HttpOnly flag, Cross-Site Tracing (XST). In a nutshell, browsers wouldn’t prevent access to HttpOnly cookies when using the TRACE request method. While most browsers have now disabled this method, my recommendation would be to disable TRACE at your webserver’s level, returning the 405 Not allowed status code.

SameSite: The CSRF killer

Last but not least, the SameSite flag, one of the latest entries in the cookie world.

Introduced by Google Chrome v51, this flag effectively eliminates Cross-Site Request Forgery (CSRF) from the web. SameSite is a simple yet groundbreaking innovation as previous solutions to CSRF attacks were either incomplete or too much of a burden to site owners.

In order to understand SameSite, we first need to have a look at the vulnerability it neutralizes. A CSRF is an unwanted request made by site A to site B while the user is authenticated on site B.

Sounds complicated? Let me rephrase.

Suppose that you are logged in on your banking website, which has a mechanism to transfer money based on an HTML rm> and a few additional parameters (destination account and amount). When the website recei ves a POST request with those parameters and your session cookie, it will process the transfer. Now, suppose a malicious 3rd party website sets up an HTML form as such:

See where this is getting?

If you click on the submit button, cleverly disguised as an attractive prize, $1000 is going to be transferred from your account. This is a cross-site request forgery - nothing more, nothing less.

Traditionally, there have been 2 ways to get rid of CSRF:

  • Origin and Referer headers: the server could verify that these headers come from trusted sources (For example //bank.com). The downside of this approach is that, as we’ve seen earlier in this series, neither the Origin nor the Referer are very reliable and could be “turned off” by the client in order to protect the user’s privacy.
  • CSRF tokens: the server could include a signed token in the form, and verify its validity once the form is submitted. This is generally a solid approach and it’s been the recommended best practice for years. The drawback of CSRF tokens is that they’re a technical burden for the backend, as you’d have to integrate token generation and validation in your web application. This might not seem to be a complicated task, but a simpler solution would be more than welcome.

SameSite cookies aim to supersede the solutions mentioned above once and for all. When you tag a cookie with this flag, you tell the browser not to include the cookie in requests that were generated by different origins. When the browser initiates a request to your server and a cookie is tagged as SameSite, the browser will first check whether the origin of the request is the same origin that issued the cookie. If it’s not, the browser will not include the cookie in the request.

We can have a practical look at SameSite with the example at github.com/odino/wasec/tree/master/cookies. When you browse to wasec.local:7888/?samesite=on the server will set a SameSite cookie and a “regular” one.

If we then visit wasec2.local:7888/same-site-form we will see an example HTML form that will trigger a cross-site request:

If we click on the submit button of the form, we will then be able to understand the true power of this flag. The form will redirect us to wasec.local:7888, but there is no trace of the SameSite cookie in the request made by the browser:

Don’t get confused by seeing same_site_cookie=test on your screen: the cookie is made available by the browser, but it wasn’t sent in the request itself. We can verify this by simply typing //wasec.local:7888/ in the address bar:

Since the originator of the request is “safe” (no origin, GET method) the browser sends the SameSite cookie with the request.

This ingenious flag has 2 variants, Lax and Strict. Our example uses the former, as it allows top-level navigation to a website to include the cookie. When you tag a cookies as SameSite=Strict instead, the browser will not send the cookie across any cross-origin request, including top-level navigation. This means that if you click a link to a website that uses strict cookies you won’t be logged in at all. An extremely high amount of protection that, on the other hand, might surprise users. The Lax mode allows these cookies to be sent across requests using safe methods (such as GET), creating a very useful mix between security and user experience.

Let’s recap what we’ve learned about cookies flags as they are crucial when you’re storing, or allowing access to, sensitive data through them, which is a very standard practice:- marking cookies as Secure will make sure that they won’t be sent across unencrypted requests, rendering man-in-the-middle attacks fairly useless- with the HttpOnly flag we tell the browser not to share the cookie with the client (for example, allowing JavaScript access to the cookie), limiting the blast radius of an XSS attack- tagging the cookie as SameSite=Lax|Strict will prevent the browser from sending it in cross-origin requests, rendering any kind of CSRF attack ineffective

Alternatives

Reading all of this material about cookies and security, you might be tempted to say “I really want to stay away from cookies!”. The reality is that, as of now, cookies are your best bet if you want to implement some sort of session mechanism over HTTP. Every now and then I’m asked to evaluate alternatives to cookies, so I’m going to try and summarize a couple things that get mentioned very often:

  • localStorage: especially in the context of single-page applications (SPA), localStorage gets sometimes mentioned when discussing where to store sensitive tokens. The problem with this approach, though, is that localStorage does not offer any kind of protection against XSS attacks. If an attacker is able to execute a simple localStorage.getItem('token') on a victim’s browser, it’s game over. HttpOnly cookies easily overcome this issue.
  • JWT: JSON Web Tokens define a way to securely create access tokens for a client. JWT is a specification that defines how an access token would look like and does not define where is the token going to be stored. In other words, you could store a JWT in a cookie, the localStorage or even in memory, so it doesn’t make sense to consider JWTs an “alternative” to cookies.

What would LeBron do?

It’s time to move on from the HTTP protocol and its features, such as cookies. Throughout this series we’ve been on a long journey, dissecting why cookies were born, how they’re structured and how you can protect them by applying some restrictions on their Domain, Expires, Max-Age and Path attributes, and how other flags such as Secure, HttpOnly and SameSite are vital in hardening cookies.

Let’s move forward and try to understand what we should do, from a security perspective, when we encounter a particular situation. The next article will try to provide advice based on best practices and past experience.

The next article in this series will introduce what I call “The Situationals”.

Originally published at odino.org (14 September 2018).

You can follow me on Twitter — rants are welcome! ?