Project

General

Profile

Download (5.12 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / common / misc.js @ d09b7ee1

1
/**
2
 * Hachette miscellaneous operations refactored to a separate file
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Copyright (C) 2021 jahoti
6
 * Redistribution terms are gathered in the `copyright' file.
7
 */
8

    
9
/*
10
 * IMPORTS_START
11
 * IMPORT sha256
12
 * IMPORT browser
13
 * IMPORT is_chrome
14
 * IMPORT TYPE_NAME
15
 * IMPORT TYPE_PREFIX
16
 * IMPORTS_END
17
 */
18

    
19
/* Generate a random base64-encoded 128-bit sequence */
20
function gen_nonce()
21
{
22
    let randomData = new Uint8Array(16);
23
    crypto.getRandomValues(randomData);
24
    return btoa(String.fromCharCode.apply(null, randomData));
25
}
26

    
27
/*
28
 * generating unique, per-site value that can be computed synchronously
29
 * and is impossible to guess for a malicious website
30
 */
31

    
32
/* Uint8toHex is a separate function not exported as (a) it's useful and (b) it will be used in crypto.subtle-based digests */
33
function Uint8toHex(data)
34
{
35
    let returnValue = '';
36
    for (let byte of data)
37
	returnValue += ('00' + byte.toString(16)).slice(-2);
38
    return returnValue;
39
}
40

    
41
function gen_nonce(length) // Default 16
42
{
43
    let randomData = new Uint8Array(length || 16);
44
    crypto.getRandomValues(randomData);
45
    return Uint8toHex(randomData);
46
}
47

    
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
/* csp rule that blocks all scripts except for those injected by us */
75
function csp_rule(nonce)
76
{
77
    const rule = `'nonce-${nonce}'`;
78
    return `script-src ${rule}; script-src-elem ${rule}; script-src-attr 'none'; prefetch-src 'none';`;
79
}
80

    
81
/* Check if some HTTP header might define CSP rules. */
82
const csp_header_names = new Set([
83
    "content-security-policy",
84
    "x-webkit-csp",
85
    "x-content-security-policy"
86
]);
87

    
88
const report_only_header_name = "content-security-policy-report-only";
89

    
90
function is_csp_header_name(string, include_report_only)
91
{
92
    string = string && string.toLowerCase() || "";
93

    
94
    return (include_report_only && string === report_only_header_name) ||
95
	csp_header_names.has(string);
96
}
97

    
98
/*
99
 * Print item together with type, e.g.
100
 * nice_name("s", "hello") → "hello (script)"
101
 */
102
function nice_name(prefix, name)
103
{
104
    return `${name} (${TYPE_NAME[prefix]})`;
105
}
106

    
107
/* Open settings tab with given item's editing already on. */
108
function open_in_settings(prefix, name)
109
{
110
    name = encodeURIComponent(name);
111
    const url = browser.runtime.getURL("html/options.html#" + prefix + name);
112
    window.open(url, "_blank");
113
}
114

    
115
/* Check if url corresponds to a browser's special page */
116
function is_privileged_url(url)
117
{
118
    return !!/^(chrome(-extension)?|moz-extension):\/\/|^about:/i.exec(url);
119
}
120

    
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
/* Parse a CSP header */
128
function parse_csp(csp) {
129
    let directive, directive_array;
130
    let directives = {};
131
    for (directive of csp.split(';')) {
132
	directive = directive.trim();
133
	if (directive === '')
134
	    continue;
135

    
136
	directive_array = directive.split(/\s+/);
137
	directive = directive_array.shift();
138
	/* The "true" case should never occur; nevertheless... */
139
	directives[directive] = directive in directives ?
140
	    directives[directive].concat(directive_array) :
141
	    directive_array;
142
    }
143
    return directives;
144
}
145

    
146
/* Make CSP headers do our bidding, not interfere */
147
function sanitize_csp_header(header, policy)
148
{
149
    const rule = `'nonce-${policy.nonce}'`;
150
    const csp = parse_csp(header.value);
151

    
152
    if (!policy.allow) {
153
	/* No snitching */
154
	delete csp['report-to'];
155
	delete csp['report-uri'];
156

    
157
	delete csp['script-src'];
158
	delete csp['script-src-elem'];
159

    
160
	csp['script-src-attr'] = ["'none'"];
161
	csp['prefetch-src'] = ["'none'"];
162
    }
163

    
164
    if ('script-src' in csp)
165
	csp['script-src'].push(rule);
166
    else
167
	csp['script-src'] = [rule];
168

    
169
    if ('script-src-elem' in csp)
170
	csp['script-src-elem'].push(rule);
171
    else
172
	csp['script-src-elem'] = [rule];
173

    
174
    const new_csp = Object.entries(csp).map(
175
	i => `${i[0]} ${i[1].join(' ')};`
176
    );
177

    
178
    return {name: header.name, value: new_csp.join('')};
179
}
180

    
181
/* Regexes and objest to use as/in schemas for parse_json_with_schema(). */
182
const nonempty_string_matcher = /.+/;
183

    
184
const matchers = {
185
    sha256: /^[0-9a-f]{64}$/,
186
    nonempty_string: nonempty_string_matcher,
187
    component: [
188
	new RegExp(`^[${TYPE_PREFIX.SCRIPT}${TYPE_PREFIX.BAG}]$`),
189
	nonempty_string_matcher
190
    ]
191
};
192

    
193
/*
194
 * EXPORTS_START
195
 * EXPORT gen_nonce
196
 * EXPORT extract_signed
197
 * EXPORT sign_data
198
 * EXPORT csp_rule
199
 * EXPORT is_csp_header_name
200
 * EXPORT nice_name
201
 * EXPORT open_in_settings
202
 * EXPORT is_privileged_url
203
 * EXPORT sanitize_csp_header
204
 * EXPORT matchers
205
 * EXPORTS_END
206
 */
(5-5/13)