JavaScript Protocol Urls

ID

html.javascript_protocol_urls

Severity

high

Resource

Injection

Language

Html

Tags

CWE:83, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.7

Description

This rule identifies the use of the javascript: URI scheme (including encoded variants) in HTML attributes that expect URLs. Such usage can lead to arbitrary JavaScript execution and cross-site scripting (XSS) vulnerabilities.

Rationale

The javascript: URI scheme allows inline execution of JavaScript code when used in attributes such as href, src, or action. If user-controlled input is injected into these attributes, attackers can execute arbitrary scripts in the victim’s browser.

This risk is amplified when applications rely on weak validation that fails to detect encoded variants such as javascript: or mixed-case representations. Exploiting this weakness can result in session hijacking, credential theft, or complete client-side compromise.

Consider the following example:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript URI Example</title>
</head>
<body>
    <a href="javascript:alert('XSS')">Click me</a> <!-- FLAW -->
</body>
</html>

In this code snippet, clicking the link causes the browser to execute arbitrary JavaScript code.

Encoded variants are equally dangerous:

<a href="jav&#x61;script:alert('XSS')">Click me</a> <!-- FLAW -->

Remediation

To mitigate this vulnerability, applications should never use the javascript: URI scheme in HTML attributes. Instead:

  • Use event listeners for client-side interactivity

  • Enforce strict server-side validation of URL schemes

  • Whitelist only trusted schemes such as http, https, and mailto

  • Decode HTML entities before validating URLs

Here is a secure alternative using an event listener:

<!DOCTYPE html>
<html>
<head>
    <title>Safe Interaction Example</title>
</head>
<body>
    <a href="#" id="safeLink">Click me</a>

    <script>
        document.getElementById('safeLink').addEventListener('click', function (e) {
            e.preventDefault();
            alert('Safe interaction');
        });
    </script>
</body>
</html>

By separating behavior from markup and enforcing strict URL validation, applications can prevent arbitrary code execution via malicious URI schemes.

References