XSS for Web Developer

Introduction

Recently, I found my knowledge in cybersecurity lacking. As a front-end engineer, security is usually not a primary focus, but when vulnerabilities exist, the consequences can be serious. Therefore, I have been trying to fill in my knowledge in this area.

What is XSS

XSS (Cross-Site Scripting) means attackers inject malicious scripts through vulnerabilities for the target website to execute. Specific malicious scripts can do things including but not limited to: getting sensitive information, modifying webpage content, redirecting to malicious sites, etc. In general, there are several types of vulnerabilities, all aiming to find ways to make the target website execute malicious scripts to control the site.

Reflected XSS

This mainly relies on users sending malicious request codes, for example, embedding malicious scripts in the URL. When users click the link, an unprotected website will execute the malicious script. For instance, the following URL will execute the malicious script: alert(1):

http://www.example.com/upload.asp?id=<script>alert(1);</script>

In this case, the malicious script is not stored in the database; as long as the backend not validate input and executes the request code, the vulnerability will occur. This type of attack often hides its intent through shortened URLs, tricking unsuspecting users into embedding malicious scripts into the website.

Stored XSS

Similar to reflected XSS, but it stores malicious scripts in the website’s database through vulnerabilities. The most common scenario is in customizable content like message boards or articles, where other users visiting the site will also execute the malicious scripts.

DOM-based XSS

This involves inserting malicious scripts into the webpage through the DOM. The most common reason is using innerHTML to directly treat any string as HTML and insert it into the DOM for execution. It can also be combined with the previous two methods to insert malicious scripts into the webpage through DOM manipulation.

Preventing XSS

  • The most direct way to prevent XSS is to “never trust any user input as safe to execute.” Treat any user input as unsafe by default, and only consider it safe for execution after sanitization (converting it to a non-threatening string).
  • CSP (Content Security Policy): Use CSP settings to restrict which scripts can be executed on the webpage.
  • HttpOnly: Set the HttpOnly attribute to prevent JavaScript from accessing cookies.
  • SameSite: Set the SameSite attribute to restrict third-party cookie access.

Conclusion

With modern comprehensive tools and documentation, the likelihood of inadvertently executing malicious scripts provided by users has significantly decreased. Never easily trust user input to prevent XSS to the greatest extent.

Further Reading