-
Notifications
You must be signed in to change notification settings - Fork 2
/
hmac-csrf.js
133 lines (111 loc) · 3.54 KB
/
hmac-csrf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
var uuid = require('uuid');
var crypto = require('crypto');
var URL = require('url');
module.exports = function(options) {
options = options || {};
options.keys = options.keys || {}
var sessionCookie = options.sessionCookie || 'connect.sid'
var secret = options.secret || uuid.v4();
var validityDelay = options.validityDelay || 86400*1000/*24h*/;
var algorithm = options.algorithm || 'sha256';
var templateResponseAttr = options.templateAttr || 'locals';
var keys = {
query : options.keys.query || '_csrf',
body : options.keys.body || '_csrf',
header: options.keys.header || 'x-csrf-token'
};
return function(req, res, next) {
if ('HEAD' == req.method || 'OPTIONS' == req.method) {
return next();
}
var sessionId = extractSessionId(sessionCookie, req, res);
if('GET' == req.method) {
if(res[templateResponseAttr]) {
res[templateResponseAttr]._csrf = generateCSRF(secret, algorithm, validityDelay, sessionId);
}
return next();
}
if(options.origin && req.headers.origin) {
if(options.origin !== req.headers.origin) {
res.writeHead(403);
res.end('CSRF attempt. Origin header mismatch.');
return;
}
}
if(options.ignore && options.ignore.length > 0) {
for(var i = 0 ; i < options.ignore.length ; i++) {
var path = options.ignore[i];
if((path instanceof RegExp && path.test(req.url)) || req.url === path) {
return next()
}
}
}
if(csrfTokenValid(secret, algorithm, validityDelay, sessionId, keys, req)) {
next();
} else {
res.writeHead(403);
res.end('CSRF attempt. Token.');
}
}
}
function csrfTokenValid(secret, algorithm, validityDelay, sessionId, keys, req) {
var token = extractCSRFToken(keys, req);
if(!token) {
console.log('CSRF attempt. Token missing.');
return false;
}
if(!sessionId) {
console.log('CSRF attempt. Could not resume session.');
return false;
}
var data = /^{(\d+)}(.*)$/.exec(token);
if(data && data.length === 3) {
var now = Date.now()
var expirationTimestamp = Number(data[1])
if(expirationTimestamp > now) {
var actualHash = data[2];
var expectedHash = generateHash(secret, algorithm, expirationTimestamp, sessionId);
if(actualHash === expectedHash) {
return true;
} else {
console.log('CSRF attempt. Invalid token.');
}
} else {
console.log('CSRF attempt. Expired token.', new Date(expirationTimestamp));
}
}
return false;
}
function extractCSRFToken(keys, req) {
if(req.headers && req.headers[keys.header]) {
return req.headers[keys.header];
}
if(req.body && req.body[keys.body]) {
return req.body[keys.body];
}
var url = URL.parse(req.url, true, false)
if(url.query && url.query[keys.query]) {
return url.query[keys.query];
}
}
function extractSessionId(sessionCookie, req, res) {
if(req.cookies && req.cookies[sessionCookie]) {
return req.cookies[sessionCookie];
}
}
function generateHash(secret, algorithm, expirationTimestamp, sessionId) {
var hmac = crypto.createHmac(algorithm, secret);
hmac.setEncoding('hex');
hmac.write(sessionId);
hmac.write('' + expirationTimestamp);
hmac.end();
return hmac.read();
}
function generateCSRF(secret, algorithm, validityDelay, sessionId) {
if(sessionId) {
var expirationTimestamp = Date.now() + validityDelay;
var hash = generateHash(secret, algorithm, expirationTimestamp, sessionId)
hash = '{' + expirationTimestamp + '}' + hash;
return hash
}
}