Debian Codegraph @

src/js/contentscripts/fingerprinting.js

raw
1 /*
2 * This file is part of Privacy Badger <https://privacybadger.org/>
3 * Copyright (C) 2015 Electronic Frontier Foundation
4 *
5 * Derived from Chameleon <https://github.com/ghostwords/chameleon>
6 * Copyright (C) 2015 ghostwords
7 *
8 * Privacy Badger is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 3 as
10 * published by the Free Software Foundation.
11 *
12 * Privacy Badger is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Privacy Badger. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 (function () {
22
23 // don't inject into non-HTML documents (such as XML documents)
24 // but do inject into XHTML documents
25 if (document instanceof HTMLDocument === false && (
26 document instanceof XMLDocument === false ||
27 document.createElement('div') instanceof HTMLDivElement === false
28 )) {
29 return;
30 }
31
32 function getPageScript(event_id) {
33
34 // code below is not a content script: no chrome.* APIs /////////////////////
35
36 // return a string
37 return "(" + function (EVENT_ID, DOCUMENT, dispatchEvent, CUSTOM_EVENT, ERROR, DATE, setTimeout, OBJECT, FUNCTION, UNDEFINED) {
38
39 function hasOwn(obj, prop) {
40 return OBJECT.prototype.hasOwnProperty.call(obj, prop);
41 }
42
43 const V8_STACK_TRACE_API = !!(ERROR &&
44 ERROR.captureStackTrace &&
45 hasOwn(ERROR, "stackTraceLimit"));
46
47 if (V8_STACK_TRACE_API) {
48 ERROR.stackTraceLimit = Infinity; // collect all frames
49 }
50
51 function apply(obj, context, args) {
52 return FUNCTION.prototype.apply.call(obj, context, args);
53 }
54
55 // adapted from Underscore v1.6.0
56 function debounce(func, wait, immediate) {
57 let timeout, args, context, timestamp, result;
58
59 let later = function () {
60 let last = DATE.now() - timestamp;
61 if (last < wait) {
62 timeout = setTimeout(later, wait - last);
63 } else {
64 timeout = null;
65 if (!immediate) {
66 result = apply(func, context, args);
67 context = args = null;
68 }
69 }
70 };
71
72 return function () {
73 context = this; // eslint-disable-line consistent-this
74 args = arguments;
75 timestamp = DATE.now();
76 let callNow = immediate && !timeout;
77 if (!timeout) {
78 timeout = setTimeout(later, wait);
79 }
80 if (callNow) {
81 result = apply(func, context, args);
82 context = args = null;
83 }
84
85 return result;
86 };
87 }
88
89 // messages the injected script
90 let send = (function () {
91 let messages = [];
92
93 // debounce sending queued messages
94 let _send = debounce(function () {
95 dispatchEvent.call(DOCUMENT, new CUSTOM_EVENT(EVENT_ID, {
96 detail: messages
97 }));
98
99 // clear the queue
100 messages = [];
101 }, 100);
102
103 return function (msg) {
104 // queue the message
105 messages.push(msg);
106
107 _send();
108 };
109 }());
110
111 /**
112 * Gets the stack trace by throwing and catching an exception.
113 * @returns {*} Returns the stack trace
114 */
115 function getStackTraceFirefox() {
116 let stack;
117
118 try {
119 throw new ERROR();
120 } catch (err) {
121 stack = err.stack;
122 }
123
124 return stack.split('\n');
125 }
126
127 /**
128 * Gets the stack trace using the V8 stack trace API:
129 * https://github.com/v8/v8/wiki/Stack-Trace-API
130 * @returns {*} Returns the stack trace
131 */
132 function getStackTrace() {
133 let err = {},
134 origFormatter,
135 stack;
136
137 origFormatter = ERROR.prepareStackTrace;
138 ERROR.prepareStackTrace = function (_, structuredStackTrace) {
139 return structuredStackTrace;
140 };
141
142 ERROR.captureStackTrace(err, getStackTrace);
143 stack = err.stack;
144
145 ERROR.prepareStackTrace = origFormatter;
146
147 return stack;
148 }
149
150 /**
151 * Strip away the line and column number (from stack trace urls)
152 * @param script_url The stack trace url to strip
153 * @returns {String} the pure URL
154 */
155 function stripLineAndColumnNumbers(script_url) {
156 return script_url.replace(/:\d+:\d+$/, '');
157 }
158
159 /**
160 * Parses the stack trace for the originating script URL
161 * without using the V8 stack trace API.
162 * @returns {String} The URL of the originating script
163 */
164 function getOriginatingScriptUrlFirefox() {
165 let trace = getStackTraceFirefox();
166
167 if (trace.length < 4) {
168 return '';
169 }
170
171 // this script is at 0, 1 and 2
172 let callSite = trace[3];
173
174 // from https://github.com/csnover/TraceKit/blob/b76ad786f84ed0c94701c83d8963458a8da54d57/tracekit.js#L641
175 const geckoCallSiteRe = /^\s*(.*?)(?:\((.*?)\))?@?((?:file|https?|chrome):.*?):(\d+)(?::(\d+))?\s*$/i,
176 scriptUrlMatches = callSite.match(geckoCallSiteRe);
177 return scriptUrlMatches && scriptUrlMatches[3] || '';
178 }
179
180 /**
181 * Parses the stack trace for the originating script URL.
182 * @returns {String} The URL of the originating script
183 */
184 function getOriginatingScriptUrl() {
185 let trace = getStackTrace();
186
187 // we failed to get a structured stack trace
188 if (OBJECT.prototype.toString.call(trace) == '[object String]') {
189 trace = trace.split('\n');
190
191 if (trace.length < 3) {
192 return '';
193 }
194
195 // Firefox 153+
196 // this script is at 0 and 1
197 let script_url_matches = trace[2].match(/.*@(https?:\/\/.*):\d+:\d+$/);
198 if (script_url_matches) {
199 return script_url_matches[1];
200 }
201
202 if (trace.length < 4) {
203 return '';
204 }
205
206 // frozen stack trace in Chromium
207 // the word "Error" is at 0, this script is at 1 and 2
208 script_url_matches = trace[3].match(/\((https?:\/\/.*):\d+:\d+\)$/);
209 return script_url_matches && script_url_matches[1] || stripLineAndColumnNumbers(trace[3]);
210 }
211
212 if (trace.length < 3) {
213 return '';
214 }
215
216 // this script is at 0 and 1
217 let callSite = trace[2];
218
219 if (callSite.isEval()) {
220 // argh, getEvalOrigin returns a string ...
221 let eval_origin = callSite.getEvalOrigin(),
222 script_url_matches = eval_origin.match(/\((http.*:\d+:\d+)/);
223
224 // TODO do we need stripLineAndColumnNumbers (in both places) here?
225 return script_url_matches && stripLineAndColumnNumbers(script_url_matches[1]) || stripLineAndColumnNumbers(eval_origin);
226 } else {
227 return callSite.getFileName();
228 }
229 }
230
231 /**
232 * Monitor the writes in a canvas instance
233 * @param item special item objects
234 */
235 function trapInstanceMethod(item) {
236 let is_canvas_write = (
237 item.propName == 'fillText' || item.propName == 'strokeText'
238 );
239
240 item.obj[item.propName] = (function (orig) {
241 // set to true after the first write, if the method is not
242 // restorable. Happens if another library also overwrites
243 // this method.
244 let skip_monitoring = false;
245
246 function wrapped() {
247 let args = arguments;
248
249 if (is_canvas_write) {
250 // to avoid false positives,
251 // bail if the text being written is too short,
252 // of if we've already sent a monitoring payload
253 if (skip_monitoring || !args[0] || args[0].length < 5) {
254 return apply(orig, this, args);
255 }
256 }
257
258 // TODO should be able to retire the V8_STACK_TRACE_API check
259 // TODO once min Firefox version reaches 153+
260 // TODO https://bugzilla.mozilla.org/show_bug.cgi?id=2037856
261 let script_url = (
262 V8_STACK_TRACE_API ?
263 getOriginatingScriptUrl() :
264 getOriginatingScriptUrlFirefox()
265 ),
266 msg = {
267 obj: item.objName,
268 prop: item.propName,
269 scriptUrl: script_url
270 };
271
272 if (hasOwn(item, 'extra')) {
273 msg.extra = apply(item.extra, this, args);
274 }
275
276 send(msg);
277
278 if (is_canvas_write) {
279 // optimization: one canvas write is enough,
280 // restore original write method
281 // to this CanvasRenderingContext2D object instance
282 // Careful! Only restorable if we haven't already been replaced
283 // by another lib, such as the hidpi polyfill
284 if (this[item.propName] === wrapped) {
285 this[item.propName] = orig;
286 } else {
287 skip_monitoring = true;
288 }
289 }
290
291 return apply(orig, this, args);
292 }
293
294 OBJECT.defineProperty(wrapped, "name", { value: orig.name });
295 OBJECT.defineProperty(wrapped, "length", { value: orig.length });
296 OBJECT.defineProperty(wrapped, "toString", { value: orig.toString.bind(orig) });
297
298 return wrapped;
299
300 }(item.obj[item.propName]));
301 }
302
303 let methods = [];
304
305 for (let method of ['getImageData', 'fillText', 'strokeText']) {
306 let item = {
307 objName: 'CanvasRenderingContext2D.prototype',
308 propName: method,
309 obj: CanvasRenderingContext2D.prototype,
310 extra: function () {
311 return {
312 canvas: true
313 };
314 }
315 };
316
317 if (method == 'getImageData') {
318 item.extra = function () {
319 let args = arguments,
320 width = args[2],
321 height = args[3];
322
323 // "this" is a CanvasRenderingContext2D object
324 if (width === UNDEFINED) {
325 width = this.canvas.width;
326 }
327 if (height === UNDEFINED) {
328 height = this.canvas.height;
329 }
330
331 return {
332 canvas: true,
333 width: width,
334 height: height
335 };
336 };
337 }
338
339 methods.push(item);
340 }
341
342 methods.push({
343 objName: 'HTMLCanvasElement.prototype',
344 propName: 'toDataURL',
345 obj: HTMLCanvasElement.prototype,
346 extra: function () {
347 // "this" is a canvas element
348 return {
349 canvas: true,
350 width: this.width,
351 height: this.height
352 };
353 }
354 });
355
356 for (let method of methods) {
357 trapInstanceMethod(method);
358 }
359
360 // save locally to keep from getting overwritten by site code
361 } + "(" + event_id + ", document, document.dispatchEvent, CustomEvent, Error, Date, setTimeout, Object, Function));";
362
363 // code above is not a content script: no chrome.* APIs /////////////////////
364
365 }
366
367 // END FUNCTION DEFINITIONS ///////////////////////////////////////////////////
368
369 // TODO race condition; fix waiting on https://crbug.com/478183
370 chrome.runtime.sendMessage({
371 type: "detectFingerprinting"
372 }, function (enabled) {
373 if (!enabled) {
374 return;
375 }
376
377 const event_id = Math.random();
378
379 // listen for messages from the script we are about to insert
380 document.addEventListener(event_id, function (e) {
381 // pass these on to the background page (handled by webrequest.js)
382 chrome.runtime.sendMessage({
383 type: "fpReport",
384 data: e.detail
385 });
386 });
387
388 window.injectScript(getPageScript(event_id));
389 });
390
391 }());