Revision 2875397f
Added by koszko about 2 years ago
common/misc.js | ||
---|---|---|
8 | 8 |
|
9 | 9 |
/* |
10 | 10 |
* IMPORTS_START |
11 |
* IMPORT sha256 |
|
12 | 11 |
* IMPORT browser |
13 |
* IMPORT is_chrome |
|
14 | 12 |
* IMPORT TYPE_NAME |
15 | 13 |
* IMPORT TYPE_PREFIX |
16 | 14 |
* IMPORTS_END |
... | ... | |
45 | 43 |
return Uint8toHex(randomData); |
46 | 44 |
} |
47 | 45 |
|
48 |
function get_secure_salt() |
|
49 |
{ |
|
50 |
if (is_chrome) |
|
51 |
return browser.runtime.getManifest().key.substring(0, 50); |
|
52 |
else |
|
53 |
return browser.runtime.getURL("dummy"); |
|
54 |
} |
|
55 |
|
|
56 |
function extract_signed(signature, data, times) |
|
57 |
{ |
|
58 |
const now = new Date(); |
|
59 |
times = times || [[now], [now, -1]]; |
|
60 |
|
|
61 |
const reductor = |
|
62 |
(ok, time) => ok || signature === sign_data(data, ...time); |
|
63 |
if (!times.reduce(reductor, false)) |
|
64 |
return undefined; |
|
65 |
|
|
66 |
try { |
|
67 |
return JSON.parse(decodeURIComponent(data)); |
|
68 |
} catch (e) { |
|
69 |
/* This should not be reached - it's our self-produced valid JSON. */ |
|
70 |
console.log("Unexpected internal error - invalid JSON smuggled!", e); |
|
71 |
} |
|
72 |
} |
|
73 |
|
|
74 | 46 |
/* csp rule that blocks all scripts except for those injected by us */ |
75 | 47 |
function csp_rule(nonce) |
76 | 48 |
{ |
... | ... | |
89 | 61 |
|
90 | 62 |
function is_csp_header_name(string, include_report_only) |
91 | 63 |
{ |
92 |
string = string && string.toLowerCase() || ""; |
|
64 |
string = string && string.toLowerCase().trim() || "";
|
|
93 | 65 |
|
94 | 66 |
return (include_report_only && string === report_only_header_name) || |
95 | 67 |
csp_header_names.has(string); |
... | ... | |
118 | 90 |
return !!/^(chrome(-extension)?|moz-extension):\/\/|^about:/i.exec(url); |
119 | 91 |
} |
120 | 92 |
|
121 |
/* Sign a given string for a given time */ |
|
122 |
function sign_data(data, now, hours_offset) { |
|
123 |
let time = Math.floor(now / 3600000) + (hours_offset || 0); |
|
124 |
return sha256(get_secure_salt() + time + data); |
|
125 |
} |
|
126 |
|
|
127 | 93 |
/* Parse a CSP header */ |
128 | 94 |
function parse_csp(csp) { |
129 | 95 |
let directive, directive_array; |
... | ... | |
193 | 159 |
/* |
194 | 160 |
* EXPORTS_START |
195 | 161 |
* EXPORT gen_nonce |
196 |
* EXPORT extract_signed |
|
197 |
* EXPORT sign_data |
|
198 | 162 |
* EXPORT csp_rule |
199 | 163 |
* EXPORT is_csp_header_name |
200 | 164 |
* EXPORT nice_name |
Also available in: Unified diff
improve signing\n\nSignature timestamp is now handled in a saner way. Sha256 implementation is no longer pulled in contexts that don't require it.