Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3801

Sanitize HTML Code to Prevent XSS Attacks

$
0
0

1. Introduction

Cross-Site Scripting (XSS) is a type of vulnerability that allows attackers to inject malicious scripts into web applications. Attackers can execute these scripts in the user’s browser, leading to data theft, session hijacking, or website defacement.

In this tutorial, we’ll explore how to sanitize HTML input in Java applications to prevent XSS attacks.

2. Setting up the Project

To begin with, we need to add the OWASP Java HTML sanitizer library to our pom.xml:

<dependency>
    <groupId>com.googlecode.owasp-java-html-sanitizer</groupId>
    <artifactId>owasp-java-html-sanitizer</artifactId>
    <version>20240325.1</version>
</dependency>

This library provides a highly configurable policy-driven sanitizer that can handle complex HTML while protecting against XSS attacks.

3. Implementing Basic OWASP HTML Sanitization

With the dependency in place, let’s define a utility method that uses the library to clean potentially harmful HTML input. We’ll create a reusable utility class that sanitizes HTML using a default policy that allows only basic formatting tags:

public class HtmlSanitizerUtil {
    private static final PolicyFactory POLICY = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    public static String sanitize(String htmlContent) {
        return POLICY.sanitize(htmlContent);
    }
}

In the example above, we configure a sanitization policy by combining two built-in sanitizers – Sanitizers.FORMATTING and Sanitizers.LINKS. This policy allows basic HTML formatting tags such as <b>, <i>, <u>, and hyperlinks via <a> tags. The sanitize() method then applies this policy to the input string and returns a cleaned version of the HTML content.

Let’s verify our sanitizer by inputting unsafe HTML and asserting that the output contains only the allowed tags:

String input = "<script>alert('XSS')</script><b>Hello</b> <a href='https://example.com'>link</a>";
String expectedOutput = "<b>Hello</b> <a href=\"https://example.com\" rel=\"nofollow\">link</a>";
String sanitized = HtmlSanitizerUtil.sanitize(input);
assertEquals(expectedOutput, sanitized);

In this test, we pass a string that includes a malicious <script> tag along with valid formatting and hyperlink elements. The sanitizer removes the script and retains the safe tags. The rel=”nofollow” attribute is added automatically to links as an additional safeguard.

4. Using OWASP HtmlPolicyBuilder for Flexible Sanitization

Although built-in policies offer convenience, we often need more control over which HTML elements and attributes to allow. The HtmlPolicyBuilder API offers a fluent approach to defining such custom policies.

Let’s implement a sanitizer that allows both block-level and inline formatting elements:

private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
  .allowCommonBlockElements()
  .allowCommonInlineFormattingElements()
  .toFactory();
public static String sanitize(String html) {
    return POLICY.sanitize(html);
}

This implementation creates a policy that allows common block-level elements like <div>, <p>, <ul>, and <ol>, as well as inline elements such as <b>, <i>, and <em>. The sanitize() method uses this policy to remove any dangerous tags and attributes while preserving common layout and styling elements. The PolicyFactory instance is thread-safe and can be reused across multiple sanitization operations without re-instantiating.

Next, we verify this implementation with an assertion-based test that compares the sanitized result with the expected output:

String input = "<div onclick='alert(1)'><p><b>Text</b></p></div><script>alert('x')</script>";
String expectedOutput = "<div><p><b>Text</b></p></div>";
String sanitized = HtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

In this case, the input contains unsafe event handlers and a <script> tag. Our custom policy strips out the dangerous attributes and elements, leaving behind only the permitted structural and formatting tags. This approach gives us a good balance between security and preserving user formatting for blog comments, CMS content, or discussion boards.

5. Creating a Custom Policy

In some applications, we might want to allow a different set of HTML elements or restrict certain attributes more tightly. The OWASP Java HTML Sanitizer provides a fluent API for building custom policies. Here’s an example of a more sophisticated policy configuration:

public class CustomHtmlSanitizer {
    private static final PolicyFactory POLICY = new HtmlPolicyBuilder()
      .allowElements("a", "p", "div", "span", "h1", "h2", "h3")
      .allowUrlProtocols("https")
      .allowAttributes("href").onElements("a")
      .requireRelNofollowOnLinks()
      .allowAttributes("class").globally()
      .allowStyling()
      .toFactory();
    public static String sanitize(String html) {
        return POLICY.sanitize(html);
    }
}

In this example, we construct a custom sanitization policy with the following rules:

  • Allowed Elements: The policy permits structural tags like <div>, <p>, and headings (<h1> to <h3>), as well as <a> and <span>
  • Allowed URL Protocols: Only HTTPS links are allowed, helping to prevent insecure HTTP links, which could lead to mixed-content issues
  • Link Attributes: The href attribute is permitted on <a> tags, and each link is automatically assigned a rel=”nofollow” attribute to reduce SEO abuse
  • Global Attributes: The class attribute is allowed on all elements, supporting CSS styling hooks
  • Inline Styling: Safe CSS styles are permitted via the style attribute, such as color, font-weight, and other non-harmful declarations

This approach gives us full control over the permitted structure and appearance of sanitized content while ensuring that any unsafe behavior, such as inline JavaScript, event handlers, or disallowed protocols, is effectively stripped out.

Let’s verify this with a test case:

String input = "<h1 class='title' style='color:red;'>Welcome</h1>"
  + "<a href='https://example.com' onclick='stealCookies()'>Click</a>"
  + "<script>alert('xss');</script>";
String expectedOutput = 
  "<h1 class=\"title\" style=\"color:red\">Welcome</h1><a href=\"https://example.com\" rel=\"nofollow\">Click</a>";
String sanitized = CustomHtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

This kind of custom policy is beneficial when sanitizing user-generated content for blogs, forums, or CMS systems, where some flexibility in formatting is required, but not at the cost of security.

6. Alternative Approach: JSoup HTML Cleaner

While the OWASP Java HTML Sanitizer is highly secure and policy-driven, another popular library for sanitizing HTML in Java is JSoup. JSoup provides robust HTML parsing and cleaning capabilities, making it ideal for scenarios where we need to inspect or manipulate the DOM in addition to sanitization.

To get started, we first add the JSoup dependency to our pom.xml:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.20.1</version>
</dependency>

Once added, we can implement a sanitizer that defines a safelist of allowed HTML elements and attributes. Here’s a sample implementation:

public class JsoupHtmlSanitizer {
    public static String sanitize(String html) {
        Safelist safelist = Safelist.basic()
          .addTags("h1", "h2", "h3")
          .addAttributes("a", "target")
          .addProtocols("a", "href", "http", "https");
        
        return Jsoup.clean(html, safelist);
    }
}

In this example, we start with Safelist.basic(), which permits basic HTML tags such as <b>, <i>, <u>, and <a>. Next, we extend it to allow heading tags like <h1>, <h2>, and <h3>.

Lastly, we also allow the target attribute on anchor tags, which enables opening links in a new tab when target=”_blank” is used and restricts link protocols to http and https.

To verify this implementation, let’s run a simple test:

String input = "<h1 onclick='x()'>Title</h1><a href='javascript:alert(1)' target='_blank'>Click</a>";
String expectedOutput = "<h1>Title</h1><a target=\"_blank\" rel=\"nofollow\">Click</a>";
String sanitized = JsoupHtmlSanitizer.sanitize(input);
assertEquals(expectedOutput, sanitized);

Unlike the OWASP sanitizer, JSoup uses a “safelist” model, which is more intuitive in some cases, especially when dealing with a predefined HTML structure or when we need to extract or modify specific HTML nodes before sanitizing.

Additionally, JSoup automatically adds rel=”nofollow” to <a> tags that use target=”_blank” to prevent reverse tabnabbing attacks, enhancing security by default.

7. Conclusion

In this article, we explored multiple methods for sanitizing HTML in Java applications to defend against XSS attacks.

The OWASP Java HTML Sanitizer is ideal when strict XSS protection and fine-grained, policy-driven control are required. JSoup is better suited for scenarios involving HTML parsing, manipulation, or when a simpler, safelist-based approach is sufficient.

As always, the source code is available over on GitHub.

The post Sanitize HTML Code to Prevent XSS Attacks first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 3801

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>