Project

General

Profile

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

haketilo / background / policy_injector.js @ 25817b68

1
/**
2
 * Hachette injecting policy to page using webRequest
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 TYPE_PREFIX
12
 * IMPORT get_storage
13
 * IMPORT browser
14
 * IMPORT is_chrome
15
 * IMPORT is_mozilla
16
 * IMPORT gen_unique
17
 * IMPORT gen_nonce
18
 * IMPORT is_privileged_url
19
 * IMPORT url_extract_target
20
 * IMPORT sign_policy
21
 * IMPORT get_query_best
22
 * IMPORT parse_csp
23
 * IMPORTS_END
24
 */
25

    
26
var storage;
27
var query_best;
28

    
29
const csp_header_names = new Set([
30
    "content-security-policy",
31
    "x-webkit-csp",
32
    "x-content-security-policy"
33
]);
34

    
35
/* TODO: variable no longer in use; remove if not needed */
36
const unwanted_csp_directives = new Set([
37
    "report-to",
38
    "report-uri",
39
    "script-src",
40
    "script-src-elem",
41
    "prefetch-src"
42
]);
43

    
44
const report_only = "content-security-policy-report-only";
45

    
46
function url_inject(details)
47
{
48
    if (is_privileged_url(details.url))
49
	return;
50

    
51
    const targets = url_extract_target(details.url);
52
    if (targets.current)
53
	return;
54

    
55
    /* Redirect; update policy */
56
    if (targets.policy)
57
	targets.target = "";
58

    
59
    let [pattern, settings] = query_best(targets.base_url);
60
    /* Defaults */
61
    if (!pattern)
62
	settings = {};
63

    
64
    const policy = encodeURIComponent(
65
	JSON.stringify({
66
	    allow: settings.allow,
67
	    nonce: gen_nonce(),
68
	    base_url: targets.base_url
69
	})
70
    );
71

    
72
    return {
73
	redirectUrl: [
74
	    targets.base_url,
75
	    '#', sign_policy(policy, new Date()), policy,
76
	    targets.target,
77
	    targets.target2
78
	].join("")
79
    };
80
}
81

    
82
function process_csp_header(header, rule, block)
83
{
84
    const csp = parse_csp(header.value);
85

    
86

    
87
    if (block) {
88
	/* No snitching */
89
	delete csp['report-to'];
90
	delete csp['report-uri'];
91
	
92
	delete csp['script-src'];
93
	delete csp['script-src-elem'];
94

    
95
	csp['script-src-attr'] = ["'none'"];
96
	csp['prefetch-src'] = ["'none'"];
97
    }
98

    
99
    if ('script-src' in csp)
100
	csp['script-src'].push(rule);
101
    else
102
	csp['script-src'] = [rule];
103

    
104
    if ('script-src-elem' in csp)
105
	csp['script-src-elem'].push(rule);
106
    else
107
	csp['script-src-elem'] = [rule];
108

    
109
    const new_policy = Object.entries(csp).map(
110
	i => `${i[0]} ${i[1].join(' ')};`
111
    );
112

    
113
    return {name: header.name, value: new_policy.join('')};
114
}
115

    
116
function headers_inject(details)
117
{
118
    const targets = url_extract_target(details.url);
119
    /* Block mis-/unsigned requests */
120
    if (!targets.current)
121
	return {cancel: true};
122

    
123
    let orig_csp_headers = is_chrome ? null : [];
124
    let headers = [];
125
    let csp_headers = is_chrome ? headers : [];
126

    
127
    const rule = `'nonce-${targets.policy.nonce}'`;
128
    const block = !targets.policy.allow;
129

    
130
    for (const header of details.responseHeaders) {
131
	if (!csp_header_names.has(header)) {
132
	    /* Remove headers that only snitch on us */
133
	    if (header.name.toLowerCase() === report_only && block)
134
		continue;
135
	    headers.push(header);
136

    
137
	    /* If these are the original CSP headers, use them instead */
138
	    /* Test based on url_extract_target() in misc.js */
139
	    if (is_mozilla && header.name === "x-orig-csp") {
140
		let index = header.value.indexOf('%5B');
141
		if (index === -1)
142
		    continue;
143

    
144
		let sig = header.value.substring(0, index);
145
		let data = header.value.substring(index);
146
		if (sig !== sign_policy(data, 0))
147
		    continue;
148

    
149
		/* Confirmed- it's the originals, smuggled in! */
150
		try {
151
		    data = JSON.parse(decodeURIComponent(data));
152
		} catch (e) {
153
		    /* This should not be reached -
154
			it's our self-produced valid JSON. */
155
		    console.log("Unexpected internal error - invalid JSON smuggled!", e);
156
		}
157

    
158
		orig_csp_headers = csp_headers = null;
159
		for (const header of data)
160
		    headers.push(process_csp_header(header, rule, block));
161
	    }
162
	} else if (is_chrome || !orig_csp_headers) {
163
	    csp_headers.push(process_csp_header(header, rule, block));
164
	    if (is_mozilla)
165
		orig_csp_headers.push(header);
166
	}
167
    }
168

    
169
    if (orig_csp_headers) {
170
	/** Smuggle in the original CSP headers for future use.
171
	  * These are signed with a time of 0, as it's not clear there
172
	  * is a limit on how long Firefox might retain these headers in
173
	  * the cache.
174
	  */
175
	orig_csp_headers = encodeURIComponent(JSON.stringify(orig_csp_headers));
176
	headers.push({
177
	    name: "x-orig-csp",
178
	    value: sign_policy(orig_csp_headers, 0) + orig_csp_headers
179
	});
180

    
181
	headers = headers.concat(csp_headers);
182
    }
183

    
184
    /* To ensure there is a CSP header if required */
185
    if (block) {
186
	headers.push({
187
	    name: "content-security-policy",
188
	    value: `script-src ${rule}; script-src-elem ${rule}; ` +
189
		"script-src-attr 'none'; prefetch-src 'none';"
190
	});
191
    }
192

    
193
    return {responseHeaders: headers};
194
}
195

    
196
async function start_policy_injector()
197
{
198
    storage = await get_storage();
199
    query_best = await get_query_best();
200

    
201
    let extra_opts = ["blocking", "responseHeaders"];
202
    if (is_chrome)
203
	extra_opts.push("extraHeaders");
204

    
205
    browser.webRequest.onBeforeRequest.addListener(
206
	url_inject,
207
	{
208
	    urls: ["<all_urls>"],
209
	    types: ["main_frame", "sub_frame"]
210
	},
211
	["blocking"]
212
    );
213

    
214
    browser.webRequest.onHeadersReceived.addListener(
215
	headers_inject,
216
	{
217
	    urls: ["<all_urls>"],
218
	    types: ["main_frame", "sub_frame"]
219
	},
220
	extra_opts
221
    );
222
}
223

    
224
/*
225
 * EXPORTS_START
226
 * EXPORT start_policy_injector
227
 * EXPORTS_END
228
 */
(4-4/7)