Lec06 2.9m
Lec06 2.9m
1. Session Management
2
HTTP is stateless
HTTP Response
(Body: You need login)
Session
4
Server-side session: Example
• PHP: $_SESSION
• Global variable
• Init session: session_start();
• Access data: $_SESSION[‘name’] = value
• NodeJS: node-persist
• Uses the HTML5 localStorage API to store JSON
documents in the file system
const storage = require('node-persist');
• Init storage: storage.initSync(), storage.init()
• Store data: storage.setItem('name’,’json’)
• Get data: storage.getItem('name’)
• Update data: storage.updateItem(‘name’, ‘json’)
Cookie
6
Cookie
• Creating cookies
• The server can create a cookie by including a Set-
Cookie header in its response
Set-Cookie: theme=dark; Expires=<date>…
name value attributes
• JavaScript in the browser can create a cookie
• Users can manually create cookies in their browser
• Storing cookies
• Cookies are stored in the web browser (not the web
server)
• The browser’s cookie storage is sometimes called a
cookie jar
Cookie
• Sending cookies
• The browser automatically attaches all relevant
cookies by Cookie header in every request
Cookie: theme=dark; lang=en
8
Basic cookies attributes
10
10
Basic cookies attributes
11
11
Cookie policy
• Security issues:
• A server should not be able to set cookies for
unrelated websites
• Example: evil.com should not be able to set a cookie that gets
sent to google.com
• Cookies shouldn’t be sent to the wrong websites
• Example: A cookie used for authenticating a user to Google
should not be sent to evil.com
• We’ll see how cookies are used for logins later
• Cookie policy: A set of rules enforced by the
browser
• When the browser receives a cookie from a server,
should the cookie be accepted?
• When the browser makes a request to a server,
should the cookie be attached?
12
12
Cookie Policy: Setting Cookies
13
13
14
14
Sending Cookies – Example
15
15
Insecure Session 1
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>My Cool Site</title>
</head>
<body>
<h1>Bank login:</h1>
<form method='POST' action='/login'> Username:
<input name='username' />
<br /> Passwor:
<input name='password' type='password' />
<br />
<input type='submit' value='Login' />
</form>
</body>
</html>
16
16
Insecure Session 1
17
17
Insecure Session 1
const USERS = { alice: 'password', bob: '50505’ }
const BALANCES = { alice: 500, bob: 100 }
18
18
Insecure Session 1
19
19
20
20
Cookie verification
Client Server
GET / HTTP/1.1
Cookie: username=alice; tag=t
21
21
Insecure Session 2
22
22
Insecure Session 2
23
23
Session token
24
24
Session token: Security
25
25
Insecure Session 3
let nextSessionId = 1
const SESSIONS = {} // sessionId -> username
if (username) {
res.send(`
<h1>Welcome, ${username}</h1>
<p>Your balance is $${BALANCES[username]}</p>
`)
} else {
createReadStream('index.html').pipe(res)
}
})
26
26
Insecure Session 3
app.post('/login', (req, res) => {
const { username } = req.body
const { password } = req.body
if (password === USERS[username]) {
SESSIONS[nextSessionId] = username
res.cookie('sessionId', nextSessionId)
nextSessionId += 1
res.redirect('/’)
} else {
res.send('fail!’)
}
})
app.get('/logout', (req, res) => {
const { sessionId } = req.cookies
delete SESSIONS[sessionId]
res.clearCookie('username’)
res.redirect('/')
})
27
27
Base64Url-encode
28
28
Store and Transmitting JWTs
29
29
Example
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
30
30
Example
// Verify the token before accessing protected routes
const authMiddleware = (req, res, next) => {
const { token } = req.cookies
// or const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ message: 'No token provided'});
}
jwt.verify(token, process.env.TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Invalid token' });
}
req.user = decoded;
next();
});
};
// Protected route
app.get('/protected', authMiddleware, (req, res) => {
res.json({ message: 'You are authorized to access this resource'
});
});
31
31
Revoking JWT
32
32
Example: Revoking JWT
Check if Refresh-token is
in table
33
33
Check if Refresh-
token is not in table
34
34
Example: Revoking JWT
refreshTokens.push(refreshToken);
res.json({accessToken, refreshToken});
});
35
35
if (!token) {
return res.sendStatus(401);
}
if (!refreshTokens.includes(token)) {
return res.sendStatus(403);
}
36
36
Example: Revoking JWT
res.send("Logout successful");
});
37
37
Session attack
38
38
Session hijacking
39
39
GET / HTTP/1.1
Cookie: session-token = LjsUh264hA
Client
GET / HTTP/1.1
Cookie: session-token = LjsUh264hA
Server
40
40
Session hijacking via Cross Site Scripting
41
41
42
42
Cross-Site Request Forgery
(CSRF)
43
43
44
44
Cross-Site Request Forgery (CSRF)
45
45
46
46
Executing a CSRF Attack
47
47
48
48
Executing a CSRF Attack
49
49
CSRF Defenses
CSRF defenses are implemented by the server
(not the browser)
50
50
CSRF tokens
51
51
52
52
CSRF tokens: Usage
GET /banking/transfer HTTP/1.1
Generate CSRF token
e.g. token = e1h5AW
<input type=“hidden”
Client name=“token” value=“e1h5AW”>
bank.com
/banking/transfer?token=e1h5A
W&amount=100&dest=Bob Check token is valid?
OK
Server
53
53
Referer Header
54
54
Referer Header: Issues
55
55
56
56
Example: SameSite=Lax
mysite.com
Set-Cookie: promo_shown=1; SameSite=Lax
othersite.com
<p>Look at this amazing cat!</p>
<img src="https://mysite.com/blog/img/amazing-cat.png" />
<p>Read the <a
href="https://mysite.com/blog/cat.html">article</a>.</p>
57
57
• Session Management
https://cheatsheetseries.owasp.org/cheatsheets/Session_
Management_Cheat_Sheet.html
• Cross-Site Request Forgery Prevention
https://cheatsheetseries.owasp.org/cheatsheets/Cross-
Site_Request_Forgery_Prevention_Cheat_Sheet.html
58
58
2. User Authentication
59
59
What is authentication?
60
60
Designing password requirements
61
61
62
62
Consider human factors
63
63
Online attack
64
64
CAPTCHA
65
65
https://anti-captcha.com/
66
66
Offline attack
67
67
Password Hashing
68
68
Example: Hashing passwords
// later...
69
69
70
70
Salted Hashes
71
71
// later...
72
72
Slow Hashes
73
73
74
74
Example: PBKDF2
75
75
bcrypt()
76
76
Example: bcrypt()
try {
// Generate a salt (10 rounds is a good default)
const salt = await bcrypt.genSalt(10);
77
77
Example: bcrypt()
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
// Retrieve the hashed password from your database
const hashedPasswordFromDB = '...'; //
if (isPasswordValid) {
res.status(200).json({ message: 'Login successful!' });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
78
78
Salt + Pepper
79
79
80
80
Response discrepancy: Login
81
81
82
82
Response discrepancy: Account Creation
83
83
84
84
Response discrepancy: Timing
• Bad or Good?
const userExists = await lookupUserExists(username)
if (userExists) {
const passwordHash = hash(password)
const isValid = await lookupCredentials(username,
passwordHash)
if (!isValid) {
throw Error('Invalid username or password’)
}
} else {
throw Error('Invalid username or password')
}
85
85
Multi-factor Authentication
86
86
How attackers use a breach database
87
87
Multi-factor authentication
88
88
Multi-factor authentication
89
89
90
90
TOTP
91
91
92
92
Example: TOTP
93
93
94
94
Relay attack
“Welcome to Google.
Please login”
“User: victim
Password: password123” Attacker
“User: victim
Password: password123”
Victim Google
“Your 2FA code is 382924”
“382924” Attacker
“382924”
95
95
WebAuthn
96
96
Authenticator
97
97
WebAuthn: Registration
98
98
WebAuthn: Authentication
99
99
References
• Demo: https://webauthn.io/
• Guide: https://webauthn.guide/
100
100
Single Sign On (SSO)
101
101
What is SSO?
102
102
OpenID Connect
103
103
104
104
OpenID Connect in NodeJS
105
105
106
106
3. Authorization
107
107
108
108
Authorization strategies
109
109
Authorization strategies
110
110
OAuth 2.0
111
111
OAuth2 flows
112
112
Authorization Code Flow
113
113
114
114
CSRF
115
115
OAuth2 in NodeJS
• OAuth2 Client:
https://github.com/panva/oauth4webapi
• OAuth2 Server: https://github.com/node-
oauth/node-oauth2-server
• ExpressJS: https://github.com/node-oauth/express-
oauth-server
116
116