You are on page 1of 9

How to Prevent Cross-Site Scripting (XSS) in JavaScript

by Nduka John  October 13, 2023 Web 0 Comments

In cross-site scripting (XSS) attacks, malicious code on a


webpage can jeopardize sensitive user information. Learn how to
  prevent this vulnerability in your JavaScript app.

What is Cross-Site Scripting?


 
Cross-site scripting (XSS) is a type of security vulnerability that
allows an attacker to inject malicious code into a webpage
viewed by other users. The attacker can use this vulnerability to

steal sensitive information from the user, such as login
credentials or credit card numbers.

There are three types of cross-site scripting attacks:

Reflected XSS: In this type of attack, the attacker injects


malicious code into a webpage that is immediately returned to
the user’s browser. This can happen when the user submits a
form that is vulnerable to XSS. Let’s say there is a web
application that allows users to search for products on an
ecommerce site. The search functionality is implemented using
a URL parameter, like so:

https://www.example.com/search?q=<search_term>
We use cookies to personalize content and
ads, to provide social media features and to
analyze our traffic. Some of these When
cookiesa user enters a search term and submits the form, the
also help improve your user experience
searchon term is included in the URL as a parameter. The server
our websites, assist with navigation and your
then processes the search request and returns the search
ability to provide feedback, and assist with ACCEPT COOKIES COOKIES SETTINGS
results in the response.
our promotional and marketing efforts.
Please read our Cookie Policy for a more
detailed description and click on the settings
Now, imagine an attacker creates a malicious link that includes a
button to customize how the site uses
script tag in the search term parameter:
cookies for you.
https://www.example.com/search?q=<script>alert('XSS attack!')</script>

If a user clicks on this link, their browser will send a request to


the server with the malicious search term in the URL parameter.
The server will then include the search term in the response,
which will contain the script tag. The user’s browser will interpret
the script tag and execute the JavaScript code, which in this
case will display an alert box with the message “XSS attack!”

Stored XSS: In this type of attack, the attacker injects malicious


code into a webpage that is stored on the server and served to
all users who view that page.

Let’s say there is a social media website that allows users to


post comments on other users’ profiles. The comments are
stored in a database and displayed on the profile page. The
website does not properly sanitize user input and allows users to
post comments containing HTML and JavaScript code.

An attacker creates a malicious comment that includes a script


tag, like so:

<script>alert('Stored XSS attack!')</script>

When the attacker posts this comment on a victim’s profile, it is


stored in the database. The next time the victim views their
profile, the malicious comment is displayed on the page and the
victim’s browser executes the script tag, displaying an alert box
with the message “Stored XSS attack!”

Unlike a reflected XSS attack, the malicious code is not included


in the URL parameter and is not dependent on the victim clicking
on a malicious link. Instead, the code is stored on the server and
is executed every time the victim views their profile, potentially
allowing the attacker to steal sensitive information or perform
unauthorized actions on behalf of the victim without their
knowledge.

We use cookies to personalize content and


DOM-based
ads, to provide social media features and to XSS: In this type of attack, the attacker injects
analyze our traffic. Some of these malicious
cookies code into a webpage that is executed by the user’s
browser,
also help improve your user experience on usually through JavaScript.Let’s say there is a webpage
that
our websites, assist with navigation andcontains
your a search box, and the search results are displayed
ability to provide feedback, and assist with
dynamically using JavaScript. The JavaScript code that handles
our promotional and marketing efforts.
the search functionality contains a vulnerability that allows an
Please read our Cookie Policy for aattacker
more to inject malicious code into the DOM.
detailed description and click on the settings
button to customize how the site uses
cookies for you. For example, consider the following search box:
<input type="text" id="searchBox">
<button onclick="search()">Search</button>
<div id="results"></div>

And the following JavaScript code that handles the search


functionality:

function search() {
var query = document.getElementById("searchBox").value;
var resultsDiv=cument.getElementById("results");
resultsDiv.innerHTML = "Search results for:" + query;
}

The vulnerability here is that the search term entered by the user
is directly added to the DOM using the innerHTML property,
without being properly sanitized or encoded.

An attacker can exploit this vulnerability by entering a search


term that contains malicious JavaScript code, such as:

<script>alert('DOM-based XSS attack!')</script>

If the user enters this search term and clicks the search button,
the attacker’s code will be executed by the victim’s browser,
displaying an alert box with the message “DOM-based XSS
attack!”

Preventing Cross-Site Scripting in JavaScript

Sanitize User Input

The first step in preventing XSS is to sanitize all user input


before it is displayed on the webpage. This can be done using a
variety
We use cookies to personalize content andof techniques, including input validation and output
encoding.
ads, to provide social media features and to
analyze our traffic. Some of these cookies
also help improve your user experience on
Input
our websites, assist with navigation and validation
your involves checking user input to check that it
meets
ability to provide feedback, and assist withcertain criteria. For example, if you are expecting a user to
our promotional and marketing efforts. an email address, you can check that the input contains
enter
Please read our Cookie Policy for athe “@” symbol and a domain name. If the input does not meet
more
these
detailed description and click on the criteria, it should be rejected.
settings
button to customize how the site uses
cookies for you.
Output encoding involves encoding user input so that it is not
interpreted as HTML or JavaScript code. This can be done using
a variety of techniques, including HTML escaping and JavaScript
encoding.

Here is an example of HTML escaping in JavaScript:

function escapeHTML(str) {
return str.replace(/[&<>"'\/]/g, function (char) (
switch (char) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
case '\':
return '&#39;';
case '/':
return '&#x2F;';
default:
return char;
}
});
}

This function takes a string as input and replaces any characters


that have special meaning in HTML (such as < and > ) with
their corresponding HTML entities.

Use a Content Security Policy

A Content Security Policy (CSP) is a security feature that allows


you to specify which sources of content are allowed to be loaded
on your webpage. This can help prevent XSS attacks by
preventing malicious code from being loaded from untrusted
sources.
We use cookies to personalize content and
Here
ads, to provide social media features andistoan example of how to use CSP in JavaScript:
analyze our traffic. Some of these cookies
also help improve your user experience on
our websites, assist with navigation and your
ability to provide feedback, and assist// with
Set the Content Security Policy header
our promotional and marketing efforts.app.use(function (req, res, next) {
Please read our Cookie Policy for a moreres.setHeader('Content-Security-Policy, "default-src 'self' ");
next();
detailed description and click on the settings
button to customize how the site uses });
cookies for you.
// Load scripts only from trusted sources
<script src="[https://trusted-site.com/script.js](https://trusted-site.com/script.j

This code sets the Content-Security-Policy header to only allow


content from the same domain as the webpage. It also specifies
that scripts can only be loaded from a trusted source.

Another example is a CSP with an HTTP header:

Content-Security-Policy: default-src 'self'

This header specifies that only content from the same origin as
the page is allowed to be loaded.

Use Input Validation

The most effective way to prevent cross-site scripting is to


validate all user input before it is displayed on a page. This can
be achieved using regular expressions or other validation
techniques to check that the input only contains allowed
characters and is not malicious. For example, to validate a user’s
email address, you can use the following regular expression:

function validateEmail (email) {


const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return pattern.test(email);
}

This function uses a regular expression to validate that the email


address contains only valid characters and follows the standard
email address format.

Encode User Input

Another way to prevent cross-site scripting is to encode all user


input before it is displayed on a page. Encoding involves
We use cookies to personalize content and
converting special characters into their corresponding HTML
ads, to provide social media features and to
analyze our traffic. Some of these entities,
cookies which are not executable by a web browser. For
example,
also help improve your user experience on to encode a user’s input, you can use the following
function:
our websites, assist with navigation and your
ability to provide feedback, and assist with
our promotional and marketing efforts.
Please read our Cookie Policy for a more
function encodeInput (input) {
detailed description and click on the settings
const encoded = document.createElement('div');
button to customize how the site uses
encoded.innerText = input;
cookies for you.
return encoded.innerHTML;
}

This function creates a new div element and sets its inner text to
the user input. The inner HTML of the div element is then
returned, which contains the encoded input.

Using HTTP-Only Cookies

HTTP-only cookies are cookies that can only be accessed by the


web server, not by client-side JavaScript code. This prevents
attackers from stealing sensitive information, such as login
credentials, by injecting malicious code into your webpages.

Here is an example of using HTTP-only cookies in JavaScript:

document.cookie = "sessionID=12345; HttpOnly";

This code sets a cookie named “sessionID” with a value of


“12345” and sets the HttpOnly flag to true. This makes it so that
the cookie can only be accessed by the web server and not by
client-side JavaScript code.

Conclusion

In conclusion, cross-site scripting (XSS) is a serious security


vulnerability that allows attackers to inject malicious code into
webpages that can steal sensitive information or perform
unauthorized actions on behalf of the victim. There are three
types of XSS attacks: Reflected XSS, Stored XSS and DOM-based
XSS.

To prevent XSS attacks, it is crucial to sanitize all user input


before it is displayed on a webpage using techniques like input
validation and output encoding. It is also essential to use a
Content Security Policy (CSP) and input validation to help
establish that only trusted sources and allowed characters are
loaded on a webpage. By implementing these measures,
developers can significantly reduce the risk of XSS attacks and
We use cookies to personalize content andtheir users’ sensitive information.
protect
ads, to provide social media features and to
analyze our traffic. Some of these cookies
also help improve your user experience on
How
our websites, assist with navigation to Secure Your Angular App
and your
ability to provide feedback, and assist with
Take a look at the types of security attacks to watch out for with
our promotional and marketing efforts.
your Angular app, including XSS and CSRF, and what you can do
Please read our Cookie Policy for a more
to secure it.
detailed description and click on the settings
button to customize how the site uses
cookies for you.
 JavaScript
ABOUT THE AUTHOR
Nduka John
Nduka John is a cyberthreat intelligence analyst and a technical writer for SaaS
brands. His publications give clear insight on how to stay proactive towards
cyberthreats through healthy cybersecurity practices.

RELATED POSTS

PRODUCTIVITY DEBUGGING

How to Effectively Debug Three Common Website Issues


Using a Web Debugging Proxy Tool

WEB

On Cross-Site Scripting and Content Security Policy

WEB ANGULAR

How to Secure Your Angular App


We use cookies to personalize content and
ads, to provide social media features and to
analyze our traffic. Some of these cookies
also help improve your user experience on
our websites, assist with navigation and your
ability to provide feedback, and assist with
our promotional and marketing efforts.
Please read our Cookie Policy for a more
COMMENTS
detailed description and click on the settings
button to customize how the site uses
cookies for you.
All articles

TOPICS

Web 
Mobile 

Desktop 
Design 
Productivity 

People 
Release

search blogs...

We use cookies to personalize content and


Latest Stories
ads, to provide social media features and to
in Your
analyze our traffic. Some ofInbox
these cookies
also help improvetoyour
Subscribe be user experience
the first to get on
our expert-written articles and tutorials for developers!
our websites, assist with navigation and your
abilityAlltofields arefeedback,
provide required and assist with
our promotional and marketing efforts.
PleaseEmailread *our Cookie Policy for a more
detailed description and click on the settings
button to customize how the site uses
cookies for you.
Country/Territory *
Select country/territory

Subscribe

Telerik and Kendo UI are part of Progress


product portfolio. Progress is the leading
provider of application development and
digital experience technologies.

Company Technology Awards Press Releases Media Coverage Careers


Offices

Copyright © 2024 Progress Software Corporation and/or its subsidiaries or affiliates. All
Rights Reserved.
Progress, Telerik, Ipswitch, Chef, Kemp, Flowmon, MarkLogic, Semaphore and certain product
names used herein are trademarks or registered trademarks of Progress Software
Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See
Trademarks for appropriate markings.

We use cookies to personalize content and


ads, to provide social media features and to
analyze our traffic. Some of these cookies
also help improve your user experience on
our websites, assist with navigation and your
ability to provide feedback, and assist with
our promotional and marketing efforts.
Please read our Cookie Policy for a more
detailed description and click on the settings
button to customize how the site uses
cookies for you.

You might also like