Javascript Security Vulnerabilities: How To Secure Your Site?

Do you know which software language is the most commonly used on modern websites? Today, Javascript libraries make it possible to present many functions in the most powerful way and to increase website performance. However, if the correct optimizations are not done, these libraries are likely to create various vulnerabilities. Search engines, who care about users’ security at the maximum level, attach great importance to this among the SEO criteria they demand. However, studies show that one out of every five uses of Javascript causes security vulnerability. So what can you do to tackle javascript security issues?

Javascript Security Vulnerabilities
Javascript Security Vulnerabilities

Today, we will talk about software language optimization, one of the most important issues of technical SEO. If you want to identify the security vulnerabilities that the code source you use for your web page users and website files and fix them, it will be enough to review this detailed guide.

What is Javascript?

Let’s start by understanding what Javascript is, if you wish, folks! Javascript, a programming language that was launched in 1995 and has been widely used since the first day, is found on most web pages. Some of the areas where Javascript is used on web pages can be listed as follows:

  1. Dynamic web pages
  2. Interaction based areas
  3. User activity monitoring areas
  4. Animations
  5. Form submission and verification fields
What is Javascript?
What is Javascript?

Java is an extremely good method for performing many of these types of functions. An HTML page is required to use Javascript. This HTML page contains a Javascript process that can interact with the DOM. The loading of the site is related to the DOM- called the Document Object Model. Note that Javascript is not the same as Java. Generally, both of these languages ​​work object-oriented. There is a syntax similar to C in both languages. However, Javascript is generally used more in websites and mobile applications.

What Are The Safe Ways To Use Javascript Libraries?

If you are using Javascript libraries when preparing source code for your website, there are several ways to make this process more secure. Identifying the risks that may arise and making certain optimizations to avoid these risks can improve the results to be obtained through Google Lighthouse.

What Are The Safe Ways To Use Javascript Libraries?
What Are The Safe Ways To Use Javascript Libraries?

  1. Don’t forget Patch managementVersion management for Javascript libraries: What you need to do is make sure that the Javascript you are using is the most up-to-date version. In general, it is very important to choose libraries that are spoken to be safer in forums or open-source development environments and to make sure that you are using the most up-to-date versions of them.
  2. Another warning is telling you that you should not use external libraries –  Well but what will you do then? Simply copy the javascript libraries to the server of the website that needs the code in question. So what is the advantage of this? Let’s say right away: If you add a code to your site using external libraries, you are actually using third parties that you have to trust. In this case, the security risk is always several times higher. However, a code that you directly copy from the library to your server will directly carry the reliability of the library.
  3. However, in certain situations, you may need to use external libraries: In this case, what you need to do is to constantly check whether the remote library server you are using is secure. To do this, make sure that the library you are using is an option that is not included in the malware blacklists, and is positively commented on by users. Browse through the contents of the library using various checksums and make sure you do not add a source of harmful code to your site. You can use checksums like MD5 or SHA for this. This is one of the best ways to browse through code content.
  4. Check the references given to external libraries: It is also extremely important to check if your website provides a reference to external libraries. Someone may have added some malicious links to the system that provided you with the external library you are using. Even if the library in question is a library marked as safe, such malicious links that are not secure will be a big problem for you. Therefore, it is necessary to constantly check the content, just like checking the source you use.
  5. Minimize XSS: You need to minimize the likelihood that XSS will occur. Whichever library you use, this will be an important factor. To reduce the risk of XSS, all you need to do is ensure that the input is verified before the function specified by Javascript is called. In this way, you will have security knowledge while developing your website. This keeps you in control. We will talk about how to avoid XSS more in the following sections of the article.

Why Is Javascript Security Important?

Nowadays, a few basic problems that can arise on websites using Javascript can negatively affect the experience of the site and the visitors who use the site. Some of these risks are as follows:

If the way Javascript and DOM interacts is not correct, malicious developers over the web can send certain scripts. Your web page runs these intervening scripts and does what the script demands. What is in demand could be data theft, financial theft, or more.

Why Is Javascript Security Important?
Why Is Javascript Security Important?

In general, there are two different ways to prevent the interaction of Javascript and DOM from providing vulnerability:

  1. First, you can try running each of the scripts separately. Thus, each of these files can only be processed by accessing a certain number of resources. There is no will to process and realize more than that. This will disqualify scripts intended to be run by malicious people.
  2. Let’s talk about another method: You need to block scripts on a website from accessing data used by another website. In this way, you will prevent the interaction of malicious scripts.

Most Common Javascript Security Vulnerabilities and How To Fix Them

Did you know that 95 percent of the web world consists of backend servers and front-facing web applications? Here, the language used in most of these servers and web applications is Javascript. This language produces excellent solutions, especially for creating dynamic spaces in websites. However, this intense popularity has made some security problems more visible. Let’s examine the most common security problems and what you can do against them.

Cross Site Scripting (XSS): Most Common Security Vulnerabilities in Javascript 1

One of the intense cyber attacks associated with Javascript is security vulnerabilities caused by cross-site scripting. Cross-Site Scripting, also called XSS, basically relates to the following: When your website runs its files as standard, malicious scripts intervene and also be run by your server. This is what causes malicious hackers to fulfill the function they demand. This problem is generally considered under two main headings:

  1. Client XSS
  2. Server XSS

Let’s examine both categories in detail.

Client XSS – Fixing Javascript Vulnerability Problem

This vulnerability, usually caused by APIs, occurs when untrusted code files update the DOM from a remote point. The updated DOM with the Javascript call used fulfills the requested malicious function.

Let’s examine this with an example.

For instance, the main purpose of the code snippet below is to take up-to-date weather information from an API and present it to users. However, this snippet encounters a problem because it uses an unreliable API. First, let’s see the snippet:

<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>DEMO XSS</title></head><body>  <p>Today's weather information reads: </br>    <div id="temp"></div>  </p>  <script type="text/javascript">    let untrusted_ajax_res = document.write(location.replace("https://www.w3schools.com"));    document.getElementById("temp").innerHTML=untrusted_ajax_res;  </script></body></html>

Notice how the malicious snippet looks in the DOM? Good! Here is what you need to do to prevent this snippet that causes the client CSS attack to be active:

Use XSS filters.

For this, you can check out the following snippet:

<!DOCTYPE html>...<script src="dist/xss-filters.min.js"></script><script>let untrusted_ajax_res = document.write(location.replace("https://www.w3schools.com"));document.getElementById("temp").innerHTML=xssFilters.inHTMLData(untrusted_ajax_res);</script>

Remember, you can only apply XSS filter packages to specific documents: UTF-8 encoded ones. Having HTML 5 mode is also important to enable these filter packages.

Server CSS – How to fix it

Running the untrusted script by your server is also in question in this case. But in this scenario, the script in question is added as user input. Also, they are stored in the database by attaching them to the backend. This data basically works to compute how to send a malicious Javascript code to the user. In this way, a fully working and functioning malicious transaction is realized. Let’s examine this situation, which is called a server XSS attack, through the example.

...

app.get('/search', (req, res) => {

const results = db.search(req.query.product);

if (results.length === 0) {

  return res.send('<p>No results found for "' + req.query.product + '"</p>');

}

...

});

There is no malicious code in the snippet above. The code simply allows users to search for products. However, in order for a server XSS attack to occur, a snippet application can be made as follows:

https://www.domain.com/search?product=<script>alert(XSS:Gat Ya!!)</script>

In the snippet above, the javascript code was sent to the server as a query. This enables the malicious script to run.

If there were code like the following in the database, everything would be different:

<script> alert (XSS: Gat Ya !!) </script>

But since there is no such record, the server will respond to this snippet as follows:

<p> No results found for "<script> alert (XSS: Gat Ya !!) </script> </p>

When the result is not found for this information detected by the server, the script information will be directly injected into the DOM tree. In this case, a result is printed on the page, which should not normally be found on the page. Let’s examine the example:

Javascript vulnerabilities - Server CSS example
Javascript vulnerabilities – Server CSS example

But what harm could that do? Is it a malicious situation to simply write “Ya Gat!”? The main thing is that this may not be a problem right now. But this shows what malicious hackers can do to your site. A malicious person can print content that will mislead people on your blog sites, social media platforms, e-commerce sites, banking platforms where you provide financial services. This information, which fulfills the requests of the attacker, can damage your site’s reputation and mislead users.

So what can you do to resolve this situation? To fix the Javacript security vulnerability, you need to download the XSS filter package:

$ npm i xss-filters --save

Have you completed the download process? Wonderful! Now what you need to do is filter the data that will come to the user’s input field. In this way, inappropriate data will not cause a piece of incorrect information to be printed on your page. Filtering is great in this respect. Examine:

...

var xssFilters = require ('xss-filters');

app.get ('/ search', (req, res) => (

var productParam = req.query.product;

const results = db.search (req.query.product);

if (results.length === 0) (

res.send ('<p> No result found for "' + xssFilters.inHTMLData (productParam) + '" </p>');

}

});

...

It’s that simple.

SQL Injection (SQLi): Most Common Security Vulnerabilities in Javascript 2

Now let’s examine another common Javascript security vulnerability. The main thing SQL injection does is to retrieve hidden data on your page. This action can create a strong enough attack to destroy your database completely. One of the most common web hacking techniques, the basic method of SQL injection is to embed malicious code into SQL statements in your source code.

The moment this injection takes place is generally the moment when user input is received. For example, when you ask a user for a username or information, what the user gives is a SQL statement. Your server starts running this statement in your database without realizing it.

Let’s have a look at the example below:

...

const db = require('./db');

app.get('/products', (req, res) => {

db.query('SELECT * FROM products WHERE id = ' + req.query.id);

.then((product) => {

...

res.send(product);

})

});

What exactly is happening here? The SQL injection used provides control of the database behind the web application. The snippet you see above causes the following problems

  1. First of all, it is ensured that the user’s input is combined with data that does not belong to the user. A new data combined with a query string is sent to your server.
  2. While performing the database query, this is done with the combined SQL input.

SQL Injection Example with 1=1 Always TRUE

Let’s give another axemple: Let’s assume that the code you have on your website that allows the user to enter an ID is the following code:

txtUserId = getRequestString ("UserId");

txtSQL = "SELECT * FROM Users WHERE UserId =" + txtUserId;

How can this code be made extremely dangereous with a malicious SQL injection? Let’s examine it together.

In code that is based on 1 = 1 Always True, SQL injection works as follows:

The main purpose of the code above is to select a user and compare the database with that user’s ID. But if the user enters an incorrect user id input and the system does not stop the user by warning the user in this situation, this creates a security vulnerability. Because the user can intelligently enter a username and cause a code to be executed.

For example, suppose the user enters data as the user ID as follows:

UserID: 105 OR 1 = 1

What will happen in this situation? Let’s say it right: the SQL statement will look like this:

SELECT * FROM Users WHERE UserId = 105 OR 1 = 1;

The added 1 = 1 part ensures that SQL is valid and causes all rows in the USERS base to be served to the user. Because the part with OR 1 = 1 is always TRUE. This makes all this input valid.

How dangerous could this situation be? Let’s say: The person entering this input can access all the usernames in your Users table and the passwords associated with these usernames. Consider how terrible this is for your platform. In short, the above SQL actually works as follows:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1 = 1;

SQL Injection Example with ‘’=’’ Always TRUE

Let’s continue with another example. Some SQL injection cases may be based on = is always true. Let’s examine this.

Let’s consider the following information as a user’s login information:

  • Username: John Doe
  • Password: mypass

In this case, the snippet will look like this:

uName = getRequestString ("username");

uPass = getRequestString ("userpassword");

sql = 'SELECT * FROM Users WHERE Name = "' + uName + '" AND Pass = "' + uPass + '"'

As a result of malicious SQL injection, the situation will be as follows:

SELECT * FROM Users WHERE Name = "John Doe" AND Pass = "myPass"

In this case, the hacker can simply type OR ” = ” in the field where users should enter their username. When this is written, the system accepts this input as valid and offers the database to the hacker in return for this process initiated through the text box. Because in this type of operation, the SQL statement looks like this:

SELECT * FROM Users WHERE Name = "" or "" = "" AND Pass = "" or "" = ""

SQL Injection Example on Batched SQL Statements

Malicious SQL statements can also be created via Batched SQL Statements.

Most databases today support batched SQL statements and execute them. But what does batched SQL mean?

Let us tell you right away: If you see two or more SQL statements separated using semicolons, you can easily call it batched SQL. Let’s see a transaction with Batched SQL.

SELECT * FROM Users; DROP TABLE Suppliers

This statement above basically ensures that all lines in the Users table are returned to the user. It will also completely delete the Suppliers table right after that.

Let’s look at one more example:

txtUserId = getRequestString ("UserId");

txtSQL = "SELECT * FROM Users WHERE UserId =" + txtUserId;

The following input can be entered in this field:

User ID: 105; DROP TABLE SUPPLIERS

In this case, the SQL statement that will be created and accepted as valid is as follows:

SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;

Open-source vulnerabilities: Most Common Security Vulnerabilities in Javascript 3

There is one more problem that is being evaluated among javascript security vulnerabilities, which is called open source vulnerabilities. Today, it is possible to say that the Javascript ecosystem has many open-source packages that serve developers. Thousands of developers can contribute to these open source packages at the same time and as a result, Javascript is developing more and more every day.

Open-source Javascript packages
Open-source Javascript packages

The main advantage of open source packages is that a large number of developers use them, thus reducing development time.

But unfortunately, it also has a downside: Malicious attackers can add malicious code to open source packages. Using them directly can cause serious security vulnerabilities in your source code.

Open-source vulnerabilities
Open-source vulnerabilities

Of course, the Javascript world has not completely surrendered to this situation. Various package managers are developing and introducing a variety of digital tools to continuously scan open-source packages and identify vulnerabilities. For example, NPM and BOLT can overcome the vulnerabilities of open source packages.

Overcome Vunerabilities Using NPM

NPM makes it possible to detect Javascript security vulnerabilities as a result of regular scans and to report these vulnerabilities. In addition, NPM can provide solutions for these vulnerabilities. We can create an npm audit in a found project directory. When we do this, the audit report provides us with all potentially dangerous areas in the code. To fix these vulnerabilities one by one, $ npm audit fix command must be run. However, not all vulnerabilities can be completely fixed with this type of command. Therefore, developers have to try to fix detected vulnerabilities manually as well.

Overcome Vunerabilities Using BOLT

Released as a Bit GitHub application, BOLT is a powerful tool that detects the damage that open source packages can cause to your site. Providing continuous scanning of open source packages, BOLT can increase the number of scans up to five a day. Opening a GitHub issue related to each vulnerability is another advantage. Links to the contents that can be examined regarding this problem, details of the vulnerability, and suggestions on how to fix the problem are also offered to users by BOLT.

Don’t forget to have a look at one of the most beneficial task from Screpy experts: Remove Javascript Libraries with Security Issues.

Screpy Divider