How XSS attacks work and mitigation techniques like input validation and output encoding.
Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy. XSS attacks occur when an application includes untrusted data in a new web page without proper validation or encoding. There are three main types: 1. Stored XSS: The malicious script is permanently stored on the target server, such as in a database, in a message forum, a visitor log, a comment field, etc. The victim retrieves the malicious script from the server when it requests the stored information. For example, an attacker posts a comment on a blog that contains a malicious script. Every user who views that blog post will have the script executed in their browser. 2. Reflected XSS: The malicious script is reflected off of a web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. The script is embedded in a URL and is activated when the victim clicks the link. 3. DOM-based XSS: The vulnerability is in the client-side code rather than the server-side code. The attack payload is executed as a result of modifying the DOM 'environment' in the victim’s browser. The primary defense against XSS is to sanitize user input and encode output. All data received from a user should be treated as untrusted and validated against a strict set of rules. When displaying user-provided data back on a page, it should be HTML-encoded to ensure the browser treats it as text, not as executable code.