Tuesday, 17 September, 2019 UTC


Summary

Security should be one of the key concerns while developing any application. If developers are aware of the security risks beforehand, they can avoid common security mistakes. This article will highlight common security risks, OWASP, and vulnerable applications.
Introduction To The OWASP Project
OWASP stands for Open Web Application Security Project. It's a comprehensive online source of documentation and tools for web security.
In this article, we will be exploring the OWASP Top 10 and Vulnerable Node Apps.
OWASP Top 10
The OWASP Top 10 is a list of top ten application security risks. This is list is compiled by multiple security experts associated with OWASP. The last version of the report was published in 2017. The risks outlined in the report are as below.

A1-Injection

Injection attacks occur when malicious code is sent to an interpreter and it gets executed. This type of attack occurs when user inputs are not sanitized.
SQL injection is one of the most common attacks. An example of a vulnerable string is below:
let sql = `SELECT * FROM students WHERE name = "id"`
If we pass the parameter Robert "; DROP TABLE students; --, it will drop table students. Sanitizing user inputs and using an ORM library can prevent such attacks.
Source: XKCD
Additionally using eval, setTimeout, setInterval, and Function functions to directly evaluate user inputs is harmful. JSON.parse should be used to evaluate user inputs.

A2-Broken Authentication and Session Management

The purpose of this attack is to gain unauthorized access. This can be achieved by brute-forcing the login system or hijacking a user session. This type of attack leverages insecure development practices like:
  • Using plaintext passwords (it's a liability; if the database is compromised, the list puts all users at risk);
  • Not enabling session timeouts (security risk if a person is using a public computer);
  • Not generating new session id (prone to Session Hijacking);
This risk can be vastly mitigated with the use of salted passwords and proper session management.

A3-Sensitive Data Exposure

The point of the attack is to retrieve sensitive data like:
  • Username;
  • Associated passwords;
  • Bank account numbers;
  • Credit card details;
  • Contact details (phone, mobile, email).
This type of attack is commonly associated with identity theft. Weakly salted or plaintext passwords can act as password dumps usable for other attacks. The data can be retrieved off the server or in-transit. To mitigate the risk, we have to enable strong salting for passwords, use encryption for sensitive details, and use SSL/TLS for transmitting data.
While securing the server and databases is crucial to address this threat, today it's equally critical to consider data exfiltration that occurs through the client-side. Web supply chain attacks like Magecart are able to place credit card skimming code via compromised third-parties and often remains undetected for a long time. To address this, we have to monitor DOM tampering, event hijacking, and API poisoning.

A4-XXE

XML External Entity Attack is an attack against a vulnerable XML processor.
Some XML processors allow the specification of an external entity, a URI which is dereferenced and evaluated while XML parsing. This allows an attacker to access local data from the server like a password list or important files. A type of deviant XML input from DVNA is below.
<!DOCTYPE foo [<!ELEMENT foo ANY >
<!ENTITY bar SYSTEM "file:///etc/passwd" >]>
<products>
   <product>
      <name>Playstation 4</name>
      <code>274</code>
      <tags>gaming console</tags>
      <description>&bar;</description>
   </product>
</products>
The external entity bar is asking system to access a file /etc/passwd. On UNIX like systems, /etc/passwd is a list of user attributes. The output will be visible in the description.
To prevent the attack we should block external entities in the parser. Most XML parsers have a flag to disable the EE parsing. XML inputs should be validated using XSD validation. Alternatively, we can just use a format like JSON to transfer data.

A5-Broken Access Control

Web Applications usually have multiple user roles. Roles like Administrators, Managers, Moderators, Vendors have more privileges than normal users.
Broken Access Control can occur in two ways.
  • Vertical Escalation: An attacker uses normal user credentials to access admin-level privileges. This is commonly known as privilege escalation.
  • Horizontal Escalation: An attacker uses normal user credentials to access the resources of other users. Such an attack can result in a massive data leak.
Some reasons for broken access:
  • Lack of Access Control on privileged pages;
  • Faulty access mechanisms which allow tampered JWT;
  • Resource access via field parameters.
To prevent broken access controls:
  • A Deny-All strategy must be applied to all privileged pages;
  • JWT tokens must be invalidated on the server after logout;
  • Resource access should not be given via parameters;
  • Web directory listing should be disabled.

A6-Security Misconfiguration

This type of attack happens when an attacker knows the application attack and tries to access default pages or use default credentials. This is usually an issue if we are using an aftermarket software stack (CMS / LMS).
This type of threat can be eliminated by changing passwords for critical accounts and disabling default user accounts. The deployed application should always in production mode. Unnecessary server ports should be blocked.

A7-XSS (Cross-Site Scripting)

XSS is the second most prevalent issue in OWASP TT. There are 3 forms of XSS:
  • Reflected XSS: The web app has invalidated and/or unescaped user input as part of HTML. This allows the attacker to execute arbitrary HTML/JS code on the client machine. This attack is commonly used in phishing emails;
  • Stored XSS: As the name suggests, an attacker can store malicious code on the webpage. A common way to do that is via comment sections in web pages that allow HTML tags. As such, the malicious code can now hijack sessions or cookies of anyone who visits the page;
  • DOM XSS: DOM XSS is client-side XSS. Malicious code is injected in DOM-based on client input. This type of attack is commonly found in search query boxes.
Having a strong CSP is recommended to control XSS attacks. Modern SPA frameworks like React and Angular have built-in XSS protection. It's advisable to avoid using Angular's DOM Sanitizer bypassSecurityTrustHtml method or React's dangerouslySetInnerHTML prop.

A8-Insecure Deserialization

This type of attack occurs if an application is using custom serialization and deserialization. This attack requires knowledge of that application and type of serialization used.
Usually, it's an issue if sensitive data is serialized and stored using custom serialization functions. An attack vector can be sent as a serialized parameter. There is a possibility of malicious code execution while the parameter is deserialized.
This is not an issue if common serialization techniques like JSON and XML are used. Enforcing strict type constraints can mitigate the risk. Other than that, the application should not accept serialized data from external sources.

A9-Using Components with Known Vulnerabilities

An attacker can leverage known vulnerabilities of dependencies to exploit the application. This includes OS, web server, DB server, or libraries like npm packages.
Some of the steps to mitigate this include keeping the server/OS/DB up to date and use tools like npm audit to check for vulnerabilities. Also, it's wise to minimize the use of third-party libraries. A more holistic approach like monitoring webpages in real-time can be used to quickly detect if a compromised component is exploiting the client-side of the application.

A10-Insufficient Logging & Monitoring

Incident response after a security breach can be initiated if the breach is detected. Also, security breaches can be prevented if the application is under active monitoring. A sufficiently logged system can provide data required for an incident response after a breach is detected. A monitored system allows a breach to be detected sooner.
It's also crucial to monitor not only the server-side but also the client-side, especially considering an increase in attacks that exploit the lack of client-side visibility, such as Magecart and other web supply chain attacks. Webpage monitoring solutions should be able to detect every suspicious client-side activity in real-time and alert application owners.
Depending on the business, important activities should be logged and monitored. These include:
  • Administrative Logins / Logouts;
  • User logins / logouts;
  • Important transactions;
  • Applications errors;
  • External API requests.
Based on the business, flow detection mechanisms for suspicious activity should be developed and deployed.
In NodeJS, we can use libraries like morgan, pino and winston for logging.
Now, let us explore some vulnerable apps to put this knowledge into practice.
Vulnerable Node Apps
Vulnerable Apps are web applications developed to be intentionally insecure. The objective of running these apps is to understand their vulnerabilities by exploiting them. The apps are accompanied by documentation of known risks. Developers should study the insecure code and the risks they carry, as well as studying and developing a risk mitigation strategy.
In this article, we will be taking a look at NodeGoat, DVNA and OWASP Juice Shop.

Setting Up The Environment

We can use any operating systems to run the applications. NodeJS, preferably an LTS version, should be installed beforehand. On UNIX-like systems, it's better to install Node via nvm. Depending on the project, we may require a separate DB provider like Mongo or MySQL. Alternatively, Docker instances of applications are also available.
We can use specialized Linux distributions to analyze the deployed vulnerable applications. Kali Linux, Parrot,BlackArch and Fedora Security Labs are some of the popular pen testing distributions available.

Node Goat

Node Goat is one of the first OWASP Apps and uses the Top Ten Vulnerabilities of the 2013 report. Hence, you will find Insecure DOR, CSRF and Redirects attacks. Additionally, the app covers Regex Denial of Service (ReDoS) & Server Side Request Forgery (SSRF).
The App uses Express as middleware and MongoDB for the backend. Here is the documentation for the app.
To setup, the app, clone this repository.
Use npm i to install dependencies
npm i 
Edit the parameter in config/env/development.js to reflect the DB URL. For example: mongodb://localhost:27017/<databasename>. The database should be created in MongoDB beforehand using use databasename.
Now, run this command to populate the DB.
npm run db:seed
Next, start the application.
npm start
The application should be available at http://localhost:4000/

DVNA

Damn Vulnerable Node App is a relatively newer application. The app contains 2017 TT vulnerabilities with CSRF and Redirects attacks. DVNA is an Express app which uses Sequelize as an ORM provider. Hence, we can use any SQL Database for a backend. The fixes and fixes-2017 branches on GitHub have fixes for the vulnerable app. Here is the documentation for DVNA.
To set up the app, clone this repository.
DVNA assumes MYSQL as primary DB provider. The config takes values from the environment. We can set the relevant environment variables.
export MYSQL_USER=dvna
export MYSQL_DATABASE=dvna
export MYSQL_PASSWORD=passw0rd
export MYSQL_HOST=127.0.0.1
export MYSQL_PORT=3306
Alternatively, DB credentials can be modified in config/db.js.
Use npm i to install dependencies
npm i
And then start the application.
npm start
The application should be available at http://localhost:9090/.

OWASP Juice Shop

OWASP Juice Shop is a flagship OWASP Project. It contains multiple vulnerabilities including the OWASP Top Ten. Juice Shop uses Angular + Material on the frontend, Express as middleware and Sequelize + SQLite for the database. The app supports Google sign-in with Oauth. Juice Shop is targeted towards security professionals. It has a separate CLI, juice-shop-ctf-cli, for setting up Capture the Flag events (CTF). Juice shop intends to highlight vulnerabilities in a SPA or RIA. The documentation for Juice shop can be found here.
To set up the app, clone this repository.
Use npm i to install dependencies
npm i
Next, start the application.
npm start
The application should be available at http://localhost:3000/.

Closing Thoughts

After understanding common risks, developers can avoid mistakes while developing. Similarly, if a risk is identified, it can be mitigated quicker.
The three presented vulnerable applications should be a great starting point for testing different attacks with the goal of understanding each vulnerability in practice. As a result, you should be much more prepared to understand vulnerabilities when developing applications and motivated to take further steps in Application Security.
To explore other topics in Web Security, check this selection of articles.

If you're developing JavaScript applications, join our upcoming webinar on "Securing Enterprise JavaScript Applications"! Simply fill the form below to save your free seat.