I noticed today that I can replace a sensitive built-in JS function like this:
async function _hackedEncrypt(algorithm, key, data) {
console.log('hacked you!');
}
const subtle = global.crypto.subtle; // Assign to get around "read-only" error.
subtle.encrypt = _hackedEncrypt;
global.crypto.subtle.encrypt(); // 'Hacked you!' appears in console.
Yikes!
This exploit is so simple. Any of the thousands of dependencies (direct and transitive) in my web app could make this function reassignment. Note that my question isn't specific to Web Crypto - it's just one of the more dangerous targets for an attacker.
How can I either detect that the function has been reassigned or guarantee that I'm always calling the original browser implementation of it?