forked from namecoin/dnssec-hsts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background-script.js
238 lines (201 loc) · 7.09 KB
/
background-script.js
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
229
230
231
232
233
234
235
236
237
238
/*
Copyright 2017-2019 Jeremy Rand.
This file is part of DNSSEC-HSTS.
DNSSEC-HSTS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DNSSEC-HSTS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with DNSSEC-HSTS. If not, see <https://www.gnu.org/licenses/>.
*/
function queryUpgradeNative(requestDetails, resolve, reject) {
const url = new URL(requestDetails.url);
const host = url.host;
const hostname = url.hostname;
const port = url.port;
if(! pendingUpgradeChecks.has(host)) {
pendingUpgradeChecks.set(host, new Set());
const message = {"host": host, "hostname": hostname, "port": port};
// Send message to the native DNSSEC app
nativePort.postMessage(message);
}
pendingUpgradeChecks.get(host).add(resolve);
}
// upgradeAsync function returns a Promise
// which is resolved with the upgrade after the native DNSSEC app replies
function upgradeAsync(requestDetails) {
var asyncCancel = new Promise((resolve, reject) => {
queryUpgradeNative(requestDetails, resolve, reject);
});
return asyncCancel;
}
// Adapted from Tagide/chrome-bit-domain-extension
// Returns true if timed out, returns false if hostname showed up
function sleep(milliseconds, queryFinishedRef) {
// synchronous XMLHttpRequests from Chrome extensions are not blocking event handlers. That's why we use this
// pretty little sleep function to try to get the API response before the request times out.
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
return true;
}
if (queryFinishedRef["val"]) {
return false;
}
}
}
// Compatibility for Chromium/Edge, which don't support async onBeforeRequest
// See Chromium Bug 904365
function upgradeSync(requestDetails) {
const url = new URL(requestDetails.url);
const host = url.host;
const hostname = url.hostname;
const port = url.port;
var certResponse;
var queryFinishedRef = {"val": false};
var upgrade = false;
var lookupError = false;
// Adapted from Tagide/chrome-bit-domain-extension
// Get the TLSA records from the API
var xhr = new XMLHttpRequest();
var apiUrl = "http://127.0.0.1:8080/lookup?domain="+encodeURIComponent(hostname);
// synchronous XMLHttpRequest is actually asynchronous
// check out https://developer.chrome.com/extensions/webRequest
xhr.open("GET", apiUrl, false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
console.log("Error received from API: status " + xhr.status);
lookupError = true;
}
// Get the certs returned from the API server.
certResponse = xhr.responseText;
// Notify the sleep function that we're ready to proceed
queryFinishedRef["val"] = true;
}
}
try {
xhr.send();
} catch (e) {
console.log("Error reaching API: " + e.toString());
lookupError = true;
}
// block the request until the API response is received. Block for up to two
// seconds.
if (sleep(2000, queryFinishedRef)) {
console.log("API timed out");
lookupError = true;
}
// Check if any certs exist in the result
var result = certResponse;
if (result.trim() != "") {
console.log("Upgraded via TLSA: " + host);
upgrade = true;
}
return buildBlockingResponse(url, upgrade, lookupError);
}
function upgradeCompat(requestDetails) {
if (onFirefox()) {
return upgradeAsync(requestDetails);
} else {
return upgradeSync(requestDetails);
}
}
function buildBlockingResponse(url, upgrade, lookupError) {
if (lookupError) {
return {"redirectUrl": compatBrowser.runtime.getURL("/pages/lookup_error/index.html")};
}
if (upgrade) {
if (onFirefox()) {
return {"upgradeToSecure": true};
}
url.protocol = "https:";
// Chromium and Edge don't support "upgradeToSecure", so we use "redirectUrl" instead
return {"redirectUrl": url.toString()};
}
return {};
}
// Only use this on initial extension startup; afterwards you should use
// resetRequestListener instead.
function attachRequestListener() {
// This shim function is a hack so that we can add a new listener before we
// remove the old one. In theory JavaScript's single-threaded nature makes
// that irrelevant, but I don't trust browsers to behave sanely on this.
currentRequestListener = function(requestDetails) {
return upgradeCompat(requestDetails);
};
// add the listener,
// passing the filter argument and "blocking"
compatBrowser.webRequest.onBeforeRequest.addListener(
currentRequestListener,
{urls: [buildPattern(matchHost)]},
["blocking"]
);
}
// Attaches a new listener based on the current matchHost, and then removes the
// old listener. The ordering is intended to prevent race conditions where the
// protection is disabled.
function resetRequestListener() {
var oldListener = currentRequestListener;
attachRequestListener();
compatBrowser.webRequest.onBeforeRequest.removeListener(oldListener);
}
// Builds a match pattern for all HTTP URL's for the specified host
function buildPattern(host) {
return "http://" + host + "/*";
}
// Based on https://stackoverflow.com/a/45985333
function onFirefox() {
if (typeof chrome !== "undefined" && typeof browser !== "undefined") {
return true;
}
return false;
}
console.log("Testing for Firefox: " + onFirefox());
var compatBrowser;
// Firefox supports both browser and chrome; Chromium only supports chrome;
// Edge only supports browser. See https://stackoverflow.com/a/45985333
if (typeof browser !== "undefined") {
console.log("Testing for browser/chrome: browser");
compatBrowser = browser;
} else {
console.log("Testing for browser/chrome: chrome");
compatBrowser = chrome;
}
// Only used with native messaging
var nativePort;
var pendingUpgradeChecks = new Map();
// host for match pattern for the URLs to upgrade
var matchHost = "*.bit";
var currentRequestListener;
// Firefox is the only browser that supports async onBeforeRequest, and
// therefore is the only browser that we can use native messaging with.
if (onFirefox()) {
/*
On startup, connect to the Namecoin "dnssec_hsts" app.
*/
nativePort = compatBrowser.runtime.connectNative("org.namecoin.dnssec_hsts");
/*
Listen for messages from the native DNSSEC app.
*/
nativePort.onMessage.addListener((response) => {
const host = response["host"];
const hasTLSA = response["hasTLSA"];
const ok = response["ok"];
if (!ok) {
console.log("Native DNSSEC app error: " + host);
}
if(! pendingUpgradeChecks.has(host)) {
return;
}
for (let item of pendingUpgradeChecks.get(host)) {
item(buildBlockingResponse(null, hasTLSA, !ok));
}
pendingUpgradeChecks.delete(host);
});
}
attachRequestListener();