Cross Site Scripting
Cross Site Scripting
Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications.
It allows attackers to inject malicious scripts into web pages viewed by other users. XSS can be
categorized into three main types: Stored XSS, Reflected XSS, and DOM-based XSS.
1. Stored XSS
In a Stored XSS attack, the malicious script is permanently stored on the target server, such as in
a database, comment field, or log. When a victim loads the affected page, the script is executed
in their browser.
Example:
html
Copy code
<script>alert('XSS Attack');</script>
Outcome: Whenever any user views the comment section, the script executes, causing an
alert box to pop up in the user’s browser. More dangerous scripts could steal cookies,
session tokens, or redirect users to malicious websites.
2. Reflected XSS
In Reflected XSS, the malicious script is reflected off a web server, typically in the form of a
search result or error message. The script is part of the URL and is executed when the URL is
visited.
Example:
html
Copy code
http://example.com/search?q=<script>alert('XSS');</script>
Outcome: When a user clicks on the crafted link, the script executes in the context of the
user's session with the website.
3. DOM-based XSS
DOM-based XSS occurs when the vulnerability is in the client-side code rather than the server-
side code. The script modifies the DOM environment in the victim’s browser, causing the
execution of malicious code.
Example:
Scenario: A web page that processes URL parameters to dynamically display content.
Attack: The attacker sends a URL to the victim:
html
Copy code
http://example.com/page?param=<script>alert('XSS');</script>
Outcome: The script directly interacts with the page's DOM and executes in the victim's
browser.
html
Copy code
<script>alert('TweetDeck XSS');</script>
Outcome: The script executed for users who viewed the tweet in TweetDeck, displaying
an alert box. Fortunately, this was a benign demonstration, but a more malicious script
could have taken control of users' accounts.
1. Input Validation: Sanitize and validate all user inputs to ensure they do not contain
malicious scripts.
2. Output Encoding: Properly encode all data before rendering it in the browser,
particularly when inserting it into HTML, JavaScript, or CSS contexts.
3. Content Security Policy (CSP): Implement CSP to restrict the sources from which
scripts can be executed.
4. HttpOnly Cookies: Use HttpOnly flag for cookies to prevent access via JavaScript.
Sources