1
|
/**
|
2
|
* This file is part of Haketilo.
|
3
|
*
|
4
|
* Function: Enforcing script blocking rules on a given page, working from a
|
5
|
* content script.
|
6
|
*
|
7
|
* Copyright (C) 2021,2022 Wojtek Kosior
|
8
|
* Copyright (C) 2021 jahoti
|
9
|
*
|
10
|
* This program is free software: you can redistribute it and/or modify
|
11
|
* it under the terms of the GNU General Public License as published by
|
12
|
* the Free Software Foundation, either version 3 of the License, or
|
13
|
* (at your option) any later version.
|
14
|
*
|
15
|
* This program is distributed in the hope that it will be useful,
|
16
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
17
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
18
|
* GNU General Public License for more details.
|
19
|
*
|
20
|
* As additional permission under GNU GPL version 3 section 7, you
|
21
|
* may distribute forms of that code without the copy of the GNU
|
22
|
* GPL normally required by section 4, provided you include this
|
23
|
* license notice and, in case of non-source distribution, a URL
|
24
|
* through which recipients can access the Corresponding Source.
|
25
|
* If you modify file(s) with this exception, you may extend this
|
26
|
* exception to your version of the file(s), but you are not
|
27
|
* obligated to do so. If you do not wish to do so, delete this
|
28
|
* exception statement from your version.
|
29
|
*
|
30
|
* As a special exception to the GPL, any HTML file which merely
|
31
|
* makes function calls to this code, and for that purpose
|
32
|
* includes it by reference shall be deemed a separate work for
|
33
|
* copyright law purposes. If you modify this code, you may extend
|
34
|
* this exception to your version of the code, but you are not
|
35
|
* obligated to do so. If you do not wish to do so, delete this
|
36
|
* exception statement from your version.
|
37
|
*
|
38
|
* You should have received a copy of the GNU General Public License
|
39
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
40
|
*
|
41
|
* I, Wojtek Kosior, thereby promise not to sue for violation of this file's
|
42
|
* license. Although I request that you do not make use of this code in a
|
43
|
* proprietary program, I am not going to enforce this in court.
|
44
|
*/
|
45
|
|
46
|
#FROM common/misc.js IMPORT gen_nonce, csp_header_regex
|
47
|
|
48
|
document.content_loaded = document.readyState === "complete";
|
49
|
const wait_loaded = e => e.content_loaded ? Promise.resolve() :
|
50
|
new Promise(c => e.addEventListener("DOMContentLoaded", c, {once: true}));
|
51
|
|
52
|
wait_loaded(document).then(() => document.content_loaded = true);
|
53
|
|
54
|
/*
|
55
|
* In the case of HTML documents:
|
56
|
* 1. When injecting some payload we need to sanitize <meta> CSP tags before
|
57
|
* they reach the document.
|
58
|
* 2. Only <meta> tags inside <head> are considered valid by the browser and
|
59
|
* need to be considered.
|
60
|
* 3. We want to detach <html> from document, wait until its <head> completes
|
61
|
* loading, sanitize it and re-attach <html>.
|
62
|
* 4. We shall wait for anything to appear in or after <body> and take that as
|
63
|
* a sign <head> has finished loading.
|
64
|
* 5. Otherwise, getting the `DOMContentLoaded' event on the document shall also
|
65
|
* be a sign that <head> is fully loaded.
|
66
|
*/
|
67
|
|
68
|
function make_body_start_observer(DOM_element, waiting) {
|
69
|
const observer = new MutationObserver(() => try_body_started(waiting));
|
70
|
observer.observe(DOM_element, {childList: true});
|
71
|
return observer;
|
72
|
}
|
73
|
|
74
|
function try_body_started(waiting) {
|
75
|
const body = waiting.detached_html.querySelector("body");
|
76
|
|
77
|
if ((body && (body.firstChild || body.nextSibling)) ||
|
78
|
waiting.doc.documentElement.nextSibling) {
|
79
|
finish_waiting(waiting);
|
80
|
return true;
|
81
|
}
|
82
|
|
83
|
if (body && waiting.observers.length < 2)
|
84
|
waiting.observers.push(make_body_start_observer(body, waiting));
|
85
|
}
|
86
|
|
87
|
function finish_waiting(waiting) {
|
88
|
if (waiting.finished)
|
89
|
return;
|
90
|
waiting.finished = true;
|
91
|
waiting.observers.forEach(observer => observer.disconnect());
|
92
|
setTimeout(waiting.callback, 0);
|
93
|
}
|
94
|
|
95
|
function _wait_for_head(doc, detached_html, callback) {
|
96
|
const waiting = {doc, detached_html, callback, observers: []};
|
97
|
|
98
|
if (try_body_started(waiting))
|
99
|
return;
|
100
|
|
101
|
waiting.observers = [make_body_start_observer(detached_html, waiting)];
|
102
|
|
103
|
wait_loaded(doc).then(() => finish_waiting(waiting));
|
104
|
}
|
105
|
|
106
|
function wait_for_head(doc, detached_html) {
|
107
|
return new Promise(cb => _wait_for_head(doc, detached_html, cb));
|
108
|
}
|
109
|
|
110
|
const blocked_str = "blocked";
|
111
|
|
112
|
function block_attribute(node, attr, ns=null, replace_with=null) {
|
113
|
const [hasa, geta, seta, rema] = ["has", "get", "set", "remove"]
|
114
|
.map(m => (n, ...args) => typeof ns === "string" ?
|
115
|
n[`${m}AttributeNS`](ns, ...args) : n[`${m}Attribute`](...args));
|
116
|
/*
|
117
|
* Disabling attributes by prepending `blocked-' allows them to still be
|
118
|
* relatively easily accessed in case they contain some useful data.
|
119
|
*/
|
120
|
const construct_name = [attr];
|
121
|
while (hasa(node, construct_name.join("")))
|
122
|
construct_name.unshift(blocked_str);
|
123
|
|
124
|
while (construct_name.length > 1) {
|
125
|
construct_name.shift();
|
126
|
const name = construct_name.join("");
|
127
|
seta(node, `${blocked_str}-${name}`, geta(node, name));
|
128
|
}
|
129
|
|
130
|
rema(node, attr);
|
131
|
if (replace_with !== null)
|
132
|
seta(node, attr, replace_with);
|
133
|
}
|
134
|
|
135
|
/*
|
136
|
* Used to disable `<script>'s and `<meta>'s that have not yet been added to
|
137
|
* live DOM (doesn't work for those already added).
|
138
|
*/
|
139
|
function sanitize_meta(meta) {
|
140
|
if (csp_header_regex.test(meta.httpEquiv) && meta.content)
|
141
|
block_attribute(meta, "content");
|
142
|
}
|
143
|
|
144
|
function sanitize_script(script) {
|
145
|
script.haketilo_blocked_type = script.getAttribute("type");
|
146
|
script.type = "text/plain";
|
147
|
}
|
148
|
|
149
|
/*
|
150
|
* Executed after `<script>' has been connected to the DOM, when it is no longer
|
151
|
* eligible for being executed by the browser.
|
152
|
*/
|
153
|
function desanitize_script(script) {
|
154
|
script.setAttribute("type", script.haketilo_blocked_type);
|
155
|
|
156
|
if ([null, undefined].includes(script.haketilo_blocked_type))
|
157
|
script.removeAttribute("type");
|
158
|
|
159
|
delete script.haketilo_blocked_type;
|
160
|
}
|
161
|
|
162
|
/*
|
163
|
* Blocking certain attributes that might allow 'javascript:' URLs. Some of
|
164
|
* these are: <iframe>'s 'src' attributes (would normally execute js in URL upon
|
165
|
* frame's load), <object>'s 'data' attribute (would also execute upon load) and
|
166
|
* <a>'s 'href' attribute (would execute upon link click).
|
167
|
*/
|
168
|
const bad_url_reg = /^data:([^,;]*ml|unknown-content-type)|^javascript:/i;
|
169
|
function sanitize_element_urls(element) {
|
170
|
if (element.haketilo_sanitized_urls)
|
171
|
return;
|
172
|
|
173
|
element.haketilo_sanitized_urls = true;
|
174
|
|
175
|
let some_attr_blocked = false;
|
176
|
|
177
|
for (const attr of [...element.attributes || []]
|
178
|
.filter(attr => /^(href|src|data)$/i.test(attr.localName))
|
179
|
.filter(attr => bad_url_reg.test(attr.value))) {
|
180
|
/*
|
181
|
* Under some browsers (Mozilla) removing attributes doesn't stop their
|
182
|
* javascript from executing, but replacing them does. For 'src' and
|
183
|
* 'data' I chose to replace the attribute with a 'data:' URL and have
|
184
|
* it replace bad <iframe>'s/<object>'s contents with a "blocked"
|
185
|
* string. For 'href' (which appears on <a>'s) I chose to use a
|
186
|
* 'javascript:' URL to avoid having the page reloaded upon a link
|
187
|
* click.
|
188
|
*/
|
189
|
const replacement_value = /^href$/i.test(attr.localName) ?
|
190
|
"javascript:void('blocked');" : "data:text/plain,blocked";
|
191
|
some_attr_blocked = true;
|
192
|
block_attribute(element, attr.localName, attr.namespaceURI,
|
193
|
replacement_value);
|
194
|
}
|
195
|
|
196
|
/*
|
197
|
* Trial and error shows that under certain browsers additional element
|
198
|
* removal and re-addition might be necessary to prevent execution of a
|
199
|
* 'javascript:' URL (Parabola's Iceweasel 75 requires it for 'src' URL of
|
200
|
* an <iframe>).
|
201
|
*/
|
202
|
if (some_attr_blocked) {
|
203
|
const replacement_elem = document.createElement("a");
|
204
|
element.replaceWith(replacement_elem);
|
205
|
replacement_elem.replaceWith(element);
|
206
|
}
|
207
|
}
|
208
|
|
209
|
function sanitize_tree_urls(root) {
|
210
|
root.querySelectorAll("*[href], *[src], *[data]")
|
211
|
.forEach(sanitize_element_urls);
|
212
|
}
|
213
|
|
214
|
#IF MOZILLA
|
215
|
function sanitize_element_onevent(element) {
|
216
|
for (const attribute_node of (element.attributes || [])) {
|
217
|
const attr = attribute_node.localName, attr_lo = attr.toLowerCase();;
|
218
|
if (!/^on/.test(attr_lo) || !(attr_lo in element.wrappedJSObject))
|
219
|
continue;
|
220
|
|
221
|
/*
|
222
|
* Guard against redefined getter on DOM object property. This is a
|
223
|
* supplemental security measure since page's own scripts should be
|
224
|
* blocked and unable to redefine properties, anyway.
|
225
|
*/
|
226
|
if (Object.getOwnPropertyDescriptor(element.wrappedJSObject, attr)) {
|
227
|
console.error("Redefined property on a DOM object! The page might have bypassed our script blocking measures!");
|
228
|
continue;
|
229
|
}
|
230
|
element.wrappedJSObject[attr] = null;
|
231
|
block_attribute(element, attr, attribute_node.namespaceURI,
|
232
|
"javascript:void('blocked');");
|
233
|
}
|
234
|
}
|
235
|
|
236
|
function sanitize_tree_onevent(root) {
|
237
|
root.querySelectorAll("*")
|
238
|
.forEach(sanitize_element_onevent);
|
239
|
}
|
240
|
#ENDIF
|
241
|
|
242
|
function start_mo_sanitizing(doc) {
|
243
|
if (!doc.content_loaded) {
|
244
|
function mutation_handler(mutation) {
|
245
|
mutation.addedNodes.forEach(sanitize_element_urls);
|
246
|
#IF MOZILLA
|
247
|
mutation.addedNodes.forEach(sanitize_element_onevent);
|
248
|
#ENDIF
|
249
|
}
|
250
|
const mo = new MutationObserver(ms => ms.forEach(mutation_handler));
|
251
|
mo.observe(doc, {childList: true, subtree: true});
|
252
|
wait_loaded(doc).then(() => mo.disconnect());
|
253
|
}
|
254
|
}
|
255
|
|
256
|
#IF MOZILLA
|
257
|
/*
|
258
|
* Normally, we block scripts with CSP. However, Mozilla does optimizations that
|
259
|
* cause part of the DOM to be loaded when our content scripts get to run. Thus,
|
260
|
* before the CSP rules we inject (for non-HTTP pages) become effective, we need
|
261
|
* to somehow block the execution of `<script>'s and intrinsics that were
|
262
|
* already there. Additionally, some browsers (IceCat 60) seem to have problems
|
263
|
* applying this CSP to non-inline `<scripts>' in certain scenarios.
|
264
|
*/
|
265
|
function prevent_script_execution(event) {
|
266
|
if (!event.target.haketilo_payload)
|
267
|
event.preventDefault();
|
268
|
}
|
269
|
#ENDIF
|
270
|
|
271
|
/*
|
272
|
* Here we block all scripts of a document which might be either an
|
273
|
* HTMLDocument or an XMLDocument. Modifying an XML document might disrupt
|
274
|
* Mozilla's XML preview. This is an unfortunate thing we have to accept for
|
275
|
* now. XML documents *have to* be sanitized as well because they might
|
276
|
* contain `<script>' tags (or on* attributes) with namespace declared as
|
277
|
* "http://www.w3.org/1999/xhtml" or "http://www.w3.org/2000/svg" which allows
|
278
|
* javascript execution.
|
279
|
*/
|
280
|
async function sanitize_document(doc, policy) {
|
281
|
#IF MOZILLA
|
282
|
/*
|
283
|
* Blocking of scripts that are in the DOM from the beginning. Needed for
|
284
|
* Mozilla.
|
285
|
*/
|
286
|
const listener_args = ["beforescriptexecute", prevent_script_execution];
|
287
|
doc.addEventListener(...listener_args);
|
288
|
wait_loaded(doc).then(() => doc.removeEventListener(...listener_args));
|
289
|
|
290
|
sanitize_tree_urls(doc.documentElement);
|
291
|
sanitize_tree_onevent(doc.documentElement);
|
292
|
#ENDIF
|
293
|
|
294
|
/*
|
295
|
* Ensure our CSP rules are employed from the beginning. This CSP injection
|
296
|
* method is, when possible, going to be applied together with CSP rules
|
297
|
* injected using webRequest.
|
298
|
* Using elements namespaced as HTML makes this CSP injection also work for
|
299
|
* non-HTML documents.
|
300
|
*/
|
301
|
const source = `\
|
302
|
<!DOCTYPE html>
|
303
|
<html>
|
304
|
<head>
|
305
|
<meta http-equiv="Content-Security-Policy" content="${policy.csp}"/>
|
306
|
</head>
|
307
|
<body>
|
308
|
Loading...
|
309
|
</body>
|
310
|
</html>`;
|
311
|
const temporary_html =
|
312
|
new DOMParser().parseFromString(source, "text/html").documentElement;
|
313
|
|
314
|
/*
|
315
|
* Root node gets hijacked now, to be re-attached after <head> is loaded
|
316
|
* and sanitized.
|
317
|
*/
|
318
|
const root = doc.documentElement;
|
319
|
root.replaceWith(temporary_html);
|
320
|
|
321
|
/*
|
322
|
* When we don't inject payload, we neither block document's CSP `<meta>'
|
323
|
* tags nor wait for `<head>' to be parsed.
|
324
|
*/
|
325
|
if (policy.payload) {
|
326
|
await wait_for_head(doc, root);
|
327
|
|
328
|
root.querySelectorAll("head meta")
|
329
|
.forEach(m => sanitize_meta(m, policy));
|
330
|
}
|
331
|
|
332
|
sanitize_tree_urls(root);
|
333
|
root.querySelectorAll("script").forEach(s => sanitize_script(s, policy));
|
334
|
temporary_html.replaceWith(root);
|
335
|
root.querySelectorAll("script").forEach(s => desanitize_script(s, policy));
|
336
|
#IF MOZILLA
|
337
|
sanitize_tree_onevent(root);
|
338
|
#ENDIF
|
339
|
|
340
|
start_mo_sanitizing(doc);
|
341
|
}
|
342
|
|
343
|
async function _disable_service_workers() {
|
344
|
if (!navigator.serviceWorker)
|
345
|
return;
|
346
|
|
347
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
348
|
if (registrations.length === 0)
|
349
|
return;
|
350
|
|
351
|
console.warn("Service Workers detected on this page! Unregistering and reloading.");
|
352
|
|
353
|
try {
|
354
|
await Promise.all(registrations.map(r => r.unregister()));
|
355
|
} finally {
|
356
|
location.reload();
|
357
|
}
|
358
|
|
359
|
/* Never actually return! */
|
360
|
return new Promise(() => 0);
|
361
|
}
|
362
|
|
363
|
/*
|
364
|
* Trying to use service workers APIs might result in exceptions, for example
|
365
|
* when in a non-HTML document. Because of this, we wrap the function that does
|
366
|
* the actual work in a try {} block.
|
367
|
*/
|
368
|
async function disable_service_workers() {
|
369
|
try {
|
370
|
await _disable_service_workers()
|
371
|
} catch (e) {
|
372
|
console.debug("Exception thrown during an attempt to detect and disable service workers.", e);
|
373
|
}
|
374
|
}
|
375
|
|
376
|
function enforce_blocking(policy) {
|
377
|
if (policy.allow)
|
378
|
return;
|
379
|
|
380
|
return Promise.all([
|
381
|
sanitize_document(document, policy),
|
382
|
disable_service_workers(),
|
383
|
wait_loaded(document)
|
384
|
]);
|
385
|
}
|
386
|
#EXPORT enforce_blocking
|