Project

General

Profile

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

haketilo / background / policy_injector.js @ 5b419aed

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 sanitize_csp_header
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 headers_inject(details)
83
{
84
    const targets = url_extract_target(details.url);
85
    /* Block mis-/unsigned requests */
86
    if (!targets.current)
87
	return {cancel: true};
88

    
89
    let orig_csp_headers = is_chrome ? null : [];
90
    let headers = [];
91
    let csp_headers = is_chrome ? headers : [];
92

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

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

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

    
110
		let sig = header.value.substring(0, index);
111
		let data = header.value.substring(index);
112
		if (sig !== sign_policy(data, 0))
113
		    continue;
114

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

    
124
		orig_csp_headers = csp_headers = null;
125
		for (const header of data)
126
		    headers.push(sanitize_csp_header(header, rule, block));
127
	    }
128
	} else if (is_chrome || !orig_csp_headers) {
129
	    csp_headers.push(sanitize_csp_header(header, rule, block));
130
	    if (is_mozilla)
131
		orig_csp_headers.push(header);
132
	}
133
    }
134

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

    
147
	headers = headers.concat(csp_headers);
148
    }
149

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

    
159
    return {responseHeaders: headers};
160
}
161

    
162
async function start_policy_injector()
163
{
164
    storage = await get_storage();
165
    query_best = await get_query_best();
166

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

    
171
    browser.webRequest.onBeforeRequest.addListener(
172
	url_inject,
173
	{
174
	    urls: ["<all_urls>"],
175
	    types: ["main_frame", "sub_frame"]
176
	},
177
	["blocking"]
178
    );
179

    
180
    browser.webRequest.onHeadersReceived.addListener(
181
	headers_inject,
182
	{
183
	    urls: ["<all_urls>"],
184
	    types: ["main_frame", "sub_frame"]
185
	},
186
	extra_opts
187
    );
188
}
189

    
190
/*
191
 * EXPORTS_START
192
 * EXPORT start_policy_injector
193
 * EXPORTS_END
194
 */
(4-4/7)