How to keep your web applications safe
Imagine, as you are browsing the internet – as any modern-day web user does, you see a random pop-up notifying you you have won a prize, or have the opportunity to win a prize. These pop-ups act as an avenue for malicious payloads to be delivered onto your system, or even capture sensitive information.
This type of incident is known as XSS (Cross-Site Scripting). They are a common vulnerability in web applications. In fact, according to studies, more than 60% of web applications are vulnerable to them and ultimately account for over 30% of all web application attacks.
In its simplest form, with XSS, threat actors enter malicious code into a web form/web app URL, often taking advantage of poor coding practices, to trick the application into doing something it was not programmed to do. This malicious code can be executed in the context of a user’s browser, leading to data exfiltration, unauthorized access or even installing malware.
We at Oppos Cybersecurity Canada understand the best way to combat this vulnerability is to gain an understanding of the nuances of its various types. This article clarifies the complexities of XSS and educates developers and security enthusiasts on practical strategies for defending against it. We’ll delve into the world of secure coding practices, emphasize the importance of input validation, and explore advanced security mechanisms like Content Security Policy (CSP). By adopting these measures, we can create a resilient defense against XSS incursions.
In this Guide
What is JavaScript?
JavaScript (JS) is a cross-platform, object-oriented programming language used by developers to make web pages interactive. It is considered one of the most popular scripting languages, as about 93% of all websites run using it. Its popularity is highlighted in its standing as a pillar for A dynamic web application – along with CSS and HTML. Every Time you interact with a web page and it displays timely content updates, control multimedia, animate images, interactive maps, graphics (3D and 2D), etc, most likely, JavaScript was involved.JavaScript Event Handlers
In JavaScript, an event handler is a callback routine or function that operates asynchronously once a particular event is triggered. In HTML, these events can represent user or browser activities, including actions like user input from the keyboard or mouse, changes in the content of an input field, page loading, and more. When javascript code is included in HTML, JS reacts to these events and allows the execution. The process of reacting to the events is called Event Handling, thus, js handles the HTML events via Event Handlers.
Here are some key concepts related to event handlers in JavaScript:
- Event Types:
- Events like “onclick” (mouse click), “onmouseover” (the user moves the mouse over an HTML element), “onload” (The browser has finished loading the page), “load” (page loading), and many others.
- Events can be categorized into user interface (UI) events, keyboard events, mouse events, and more.
- Event Handling Syntax:
- Event handlers can be attached to HTML elements in the markup or dynamically through JavaScript.
- In HTML, an event handler is typically added as an attribute to an element.
Example:
Callback Functions:
- An event handler is a callback function that is passed into another function as an argument and then executed when the associated event happens.
- The callback function can be predefined or defined inline as an anonymous function.
- Event Propagation:
- Events in the DOM propagate through different phases, such as capturing and bubbling. Understanding these phases is important for more complex event-handling scenarios.
Event handlers play a crucial role in creating dynamic and interactive web pages. They allow web developers to create unique responses to user input and create engaging user interactions and experiences. However, despite the overwhelming benefits, it is important to handle the events securely, as improper handling can lead to vulnerabilities such as Cross-Site Scripting (XSS).
What is Cross-Site Scripting?
Cross-site scripting attacks where malicious scripts are injected into benign and trusted websites, to trick the web application into doing something it’s not supposed to do. This malicious script, often written in JavaScript can vandalize the website, and steal user private data, keystrokes, or other login credentials. Weaknesses in the system that allow these attacks to succeed are very prolific and occur anywhere a web application accepts user input within the output it generates without validating or encoding it. Attackers can employ XSS to send code to unsuspecting users whose browsers cannot know what script should be trusted and executed. As a result, the malicious scripts can access session tokens, cookies*, and other sensitive information stored by the browser and associated websites. According to Cloudflare, Cookies are “small files of information that a web server generates and sends to a web browser. Web browsers store the cookies they receive for a predetermined period or the length of a user’s session on a website. They attach the relevant cookies to any future requests the user makes of the web server”. A simple example of cookies is when you open up a website, and your username and password are auto-filled. Threat actors use XSS to take advantage of modern web applications. Many websites are built dynamically when pages load, often through code executed within the user’s browser. This inherent nature can pose challenges in effectively preventing such attacks.What is an XSS Payload?
The Payload is the injected code that can potentially steal sensitive user information, like cookies and login credentials. It can even execute actions on behalf of the user, such as posting comments or making purchases. XSS payloads vary, ranging from straightforward scripts that trigger pop-up messages to intricate attacks designed to extract sensitive data or assume user browser control.How does an XSS attack work?
Let’s start with an example!If the website does not properly validate or sanitize the user input, the above script will be executed redirecting the user to another page, often a phishing site or a page controlled by the attacker, Capturing the keystrokes of a user, running browser-based exploits, and capturing cookie information, once they click the particular button.
What are some types of XSS attacks?
Reflected XSS Attack
Reflected XSS attacks, also known as non-persistent attacks, occur when a malicious script is reflected off of a web application to the victim’s browser. The payload echoes back in response since it doesn’t have any server-side output encoding. These attacks are activated through a link that sends the request to a website with a vulnerability that enables the execution of malicious code. Reflected XSS is often part of a phishing scam, where the evil link is disguised as something more palatable and sent to the victim via email or text message.
DOM XSS
This XSS vulnerability appears in a Document Object Model rather than in the HTML pages. A DOM can be described as a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text.
The DOM provides a way for programs to manipulate the structure, style, and content of web documents dynamically. Attackers can read and manipulate the DOM data to craft a malicious URL. If the user is tricked into clicking this URL, the attacker can steal the user’s active session information, keystrokes, and so on. Unlike stored XSS and reflected XSS, the entire DOM-based XSS attack happens on the client browser (i.e., nothing goes back to the server).
Stored XSS
A stored XSS attack occurs when the malicious script is injected into a web application and permanently stored on the server or in a database.
Note this is the most dangerous form of XSS attack, as the attacker only injects the malicious payload into the server once, but it can affect a large number of users.
What is Web Application Penetration Testing
How to prevent XSS vulnerabilities
Preventing XSS vulnerabilities involves implementing security measures early in an application’s development life cycle. That is, in the software design phase, you should perform activities such as architecture risk analysis and threat modeling. Further, it is equally important to conduct security testing once application development is complete. Strategies to prevent XSS attacks include:Input Sanitization
Input Sanitization is a standard security measure that checks and filters input data to ensure it’s free of characters or strings that could inject malicious code into an application or system. This method is easier said than done, as skillful hackers can craft snippets of executable code that can slip through the filters.
One way to tackle this issue is to take a whitelist rather than a blacklist approach. Instead of attempting to create a filter that restricts all malicious code from entering a web form, design your application to exclusively accept data in predefined formats (such as phone numbers or email addresses) if that aligns with the expected input.
Similarly, Input Validation should also be exercised. One of the most effective ways to prevent cross-site scripting. Input Validation is the process of analyzing input and prohibiting those deemed unsuitable. Input validation entails scrutinizing inputs and prohibiting those deemed unsuitable.
The concept behind input validation is to allow only inputs that meet defined criteria, making it infeasible for an attacker to introduce input intended to cause harm to a system. It is recommended that input validation be conducted as early as feasible in the data flow, ideally immediately upon receiving the data from external sources.
Output Encoding
It involves encoding or escaping user input before rendering it in a web page ensuring the browser interprets any potentially harmful characters or scripts as benign data or plain text and not as code.
It typically involves replacing special characters with their corresponding HTML or URL entities. For example:
- < is encoded as <
- > is encoded as >
- ” is encoded as "
- ‘ is encoded as ' or '
- & is encoded as &
These characters are displayed as plain text on the webpage by performing output encoding, preventing them from being interpreted as part of an HTML or JavaScript code.
Follow the practice of defense-in-depth
This strategy utilizes a variety of security controls to ensure the safety of your most valuable assets. Multiple layers of defense (Physical, technical, and administrative) ensure that even if one wall is breached, there are others in place for protection from malicious attacks.
It is essential to align web application development with OWASP’s XSS Prevention Cheat Sheet, a compilation of proven techniques designed to thwart Cross-Site Scripting (XSS) vulnerabilities. OWASP advises using a combination of techniques as an XSS defense mechanism that can be customized for your specific application.
After, it is recommended that the effectiveness of the remediation efforts be tested and validated by conducting thorough penetration testing. Experienced penetration testers can simulate real-world attack scenarios, strategically assessing your web application’s vulnerabilities and confirming that high-risk XSS points are effectively fortified against potential security breaches.
Web Application Firewalls
Moreover, web application firewalls (WAFs) are crucial in minimizing the impact of reflected XSS attacks. By utilizing signature-based security rules in conjunction with other heuristics, a WAF can address the absence of input sanitization and proactively block abnormal requests. This encompasses a range of requests attempting to execute reflected cross-site scripting attacks.
It is also important to highlight that, unlike a stored attack where the malicious requests from the perpetrator to a website are obstructed, in a reflected XSS attack, it is the user’s requests that face blocking. This is done to protect the user and prevent collateral damage to all other website visitors.
Content Security Policy
This can be implemented as a last line of defense, to reduce the severity of any XSS vulnerabilities if it does still occur.
How to Detect XSS Vulnerabilities
Manual Code Review
This aims to identify security vulnerabilities in the application’s source code, especially client-side code (JavaScript), to identify places where user input is used in a way that might be vulnerable to XSS attacks. This also involves auditing the source code of an application to ensure that it is self-defending.
Check that the output is encoded
Check that HtmlEncode is used to encode HTML output that includes any type of input. Additionally, confirm that UrlEncode is applied to encode URL strings. Input data originating from various sources, such as query strings, form fields, cookies, HTTP headers, and database inputs (especially in shared databases with other applications), should undergo these encodings. The lack of these encodings increases the risk of XSS vulnerability, and encoding helps prevent the browser from interpreting HTML as an executable script.
Identify Code that Handles URL
It is important to review code sections that process URLs as they can pose XSS and other vulnerabilities. It is therefore important to ensure your web server is up-to-date by checking for the latest security patches. An outdated web server could be susceptible to directory traversal attacks.
If your code includes filters for “/”, be aware that an attacker can potentially bypass this filter using URL encoding (percent-encoding) for the same character. For instance, the percent-encoding for “/” is “%c0f%af,” which could be exploited to bypass the filter.
For code that processes query string input, confirm that it uses constraints on input data and conducts boundary checks. Additionally, ensure the code is not vulnerable to attacks involving the injection of a substantial amount of data through a query string parameter.
Perform Unit Testing
Unit testing is the process where you test the smallest functional unit of code. Unit testing aims to isolate each part of the program and show that the individual components are correct. Use unit testing to make sure that a particular bit of data is correctly escaped. It is therefore ideal to identify XSS vulnerabilities early in development. You should also consider adding regression tests for previously fixed XSS bugs.
Automated Application Testing
There are three forms of automated application testing. Dynamic, Static, and Interactive. Dynamic Application Security Testing (DAST) tools interact directly with applications to discover potential security vulnerabilities through the application’s front end. They operate without access to source codes and employ a black-box testing strategy, executing attacks to identify vulnerabilities. Dynamic analysis conducts security checks during code execution or the application under review.
Fuzzing, a technique used in dynamic tests, involves submitting random, malformed data as inputs to the application to assess its ability to unveil XSS flaws. Similarly, static application security testing (SAST) aims to enhance application security by analyzing the source code to identify vulnerabilities or signs of known insecure practices when the application is not running.
One advantage of static code analysis is conducting assessments before the application is deployed in a staging environment, eliminating the need for test data. This comprehensive code-level evaluation ensures 100% coverage while cost-effectively identifying vulnerabilities. SAST tools use a white-box testing approach, examining the source code and components to uncover potential security flaws.
Interactive Application Security Testing (IAST) combines the strengths of both SAST and DAST. It analyzes code for XSS and other security vulnerabilities while the application is active, responding to any activity that interacts with its functionality. This integrated approach provides a comprehensive assessment, offering real-time insights into security issues during application runtime.
By combining manual review, automated tools, dynamic testing, and regular security audits, you can effectively detect and mitigate XSS vulnerabilities in your web application. It’s important to adopt a comprehensive and ongoing approach to ensure the continued security of your application.
Difference Between a Penetration Test and a Vulnerability Assessment
Now, where does Oppos come in all this?
XSS poses a significant risk to the integrity and confidentiality of user data. When you start fortifying your web applications against XSS attacks, partnering with a specialized security firm is crucial in ensuring you have a robust defense.
Why Choose Oppos?
Our company boasts a team of seasoned cybersecurity experts who deeply understand XSS vulnerabilities and other web application security challenges. With a wealth of experience in identifying, analyzing, and mitigating XSS risks, our professionals are well-equipped to provide comprehensive solutions tailored to your specific needs.
We can assist with vulnerability assessments through automated and manual testing to identify potential XSS vulnerabilities, examining every layer of your application for weaknesses. After that, we provide customized solutions, as we understand that each web environment is unique and, therefore, needs tailored solutions to address the specific XSS vulnerabilities present in your systems.
Whether it’s implementing secure coding practices, validating user inputs, or deploying a Content Security Policy (CSP), our recommendations are customized to enhance your application’s security posture.
Final Thoughts
It is clear that Cross-site scripting (XSS) is a multifaceted attack that uses social engineering methods to target client-side scripts, accounting for 30% of all web application attacks. As we’ve explored, the intricate mechanisms and devastating consequences of XSS vulnerabilities include credential and cookie theft, user redirection to malicious websites, impersonating the victim user, and more.
This enables attackers to infiltrate an organization’s internal network, providing them entry to a system or web application. Thus, it is imperative to Implement secure coding practices, enforce strict input validation, and leverage advanced security mechanisms like Content Security Policy (CSP). Moreover, combining manual code reviews, automated testing, and ongoing security audits is essential to detect and mitigate vulnerabilities effectively.
Our team at Oppos recognizes the gravity of XSS vulnerabilities and is ready to assist your team. From comprehensive vulnerability assessments to customized remediated strategies, we are committed to empowering organizations with the tools and expertise to bolster their web application security.
By teaming up with Oppos, organizations can be confident that they have a reliable partner committed to protecting their digital assets amidst the continually changing threat landscape. Together, we can navigate the complexities of XSS vulnerabilities, creating a safe and secure online ecosystem for your web applications.