Guard against a session id collision: check the session file does not already exist, regenerate if it does

A RAND_bytes()-generated 160-bit session id colliding with an existing session file is astronomically unlikely, but the check is cheap and removes any dependence on that probability - regenerates (up to 5 attempts, then throws) rather than ever reusing an existing sessions file.
This commit is contained in:
Brad Arant committed 2026-08-26 11:12:41 -07:00
1 parent 7f6ebb0ea8
commit b276bdb6cc
1 file changed
+14
+14
View File
@@ -24,6 +24,20 @@ namespace jet {
// follow sessiontimeoutredirecturl.
} else {
SessionId sessionId;
// A 160-bit CSPRNG value colliding with an existing session file
// is astronomically unlikely, but cheap to guard against outright
// rather than trust the probability - regenerate on an actual
// collision instead of ever reusing another session's file.
int sessionIdAttempts = 0;
while(true) {
coreutils::MString candidatePath;
candidatePath << resolveKeyword("sessiondir") << "/" << sessionId << ".json";
if(access(candidatePath.c_str(), F_OK) != 0)
break;
if(++sessionIdAttempts >= 5)
throw coreutils::Exception("could not generate a unique session id after multiple attempts.");
sessionId = SessionId();
}
global.headers["Set-Cookie"] << "session=" << sessionId;
global.cookies.data["session"] = sessionId;
sessionIdValue = sessionId;