🚀 Cyber Security New Batch Start from 1 JunEnroll Now
Cyber Defence
Ethical Hacking

Cross-Site Scripting (XSS): A Complete Attack and Defense Guide

Complete XSS attack guide covering stored, reflected, and DOM-based XSS. Learn exploitation techniques, cookie stealing, bypass methods, and comprehensive prevention strategies.

Amit Kumar
Amit KumarEthical Hacker & Founder
5 min read
# Cross-Site Scripting (XSS): A Complete Attack and Defense Guide ## Introduction to XSS Cross-Site Scripting (XSS) is a client-side code injection attack where attackers inject malicious scripts into trusted websites. When successful, XSS allows attackers to execute arbitrary JavaScript in the victim browser, potentially compromising accounts, stealing data, or performing actions on behalf of users. XSS vulnerabilities occur when web applications include untrusted data in web pages without proper validation or escaping. Attackers use various techniques to inject malicious scripts that appear legitimate to the browser. ## Types of XSS Attacks ### Reflected XSS (Non-Persistent) The malicious script comes from the current HTTP request. The vulnerable application includes unvalidated input from requests in immediate responses. Example: https://target.com/search?q= where the server reflects the script without sanitization and the browser executes it when the page loads. ### Stored XSS (Persistent) The malicious script is stored on the server (database, message forum, comment field). Every user accessing the affected page executes the script. Example: User submits comment with script content like . The server stores the script in database and every user viewing this comment executes the script. ### DOM-Based XSS The vulnerability exists in client-side code rather than server-side code. The attack payload is executed by modifying the DOM environment in the victim browser. Example: Vulnerable JavaScript like document.write(document.URL.substring(position, document.URL.length)) when manipulated with URL fragment like https://target.com/page.html?item= causes the browser to write the script to the page. ## XSS Attack Consequences ### Session Hijacking Steal session cookies with script that captures document.cookie and sends it to attacker server. ### Credential Theft Inject fake login forms that appear as legitimate session expiry prompts to capture usernames and passwords. ### Keylogging Capture all keystrokes using document.addEventListener('keypress') to record user input. ### Defacement Modify page content and styles using document.body.innerHTML or document.body.style properties. ## Practical XSS Exploitation ### Finding XSS Vulnerabilities Test all input points systematically with basic test payloads like , , and . ### Stored XSS Attack (DVWA Walkthrough) Lab Setup involves navigating to DVWA XSS (Stored), setting security level to Low, and accessing the message board. Attack Steps include entering normal text to understand application flow, injecting basic XSS payload in the message field like , submitting and observing alert popup on page load, and injecting cookie-stealing payload. Set up attacker server to capture cookies using Python Flask with endpoint that logs stolen cookies. ### Reflected XSS Attack Find parameters reflected in the response by testing URL parameters like /search?q=test and injecting payload in each parameter. ### DOM-Based XSS Attack Analyze client-side JavaScript for DOM manipulation patterns like document.write(), element.innerHTML, and location.href parsed without encoding. ## XSS Bypass Techniques ### Filter Bypass Methods Case variation with and HTML tag breaking with ipt>alert('XSS')ipt>. Encoded payloads using URL encoding like %3Cscript%3Ealert('XSS')%3C/script%3E, HTML entity encoding like <script>alert('XSS')</script>, and hex encoding like <script>alert('XSS')</script>. Event handler variants including , , and 4. Test encoding bypasses with URL encoding and HTML entities 5. Test attribute context with " onmouseover=alert(1) x=" 6. Test JavaScript context with ';alert(1);// 7. Verify persistence for stored XSS ### Automated Scanning Use Burp Suite professional scanner, OWASP ZAP with zap-cli quick-scan, or SQLMap for XSS detection in parameters. ## XSS in Different Contexts ### XSS in JavaScript Variables Vulnerable code like var user = "<%= request.getParameter("name") %>" with attack payload like ?name=";alert('XSS');//. ### XSS in HTML Attributes Vulnerable code like with attack payload like " onfocus="alert('XSS')" x=". ### XSS in URL Parameters Vulnerable code like var page = location.hash.substring(1); document.write(page) with attack URL fragment like #. ## Frequently Asked Questions ### What is the difference between reflected and stored XSS? Reflected XSS requires the victim to click a malicious link; stored XSS persists on the server and executes whenever affected pages load. ### Can XSS be used to execute system commands? XSS executes in the browser context and cannot directly access the server file system. However, it can perform actions as the logged-in user, potentially including admin functions. ### How does CSP prevent XSS? CSP restricts which sources JavaScript can be loaded from and can block inline script execution, preventing injected scripts from running. ### Is XSS dangerous if users have JavaScript disabled? While disabling JavaScript reduces XSS risk, modern web applications depend on JavaScript, making this an impractical defense. Proper input validation and output encoding are essential. ## Conclusion Cross-Site Scripting remains one of the most prevalent and dangerous web application vulnerabilities. Understanding XSS attack vectors is crucial for both security professionals and developers. Key takeaways include sanitizing all user input with strict validation, encoding all output to prevent script injection, implementing Content Security Policy as additional defense, using HttpOnly and Secure flags for sensitive cookies, and regularly testing applications for XSS vulnerabilities. Cyber Defence offers comprehensive web application security training covering XSS and other critical vulnerabilities. Our hands-on courses include practical labs for both attack and defense techniques. Master XSS testing and prevention. Protect your applications and users from client-side code injection attacks.

Talk to a Cyber Defence Expert

Get a free consultation on cybersecurity, training and certifications. Our team responds within 10 minutes during business hours.