MatchMedia

The window.matchMedia() method returns a new MediaQueryList object representing the parsed results of the specified media query string. Web developers primarily use it to apply CSS styles based on different device characteristics, such as display type or screen resolution.

However, in the context of fingerprinting, matchMedia can be utilized to gather information about the user’s browser environment. By querying a set of predefined media features, an attacker can generate a profile or a ‘fingerprint’ of a user’s browser, which can often be unique or nearly unique.

How is MatchMedia used for fingerprinting?

Let’s look at a simple example. Suppose a website wants to determine whether a user’s device prefers dark or light themes. It can use the matchMedia method as follows:

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    console.log('User prefers a dark color scheme');
} else {
    console.log('User prefers a light color scheme or does not specify a preference');
}

While this seems innocent enough, consider an attacker querying a series of such media features. By gathering all the results, the attacker can generate a fingerprint that can be used to track the user across multiple sessions and websites.

Implementing MatchMedia fingerprinting in JavaScript

A more detailed matchMedia fingerprinting script might involve querying a multitude of device features. Here’s a rudimentary example:

function generateFingerprint() {
    const features = [
        '(prefers-color-scheme: dark)',
        '(pointer: coarse)',
        '(hover: hover)',
        '(display-mode: standalone)',
        '(orientation: landscape)',
        // ... and many more
    ];

    const fingerprint = features.map(feature => {
        return window.matchMedia(feature).matches ? 1 : 0;
    }).join('');

    return fingerprint;
}

const userFingerprint = generateFingerprint();
console.log('Generated Fingerprint:', userFingerprint);

Bypassing MatchMedia fingerprinting

MatchMedia fingerprinting is often combined and used to validate data of Screen Size Fingerpriting. Multiple MatchMedia queries are also used to validate devicePixelRatio and flag the user in case of non-matching data as an attempted spoofing. The query (prefers-color-scheme: dark) is also often used as a direct validation of legitimate user like it’s done for F5 Device ID+.