AntiSamy

repository·main·Indexed 42 days ago

https://github.com/nahsra/antisamy

A Java library for fast and configurable cleansing of untrusted HTML to prevent XSS (Cross-Site Scripting) attacks. It uses policy files to define allowed HTML tags and attributes, providing a scan API that returns a CleanResults object containing sanitized HTML. Version 1.7.0 introduced breaking changes including the removal of XHTML support and mandatory XML Schema validation for policy files.

Tokens
1.1K
Snippets
2
Records
7
Agent score
3%

What's inside AntiSamy

  1. Tailor policy file tag actions

    main

    When creating or modifying a policy file, you can specify how different tags are handled using these actions:

    • filter: Removes the tag but keeps its content.
    • validate: Keeps the content only if it passes defined rules.
    • remove: Removes both the tag and its contents.
    • truncate: Removes the tag attributes and all child tags, leaving only the text content.
    • encode: Similar to filter, but encodes the tag for HTML to preserve it as raw text, moving its children up one level in the hierarchy.
  2. Choose a base AntiSamy policy file

    main

    AntiSamy uses policy files to define which HTML tags and attributes are allowed. You can choose a predefined policy based on your use case:

    1. antisamy-slashdot.xml: Very strict. Allows basic text formatting (e.g., <b>, <i>, <a>) but no CSS.
    2. antisamy-ebay.xml: Moderate. Allows richer HTML content suitable for public listings.
    3. antisamy-myspace.xml: Permissive. Allows most HTML and CSS, but strictly forbids JavaScript.
    4. antisamy-anythinggoes.xml: Extremely permissive. Allows almost all valid HTML and CSS (without JS or phishing-related CSS). Use this as a reference for all possible element rules when tailoring your own policy.
  3. Configure logging with SLF4J

    main

    AntiSamy uses slf4j-simple for logging by default.

    Warning: By default, slf4j-simple logs to standard output in a buffered manner. If a PolicyException is thrown, log messages might be lost. To prevent this, configure slf4j-simple to log to standard error or provide an alternative SLF4J-compatible logging library (and exclude slf4j-simple).

  4. Install AntiSamy via Maven

    main

    To use AntiSamy in your Java project, add the following dependency to your pom.xml file. Ensure you replace LATEST_VERSION with the current version of AntiSamy.

    <dependency>
       <groupId>org.owasp.antisamy</groupId>
       <artifactId>antisamy</artifactId>
       <version>LATEST_VERSION</version>
    </dependency>
  5. Important API changes in version 1.7.0

    main

    If upgrading to version 1.7.0 or later, note the following breaking changes:

    • CssHandler Constructors: The LinkedList<URI> embeddedStyleSheets parameter has been removed. Constructors now create an empty internal list. Use getImportedStylesheetsURIList() to access it.
    • XHTML Support: Support for XHTML has been dropped; AntiSamy now only supports HTML.
    • Policy Validation: XML Schema validation for policy files is now mandatory and cannot be disabled.
    • Anchor Security: The noopenerAndNoreferrerAnchors policy directive is now ON by default.
    • CssHandler Signature Change: The order of the last two parameters in the CssHandler constructor was reversed.
  6. Analyze CleanResults

    main

    The CleanResults object returned by as.scan() contains the output and metadata of the sanitization process:

    • getCleanHTML(): Returns the sanitized, safe HTML string.
    • getCleanXMLDocumentFragment(): Returns the sanitized XMLDocumentFragment.
    • getErrorMessages(): A list of error messages describing policy violations.
    • getNumberOfErrors(): The count of errors found.
    • getScanTime(): The time taken for the scan in seconds.

    CRITICAL SECURITY NOTE: Do not rely on getErrorMessages() or getNumberOfErrors() to determine if an input was malicious. An empty error list does not guarantee the input was safe. Always use the output from getCleanHTML() for your application logic.

  7. Scan HTML using the AntiSamy API

    main

    To cleanse untrusted HTML, create a Policy object and pass it to the AntiSamy#scan method.

    Ways to initialize a Policy:

    • From a filename (String)
    • From a File object
    • From an InputStream

    You can also pass the policy file path or a File object directly to the scan method.

    import org.owasp.validator.html.*;
    
    // 1. Initialize the policy
    Policy policy = Policy.getInstance("path/to/policy.xml");
    
    // 2. Create AntiSamy instance and scan
    AntiSamy as = new AntiSamy();
    CleanResults cr = as.scan(dirtyInput, policy);
    
    // 3. Use the clean HTML
    String safeHtml = cr.getCleanHTML();