Insecurely generated cookies - HttpOnly
Need
Protection of session cookies from access by client-side scripts
Context
• Usage of Rust 1.75+ for building application services
• Usage of the actix-web crate for handling HTTP requests and cookies
Description
1. Non compliant code
use actix_web::cookie::{Cookie, SameSite};
fn session_cookie(session_id: String) -> Cookie<'static> {
// Without HttpOnly, any script on the page can read the session id
Cookie::build("session_id", session_id)
.path("/")
.secure(true)
.same_site(SameSite::Strict)...The `session_cookie` function below builds the cookie that carries the session identifier. It sets the `Secure` and `SameSite` attributes, but it never calls `.http_only(true)`, so the cookie is created without the `HttpOnly` attribute. Without `HttpOnly`, the browser exposes the cookie to JavaScript through `document.cookie`. Any cross-site scripting flaw in the application, or a compromised third-party script such as an analytics or advertising library, can read the session identifier and send it to an attacker, who then uses it to take over the session from their own browser. Calling `.http_only(false)` explicitly has the same effect.
2. Steps
• Call `.http_only(true)` on every `Cookie::build` chain that creates a session, authentication or CSRF cookie.
• Remove explicit `.http_only(false)` calls from cookies that carry credentials.
• Keep the default `HttpOnly` behavior of `actix_session::SessionMiddleware` and never call `cookie_http_only(false)`.
• Build sensitive cookies in a single helper function so the attributes cannot be forgotten in individual handlers.
• Combine `HttpOnly` with the `Secure` and `SameSite` attributes and with a restrictive Content-Security-Policy.
3. Secure code example
use actix_web::cookie::{Cookie, SameSite};
fn session_cookie(session_id: String) -> Cookie<'static> {
// HttpOnly keeps the cookie out of reach of document.cookie
Cookie::build("session_id", session_id)
.path("/")
.http_only(true)
.secure(true)...The corrected function adds `.http_only(true)` to the builder, so the browser sends the cookie with each request but refuses to expose it to JavaScript. Scripts injected into the page can no longer read or copy the session identifier. `HttpOnly` does not fix cross-site scripting, since an injected script can still act on behalf of the user while the page is open, but it prevents the theft of the session that would let the attacker keep using it from elsewhere. The same attribute applies to sessions managed by the `actix-session` crate: its `SessionMiddleware` sets `HttpOnly` by default, and it must not be turned off with `cookie_http_only(false)`.
References
• 128. Insecurely generated cookies - HttpOnly