summaryrefslogtreecommitdiff
path: root/background/policy_injector.js
blob: f573d484dc97859308c07104a509161bf6e7191a (about) (plain)
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
/**
 * Hachette injecting policy to page using webRequest
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Copyright (C) 2021 jahoti
 * Redistribution terms are gathered in the `copyright' file.
 */

/*
 * IMPORTS_START
 * IMPORT TYPE_PREFIX
 * IMPORT get_storage
 * IMPORT browser
 * IMPORT is_chrome
 * IMPORT is_mozilla
 * IMPORT gen_unique
 * IMPORT gen_nonce
 * IMPORT is_privileged_url
 * IMPORT url_extract_target
 * IMPORT sign_policy
 * IMPORT get_query_best
 * IMPORT parse_csp
 * IMPORTS_END
 */

var storage;
var query_best;

const csp_header_names = new Set([
    "content-security-policy",
    "x-webkit-csp",
    "x-content-security-policy"
]);

/* TODO: variable no longer in use; remove if not needed */
const unwanted_csp_directives = new Set([
    "report-to",
    "report-uri",
    "script-src",
    "script-src-elem",
    "prefetch-src"
]);

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

function url_inject(details)
{
    if (is_privileged_url(details.url))
	return;

    const targets = url_extract_target(details.url);
    if (targets.current)
	return;

    /* Redirect; update policy */
    if (targets.policy)
	targets.target = "";

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

    const policy = encodeURIComponent(
	JSON.stringify({
	    allow: settings.allow,
	    nonce: gen_nonce(),
	    base_url: targets.base_url
	})
    );

    return {
	redirectUrl: [
	    targets.base_url,
	    '#', sign_policy(policy, new Date()), policy,
	    targets.target,
	    targets.target2
	].join("")
    };
}

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


    if (block) {
	/* No snitching */
	delete csp['report-to'];
	delete csp['report-uri'];
	
	delete csp['script-src'];
	delete csp['script-src-elem'];

	csp['script-src-attr'] = ["'none'"];
	csp['prefetch-src'] = ["'none'"];
    }

    if ('script-src' in csp)
	csp['script-src'].push(rule);
    else
	csp['script-src'] = [rule];

    if ('script-src-elem' in csp)
	csp['script-src-elem'].push(rule);
    else
	csp['script-src-elem'] = [rule];

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

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

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

    let orig_csp_headers = is_chrome ? null : [];
    let headers = [];
    let csp_headers = is_chrome ? headers : [];

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

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

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

		let sig = header.value.substring(0, index);
		let data = header.value.substring(index);
		if (sig !== sign_policy(data, 0))
		    continue;

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

		orig_csp_headers = csp_headers = null;
		for (const header of data)
		    headers.push(process_csp_header(header, rule, block));
	    }
	} else if (is_chrome || !orig_csp_headers) {
	    csp_headers.push(process_csp_header(header, rule, block));
	    if (is_mozilla)
		orig_csp_headers.push(header);
	}
    }

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

	headers = headers.concat(csp_headers);
    }

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

    return {responseHeaders: headers};
}

async function start_policy_injector()
{
    storage = await get_storage();
    query_best = await get_query_best();

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

    browser.webRequest.onBeforeRequest.addListener(
	url_inject,
	{
	    urls: ["<all_urls>"],
	    types: ["main_frame", "sub_frame"]
	},
	["blocking"]
    );

    browser.webRequest.onHeadersReceived.addListener(
	headers_inject,
	{
	    urls: ["<all_urls>"],
	    types: ["main_frame", "sub_frame"]
	},
	extra_opts
    );
}

/*
 * EXPORTS_START
 * EXPORT start_policy_injector
 * EXPORTS_END
 */