TYPeee

Understanding Cross-site Scripting (XSS) and Ways to prevent

What is XSS attack?

The xss occurs when an attacker is  able to inject malicious scripts into web pages viewed by users. these malicious sciprts are then executed in the context of the user's browser, allowing the attacker to perform malicious actions, steal sensitive information, or deface websites.

 

Types of XSS attacks

1. Stored XSS

The attacker injects malicious scripts into  application's DB. These scripts are then  retrieved and displayed  to other users who visit the page.

Script injection
1const comment = "<script>alert('XSS attack!');</script>"; 
2saveCommentToDatabase(comment);
Rendering page
1//comment section
2<div>
3  <script>
4    alert('XSS attack!');
5  </script>
6</div>

 

2. Reflected XSS

The malicious script is  reflected off  the web server, such as in an  error message  or  search result. Attacker typically tricks the user into clicking on a specially  manipulated link  that contains the malicious script.

Malicious URL
1http://example.com/path?name=</div><script>alert('XSS')</script><div>

When user click the link above, the server will serve html that contain malicious script.

 

3. DOM based XSS

Unlike previous cases, DOM based XSS execute malicious script as a result of  modifying the DOM environment  in the browser used by the client side. The difference between Reflected XSS is that the Reflected XSS create and return a content that malicious script is included in the server.

Malicious URL
1http://example.com/path#<script>alert('XSS')</script>

 

How can i prevent XSS?

1. Sanitization

Validate and sanitize all user input on the server side using library or frameworks like 'sanitize-html' before processing or display it.

 

2. Encoding

Encode all user-controlled data before it rendered in the browser to prevent malicious script execution.

 

3. Content Security Policy(CSP)

Utilize CSP to restrict the sources from which scripts can be loaded, thereby preventing the execution of unauthorized scripts even if they ar injected into the page.

 

4. Secure Javascript Development

Be cautious when dynamically updating the DOM with untrusted data. Avoid using 'innerHTML'(use innerText) and 'eval' functions with user-generated content.

 

Related Posts