This repository has been archived by the owner on Apr 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathautoauth-fingerprint.js
658 lines (541 loc) · 20.5 KB
/
autoauth-fingerprint.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/*******************
* Utility Functions
* ******************/
/* FIXME:
* Requires lodash as depedency since it is using the map function from lodash
*/
var sha256 = (function(){
// Eratosthenes seive to find primes up to 311 for magic constants. This is why SHA256 is better than SHA1
var i = 1,
j,
K = [],
H = [];
while(++i < 18){
for(j = i * i; j < 312; j += i){
K[j] = 1;
}
}
function x(num, root){
return (Math.pow(num, 1 / root) % 1) * 4294967296|0;
}
for(i = 1, j = 0; i < 313; ){
if(!K[++i]){
H[j] = x(i,2);
K[j++] = x(i,3);
}
}
function S (X, n) { return ( X >>> n ) | (X << (32 - n)); }
function SHA256(b){
var HASH = H.slice(i = 0),
s = unescape(encodeURI(b)), /* encode as utf8 */
W = [],
l = s.length,
m = [],
a, y, z;
for(; i < l; ) m[i >> 2] |= (s.charCodeAt(i) & 0xff) << 8 * (3 - i++ % 4);
l *= 8;
m[l >> 5] |= 0x80 << (24 - l % 32);
m[z = (l + 64 >> 5) | 15] = l;
for(i = 0; i < z; i += 16){
a = HASH.slice(j = 0, 8);
for(; j < 64; a[4] += y){
if(j < 16){
W[j] = m[j + i];
}else{
W[j] =
(S(y = W[j - 2], 17) ^ S(y, 19) ^ (y >>> 10)) +
(W[j - 7]|0) +
(S(y = W[j - 15], 7) ^ S(y, 18) ^ (y >>> 3)) +
(W[j - 16]|0);
}
a.unshift(
(
y = (
a.pop() +
(S(b = a[4], 6) ^ S(b, 11) ^ S(b, 25)) +
(((b & a[5]) ^ ((~b) & a[6])) + K[j])|0
) +
(W[j++]|0)
) +
(S(l = a[0], 2) ^ S(l, 13) ^ S(l, 22)) +
((l & a[1]) ^ (a[1] & a[2]) ^ (a[2] & l))
);
}
for(j = 8; j--; ) HASH[j] = a[j] + HASH[j];
}
for(s = ''; j < 63; ) s += ((HASH[++j >> 3] >> 4 * (7 - j % 8)) & 15).toString(16);
return s;
}
return SHA256;
})();
//For canvas
var isCanvasSupported = function () {
var e = document.createElement('canvas')
return !!(e.getContext && e.getContext('2d'))
}
var getCanvasFp = function (options) {
var result = []
// Very simple now, need to make it more complex (geo shapes etc)
var canvas = document.createElement('canvas')
canvas.width = 2000
canvas.height = 200
canvas.style.display = 'inline'
var ctx = canvas.getContext('2d')
// detect browser support of canvas winding
// http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/winding.js
ctx.rect(0, 0, 10, 10)
ctx.rect(2, 2, 6, 6)
result.push('canvas winding:' + ((ctx.isPointInPath(5, 5, 'evenodd') === false) ? 'yes' : 'no'))
// detect if photoshops bending modes are available in canvas
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/blending.js
// firefox 3 throws an error when setting an invalid `globalCompositeOperation`
try {
ctx.globalCompositeOperation = 'screen';
} catch (e) {}
result.push('canvas blending:' + ((ctx.globalCompositeOperation === 'screen')? 'yes' : 'no'))
//To data URL
if (canvas.toDataURL) { result.push('canvas fp:' + sha256(canvas.toDataURL())) }
return result
}
//For WebGL
var isWebGlSupported = function () {
// code taken from Modernizr
if (!isCanvasSupported()) {
return false
}
var canvas = document.createElement('canvas')
canvas.setAttribute("id", "autoauth-test-webgl");
var gl = null
try {
gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl')
} catch (e) { /* squelch */ }
if (!gl) { gl = null }
return !!window.WebGLRenderingContext && !!gl
}
var getWebglFp = function() {
var canvas, ctx, width = 256, height = 128;
var c = document.createElement("canvas");
c.setAttribute('id', 'autoauth-test-webglfp');
canvas = document.body.appendChild(c);
canvas.width = width,
canvas.height = height,
ctx = canvas.getContext("webgl2") || canvas.getContext("experimental-webgl2") || canvas.getContext("webgl") || canvas.getContext("experimental-webgl") || canvas.getContext("moz-webgl");
try {
var f = "attribute vec2 attrVertex;varying vec2 varyinTexCoordinate;uniform vec2 uniformOffset;void main(){varyinTexCoordinate=attrVertex+uniformOffset;gl_Position=vec4(attrVertex,0,1);}";
var g = "precision mediump float;varying vec2 varyinTexCoordinate;void main() {gl_FragColor=vec4(varyinTexCoordinate,0,1);}";
var h = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER, h);
var i = new Float32Array([-.2, -.9, 0, .4, -.26, 0, 0, .7321, 0]);
ctx.bufferData(ctx.ARRAY_BUFFER, i, ctx.STATIC_DRAW), h.itemSize = 3, h.numItems = 3;
var j = ctx.createProgram();
var k = ctx.createShader(ctx.VERTEX_SHADER);
ctx.shaderSource(k, f);
ctx.compileShader(k);
var l = ctx.createShader(ctx.FRAGMENT_SHADER);
ctx.shaderSource(l, g);
ctx.compileShader(l);
ctx.attachShader(j, k);
ctx.attachShader(j, l);
ctx.linkProgram(j);
ctx.useProgram(j);
j.vertexPosAttrib = ctx.getAttribLocation(j, "attrVertex");
j.offsetUniform = ctx.getUniformLocation(j, "uniformOffset");
ctx.enableVertexAttribArray(j.vertexPosArray);
ctx.vertexAttribPointer(j.vertexPosAttrib, h.itemSize, ctx.FLOAT, !1, 0, 0);
ctx.uniform2f(j.offsetUniform, 1, 1);
ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, h.numItems);
}
catch (e) { }
var m = "";
var n = new Uint8Array(width * height * 4);
ctx.readPixels(0, 0, width, height, ctx.RGBA, ctx.UNSIGNED_BYTE, n);
m = JSON.stringify(n).replace(/,?"[0-9]+":/g, "");
//SHA256:
//credit : https://codepen.io/jon/pen/LLPKbz
canvas.parentNode.removeChild(c);
return sha256(m);
}
var getWebglVendorAndRenderer = function () {
try {
var glContext = getWebglCanvas()
var extensionDebugRendererInfo = glContext.getExtension('WEBGL_debug_renderer_info')
return glContext.getParameter(extensionDebugRendererInfo.UNMASKED_VENDOR_WEBGL) + '~' + glContext.getParameter(extensionDebugRendererInfo.UNMASKED_RENDERER_WEBGL)
} catch (e) {
return undefined;
}
}
// For audio
var getAudio = async function() {
function setCompressorValueIfDefined(item, value) {
if (compressor[item] !== undefined && typeof compressor[item].setValueAtTime === 'function') {
compressor[item].setValueAtTime(value, context.currentTime);
}
}
// https://github.com/rickmacgillis/audio-fingerprint
var audioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext;
if (audioContext == null) {
return undefined;
}
var context = new audioContext(1, 44100, 44100);
var oscillator = context.createOscillator();
oscillator.type = "triangle";
oscillator.frequency.setValueAtTime(10000, context.currentTime);
compressor = context.createDynamicsCompressor();
setCompressorValueIfDefined('threshold', -50);
setCompressorValueIfDefined('knee', 40);
setCompressorValueIfDefined('ratio', 12);
setCompressorValueIfDefined('reduction', -20);
setCompressorValueIfDefined('attack', 0);
setCompressorValueIfDefined('release', .25);
oscillator.connect(compressor);
compressor.connect(context.destination);
oscillator.start(0);
var audioTimeoutId = setTimeout(function () {
context.oncomplete = function () {}
context = null;
return undefined;
}, 1000)
let buffer = await context.startRendering();
try {
clearTimeout(audioTimeoutId);
var fingerprint = buffer.getChannelData(0)
.slice(4500, 5000)
.reduce(function (acc, val) { return acc + Math.abs(val) }, 0)
.toString();
oscillator.disconnect();
compressor.disconnect();
} catch (error) {
return undefined;
}
return fingerprint;
}
/** Utilit Funcs End **/
class Fingerprint {
static userAgent() {
var value = navigator.userAgent;
return value;
}
static language() {
var value = navigator.language;
return value;
}
static languages() {
var value = navigator.languages;
return value;
}
static colorDepth() {
var value = screen.colorDepth;
return value;
}
static deviceMemory() {
var value = navigator.deviceMemory;
return value;
}
static pixelRatio() {
var value = window.devicePixelRatio;
return value;
}
static hardwareConcurrency() {
var value = navigator.hardwareConcurrency;
return value;
}
static screenResolution() {
var resolution = [window.screen.width, window.screen.height];
return resolution;
}
static availableScreenResolution() {
if (window.screen.availWidth && window.screen.availHeight) {
var availResolution = [window.screen.availWidth, window.screen.availHeight];
return availResolution;
}
// headless browsers
return undefined;
}
static timezoneOffset() {
return new Date().getTimezoneOffset();
}
static timezone() {
if (window.Intl && window.Intl.DateTimeFormat) {
return new window.Intl.DateTimeFormat().resolvedOptions().timeZone;
} else {
return undefined;
}
}
static sessionStorage() {
try {
return !!window.sessionStorage;
} catch (e) {
return undefined;
}
}
static localStorage() {
try {
return !!window.localStorage;
} catch (e) {
return undefined;
}
}
static indexedDb() {
try {
return !!window.indexedDB;
} catch (e) {
return true; // SecurityError means indexedDB exists
}
}
static addBehavior() {
// body may not exist yet or has been removed
return !!(document.body && document.body.addBehavior);
}
static openDatabase() {
return !!window.openDatabase;
}
static cpuClass() {
return navigator.cpuClass;
}
static platform() {
return navigator.platform;
}
static doNotTrack() {
if (navigator.doNotTrack) {
return navigator.doNotTrack;
} else if (navigator.msDoNotTrack) {
return navigator.msDoNotTrack;
} else if (window.doNotTrack) {
return window.doNotTrack;
} else {
return undefined;
}
}
static plugins() {
if (navigator.plugins == null) {
return 'not available'
}
var plugins = []
for (var i = 0, l = navigator.plugins.length; i < l; i++) {
if (navigator.plugins[i]) { plugins.push(navigator.plugins[i]) }
}
return _.map(plugins, function (p) {
var mimeTypes = _.map(p, function (mt) {
return [mt.type, mt.suffixes];
});
return [p.name, p.description, mimeTypes];
})
}
static canvas() {
if (isCanvasSupported()) {
return getCanvasFp();
}
return undefined;
}
static webgl() {
if (isWebGlSupported()) {
return getWebglFp()
}
return undefined;
}
static webglVendorAndRenderer() {
if (isWebGlSupported()) {
return getWebglVendorAndRenderer();
}
return undefined;
}
static adBlock() {
var ad = document.createElement('div')
ad.innerHTML = ' '
ad.className = 'adsbox'
var res = false
try {
// body may not exist, that's why we need try/catch
document.body.appendChild(ad)
res = document.getElementsByClassName('adsbox')[0].offsetHeight === 0
document.body.removeChild(ad)
} catch (e) {}
return res
}
static touchSupport() {
var maxTouchPoints = 0;
if (typeof navigator.maxTouchPoints !== 'undefined') {
maxTouchPoints = navigator.maxTouchPoints;
} else if (typeof navigator.msMaxTouchPoints !== 'undefined') {
maxTouchPoints = navigator.msMaxTouchPoints;
}
return maxTouchPoints;
}
// https://gist.github.com/szepeviktor/d28dfcfc889fe61763f3
static fonts() {
// base fonts to compare candidates against
const baseFonts = ['monospace', 'sans-serif', 'serif'];
const fontList = [
'Andale Mono', 'Arial', 'Arial Black', 'Arial Hebrew', 'Arial MT', 'Arial Narrow', 'Arial Rounded MT Bold', 'Arial Unicode MS',
'Bitstream Vera Sans Mono', 'Book Antiqua', 'Bookman Old Style',
'Calibri', 'Cambria', 'Cambria Math', 'Century', 'Century Gothic', 'Century Schoolbook', 'Comic Sans', 'Comic Sans MS', 'Consolas', 'Courier', 'Courier New',
'Geneva', 'Georgia',
'Helvetica', 'Helvetica Neue',
'Impact',
'Lucida Bright', 'Lucida Calligraphy', 'Lucida Console', 'Lucida Fax', 'LUCIDA GRANDE', 'Lucida Handwriting', 'Lucida Sans', 'Lucida Sans Typewriter', 'Lucida Sans Unicode',
'Microsoft Sans Serif', 'Monaco', 'Monotype Corsiva', 'MS Gothic', 'MS Outlook', 'MS PGothic', 'MS Reference Sans Serif', 'MS Sans Serif', 'MS Serif', 'MYRIAD', 'MYRIAD PRO',
'Palatino', 'Palatino Linotype',
'Segoe Print', 'Segoe Script', 'Segoe UI', 'Segoe UI Light', 'Segoe UI Semibold', 'Segoe UI Symbol',
'Tahoma', 'Times', 'Times New Roman', 'Times New Roman PS', 'Trebuchet MS',
'Verdana', 'Wingdings', 'Wingdings 2', 'Wingdings 3'
];
// m because because it takes take up maximum width
// LLi so that same matching fonts can get separated
const testString = 'mmmmmmmmmmlli';
const testSize = '72px';
const bodyHead = document.getElementsByTagName('body')[0];
const baseFontsDiv = document.createElement('div');
const fontsDiv = document.createElement('div');
let defaultWidth = {};
let defaultHeight = {};
// make span for loading fonts
const createSpan = () => {
let span = document.createElement('span');
// make span invisible so that user doesn't see it
span.style.position = 'absolute';
span.style.left = '-9999px';
// set default CSS styles for everything
span.style.fontStyle = 'normal';
span.style.fontWeight = 'normal';
span.style.letterSpacing = 'normal';
span.style.lineBreak = 'auto';
span.style.lineHeight = 'normal';
span.style.textTransform = 'none';
span.style.textAlign = 'left';
span.style.textDecoration = 'none';
span.style.textShadow = 'none';
span.style.whiteSpace = 'normal';
span.style.wordBreak = 'normal';
span.style.wordSpacing = 'normal';
// set span font size and test string
span.style.fontSize = testSize;
span.innerHTML = testString;
return span;
};
// create span and load candidate font with base font for fallback
const createTestSpanWithFonts = (candidateFont, baseFont) => {
let span = createSpan();
span.style.fontFamily = `'{candidateFont}', {baseFont}`;
return span;
};
// create base font spans and add them to baseFontDiv
const initBaseFontSpans = () => {
let spans = [];
for (let i = 0; i < baseFonts.length; i++) {
let span = createSpan();
span.style.fontFamily = baseFonts[i];
baseFontsDiv.appendChild(span);
spans.push(span);
}
return spans;
};
// create candidate font spans and add them to fontsDiv
const initFontSpans = () => {
let spans = {};
for (let i = 0; i < fontList.length; i++) {
let fontSpans = [];
for (let j = 0; j < baseFonts.length; j++) {
let span = createTestSpanWithFonts(fontList[j], baseFonts[i]);
fontsDiv.appendChild(span);
fontSpans.push(span);
}
spans[fontList[i]] = fontSpans; // fontName: [fontSpans]
}
return spans;
}
// check if candidate font is available
const isFontAvailable = (fontSpans) => {
let available = false;
for (let i = 0; i < fontSpans.length; i++) {
available = (fontSpans[i].offsetWidth !== defaultWidth[baseFonts[i]] || fontSpans[i].offsetHeight !== defaultHeight[baseFonts[i]]);
if (available) {
return true;
}
}
return available;
}
// create spans for base fonts
const baseFontSpans = initBaseFontSpans();
// add base font spans to DOM
bodyHead.appendChild(baseFontsDiv);
// get default width and height for base fonts
for (let i = 0; i < baseFonts.length; i++) {
defaultWidth[baseFonts[i]] = baseFontSpans[i].offsetWidth // width for the default font
defaultHeight[baseFonts[i]] = baseFontSpans[i].offsetHeight // height for the default font
}
// create spans for candidate fonts
const fontSpans = initFontSpans();
// add candidate font spans to DOM
bodyHead.appendChild(fontsDiv);
// check which candidate fonts are available
let availableFonts = []
for (let i = 0; i < fontList.length; i++) {
if (isFontAvailable(fontSpans[fontList[i]])) {
availableFonts.push(fontList[i]);
}
}
// remove DOM elements used for testing
bodyHead.removeChild(fontsDiv);
bodyHead.removeChild(baseFontsDiv);
return availableFonts;
}
static async audio() {
// iOS 11 does not allow fingerprinting
if (navigator.userAgent.match(/OS 11.+Version\/11.+Safari/))
return undefined;
else
return await getAudio();
}
static async enumerateDevice() {
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
return undefined;
}
try {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.map((device) => {
return 'id=' + device.deviceId + ';gid=' + device.groupId + ';' + device.kind + ';' + device.label;
});
} catch (e) {
return undefined;
}
}
static async get() {
const components = {
userAgent: this.userAgent(),
language: this.language(),
colorDepth: this.colorDepth(),
deviceMemory: this.deviceMemory(),
pixelRatio: this.pixelRatio(),
hardwareConcurrency: this.hardwareConcurrency(),
screenResolution: this.screenResolution(),
availableScreenResolution: this.availableScreenResolution(),
timezoneOffset: this.timezoneOffset(),
timezone: this.timezone(),
sessionStorage: this.sessionStorage(),
localStorage: this.localStorage(),
indexedDb: this.indexedDb(),
addBehavior: this.addBehavior(),
openDatabase: this.openDatabase(),
cpuClass: this.cpuClass(),
platform: this.platform(),
doNotTrack: this.doNotTrack(),
plugins: this.plugins(),
canvas: this.canvas(),
webgl: this.webgl(),
webglVendorAndRenderer: this.webglVendorAndRenderer(),
adBlock: this.adBlock(),
touchSupport: this.touchSupport(),
fonts: this.fonts(),
audio: await this.audio(),
enumerateDevice: await this.enumerateDevice(),
};
Object.keys(components).forEach((key) => {
if (components[key] === undefined) {
components[key] = 'unknown';
}
});
return components;
}
}
//export default Fingerprint;