DEV Community

WangLiwen
WangLiwen

Posted on

JavaScript Magic Tricks: Executing Privately

If it is possible to load and execute JavaScript code in a webpage privately, it would be very beneficial for protecting JavaScript code. In this article, we will explore and demonstrate a technique for privately executing JavaScript code.

Source

<html>
<script>
    window.onload =  function () {
        var  xhr =  new  XMLHttpRequest();
        //获取png文件
        xhr.open("GET" , "http://127.0.0.1:2080/backup/js_png/test.png");
        xhr.send("");

        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status == 200){
                console.log(xhr.responseText);
                //执行png文件中的js代码
                eval(xhr.responseText);
            }
        }
    }
</script>
</html>
Enter fullscreen mode Exit fullscreen mode

The above is the front-end HTML page code. The principle is: when the page is loaded, an Ajax request is made for a png image file. After obtaining the png file, the file content is executed as js code. The content of the png file on the server is shown in the following figure.

Image description

The above image looks like a png image file, but it is actually a javascript file with a png suffix, which is used to disguise it during transmission, making others think it is just a picture.

Image description

Execute

Image description

This achieves the effect of removing this js code and js file from the webpage, and the js file loading is not visible in the developer tools, but the js function is executed.

However, someone who is attentive may detect abnormalities from two aspects. The first is at the location of Ajax requests in the webpage.

Image description

The second is that opening the js file disguised as a png image may reveal its js code.

As shown in the figure below, Firefox browser cannot be identified.

Image description

As shown in the figure below, the Chome browser can recognize js.

Image description

In comparison, the JavaScript code can be obfuscated to further improve security.

After the javascript code is obfuscated using the JShaman JavaScript Obfuscator, it can be made impossible to discern the Ajax request logic, as shown in the following image.

Image description

The backend disguises a JavaScript file as a PNG image, encrypts it with jjencode to make it appear as gibberish, as shown in the following figure.

Image description

In this way, both ends of the JavaScript code are encrypted, making it harder to analyze and making the execution more secretive.

Top comments (0)