-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
450 lines (392 loc) · 13 KB
/
main.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"use strict";
/*
Session Armor Protocol, Google Chrome Extension
Copyright (C) 2016 Andrew Sauber
This software is licensed under the AGPLv3 open source license. See
LICENSE.txt. The license can also be found at the following URL, please note
the above copyright notice. https://www.gnu.org/licenses/agpl-3.0.en.html
*/
var _ = require("underscore");
var Hashes = require("jshashes");
var compare = require("secure-compare");
require("./status-icon");
/* request related */
var hashAlgoMask = "\x01\x05";
var hashModules = [
[1 << 0, new Hashes.SHA256({'utf8': false})],
// [1 << 1, Hashes.SHA384],
[1 << 2, new Hashes.SHA512({'utf8': false})],
[1 << 3, new Hashes.RMD160({'utf8': false})]
]
hashModules = _.object(hashModules);
var bodyCache = {}
var headerChoices = [
'', /* least-significant bit used for nonce flag */
'Host',
'User-Agent',
'Accept',
'Connection',
'Accept-Encoding',
'Accept-Language',
'Referer',
'Cookie',
'Accept-Charset',
'If-Modified-Since',
'If-None-Match',
'Range',
'Date',
'Authorization',
'Cache-Control',
'Origin',
'Pragma',
'DNT',
'X-Csrf-Token',
'Sec-WebSocket-Version',
'Sec-WebSocket-Protocol',
'Sec-WebSocket-Key',
'Sec-WebSocket-Extensions',
'TE',
'X-Requested-With',
'X-Forwarded-For',
'X-Forwarded-Proto',
'Forwarded',
'From',
'HTTP2-Settings',
'Upgrade',
'Proxy-Authorization',
'If',
'If-Match',
'If-Range',
'If-Unmodified-Since',
'Max-Forwards',
'Prefer',
'Via',
'ALPN',
'Expect',
'Alt-Used',
'CalDAV-Timezones',
'Schedule-Reply',
'If-Schedule-Tag-Match',
'Destination',
'Lock-Token',
'Timeout',
'Ordering-Type',
'Overwrite',
'Position',
'Depth',
'SLUG',
'Trailer',
'MIME-Version'
];
function getHost(url) {
// capture everything up to the first lone slash
// excluding the scheme and port
return url.match(/(.+:\/\/)([^/:]+)(.*)?\/([^/]|$)/)[2];
}
function getOrigin(url) {
// capture everything up to the first lone slash
// including the scheme, host, and port
return url.match(/(.+:\/\/[^/]+)\/([^/]|$)/)[1];
}
function getPath(url) {
// capture everything after the first lone slash
var path = url.match(/(.+:\/\/[^/]+)\/(.*|$)/)[2];
return '/' + path;
}
function domainHasSession(url) {
return localStorage[getOrigin(url)] !== undefined;
}
function unpackMask(mask) {
return stringToBytes(mask.slice(1));
}
function stringToBytes(str) {
var bytes = [], charCode;
for (var i = 0, len = str.length; i < len; ++i) {
charCode = str.charCodeAt(i);
if ((charCode & 0xFF00) >> 8) {
bytes.push((charCode & 0xFF00) >> 8);
}
bytes.push(charCode & 0xFF);
}
return bytes;
}
function bytesToInt(bytes) {
var n = 0;
for (var i = bytes.length - 1, len = bytes.length; i >= 0; --i) {
n |= bytes[i] << (8 * (len - 1 - i));
}
return n;
}
function intToBytes(i) {
// Not using an arbitrary precision implementation of this for two reasons:
// 1. Bitwise operators in JavaScript convert operands to 32-bit signed
// integers, unlike Python, which maintains arbitrary precision.
// 2. If the input has it's MSB as 1, it's treated as negative number, and
// gets 1-filled on the right when shifted, resulting in "negative" byte
// values which are not amenable to string encoding.
// Thus, this 0x00ff mask, which is used to kill the 1-filled bits of
// parameters which happen to be negative when coerced.
return [
(i >> 24 & 0x00ff),
(i >> 16 & 0x00ff),
(i >> 8 & 0x00ff),
(i >> 0 & 0x00ff)
];
}
function bytesToString(bytes) {
return String.fromCharCode.apply(this, bytes);
}
function objToHeaderString(obj) {
return _.map(_.keys(obj), function (key) {
return key + ':' + btoa(obj[key]);
}).join(';');
}
function unpackMasks(headerValues) {
if (headerValues.h) {
headerValues.hashMask = unpackMask(headerValues.h)[0];
}
if (headerValues.ah) {
headerValues.headerMask = unpackMask(headerValues.ah);
}
return headerValues;
}
function headerStringToObj(str) {
if (!str) return {};
var pairs = str.split(';');
var headerValues = {};
_.each(pairs, function(pair) {
pair = pair.split(':');
headerValues[pair[0]] = atob(pair[1]);
});
headerValues = unpackMasks(headerValues);
return headerValues;
}
function hmac(key, hashMask, string) {
var macObj = hashModules[hashMask];
return macObj.b64_hmac(key, string);
}
function headerValuesToAuth(headerMask, extraHeaders, requestHeaders) {
var selectedHeaders = [];
for (var i = 0, len = headerMask.length; i < len; ++i) {
var currentByte = headerMask[len - 1 - i];
for (var j = 0; j < 8; ++j) {
if (currentByte & (1 << j)) {
selectedHeaders.push(headerChoices[i * 8 + j]);
}
}
}
// Append the extra authenticated headers in their order
selectedHeaders = selectedHeaders.concat(extraHeaders);
// These need to be appended in the bitmask order
var authHeaderValues = [];
for (var header of selectedHeaders) {
for (var reqHeader of requestHeaders) {
if (header.toLowerCase() === reqHeader.name.toLowerCase()) {
authHeaderValues.push(reqHeader.value);
}
}
}
return authHeaderValues;
}
function stringForAuth(nonce, requestTime, lastRequestTime, authHeaderValues,
path, body) {
var macTokens = ['+', requestTime, lastRequestTime];
if (nonce !== null) {
macTokens.unshift(nonce);
}
macTokens = macTokens.concat(authHeaderValues);
macTokens = macTokens.concat(path);
macTokens.push(body || '');
return macTokens.join('|');
}
function genHeaderString(originValues, ourMac, requestTime, lastRequestTime,
nonce) {
var requestValues = {}
requestValues.c = ourMac;
requestValues.t = requestTime;
requestValues.lt = lastRequestTime;
requestValues.s = originValues.s;
requestValues.iv = originValues.iv;
requestValues.tag = originValues.tag;
requestValues.h = originValues.h;
requestValues.ah = originValues.ah;
if (originValues.eah) {
requestValues.eah = originValues.eah;
}
if (nonce !== null) {
requestValues.n = nonce;
}
return objToHeaderString(requestValues);
}
function genSignedHeader(details) {
var originValues = JSON.parse(localStorage[getOrigin(details.url)]);
var hmacKey = originValues['kh'];
if (usingNonceReplayPrevention(originValues.ah)) {
var nonce = getNonce(details.url);
}
nonce = nonce ? setAndIncrementNonce(details.url, nonce) : null;
var requestTime = Math.floor(Date.now() / 1000);
var lastRequestTime = localStorage[getOrigin(details.url) + '|lrt'];
var path = getPath(details.url);
var body = bodyCache[details.requestId];
/* we use two seperate callbacks, so don't leak memory*/
delete bodyCache[details.requestId];
var authHeaderValues = headerValuesToAuth(originValues.headerMask,
originValues.eah.split(','),
details.requestHeaders);
var authString = stringForAuth(nonce, requestTime, lastRequestTime,
authHeaderValues, path, body);
var ourMac = hmac(hmacKey, originValues.hashMask, authString);
ourMac = atob(ourMac);
return genHeaderString(originValues, ourMac, requestTime, lastRequestTime,
nonce);
}
function genReadyHeader() {
var headerValue = objToHeaderString({
'r': hashAlgoMask
});
return headerValue;
}
function usingNonceReplayPrevention(headerMask) {
var charCode = headerMask.charCodeAt(headerMask.length - 1);
return !!(charCode & 0x01);
}
function getNonce(url) {
var origin = getOrigin(url);
var nonce = localStorage[origin + '|nonce'];
return nonce ?
bytesToInt(stringToBytes(nonce)) :
null;
}
function setNonce(url, nonce) {
var origin = getOrigin(url);
nonce = bytesToString(intToBytes(nonce));
localStorage[origin + '|nonce'] = nonce;
return nonce;
}
function setAndIncrementNonce(url, nonce) {
nonce++;
return setNonce(url, nonce);
}
function storeNewSession(url, headerValues) {
var origin = getOrigin(url);
if (!origin.startsWith("https")) {
console.log("Won't store SessionArmor session delivered insecurely.");
return;
}
if (usingNonceReplayPrevention(headerValues.ah)) {
setNonce(url, bytesToInt(stringToBytes(headerValues['n'])));
}
localStorage[origin] = JSON.stringify(headerValues);
}
function invalidateSession(url, serverMac) {
var origin = getOrigin(url);
var originValues = JSON.parse(localStorage[origin]);
var hmacKey = originValues['kh'];
var ourMac = hmac(hmacKey, originValues.hashMask, "Session Expired");
serverMac = btoa(serverMac);
if (!compare(serverMac, ourMac)) return;
localStorage.removeItem(origin);
localStorage.removeItem(origin + '|nonce');
localStorage.removeItem(origin + '|lrt');
}
function onHeaderReceived(details) {
var headerValues = {};
_.each(details.responseHeaders, function(header) {
if (header.name !== "X-S-Armor") return;
headerValues = headerStringToObj(header.value);
});
if (headerValues.hasOwnProperty('s')) {
storeNewSession(details.url, headerValues);
} else if (headerValues.hasOwnProperty('i')) {
invalidateSession(details.url, headerValues['i']);
}
}
function beforeSendHeader(details) {
details.requestHeaders.push({
"name": "Host",
"value": getHost(details.url)
});
var headerValue =
domainHasSession(details.url)
? genSignedHeader(details)
: genReadyHeader();
details.requestHeaders.push({
"name": "X-S-Armor",
"value": headerValue
});
// Set "last request time" for this domain to now
var lastRequestTimeKey = getOrigin(details.url) + '|lrt';
localStorage[lastRequestTimeKey] = Math.floor(Date.now() / 1000);
return {requestHeaders: details.requestHeaders};
}
/* body-related */
function extendedEncodeURIComponent(s) {
return encodeURIComponent(s).replace(/[()'!]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
function formDataToString(formData) {
return _.map(Object.keys(formData), function(key) {
// each key has an array of values
return _.map(formData[key], function(value) {
return key + '=' +
extendedEncodeURIComponent(value).replace(/%20/g, '+');
}).join('&');
// forms are encoded with key=value pairs joined with '&'
// keys can be repeated
}).join('&');
}
function beforeRequest(details) {
/* Skip this step if this request does not have a related, active,
* SessionArmor session, or does not have body data */
if (!domainHasSession(details.url) || !details.requestBody) return;
if (details.requestBody.error) {
/* If Chrome has a problem parsing the request body,
* log and continue. The request will fail on the server side. */
console.log("request body error: " + details.requestBody.error);
} else if (details.requestBody.raw) {
/*
Raw body authentication requires patching Chromium as follows. This
forces Chrome to use the "raw" presenter for both the MIME type of
multipart/form-data _and_ the MIME type of
application/x-www-form-urlencoded
(as of 2016-08-24)
diff --git
a/extensions/browser/api/web_request/web_request_event_details.cc
b/extensions/browser/api/web_request/web_request_event_details.cc
index a9f2f83..835b0eb5 100644
--- a/extensions/browser/api/web_request/web_request_event_details.cc
+++ b/extensions/browser/api/web_request/web_request_event_details.cc
@@ -84,7 +84,6
@@ void WebRequestEventDetails::SetRequestBody(
const net::URLRequest* request) {
if (presenters[i]->Succeeded()) {
request_body->Set(kKeys[i], presenters[i]->Result());
some_succeeded = true;
- break;
}
}
*/
bodyCache[details.requestId] = String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes));
}
}
/* handle body data and store it for HMAC */
chrome.webRequest.onBeforeRequest.addListener(
beforeRequest,
{"urls": ["https://*/*", "http://*/*"]},
["blocking", "requestBody"]
);
/* prepare HMAC before requests */
chrome.webRequest.onBeforeSendHeaders.addListener(
beforeSendHeader,
{"urls": ["https://*/*", "http://*/*"]},
["blocking", "requestHeaders"]
);
/* handle Session initialization */
chrome.webRequest.onHeadersReceived.addListener(
onHeaderReceived,
{"urls": ["https://*/*", "http://*/*"]},
["blocking", "responseHeaders"]
);