Protect From Cross-Site Scripting Attacks

Learn via video courses
Topics Covered

Overview

Cross Site Scripting is probably a term you've heard of if you've been developing apps for some time. According to OWASP, one of the top 10 most prevalent web security vulnerabilities is cross-site scripting, or XSS. Attackers can use this client-side script injection method to steal data or make nefarious requests to a server. An XSS attack can be carried out in a variety of ways, depending on the design of the target application and the attackers' ingenuity. Cross-site scripting and how to prevent cross-site scripting is still a significant issue in many web applications, and it can have devastating consequences. Developers must understand XSS and be aware of it, but it's even more crucial to understand how to stop it.

What is Cross-Site Scripting (XSS)?

Malicious scripts are injected into websites that are normally safe and reputable in Cross-Site Scripting (XSS) attacks. XSS attacks take place when an online application is used by an attacker to deliver malicious code, typically in the form of a client-side script, to a separate end user. Wherever a web app incorporates user input into the output it produces without verifying or encoding it, flaws that enable these attacks to succeed can be found.

A malicious script can be sent to an unknowing user by an attacker using XSS. The end user's browser will run the script even though it shouldn't be trusted. The malicious script can access any cookies, session tokens, or other sensitive data stored by the user's browser and used with that site since it believes the script is from a reliable source. These scripts can completely change HTML page content.

How does XSS Work?

Cross-Site Scripting happens when dynamically generated web pages show user input that hasn't been properly validated, like login information. This situation allows an attacker to embed malicious scripts into the generated page and then run the script on the computer of any user who visits the website. In this case, the online application was susceptible to an automatic payload, which required just the user to visit a page for malicious scripts to run.

Attacks using XSS get around the Same Origin Policy. A security technique known as SOP stops scripts from one website from interacting with scripts from another. A website's whole material must originate from the same source, according to SOP. Malicious actors can insert scripts and alter a webpage to suit their needs if the policy isn't followed.

A malicious script is injected into user-provided input to conduct a cross-site scripting attack. Attackers may also alter a request to conduct an attack. The user-supplied input runs as code if the web app is susceptible to XSS attacks. The script, for instance, displays a message box with the text "xss" in the request below.

http://www.site.com/page.php?var=

An XSS attack might start in several different ways. For instance, the execution might begin automatically when a user hovers over certain website elements or when the page first loaded (e.g., hyperlinks).

Cross-site scripting attacks may have the following effects:

  • Recording a user's keystrokes.
  • Redirecting a visitor to a harmful website.
  • Utilising web browser exploits (e.g., crashing the browser).
  • Obtaining a website user's cookie information and using it to compromise the victim's account.

In some cases, an XSS attack completely compromises the victim's account. Users can be tricked into entering their credentials on a bogus form, granting the attacker access to all data.

What are the 3 Types of XSS Attacks?

XSS attacks can be categorised into three groups based on where an attacker places an injection for execution: reflected (nonpersistent), stored (persistent), and DOM-based XSS attacks.

  1. Reflected (Non-Persistent) XSS:

    One of the most typical forms of XSS is reflected in XSS. Attackers create malicious links, phishing emails, or employ a variety of other strategies to dupe victims into sending the server fraudulent requests to carry out this kind of invasion.

    The victim inadvertently sends the malicious script as part of the regular client request to the server. The malicious script will be sent as part of the response if the application isn't utilising the correct escaping to insert user-provided data in an HTML context. The malicious script is loaded and executed on the victim's client, along with the server response when it loads. When a request contains a malicious script, the server will process the request and instantly send the malicious script back with the response.

    The malicious script is reflected from the server back to the client in this particular sort of XSS. As a result, it is known as reflected XSS. An attacker must deliver the payload to each victim if they want to utilise mirrored XSS. As a result, non-persistent XSS is another name for reflected XSS.

  2. Stored (Persistent) XSS:

    The function of this XSS is kind of implied in the title. The word "stored" denotes a location where the payload is kept. The payload is kept on the server side in stored XSS. Anyone viewing the portion of the app that contains the payload would run the malicious script once the payload is there, assuming the developer didn't correctly escape it when it was prepared for display.

    Consider the case when an application has a video channel that is XSS-prone. Your subscribers can view your videos, like them, and comment on them. The system keeps a database of all the comments. Take the case when you have a cybersecurity video with 100 comments. The application downloads all the comments and shows them on the homepage each time a user accesses this video.

    Consider a scenario where one of these comments is a harmful script that a hacker has injected rather than just a comment. Every user who watches the video will receive the dangerous script, which the application stores in its database. When the page loads, the malicious script is then run by the victim's browser.

    While using cached XSS, the attacker only injects the harmful script once. All users who access that area of the app receive the payload after it has been saved by the application. As a result, it is also known as persistent XSS.

  3. DOM-based XSS:

    This particular form of XSS vulnerability only arises when a program makes use of a Document Object Model (DOM). The data only stays on the client side when an application utilises a DOM to store data, and the browser reads and displays the result. A DOM does not send data to the server for storage.

    An attacker uses the URL or another sink supported by the browser's API to inject the payload into the DOM in a DOM XSS. The browser modifies the DOM to add the attacker-provided script whenever a user accesses the page at that URL or initiates an activity on this page. The application then runs the payload at that point.

How do You Test for XSS Vulnerabilities?

When it returns to the client unvalidated input from requests, how to prevent cross-site scripting?

To check the vulnerability of a website or application, use web scanning tools. These tools insert scripts such as POST or GET variables, cookies, URLs, and other code that could be used in a cross-scripting attack into the online application. The website is prone to XSS if the tool can insert that kind of data into the page. The user is informed of the vulnerability and the injected script that was used to find it by the tool.

The steps listed below can also be used to manually check for XSS vulnerabilities:

  • Locate the input vectors. This entails figuring out every user-defined input used by the application. Web proxies or in-browser HTML editors can be used to achieve this.
  • Observe the input vectors. The browser's responses are triggered by specific input data and reveal the vulnerability. An inventory of test input data is provided by the (OWASP) Open Web Application Security Project.
  • Analyze the effect of the test input. The tester should evaluate the outcomes of the input they select and decide whether the vulnerabilities found would compromise the security of the app. The tester must locate HTML special characters that lead to security holes and must be changed, filtered, or otherwise eliminated.

How do You Prevent Cross-Site Scripting in an Express Server?

Now let us understand how to prevent cross-site scripting, always render HTML content using a template engine and res.render(). Pug, Mustache, and EJS are some examples of widely used template engines. Escape the content if HTML escape is necessary. Suppose you can try to implement it with JavaScript code. Examine each situation in detail. After evaluation, use # nosemgrep to exclude the discovery. Data shouldn't be placed in potentially harmful places like script tags. Run a security checker on your code as usual.

A few things you must take care of in how to prevent cross-site scripting are as follows:

  • Direct Use of res.send():
    As the template engine is not used when writing directly to the response object, autoscaling of the content is not possible. There may now be an XSS vulnerability as a result. Example: res.send("<div>" + user.name + "</div>")

  • Direct Use of res.write():
    As the template engine is not used when writing directly to the response object, content will not automatically be escaped. This might create an XSS vulnerability. Example : res.write("<div>" + user.name + "</div>")

  • Cookie Policies:
    Cookies are one of the most frequent targets of cross-site scripting attacks. One effective way to crack down on these attacks is to implement an HttpOnly cookie policy. This policy essentially prevents JavaScript from having access to cookies.

    One way to achieve this in Node.js is the following:

  • Use of Validators:
    Express-validator is a collection of middlewares for Express.js that encapsulates the validator and sanitizer functionality of Validator.js.

    Input sanitization using Express-validator:

    A POST request can be sent to the /comment route, as shown below:

    The response to the above request :

    The sanitized text is : &lt;script&gt;alert(1337);&lt;&#x2F;script&gt;

FAQs

Q: How widespread are XSS vulnerabilities?

A: XSS vulnerabilities are perhaps the most frequent web security flaws, and they are quite prevalent.

Q: How frequent are XSS attacks?

A: Real-world XSS assaults are hard to accurately measure, but they presumably happen less frequently than other vulnerabilities.

Q: What distinguishes XSS and CSRF from one another?

A: In contrast to CSRF, which involves tricking a vulnerable user into taking actions they did not plan to take, XSS involves getting a website to return harmful JavaScript.

Q: What differentiates SQL injection from XSS?

A: Whereas SQL injection is a server-side vulnerability that targets the application's database, XSS is a client-side vulnerability that targets other application users.

Conclusion

  • Malicious Scripts are injected into websites that are normally safe and reputable in Cross-Site Scripting (XSS) attacks.
  • Cross-Site Scripting happens when dynamically generated web pages show user input that hasn't been properly validated, like login information.
  • Cross-site scripting attacks may have the following effects:
    • Recording a user's keystrokes.
    • Redirecting a visitor to a harmful website.
    • Utilising web browser exploits
  • XSS attacks can be categorised into three groups based on where an attacker places an injection for execution: reflected (nonpersistent), stored (persistent), and DOM-based XSS attacks.
  • To check the vulnerability of a website or application, we can use web scanning tools.