From HTTP to HTTPS: A Deep Dive into HTTP Strict Transport Security (HSTS)

#Understanding HSTS and Its Importance
One of the security headers you’ll come across is HSTS (HTTP Strict Transport Security). If you’re using Node.js with frameworks like Express, Fastify, or NestJS, you might find libraries like Helmet useful for managing these headers.
#The SSL Handshake Process
As you know, the SSL handshake process happens right after the TCP handshake to establish an encrypted secure connection. This ensures that any attacker trying to intercept a request or response will encounter encrypted data.
However, if you revisit the handshake process, you’ll notice that the first request sent by the client (the client hello) can be over HTTP if the client hasn’t specified the protocol. This poses a problem because an attacker could intercept this initial HTTP request, potentially leading to a Man-in-the-Middle (MITM) attack. This could result in:
#SSL Stripping
The attacker redirects the client to a different website, making all the traffic go to the attacker’s site.
#Downgrade Attack
During the SSL handshake, the client sends all supported cipher suites, and the server matches the latest one available. The attacker could downgrade these suites to use older, less secure algorithms (except for TLS 1.3, which has a different handshake process).
#The Solution
The solution is to ensure that the client never sends an HTTP request. This control needs to come from the client side, particularly from the browser. The server initially sends a specific header that informs the client that any request to the domain or subdomains must be an HTTPS request. The browser then stores this information in its preload list, ensuring all future connections to the server are HTTPS.
This specific header is the HSTS (HTTP Strict Transport Security) header. However, there’s a small issue: the first request the client makes to the server might not have the HSTS information yet, so it could be an HTTP request. This depends on whether the browser enforces HTTPS for the first request.
#Preloading the Website URL
To solve this, you can preload the website URL in the browser’s list, ensuring every request is HTTPS right from the start. This mitigates the initial risk.
#Why Not Just Rely on the Client?
You might wonder, “Why go through all this? Can’t the client just specify the protocol?” Relying on the client isn’t ideal, especially for security-related aspects, and clients might not always enter the URL manually—they might click on links, for example.
For a deeper dive, check out the resource below: