Search code examples
javaesapi

Encoding in Java ESAPI


To prevent from SQL injections, OWASP encodes characters received.Below is the code implemented for org.owasp.esapi.codecs.OracleCodec.java class

 //Default implementation that should be overridden in specific codecs. Encodes ' to '' Encodes ' to '' (according to doc)


 public String encodeCharacter( char[] immune, Character c ) {
    if ( c.charValue() == '\'' )
        return "\'\'";
    return ""+c;
}

How does above help for the prevention of SQL injection?Please explain.


Solution

  • Using the guidelines at OWASP, multiple test cases can be found here.

    The snippet of code you're looking at here defends against someone trying to escape out of the query to run their own arbitrary command.

    if ( c.charValue() == '\'' )
    

    If the input value is equal to ASCII char value 0x27 (a single quote)

    return "\'\'";
    

    Escape the single quote.

    Oracle escaping is here.

    Lets say your query is "select * from users where id = \'" + request.getParameter("id")

    By not escaping single-quotes, an input like this:

    request.setParameter("id", "\' OR 1=1;"); would result in returning all the information in that table by changing the final, non-Java formatted query to select * from users where id = '' OR 1=1;

    I highly recommend you download the WebGoat program, and follow its lessons. It will teach you how to use SQL injection, and many other basic web attacks. And the ESAPI swingset will help you learn how to mitigate them.