Answer#
The OWASP Session Management Cheat Sheet asks for session IDs with enough entropy (at least 64 bits of it, and more is better), made by a secure random generator, and meaningless to anyone who sees them. The code below uses 256 bits.
Storing a hash of the ID instead of the ID adds protection for the day a backup or a database dump leaks: the hashes cannot be turned back into working cookies. A fast hash is enough here, because the input is already 256 random bits (unlike a password, there is nothing to guess).
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
/// The value that goes in the cookie: 256 random bits.
fn new_session_id() -> String {
let mut raw = [0u8; 32];
getrandom::getrandom(&mut raw).unwrap();
URL_SAFE_NO_PAD.encode(raw)
}
/// The server stores only a hash, so a leaked table cannot be replayed as cookies.
fn lookup_key(id: &str) -> String {
hex::encode(Sha256::digest(id.as_bytes()))
}
fn main() {
let mut store: HashMap<String, &str> = HashMap::new();
let id = new_session_id();
store.insert(lookup_key(&id), "user 42");
println!("cookie value is {} characters", id.len());
println!("stored key is {} characters", lookup_key(&id).len());
println!("valid id: {:?}", store.get(&lookup_key(&id)));
println!("guessed id: {:?}", store.get(&lookup_key("AAAA")));
}cookie value is 43 characters
stored key is 64 characters
valid id: Some("user 42")
guessed id: None(The HashMap stands in for a database table or a cache. The strings shown are lengths, never values.)
How to do it#
- Create the ID with
getrandomand encode it with URL-safe base64. - Put the ID in the cookie (see the cookie attributes thread), and the hash in the store with the user ID, creation time and last-seen time.
- On each request, hash the cookie value and look up the hash.
- Expire sessions on the server: after an idle period and after an absolute lifetime.
- Give users a way to sign out everywhere (delete all rows for the user).
Common mistakes#
- Using a counter, a UUID of unknown version, or a hash of the user name as an ID.
- Putting data such as the user's role in the cookie without a signature. If you want data in the cookie, use an authenticated (signed) format.
- Keeping sessions forever.
Related questions#
Should I use JWTs for sessions?#
For a browser application with a single server (or a shared store), a random ID with server-side data is simpler and can be revoked at once. Signed tokens suit cases where other services must verify them without asking you; they then need expiry and a plan for revocation.
Why a hash and not encryption of the ID?#
Encryption needs a key that must be stored and can be lost or stolen together with the table. A one-way hash needs no key, and the server only ever needs to look the value up.
Sources#
- OWASP Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
sha2documentation: https://docs.rs/sha2/0.10.9/sha2/