JavaScript VULNERABILITY and CONTENT SECURITY POLICY
Introduction
According to recent research over 14 million developers make us of JavaScript, making JavaScript the most popular web software development language. With the popular and dynamic nature of JavaScript comes more responsibility to know and understand JavaScript vulnerabilities, in order to ensure web application is secured. But what exactly is JavaScript vulnerability? How do developers keep web applications save? And how many JavaScript vulnerability attacks can we find? These are some of the questions we should be asking ourselves right now. In this article we are going to explore the different vulnerability attacks that are associated to JavaScript and how we can mitigate them, we will equally talk about web security.
Outline
1) What is JavaScript vulnerability
2) List of JavaScript vulnerabilities
3) List of JavaScript vulnerability attacks
i) Cross Site Scripting
ii) Cross Site Request Forgery
iii) Broken Authentication Control
iv) SQL Injection
4) Content Security Policy
i) How CSP Protects Against Cross Site Scripting (XSS) Attacks
ii) Implementation of Content Security Policy
iii) CSP HTTP header and their browser supports
iv) CSP directives
v) CSP Directive sources
vi) Content Security Policy (CSP) syntax
vii) Implementation examples
viii) Testing Your Policy
5) Conclusion
WHAT IS JavaScript Vulnerability
While JavaScript remains the most popular and widely used technology in developing web applications, mobile application and desktop applications, it still have it’s own share of vulnerabilities. A vulnerability consists of anything that affects the security of a JavaScript powered application, some of these vulnerabilities include, stealing of users session data by attackers. Below is a comprehensive list of some of these vulnerabilities. The list is not restricted to this, but it will help in giving a more focused idea on the subsequent sections of this article.
LIST OF JAVASCRIPT VULNERABILITIES
1) Input validation vulnerabilities: Inputs that are sent to the browser from untrusted sources such as users of a web application must be properly validated. For example while collecting a form submitted by the user, the inputs must be properly checked, in order to make sure that the data received are correct, but in the case of most vulnerable web application there Is no validation means in place and whatever data that is been sent to the browser is treated as valid.
2) Depending on Client-Side Validation alone: Well here is another mistake that most developers make while trying to build a secured application, they tend to validate user’s input only on the client-side of the web application, leaving data on the server-side invalidated. An obvious implication of this is that attacker can decide to skip the client-side validation process by sending data directly to the server-side. An attack can send malicious data to the server since there is no proper validation on the data it receives and with this, the attacker can successfully modify or corrupt data stored in the server. The best practice for validating users input is the use of both server and client side validation techniques.
3) Exposure of user’s session data: One powerful ability that the client side have is the ability to access all the content returned by a web application to the browser. Some of these contents includes cookies that stores sensitive data such as a user’s session ID. If these content are not properly protected and becomes exposed an attacker can exploit them, in fact one of the attacks we will be discussing on (Cross Site Scripting) is known for this kind of exploitation. A good practice for keeping contents in the cookie save is by implementing the Http-Only attribute on cookies. With this attribute the browser will not allow access to cookie content through the DOM. But also this will not give a complete security so it is proper you avoid storing more sensitive data such tokens in the browser.
4) Escaping user input: In most web applications if users should input special kinds of data that contain characters that are used in HTML, JavaScript and CSS, they are rendered as part of the web page by the browser, this is because the application have no policy for preventing this from happening and this is what allows attacker to supply browser-side code that gets executed. To get rid of this vulnerability the application should be programmed in such a way that whenever the browser tries to render a supplied data in a response this special characters should be replaced with escaping codes rather than interpreting and executing them. So these are some of the numerous vulnerabilities that could occur when using JavaScript to power your web application without properly putting security measures in place. Now with this vulnerabilities an attack can exploit a web application to perform the following attacks.
List Of JavaScript Vulnerability Attack
i) CROSS SITE SCRIPTING (XSS): This is the most common vulnerability attack associated with JavaScript applications according to OWASP (Open Web Application Security Project). Research has it that this particular kind of attack is accountable for at least two-thirds of all web application security vulnerability, so what is Cross site Scripting by the way? Cross Site Scripting vulnerability attacks also called XSS attacks is a type of injection attack that involves injection of malicious codes into the client-side of web application that are not properly secured. Cross Site Scripting attacks are mostly targeted at the users of web applications, causing them to carryout unintended actions like clicking on links that are not safe. Applications that falls for this trick most times are those ones that displays content from untrusted sources without proper escaping and validation. Which is why developers are advised to always make sure that request and other forms of data sent to the browser from untrusted sources are properly validated. We have three major kinds of Cross site Scripting vulnerability attacks.
i) Stored or persistent XSS attacks
ii) Reflected XSS attacks
iii) DOM-Based XSS attacks
- Stored or persistent XSS attacks: Stored XSS attacks occur when the malicious inputs are stored in the database of the web application. Common targets for stored XSS attacks includes message forums, comment fields and any feature of the web application where users can interact and share comments. Attackers normally looks out for web applications with known vulnerability in entry points, such as comment sections and inputs malicious scripts that will be stored as part of the page source code. So whenever a user opens the page the browser executes, the script as part of the page
Here is a four step break down of how a stored XSS attack works:
1) First attackers make use of input form in the vulnerable we application to store malicious link in the database of the web application.
2) When a user request that site or page where this malicious link is stored unknowingly
3) The server will send the response to the server with the malicious content
4) When the user’s browser renders the page the malicious content will be executed, and this makes user a victim of XSS attack. The next XSS attack on our list is the Reflected XSS attack. Stored XSS attacks are considered to be one of the most dangerous type of XSS attack compared to the other two, as it is stored in the application and is display to the victim every time the page is loaded. Stored XSS attacks does not require the use of third party mechanism in inducing victims to make a request, this attack is also self contained
- Reflected XSS attacks: Reflected Cross Site Scripting attacks is a kind of vulnerability attack that involves bouncing injected scripts from the web server, that is the browser tends to execute JavaScript codes that were not supposed to be part of a web application’s page. This injected scripts are reflected in error messages, or any other response from the browser that includes data sent from requests. So in order words web applications that receives data from untrusted sources without properly validating or escaping such data is likely vulnerable to this kind of attack.
To activate these scripts the targeted user of vulnerable web applications are entice to click on a link that will enable the execution of the injected script.
For example if an attacker makes a HTTP request in a web application and this request causes the web application to display a script that he/she injects as part of the search term as a response, to make sure that this scripts are executed by a victims browser, the attacker device means of making sure the victim makes a request to the same URL where the malicious scripts are executed, so in order to achieve this the attacker embeds a link that will trigger the execution of these scripts in either comment sections, post sections or send them through emails. Once this script is activated attackers can actually steal users session and assume permanent or temporal identity of the victim user.
The implications of this is that they can do whatever the actual user is able to do in the web application, they would be able to view information available to the user and they can also modify information that the user is able to modify. In fact they compromise the user and take control of their session
DOM-BASED XSS ATTACKS: A DOM-based cross site scripting attack is an example of an XSS attack that affects the client-side of a web application. DOM-based XSS are also called type-0 XSS, they involve the modification of the DOM environment used by the client code, causing it to malfunction. In DOM-based attacks the actual page of the web application is not affected, unlike the stored and reflected XSS attacks where the attack works on the response page of a vulnerable web application. The logic behind DOM-based XSS attacks is that the input of a user (which is also called a sink) is taken to an execution point (called sink) , where the attacker’s malicious code can be executed. After the execution of the attacker’s code, session cookie can be stolen fro the user’s browser and the total behavior of the web application can be under their control. Now we have studied what a Cross Site Scripting attack is and we have seen some examples on it, but how do you know if a web site or a web page is vulnerable to this kind of attack? Basically the simplest method you can use is performing a security review on your codes. By using this method we search for places where input from HTTP request could actually make it’s way into your HTML output. Doing a security review on codes and performing checks on places where HTTP request could actually be displayed on the HTML output of our web site could take a lot of time if we have to do so manually, but we have tools like commercial scanners that will be able to help us automate the process and ease a lot of stress and time. After performing this test the next step you need to take is to find out way you can actually use in preventing Cross site Scripting attacks, but in order to do this successfully we have to get a good understanding of JavaScript vulnerability attack vectors, we will talk more about them later in this article, but for now let’s just move on and talk about some of the preventive measures to take against cross site scripting vulnerability attack:
validating inputs that the web application receives: One of JavaScript’s vulnerability attack vector is the inability of web applications to check and properly validate inputs that it receives from untrusted source. This have also contributed to the dynamic growth of Cross site Scripting attacks. In order to properly mitigate XSS attacks developers must be strict when it comes to validating inputs and sharing of data with the web application’s server, because this the most basic prevention method
Encode HTML before sending to the Browser: To help prevent against XSS attacks on a web application, there should be security measure put into place that will ensure that all variables that will be Properly encoding HTML documents before rendering will help in preventing XSS attacks as not doing so is also an attack vector.
Use Content-Security-Policy (CSP): We will discuss about Content security Policy later in this article, but placing a policy that can help the browser to know what and what to display or execute alongside the source code of the web application. Filter input from untrusted sources: If the web application will have to collect input from users, then such inputs should be filtered, before they are sent to the HTTP request. This will help in preventing attackers from injecting scripts as data.
Use Web Application Firewall (WAF): Web Application Firewall can be very helpful in creating a protection against XSS attacks. Web Application Firewall is a form of application firewall that helps in filtering, monitoring and subsequently blocking HTTP traffics that goes to and from a web service. With this method developers can actually prevent attackers from exploiting web applications known vulnerabilities. Web Application Firewall is out of the scope of this article, in fact it is an entire different topic on it’s own, but you can follow me for more content on it, I will be dropping an article on it later this week. We have talked a lot about Cross Site Scripting (XSS) attacks, but as we already know it is not the only vulnerability attack, so without wasting more time, let’s look at the next vulnerability attack
Cross Site Request Forgery: Another popular JavaScript vulnerability attack is the Cross Site Request Forgery (also known as CSRF for short) Cross Site Request Forgery or CSRF is described as a kind of attack that tricks it’s victim to submit a malicious request to the browser. An attacker of a successful Cross Site Request Forgery attack inherits the privileges of the victims and performs undesired actions on their behalf. For example an attacker can change login details such as password or to make funds transfer. Depending on the nature of the attack it is possible for an attacker to take full control of a victim’s account
The main target of CSRF attack is to cause a change of state on the server, examples of such functionality includes changing email address of a victim, changing passwords and they can even go as far making purchases. A CSRF attack does not try to retrieve data from victims, because doing so is useless to the attacker, as the response of such attempt is not sent to the attacker but rather it’s sent to the victim.
Just like the Cross Site Scripting attacks, CSRF attacks can also be stored on vulnerable sites (stored vulnerability flaws). In a situation where CSRF attacks are stored on the vulnerable site, the attack is said to be severe, and also the possibility in this case is more established as the users of such web application is likely to view page containing an attack compared to other pages on the internet that do not have stored CSRF, and also if most users of the web application are authenticated (which they possibly would be). For the success of a CSRF attack three things must be met:
Relevant action: For an attacker to carry out a CSRF attack the must be an action within the application that the attacker would want to induce, something like modifying permission for other users (this reason is associated to attacks on users with admin privileges) or changing a users password or carrying out transactions on their behalf. To think of it no body wants to be involved in any transaction or activity that won’t profit them, so there must be something of great profit to the attacker
Cookie-based session handling: Applications that solely depends on cookies to identify users who have made HTTP requests will be prone to CSRF attacks, because performing a CSRF attack involves sending HTTP requests, so if there are no means of validating a user sessions apart from using cookies then the web application can be vulnerable.
Unavailability of strong authentication mechanism: If a web application does not employ strong mechanism, for checking requests from users to change password or email address, it will be very easy for an attacker to perform this process. Example if a user should request for a change of password, the application should be able ask some questions like what the previous password was and stuffs like that, some application even go as far as asking some few question that was set by the user for further protection, this will surely help in putting the attacks on check.
The delivery process of a Cross Site Request Forgery attack is essentially the same with the reflected XSS. The attacker places malicious contents on a web site that they control and tries to induce victims to click on their link through the help of social engineering tools, like email and social media messages.
Well it’s still good to note that some CSRF attacks may not require the attacker to employ the use of an external site, in this case the attacker employs the GET method and can send the users of a vulnerable site malicious URL through the domain. From the last example above, if the site is so vulnerable that an attack can be carried out using the GET method.
HOW TO PROTECT AGAINST CSRF ATTACKS
To properly mitigate and defend against CSRF, an application must be have a way to determine and differentiate between legitimately generated HTTP requests and forged HTTP requests. One way to achieve this functionality is by the use CSRF tokens. A csrf token is a random, unpredictable and unique set of value that is issued by an application to user during a session in order to identify users. I will give a more elaborate explanation about this in a later section of this article, but for now, let’s focus on how to protect a web application from csrf attacks.
Another method you can implement as a developer is the double submission of cookies, this is similar to the use of random cookies. In this method random tokens are assigned to both a cookie and a request parameter. When a request is made by a user, the token in the cookie and the one from the request is match if the tokens match then they are granted access, but the tokens does not match, then a denial is issued. Well protection against csrf attack is not only on the side of the web application and development practices alone, even users of web application can also play a major role in contributing to their own protections. Some of the ways a user can contribute to this is by adhering to these best practices when browsing the web especially when they do so on applications that they don’t trust
Log off web application when you done using them or when you want to take a break
Must times people safe their passwords on browsers and it helps them in auto filling when ever they want to. Well this practice might help to some extent, but it should not be encouraged especially when you have to do so with untrusted browsers.
Use a safer method instead for securing and storing user names, passwords and other login credentials. These are some of the best practices web application builders and users can introduce in order to protect against csrf attacks.
Now you have seen some of the possible ways you can avoid CSRF attack both as users of a web application and as a developer. And among some of the best practices I made mention of using a CSRF token. So, what is a csrf token and how do we generate a good CSRF token that can actually mitigate a CSRF attack. A csrf token is a unique, unpredictable and randomly generated set of value that is generated and assigned to a particular user of a web application within a certain period of time (a subsequent HTTP request). A CSRF token should be unique, secrete and unpredictable, so therefore the process of it’s generation and transmission must be unique and secured too. A good CSRF token should contain significant entropy, it should also have the same properties as session tokens. To generate a good CSRF token you can use Pseudo-Random Number Generator (PRNG). To transmit CSRF tokens to the client side, it is good to do so within hidden html form field that are submitted using the POST method.
Some applications transmit CSRF tokens within a custom request header, this is also a good practice, as it presents a more advanced kind of defense, incase an attacker succeeds in predicting or capturing another user’s token, but this practice limits the application to making CSRF protected requests using XHR only. CSRF tokens should not be transmitted within cookies
Now finally how should a CSRF token be validated? After the generation of a token, it should stored on the server-side within the user’s session data awaiting subsequent request that requires validation to be received. Now the validation is done by the server-side, which matches the request token and the token stored on the user’s session ID. The validation must be performed regardless of the kind of HTTP request method (whether it is GET or POST).
As a good practice a csrf token should not be reusable. So in this case it is good to always expire tokens after a short period of time, and also sending of tokens should not be done in HTTp GET requests. Sending tokens in HTTP GET request will not guarantee in availability of token in the URL.
In recent times most people do compare CSRF attacks with the XSS attacks, well let’s take at the both of them side by side and also check for possible ways we can mitigate through both attacks with one action.
CSRF VS XSS
Cross site Scripting (XSS) allows execution of malicious JavaScript within victims browser, in order words an attacker can actually execute JavaScript that are not original in a vulnerable causing the application to loose it’s trust from the user.
Cross site Request Forgery (CSRF) on the other hand induces a user of a vulnerable website to perform certain actions that they do not intend to, in order words Cross site request forgery attacks tries to manipulate the trust a web application have for a victim user
The consequences of XSS attacks are more serious compared to that of CSRF, but they all dangerous though
CSRF attacks are also called one way attacks, because attackers can only send request, but cannot read the responses, but with XSS attacks it’s a two-way thing, attackers can actually send and read HTTP request and response respectively.
Now one question most people do ask is, can a CSRF token protect against XSS attacks? Well if you guessed no you are actually wrong to some extent. Remember I once said CSRF attack behave like reflected XSS, well XSS attacks such as reflected XSS attacks can actually be prevented using CSRF token.
So that is all for Cross Site Scripting attacks (CSRF). Now let’s move on to another JavaScript Vulnerability attack.
Broken Authentication Control
Broken authentication control is No. 2 on the OWASP top 10 list of vulnerability attacks. What is broken authentication by the way?
Well broken authentication implies that an attacker have the ability to compromise passwords, keys and session tokens to assume users identities. In a broken authentication control attack an attacker breaks through the security measures put in place to verify the identity of users, these could be password verification or any other form of verification. Well in 2019 a survey was made in great Britain and this survey discovered that over 23 million people make use of easy to guess and common passwords, this is also a vulnerability as an attacker is able to guess login credential if they are not strong enough.
Broken authentication control is now widespread due to poor design and implementation of access controls. So simply put that broken authentication control happens when a hacker gains access into a system admin’s account. Two major areas where attackers can implement in carrying out a broken authentication attack are: credential management and session management, attackers tend to target web applications that are vulnerable in this area for exploitation.
Authentication in application protects users identity because it is useful for allowing only verified users to access the system, so if the authentication process of the system is broken, what do you think will be the outcome of such attacks? Well broken authentication attacks come with a lot of after effects some of which are:
Stealing critical business data
Theft of identity and impersonation
Attackers can perform social engineering activities such sending mails to other users, and this can be used in fraudulent acts
Cyber terrorism
Sales of illegal items, etc In fact it is very possible for attackers to use Broken authentication attacks to hijack sessions and gain access to the system by forging session data such as cookie. Let’s see one or two examples of cases where Broken authentication attacks can occur in real life.
-Example 1:
In cases where the web application was built for commercial activities such as selling of groceries online, the owners of such web application will probably need a CRM to store things like the user’s name and phone number. If the web application is vulnerable to this kind of attack, it is very possible for hacker to hack through the CRM system to steal all those data. With these data hackers can gain access to communicate with users and perform social engineering activities. In worst cases it is possible for attackers to gain access to bank details of victims through these data. A case like this is called credential stuffing. But what if the attacker decides not to go through credential stuffing, what other scenarios can a Broken Authentication attack occur?
-Example 2:
Now let’s look at a case where a web application that uses the hash method for storing passwords. Let’s say they have three customers Bob, Alice and Precious. Now the hash method is used for storing passwords in the system as hash instead of plain text. Well the hash method itself is a approach for security but what if two users (in our case let’s Bob and Precious) happens to use the same password what do you think will happen? Well it is obvious that their hashes will look exactly the same.
Now let’s say an attacker manages to crack one of the similar password, then the same attacker can use that password to gain access to other accounts with the same password hash.
Well using the hash method is a good approach all together and should be implemented, but in a different way from the one listed above. Let’s say you want to store password with the hash method, then the best approach of doing so is by salting the password. Salting refers to appending or prepending random value in to passwords while storing them in hash format. With salting even the same passwords will look unique. So the above mentioned scenarios are some of the real life applications of broken authentication attacks, but it is not limited to this examples alone. Now let’s talk about some of the causes of a broken authentication attack. Well there are two main causes of broken authentication attack and they include:
- Poor management of users credential: When the web application was no properly programmed to manage users credential such as password, names and phone number, it is possible an attacker can hijack some of this credentials. For instance, allowing users to create accounts using weak passwords like, a single character type password or password that hijackers can easily guess, will make it easy for attackers to use cracking techniques like dictionaries to gain access to the system.
And also using weak encryption techniques to store credentials can make them vulnerable. Passwords must be stored using strong hashing algorithm this way cracking will be made much more difficult Another vulnerability that attracts Broken authentication attacks is :
- Poor Session management: Let’s say you are a fan of shopping for things online, you visit a particular online groceries store, you shop online, you pay for things that you buy with your card and stuffs like that.
Now whenever you log in to that online store, the application issues a session ID to you and records all the transaction you did, and it’s also through this ID that the application receives requests from you and also send responses to you. Well you can say that all communications with the application is done with the session ID issued. What if an application is vulnerable (ie it has a poor session management) and an attacker happens to hijack a users session ID? Well you guessed right if you said the attacker will assume the user’s identity and obviously what will follow will be impersonation of the user. The attacker will be able to do everything that an authenticated user is privileged to do, which is a wide range of possibilities. So therefore from these two vulnerability above, broken authentication attack vulnerabilities can be properly broken down into five:
Allowing weak passwords
URL rewriting
Inability to protect users identity
Poor session fixation and lastly
Transfer of users identity is done over unencrypted connections
We have seen so far what broken authentication attack is and we have looked at some real life scenarios, so why don’t we look at how we can actually prevent this from happening in our application. We can protect users of our applications from getting involved in broken authentication attack if we Implement this methods while building up the security of our web application
If you implement multi-factor authentication also known as (MFA) for verifying users identity, it will be possible to prevent brute force attacks and credential stuffing. Example of MFA is the use of One Time Password (OTP). These passwords expires after they have been used ones
As developers you should also encourage your users to make use of stronger password to avoid theft. Users should be encouraged to use stronger password that constitute character mixture.
Placing a limit to failed login attempts will also help in protecting users. Applications should be able to pay attention to failed login attempts as these could be signs of failed attack attempts
Generation of new random session IDs with high entropy should be done and after a user must have logged out this session should be invalidated. Please remember that this session should not be in the URL.
Now that is all for Broken authentication attack, I would to see you in the next section of this article, where we can talk more on other kind of vulnerability attacks
SQL INJECTION
SQL injection is a backend (server-side) database manipulation attack. SQL injection attack uses malicious SQL codes to manipulate the backend of web applications, the reason for this is to access information that were not originally intended to be displayed.
The impact of SQL injection is far reaching on businesses and it’s outcome ranges from unauthorized viewing of users list by attacker and gaining administrative rights, which means an attacker can actually delete a user’s account if an attack was successful. It is important to note also that customer’s trust can be lost if personal details such as phone numbers and credit card details were stolen.
For better understanding of SQLi attack it is good to first of all understand how an SQL works, I think it would be a great idea to talk about how an SQL query works.
SQL is a standardized language used for accessing and manipulating databases. The reason for this manipulation is to build customizable view for each user. SQL can execute command such as data retrieval, data updates, and removal.
Now from the description of SQL operations above, you can probably guess what an attack can do if successful, so how exactly can an attack be successful? Well here is the thing, SQL injection targets vulnerabilities in dynamic SQL statements. With these vulnerabilities present attackers can enter complex scripts into the form that interferes with the preexisting parameters to alter the meaning of the complete statement. We have three major types SQL injection attacks, these attacks are sub-divided into sub-variations, they include:
IN-BAND SQLi: In this kind of SQL injection attack, the attacker launches their attack and gather the result of their attack from the same channel. In-band SQLi is a very simple and efficient method of SQL injection attack, which is why it is ranked amongst the most common types of SQL injection attack. This type of SQL injection attack is divided into two sub-variation namely:
Error-based, which causes the database to produce error messages. The attacker intentionally sends requests that will produce an error message to the browsers, on receiving this error message the attacker tries to study and understand the structure of the application’s database. In some cases it is enough for attacker to just use this error messages to completely enumerate the entire database of the application. In order to mitigate this attacks from occurring in the future, web application’s developer should avoid sending error messages from the database on live site, although error messages are useful during the development stages, it should be included on the live site.
Union-based, which fuses multiple select statements generated by the database to get a single HTTP response. A successful union-band SQLI attack takes advantage of UNION SQL operator in combining the results of two or more SELECT statements into a single result, and this result is returned as the HTTP response.
Inferential (Blind) SQLi: An attacker that implements this sends data payloads to a server and observe the server to understand how it’s behave, by doing so he or she learns about the server structure. The reason for the alias “blind” owes it’s explanation to the fact that the attackers can not see the result of the attack, because in this method the data is not transferred from the website’s data base to the attacker. Blind SQLi rely on behavioral patterns and responses and they are slower compared to in-band.
Blind SQLi are sub-divided into two techniques:
Boolean: In this kind of technique the attacker sends a query to the database prompting the application to return a result. The interesting part of this method is that the attack makes use of the Boolean method to determine the kind of result he/she will get, that is to say the result will vary depending on whether the query is true or false
Time-based: As the name implies, the time-based attack affects the database by making it wait for a certain period of time before reacting to it. The attacker can see from the time taken by the database to respond, whether the query is true or false Lastly we have the third type of SQL injection.
Out-of-band SQLi: This type of attack solely depends on certain enabled features on the database server used by the web application. Without these features been enabled it will be difficult to carry out this attack, so therefore this attack is primarily an alternative to the other two listed above. When an attacker can not launch an attack with the same channel and gather information or when servers are too slow then an alternative would be the Out of band. This attack depends on the capacity of the server to create DNS or HTTP requests to send data to an attacker. So these are some of the examples we have on SQL injection attacks, there effectives ways through which an SQL injection attack can be mitigated and avoided.
The first approach every developer should try to implement while developing a web application that will prevent attacks like SQL injection is input validation. Every input coming from the user’s side of the web application should be properly sanitized and illegitimate user input should be identifiable. Well while it is of a good practice to implement user validation methods, most times it is not always feasible to validate and check for legal and illegal inputs without affecting the user’s experience. So in this case the application developer could also apply the use of Web Application Firewall (WAF). With the use of WAF web applications can successfully weed out malicious SQL queries with the help of well updated large list of meticulously crafted signatures. We will a better discussion of WAF on a later article that I will release very soon, because WAF on it’s own is a topic to discuss about, so you can follow me and make sure to turn on notification so that you can get informed on the released date.
Content Security Policy (CSP)
Content Security Policy is a security mechanism that restricts the resources like scripts and images which the page can load. With this mechanism a web application can prevent Cross Site Scripting attacks and some other major types of attack that involves injection of inline scripts.
To enable a Cross Site Scripting in a web application a developer must include it on the server side HTTP response and this is done using a server-side language such as PHP, Node.js etc. You can also apply Content Security Policy in a single page within the tag of the page using the tag
How Can Content Security Policy Prevent Cross Site Scripting
With content security policy you can limit the amount of sources where scripts can be loaded from and prevent an attacker from injecting a malicious script into the web application. Defining a policy with a script-src directive as none, will only allow loading of scripts from the same origin as the page itself, so any other scripts that comes from a different source will not be loaded in the page. Also you can allow scripts to be loaded form trusted third party sources, but you have to specify the source URL something like this:
Script-src ‘scripts.trustedwebsite.com
But this is mostly risky if you do not do so with care. For example if an attacker can control content that is served from the third party domain, then it is possible to deliver an attack.
How to implement Content Security Policy
In order to enable a Security Policy to secure your web application you have to configure it in the web application’s server HTTP response or you can use the tag in HTML. The following example describes a policy that will only load scripts from the same source as the web application’s origin using a tag
<meta http-equiv=”Content-Security-Policy” content=”script-src ’self’ “>
There are other types of directives that defines different kinds of policy and we will talk more about them in the next section but for now let’s use the script-src directive as an example. So from the example above notice that two properties were passed into the content attribute. Those two properties are the directive attribute and the source attribute, they are very important in implementing CSP, no matter the methods employed, so let’s talk about these properties shall we:
CSP DIRECTIVES
There are multiple types of directives that allows a developer to control the policies. These directives are generally grouped into 4 groups, which are fetch directives, Document directives, Navigation directives and Reporting directives.
FETCH DIRECTIVES
The fetch directives is use to direct the browser on sources where it can load resources into the web application from. The list below is a comprehensive list of some fetch directives that tells the browser where to load resources such as scripts, fonts, images, other media files etc.
Child-src: the child-src directive helps the developer to control the where nested browsing context can be loaded from
Style-src: the style-src directive defines a valid source from which a browser should load stylesheet from.
Connect-src: a connect-src directive helps the developer to restrict source through which the browser can retrieve JavaScript data, with the use of Ajax, EventSource and webSocket
Font-src: this tells the browser where to load fonts into the web application. If a URL is not specified to load fonts into the site in this directive, it will be impossible to load fonts from them
Sandbox : a sandbox is used in defining the method of form submission in the web application.
Script-src: ** the script-src directive tells the browser where to load scripts from. Every other sources that are not specified in this directive can not submit a script that will be executable to the browser
Default-src: a default-src acts as a fallback policy for other directives. It is typically set as self or none and this ensures that other directives are declared.
It is not compulsory that you should declare all of these directives before the content before the content security policy would work. You can actually declare one or two directives depending on the kind of policy you want to pass in your web application
DOCUMENT DIRECTIVE
The document directives can be used by a developer to instruct the browser on properties of the document policies can be applied to. We have:
Base-uri: a base-uri directive defines possible URLs that the base element can use
Plugin-types: this directive controls the resources that could be loaded into the document. Navigation directive: with navigation directives a developer can instruct the browser on locations to navigate document to. These directives include navigate-to, form-action, frame-ancestors etc
REPORTING DIRECTIVES: Report directives delivers a report of violations of prevented behaviors. On their own these directives have no purpose so they rely on the other types of directive in order to prevent and mitigate attacks. These directives includes report-to and report-uri directives. So next up let us look at source from which these directive can load resources from. After specifying a directive, you have to specify a source from which resource can be loaded. For example let’s say you specify a script-src directive and you want only scripts in that are from the same origin and no external domain to be executed, you can do that with the aid of the source property. So in this case you use the ‘none’ source attribute we have variety of source attributes and their different values and they include
None: the none source directive tells the browser not to load a specified resource from any source. That no URL matches
Self: this helps the developer to tell the browser that a specified directive should be loaded from only origin site with the port number and no other site should match Unsafe-inline: this will allow the browser to load inline scripts and execute them.
domain.com: a directive that has this kind of source can load resource from the specified domain, so in this case a developer can pass in a trusted domain that he or she wants to load resources such as scripts and fonts from. So that all for content security policy and how to implement them. Having a content security policy in your application will go a long way in
Protecting it from attacks, as it places restriction defined by the developer on what resources the browser can execute and from which source these resources should come from
Conclusion
Web security is a thing of major concern and Vulnerability of web applications keeps on adding as the day goes by. JavaScript have become widely used in building web site both in the front end and backend so, It is very important to note some of the major JavaScript vulnerabilities that might lead to an attack. In this article we were able to look at some of JavaScript’s vulnerability attacks, including their attack vectors. We also covered ways developers can protect against these attacks, where we saw Content Security Policy. We looked at different techniques developers can actually use in implementing Content Security Policy. For more exciting from this blog hit the follow icon and also drop all your wonderful comments on the comment section below
Well so far good we have seen some possible vulnerabilities that could be seen in a web application that is designed with JavaScript technology and we have also seen possible vulnerability attacks and how to prevent them. But in the next section I am going to show you a more handy technique you can use in mitigating a vulnerability attack, especially a Cross Site Scripting attack, it is called a Content Security Policy.