Project

General

Profile

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

haketilo / common / misc.js @ 2875397f

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 browser
12
 * IMPORT TYPE_NAME
13
 * IMPORT TYPE_PREFIX
14
 * IMPORTS_END
15
 */
16

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

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

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

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

    
46
/* csp rule that blocks all scripts except for those injected by us */
47
function csp_rule(nonce)
48
{
49
    const rule = `'nonce-${nonce}'`;
50
    return `script-src ${rule}; script-src-elem ${rule}; script-src-attr 'none'; prefetch-src 'none';`;
51
}
52

    
53
/* Check if some HTTP header might define CSP rules. */
54
const csp_header_names = new Set([
55
    "content-security-policy",
56
    "x-webkit-csp",
57
    "x-content-security-policy"
58
]);
59

    
60
const report_only_header_name = "content-security-policy-report-only";
61

    
62
function is_csp_header_name(string, include_report_only)
63
{
64
    string = string && string.toLowerCase().trim() || "";
65

    
66
    return (include_report_only && string === report_only_header_name) ||
67
	csp_header_names.has(string);
68
}
69

    
70
/*
71
 * Print item together with type, e.g.
72
 * nice_name("s", "hello") → "hello (script)"
73
 */
74
function nice_name(prefix, name)
75
{
76
    return `${name} (${TYPE_NAME[prefix]})`;
77
}
78

    
79
/* Open settings tab with given item's editing already on. */
80
function open_in_settings(prefix, name)
81
{
82
    name = encodeURIComponent(name);
83
    const url = browser.runtime.getURL("html/options.html#" + prefix + name);
84
    window.open(url, "_blank");
85
}
86

    
87
/* Check if url corresponds to a browser's special page */
88
function is_privileged_url(url)
89
{
90
    return !!/^(chrome(-extension)?|moz-extension):\/\/|^about:/i.exec(url);
91
}
92

    
93
/* Parse a CSP header */
94
function parse_csp(csp) {
95
    let directive, directive_array;
96
    let directives = {};
97
    for (directive of csp.split(';')) {
98
	directive = directive.trim();
99
	if (directive === '')
100
	    continue;
101

    
102
	directive_array = directive.split(/\s+/);
103
	directive = directive_array.shift();
104
	/* The "true" case should never occur; nevertheless... */
105
	directives[directive] = directive in directives ?
106
	    directives[directive].concat(directive_array) :
107
	    directive_array;
108
    }
109
    return directives;
110
}
111

    
112
/* Make CSP headers do our bidding, not interfere */
113
function sanitize_csp_header(header, policy)
114
{
115
    const rule = `'nonce-${policy.nonce}'`;
116
    const csp = parse_csp(header.value);
117

    
118
    if (!policy.allow) {
119
	/* No snitching */
120
	delete csp['report-to'];
121
	delete csp['report-uri'];
122

    
123
	delete csp['script-src'];
124
	delete csp['script-src-elem'];
125

    
126
	csp['script-src-attr'] = ["'none'"];
127
	csp['prefetch-src'] = ["'none'"];
128
    }
129

    
130
    if ('script-src' in csp)
131
	csp['script-src'].push(rule);
132
    else
133
	csp['script-src'] = [rule];
134

    
135
    if ('script-src-elem' in csp)
136
	csp['script-src-elem'].push(rule);
137
    else
138
	csp['script-src-elem'] = [rule];
139

    
140
    const new_csp = Object.entries(csp).map(
141
	i => `${i[0]} ${i[1].join(' ')};`
142
    );
143

    
144
    return {name: header.name, value: new_csp.join('')};
145
}
146

    
147
/* Regexes and objest to use as/in schemas for parse_json_with_schema(). */
148
const nonempty_string_matcher = /.+/;
149

    
150
const matchers = {
151
    sha256: /^[0-9a-f]{64}$/,
152
    nonempty_string: nonempty_string_matcher,
153
    component: [
154
	new RegExp(`^[${TYPE_PREFIX.SCRIPT}${TYPE_PREFIX.BAG}]$`),
155
	nonempty_string_matcher
156
    ]
157
};
158

    
159
/*
160
 * EXPORTS_START
161
 * EXPORT gen_nonce
162
 * EXPORT csp_rule
163
 * EXPORT is_csp_header_name
164
 * EXPORT nice_name
165
 * EXPORT open_in_settings
166
 * EXPORT is_privileged_url
167
 * EXPORT sanitize_csp_header
168
 * EXPORT matchers
169
 * EXPORTS_END
170
 */
(5-5/14)