Cross-Site Scripting (XSS) attacks occur when an attacker injects malicious scripts (e.g., JavaScript) into a web application, which are then executed in a victim’s browser. Effective input validation is a key defense against XSS by ensuring that user input does not contain malicious content.
Option A ("Blacklisting HTML and other harmful characters"): Blacklisting involves blocking known harmful characters (e.g., <, >, &) or patterns. While this can mitigate some XSS attacks, it is not the most effective approach because blacklists can be bypassed (e.g., using alternate encodings, nested tags, or new attack vectors). Blacklisting is inherently reactive and prone to evasion.
Option B ("Whitelisting and allowing only trusted input"): Whitelisting involves defining a strict set of allowed characters or patterns (e.g., only alphanumeric characters for a username). This is the most effective method because it explicitly permits only safe input and rejects everything else, making it much harder for attackers to inject malicious scripts. For example, if a field expects a phone number, a whitelist might allow only digits, spaces, and dashes, rejecting any HTML or script tags outright.
Option C ("Using a Web Application Firewall (WAF)"): A WAF can help detect and block XSS attacks by filtering malicious requests, but it is not an input validation method. WAFs are a secondary defense and can be bypassed; they are not a substitute for proper validation at the application level.
Option D ("Marking Cookie as HttpOnly"): The HttpOnly flag prevents cookies from being accessed by JavaScript, mitigating the impact of XSS (e.g., stealing session cookies), but it does not prevent the XSS attack itself. It addresses the consequence, not the root cause, and is not an input validation technique.
The correct answer is B, aligning with the CAP syllabus under "Cross-Site Scripting (XSS)" and "Input Validation Best Practices."References: SecOps Group CAP Documents - "XSS Prevention," "Input Validation and Sanitization," and "OWASP XSS Prevention Cheat Sheet" sections.