JavaScript Anti Eval Debugging

wangliwen

WangLiwen

Posted on November 29, 2024

JavaScript Anti Eval Debugging

The proper use of eval is to execute a string of JavaScript code. However, it is also frequently used by code analyzers for debugging and analysis purposes: running certain functions with eval to get the return values and understand the execution results of the code.
How to implement anti-eval debugging and prevent code from being executed by eval? We can throw an error within a function and catch its stack trace, then check if the call stack contains eval. This way, we can identify whether the function was called through eval and take appropriate actions accordingly.

Example Code:


function checkIfEvalled() {
    try {
        throw new Error();
    } catch (e) {
        console.log(e.stack);
        if (e.stack.includes('eval')) {
            console.log("This function might have been called by eval.");
        } else {
            console.log("This function was not called by eval.");
        }
    }
}

// Normal call
checkIfEvalled();

// Call using eval
eval('checkIfEvalled();');
Enter fullscreen mode Exit fullscreen mode

In actual application, to avoid the anti-eval logic being easily seen, one would not use console.log for notifications; instead, they could return an incorrect value or take other measures. Additionally, it's recommended to obfuscate and encrypt the code, such as using JS-Obfuscator for JavaScript code obfuscation.

💖 💪 🙅 🚩
wangliwen
WangLiwen

Posted on November 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related