User controllable tag parameter (DOM-based)
Description
This vulnerability occurs when user-controlled input is used to set attributes of sensitive HTML tags (such as the href attribute of or tags) without proper validation or sanitization. The manipulation happens in the DOM (Document Object Model) through client-side JavaScript, allowing attackers to inject malicious values that can alter page behavior or execute unauthorized scripts.
Remediation
Implement strict input validation and output encoding for all user-controlled data before using it to set HTML tag attributes. Follow these steps:
1. Validate Input: Use allowlists to restrict input to expected values and formats. Reject any input that doesn't match the expected pattern.
2. Sanitize Output: Use context-appropriate encoding when inserting user data into the DOM. For URLs, use URL encoding and validate that the protocol is safe (http/https only).
3. Use Security Libraries: Leverage established sanitization libraries such as DOMPurify for JavaScript or built-in framework sanitizers.
Example of safe URL handling:
// Unsafe - directly using user input
const userInput = getUrlParameter('redirect');
element.href = userInput; // Vulnerable!
// Safe - validate and sanitize
function isSafeUrl(url) {
try {
const parsed = new URL(url, window.location.origin);
return ['http:', 'https:'].includes(parsed.protocol);
} catch (e) {
return false;
}
}
const userInput = getUrlParameter('redirect');
if (isSafeUrl(userInput)) {
element.href = userInput;
} else {
element.href = '/default-page'; // Safe fallback
}
4. Implement Content Security Policy (CSP): Deploy CSP headers to provide an additional layer of defense against XSS attacks.