Failure to abandon session¶
ID: js/session-fixationKind: problemSecurity severity: 5Severity: warningPrecision: mediumTags: - security - external/cwe/cwe-384Query suites: - javascript-security-extended.qls - javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Reusing a session could allow an attacker to gain unauthorized access to another account. Always ensure that, when a user logs in or out, the current session is abandoned so that a new session may be started.
Recommendation¶
Always usereq.session.regenerate(...); to start a new session when a user logs in or out.
Example¶
The following example shows the previous session being used after authentication. This would allow a previous user to use the new user’s account.
constexpress=require('express');constsession=require('express-session');varbodyParser=require('body-parser')constapp=express();app.use(bodyParser.urlencoded({extended:false}))app.use(session({secret:'keyboard cat'}));app.post('/login',function(req,res){// Check that username password matchesif(req.body.username==='admin'&&req.body.password==='admin'){req.session.authenticated=true;res.redirect('/');}else{res.redirect('/login');}});
This code example solves the problem by not reusing the session, and instead callingreq.session.regenerate() to ensure that the session is not reused.
constexpress=require('express');constsession=require('express-session');varbodyParser=require('body-parser')constapp=express();app.use(bodyParser.urlencoded({extended:false}))app.use(session({secret:'keyboard cat'}));app.post('/login',function(req,res){// Check that username password matchesif(req.body.username==='admin'&&req.body.password==='admin'){req.session.regenerate(function(err){if(err){res.send('Error');}else{req.session.authenticated=true;res.redirect('/');}});}else{res.redirect('/login');}});
References¶
OWASP:Session fixation
Stack Overflow:Creating a new session after authentication with Passport
jscrambler.com:Best practices for secure session management in Node
Common Weakness Enumeration:CWE-384.