Search code examples
javajax-rsesapi

Perfect way to configure esapi to mitigate XSS SQLI {GET/POST data}


We have a jaxrs service, Unfortunately the raw query is executed,No prepared statement. We used ESAPI to mitigate XSS,SQLI. Something like below:

private String mitigateSQLI(String value) {

        Encoder instance = ESAPI.encoder();
        Codec c = new MySQLCodec(MySQLCodec.Mode.ANSI);

        return instance.encodeForSQL(c, value);
    }

    private String mitigateXSS(String value) {
        if (value == null)
            return null;

        // Use the ESAPI library to avoid encoded attacks.
        value = ESAPI.encoder().canonicalize(value);

        // Avoid null characters
        value = value.replaceAll("\0", "");

        // Clean out HTML
        Document.OutputSettings outputSettings = new Document.OutputSettings();
        outputSettings.escapeMode(EscapeMode.xhtml);
        outputSettings.prettyPrint(false);
        value = Jsoup.clean(value, "", Whitelist.none(), outputSettings);

        return value;
    }

Along with the ESAPI.properties file with default configuration.

Still we are facing SQLI on certain scenarios, Knowing the queries are concatenated and formed.

Wanted to know if the best way/configuration to mitigate these things. Way can be the ESAPI properties or these ESAPI available methods.


Solution

  • Don't run away to the alternatives. As quoted in bold in the OWASP

    Primary Defenses:

    • Option 1: Use of Prepared Statements (with Parameterized Queries)
    • Option 2: Use of Stored Procedures
    • Option 3: Whitelist Input Validation
    • Option 4: Escaping All User Supplied Input

    Additional Defenses:

    • Also: Enforcing Least Privilege
    • Also: Performing Whitelist Input Validation as a Secondary Defense

    Configuring ESAPI.properties as per application requirement is important. When not using Prepared Statement, You must escape inputs on the server side. For Java , StringEscapeUtils from Apache does the job.