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.
The attacker injects malicious scripts into application's DB. These scripts are then retrieved and displayed to other users who visit the page.
1const comment = "<script>alert('XSS attack!');</script>";
2saveCommentToDatabase(comment);
script injection
1//comment section
2<div>
3 <script>
4 alert('XSS attack!');
5 </script>
6</div>
rendering page
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.
1http://example.com/path?name=</div><script>alert('XSS')</script><div>
malicious URL
When user click the link above, the server will serve html that contain malicious script.
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.
1http://example.com/path#<script>alert('XSS')</script>
malicious URL
Validate and sanitize all user input on the server side using library or frameworks like 'sanitize-html' before processing or display it.
Encode all user-controlled data before it rendered in the browser to prevent malicious script execution.
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.
Be cautious when dynamically updating the DOM with untrusted data. Avoid using 'innerHTML'(use innerText) and 'eval' functions with user-generated content.