OWASP Java Encoder

repository·main·Indexed 19 days ago

https://github.com/owasp/owasp-java-encoder

A high-performance, low-overhead Java library for contextual output encoding to prevent Cross-Site Scripting (XSS) attacks. It provides encoding for various contexts including HTML, JavaScript, CSS, XML, and URIs via the org.owasp.encoder.Encode class. The library supports Java 1.8+, the Java Module System (JPMS), and provides specific integration modules for Jakarta and legacy JSP Servlet specifications.

Tokens
4.3K
Snippets
15
Records
21
Agent score
67%

What's inside OWASP Java Encoder

  1. Install the OWASP Java Encoder via Maven

    main

    To use the core encoding functionality in your Java project, add the encoder dependency to your pom.xml. This library requires Java 1.8 or higher.

    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder</artifactId>
        <version>1.4.0</version>
    </dependency>
  2. Use the Encode API for contextual encoding

    main

    The core functionality is accessed through the org.owasp.encoder.Encode class. Use its static methods to perform contextual encoding, which helps prevent Cross-Site Scripting (XSS) vulnerabilities. For example, use Encode.forHtml(string) when inserting data into an HTML body or element content.

    import org.owasp.encoder.Encode;
    
    //...
    
    PrintWriter out = ....;
    // Encodes userData for safe inclusion in an HTML context
    out.println("<textarea>" + Encode.forHtml(userData) + "</textarea>");
  3. Use the OWASP Java Encoder in JSP

    main

    To prevent Cross-Site Scripting (XSS) in JSP applications, you can use the encoder-jsp library. This library provides a Tag Library Descriptor (TLD) that includes custom tags and JSP Expression Language (EL) functions for contextual encoding.

    1. Add the dependency

    Include the encoder-jsp artifact in your project's dependency management system (e.g., Maven):

    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jsp</artifactId>
        <version>1.2.3</version>
    </dependency>

    2. Configure the JSP page

    At the top of your JSP file, declare the tag library using the following URI:

    <%@taglib prefix="e" uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project" %>

    3. Encode data

    You can encode dynamic data using either JSP EL functions or custom tags:

    • Via EL functions: Use the syntax ${e:functionName(value)}.
    • Via tags: Use the syntax <e:functionName value="..." />.

    Example usage for HTML encoding:

    <p>Dynamic data via EL: ${e:forHtml(param.value)}</p>
    <p>Dynamic data via tag: <e:forHtml value="${param.value}" /></p>
    <%@taglib prefix="e" uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project" %>
    
    <%-- ... --%>
    
    <p>Dynamic data via EL: ${e:forHtml(param.value)}</p>
    <p>Dynamic data via tag: <e:forHtml value="${param.value}" /></p>
  4. Install and use the JSP Encoder

    main

    For JSP-based applications, you can use the encoder-jsp artifact which provides Tag Library Descriptor (TLD) tags and JSP Expression Language (EL) functions for easier integration.

    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jsp</artifactId>
        <version>1.2.3</version>
    </dependency>
  5. Install JSP integration for Jakarta or Legacy Servlet Specs

    main

    If you are using JSP, you should use the specific integration module corresponding to your Servlet specification to access JSP tags and EL functions.

    For Servlet Spec 5 (using jakarta.servlet package):

    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jakarta-jsp</artifactId>
        <version>1.4.0</version>
    </dependency>

    For Legacy Servlet Spec (using javax.servlet package):

    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jsp</artifactId>
        <version>1.4.0</version>
    </dependency>
    <!-- using Servlet Spec 5 in the jakarta.servlet package use: -->
    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jakarta-jsp</artifactId>
        <version>1.4.0</version>
    </dependency>
    
    <!-- using the Legacy Servlet Spec in the javax.servlet package use: -->
    <dependency>
        <groupId>org.owasp.encoder</groupId>
        <artifactId>encoder-jsp</artifactId>
        <version>1.4.0</version>
    </dependency>
  6. Use JavaScriptEncoder with ASCII-only restriction

    main

    When initializing a JavaScriptEncoder, you can specify whether the output should be restricted to ASCII characters.

    If asciiOnly is set to true, all code-points outside the ASCII range will be encoded (using \uXXXX format), even if they are otherwise considered valid characters. This is useful for environments with strict character encoding requirements.

    // Constructor signature
    JavaScriptEncoder(Mode mode, boolean asciiOnly)
  7. Encode unquoted HTML attribute values

    main
    The HTMLEncoder is specifically designed to handle the HTML context of unquoted attribute values. While most HTML contexts are covered by XMLEncoder, unquoted attributes require a specific encoding strategy to prevent injection attacks. Use this encoder when you are placing data into an HTML attribute that is not enclosed in quotes (e.g., <div attr=DATA_HERE>).
  8. Encode for XML/HTML comment context

    main

    Use the XMLCommentEncoder to safely encode data intended for use within XML or HTML comment sections (e.g., <!-- data -->).

    This encoder prevents common injection vulnerabilities by:

    1. Handling Hyphens: The sequence -- is forbidden in XML comments. The encoder replaces the second hyphen in a -- sequence with a ~ (the HYPHEN_REPLACEMENT character). It also handles trailing hyphens at the end of input to prevent them from combining with the comment terminator --> to form an invalid ---> sequence.
    2. Filtering Invalid Characters: It replaces invalid XML characters and non-characters with the XMLEncoder.INVALID_CHARACTER_REPLACEMENT character.
    3. Surrogate Pair Validation: It ensures that high and low surrogate pairs are valid and not non-characters.
  9. Configure URI encoding modes

    main

    The URIEncoder uses different Mode settings to determine which characters are escaped during URI encoding. This allows you to choose between encoding only specific components or encoding a full URI.

    • COMPONENT: Only RFC 3986 unreserved characters are left unescaped. Everything else (including reserved characters like :, /, ?, etc.) is percent-encoded. Use this when encoding a single part of a URI, such as a query parameter value.
    • FULL_URI: Both unreserved and reserved characters are left unescaped. Use this when you want to encode a complete URI string while preserving its structural delimiters.
    public enum Mode {
        COMPONENT,
        FULL_URI
    }
  10. Configure JavaScriptEncoder modes

    main

    The JavaScriptEncoder supports four distinct modes of operation depending on where the encoded string will be placed in your web application. Choosing the correct mode is critical for preventing Cross-Site Scripting (XSS) attacks in specific contexts.

    • SOURCE: Standard encoding for JavaScript strings. Uses the shortest possible escape sequences.
    • ATTRIBUTE: For use within HTML attributes (e.g., onclick='...'). It uses hex encoding (\x22, \x27) for quotes instead of backslashes to ensure compatibility with XML-based attributes.
    • BLOCK: For use inside HTML <script> blocks. It specifically escapes / as \/ and - as \- to prevent premature termination of the script block (e.g., by </script> or <!--).
    • HTML: A hybrid mode for use in either HTML script attributes or blocks. It combines special escapes from both ATTRIBUTE and BLOCK modes.
    /**
     * Mode of operation constants for the JavaScriptEncoder.
     */
    enum Mode {
        SOURCE,
        ATTRIBUTE,
        BLOCK,
        HTML
    }
  11. Configure XMLEncoder modes and versions

    main

    The XMLEncoder class provides different encoding strategies depending on whether you are encoding XML content or attribute values, and which XML version you are targeting.

    XML Versions

    • XML_1_0: Control characters (except tab, LF, CR) are replaced with a space (U+0020).
    • XML_1_1: Control characters (except tab, LF, CR) are encoded as character references (e.g., &#x01;).

    Encoding Modes

    Select a mode based on the context where the encoded string will be placed:

    • ALL: Encodes &, <, >, ', and ". Safe for both content and attributes.
    • CONTENT: Encodes &, <, and >. Use this for XML text nodes (CharData).
    • ATTRIBUTE: Encodes &, <, ', and ". Use this for attribute values.
    • SINGLE_QUOTED_ATTRIBUTE: Encodes & and <. Use this when the attribute is wrapped in single quotes (the ' itself is not encoded).
    • DOUBLE_QUOTED_ATTRIBUTE: Encodes & and <. Use this when the attribute is wrapped in double quotes (the " itself is not encoded).

    Note: In CONTENT mode, > is always encoded as &gt; to avoid issues with ]]> sequences.

    // Example: Creating an encoder for XML 1.1 attribute values wrapped in double quotes
    XMLEncoder encoder = new XMLEncoder(XMLEncoder.Mode.DOUBLE_QUOTED_ATTRIBUTE, XMLEncoder.Version.XML_1_1);