Class DefaultEncoder

  • All Implemented Interfaces:
    Encoder

    public class DefaultEncoder
    extends java.lang.Object
    implements Encoder
    Reference implementation of the Encoder interface. This implementation takes a whitelist approach to encoding, meaning that everything not specifically identified in a list of "immune" characters is encoded.
    Since:
    June 1, 2007
    Author:
    Jeff Williams (jeff.williams .at. aspectsecurity.com) Aspect Security
    See Also:
    Encoder
    • Constructor Summary

      Constructors 
      Constructor Description
      DefaultEncoder​(java.util.List<java.lang.String> codecNames)  
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected java.lang.String buildUrl​(java.util.Map<DefaultEncoder.UriSegment,​java.lang.String> parseMap)
      All the parts should be canonicalized by this point.
      java.lang.String canonicalize​(java.lang.String input)
      This method is equivalent to calling Encoder.canonicalize(input, restrictMultiple, restrictMixed);.
      java.lang.String canonicalize​(java.lang.String input, boolean strict)
      This method is the equivalent to calling Encoder.canonicalize(input, strict, strict);.
      java.lang.String canonicalize​(java.lang.String input, boolean restrictMultiple, boolean restrictMixed)
      Canonicalization is simply the operation of reducing a possibly encoded string down to its simplest form.
      java.lang.String decodeForHTML​(java.lang.String input)
      Decodes HTML entities.
      byte[] decodeFromBase64​(java.lang.String input)
      Decode data encoded with BASE-64 encoding.
      java.lang.String decodeFromURL​(java.lang.String input)
      Decode from URL.
      java.lang.String encodeForBase64​(byte[] input, boolean wrap)
      Encode for Base64.
      java.lang.String encodeForCSS​(java.lang.String input)
      Encode data for use in Cascading Style Sheets (CSS) content.
      java.lang.String encodeForDN​(java.lang.String input)
      Encode data for use in an LDAP distinguished name.
      java.lang.String encodeForHTML​(java.lang.String input)
      Encode data for use in HTML using HTML entity encoding
      java.lang.String encodeForHTMLAttribute​(java.lang.String input)
      Encode data for use in HTML attributes.
      java.lang.String encodeForJavaScript​(java.lang.String input)
      Encode data for insertion inside a data value or function argument in JavaScript.
      java.lang.String encodeForLDAP​(java.lang.String input)
      Encode data for use in LDAP queries.
      java.lang.String encodeForLDAP​(java.lang.String input, boolean encodeWildcards)
      Encode data for use in LDAP queries.
      java.lang.String encodeForOS​(Codec codec, java.lang.String input)
      Encode for an operating system command shell according to the selected codec (appropriate codecs include the WindowsCodec and UnixCodec).
      java.lang.String encodeForSQL​(Codec codec, java.lang.String input)
      Encode input for use in a SQL query, according to the selected codec (appropriate codecs include the MySQLCodec and OracleCodec).
      java.lang.String encodeForURL​(java.lang.String input)
      Encode for use in a URL.
      java.lang.String encodeForVBScript​(java.lang.String input)
      Encode data for insertion inside a data value in a Visual Basic script.
      java.lang.String encodeForXML​(java.lang.String input)
      Encode data for use in an XML element.
      java.lang.String encodeForXMLAttribute​(java.lang.String input)
      Encode data for use in an XML attribute.
      java.lang.String encodeForXPath​(java.lang.String input)
      Encode data for use in an XPath query.
      java.lang.String getCanonicalizedURI​(java.net.URI dirtyUri)
      Get a version of the input URI that will be safe to run regex and other validations against.
      static Encoder getInstance()  
      java.util.Map<java.lang.String,​java.util.List<java.lang.String>> splitQuery​(java.net.URI uri)
      The meat of this method was taken from StackOverflow: http://stackoverflow.com/a/13592567/557153 It has been modified to return a canonicalized key and value pairing.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • DefaultEncoder

        public DefaultEncoder​(java.util.List<java.lang.String> codecNames)
    • Method Detail

      • getInstance

        public static Encoder getInstance()
      • canonicalize

        public java.lang.String canonicalize​(java.lang.String input)
        This method is equivalent to calling Encoder.canonicalize(input, restrictMultiple, restrictMixed);. The default values for restrictMultiple and restrictMixed come from ESAPI.properties
         Encoder.AllowMultipleEncoding=false
         Encoder.AllowMixedEncoding=false
         
        Specified by:
        canonicalize in interface Encoder
        Parameters:
        input - the text to canonicalize
        Returns:
        a String containing the canonicalized text
        See Also:
        Encoder.canonicalize(String, boolean, boolean), W3C specifications
      • canonicalize

        public java.lang.String canonicalize​(java.lang.String input,
                                             boolean strict)
        This method is the equivalent to calling Encoder.canonicalize(input, strict, strict);.
        Specified by:
        canonicalize in interface Encoder
        Parameters:
        input - the text to canonicalize
        strict - true if checking for multiple and mixed encoding is desired, false otherwise
        Returns:
        a String containing the canonicalized text
        See Also:
        Encoder.canonicalize(String, boolean, boolean), W3C specifications
      • canonicalize

        public java.lang.String canonicalize​(java.lang.String input,
                                             boolean restrictMultiple,
                                             boolean restrictMixed)
        Canonicalization is simply the operation of reducing a possibly encoded string down to its simplest form. This is important, because attackers frequently use encoding to change their input in a way that will bypass validation filters, but still be interpreted properly by the target of the attack. Note that data encoded more than once is not something that a normal user would generate and should be regarded as an attack.

        Everyone says you shouldn't do validation without canonicalizing the data first. This is easier said than done. The canonicalize method can be used to simplify just about any input down to its most basic form. Note that canonicalize doesn't handle Unicode issues, it focuses on higher level encoding and escaping schemes. In addition to simple decoding, canonicalize also handles:

        • Perverse but legal variants of escaping schemes
        • Multiple escaping (%2526 or &lt;)
        • Mixed escaping (%26lt;)
        • Nested escaping (%%316 or &%6ct;)
        • All combinations of multiple, mixed, and nested encoding/escaping (%253c or ┦gt;)

        Using canonicalize is simple. The default is just...

             String clean = ESAPI.encoder().canonicalize( request.getParameter("input"));
         
        You need to decode untrusted data so that it's safe for ANY downstream interpreter or decoder. For example, if your data goes into a Windows command shell, then into a database, and then to a browser, you're going to need to decode for all of those systems. You can build a custom encoder to canonicalize for your application like this...
             ArrayList list = new ArrayList();
             list.add( new WindowsCodec() );
             list.add( new MySQLCodec() );
             list.add( new PercentCodec() );
             Encoder encoder = new DefaultEncoder( list );
             String clean = encoder.canonicalize( request.getParameter( "input" ));
         
        In ESAPI, the Validator uses the canonicalize method before it does validation. So all you need to do is to validate as normal and you'll be protected against a host of encoded attacks.
             String input = request.getParameter( "name" );
             String name = ESAPI.validator().isValidInput( "test", input, "FirstName", 20, false);
         
        However, the default canonicalize() method only decodes HTMLEntity, percent (URL) encoding, and JavaScript encoding. If you'd like to use a custom canonicalizer with your validator, that's pretty easy too.
             ... setup custom encoder as above
             Validator validator = new DefaultValidator( encoder );
             String input = request.getParameter( "name" );
             String name = validator.isValidInput( "test", input, "name", 20, false);
         
        Although ESAPI is able to canonicalize multiple, mixed, or nested encoding, it's safer to not accept this stuff in the first place. In ESAPI, the default is "strict" mode that throws an IntrusionException if it receives anything not single-encoded with a single scheme. This is configurable in ESAPI.properties using the properties:
         Encoder.AllowMultipleEncoding=false
         Encoder.AllowMixedEncoding=false
         
        This method allows you to override the default behavior by directly specifying whether to restrict multiple or mixed encoding. Even if you disable restrictions, you'll still get warning messages in the log about each multiple encoding and mixed encoding received.
             // disabling strict mode to allow mixed encoding
             String url = ESAPI.encoder().canonicalize( request.getParameter("url"), false, false);
         
        WARNING!!! Please note that this method is incompatible with URLs and if there exist any HTML Entities that correspond with parameter values in a URL such as "&para;" in a URL like "https://foo.com/?bar=foo&parameter=wrong" you will get a mixed encoding validation exception.

        If you wish to canonicalize a URL/URI use the method Encoder.getCanonicalizedURI(URI dirtyUri);

        Specified by:
        canonicalize in interface Encoder
        Parameters:
        input - the text to canonicalize
        restrictMultiple - true if checking for multiple encoding is desired, false otherwise
        restrictMixed - true if checking for mixed encoding is desired, false otherwise
        Returns:
        a String containing the canonicalized text
        See Also:
        W3C specifications, Encoder.getCanonicalizedURI(URI dirtyUri)
      • decodeForHTML

        public java.lang.String decodeForHTML​(java.lang.String input)
        Decodes HTML entities.
        Specified by:
        decodeForHTML in interface Encoder
        Parameters:
        input - the String to decode
        Returns:
        the newly decoded String
      • encodeForHTMLAttribute

        public java.lang.String encodeForHTMLAttribute​(java.lang.String input)
        Encode data for use in HTML attributes.
        Specified by:
        encodeForHTMLAttribute in interface Encoder
        Parameters:
        input - the untrusted data to output encode for an HTML attribute
        Returns:
        the untrusted data safely output encoded for use in a use as an HTML attribute
      • encodeForCSS

        public java.lang.String encodeForCSS​(java.lang.String input)
        Encode data for use in Cascading Style Sheets (CSS) content.
        Specified by:
        encodeForCSS in interface Encoder
        Parameters:
        input - the untrusted data to output encode for CSS
        Returns:
        the untrusted data safely output encoded for use in a CSS
        See Also:
        CSS Syntax [w3.org]
      • encodeForJavaScript

        public java.lang.String encodeForJavaScript​(java.lang.String input)
        Encode data for insertion inside a data value or function argument in JavaScript. Including user data directly inside a script is quite dangerous. Great care must be taken to prevent including user data directly into script code itself, as no amount of encoding will prevent attacks there. Please note there are some JavaScript functions that can never safely receive untrusted data as input – even if the user input is encoded. For example:
          <script>
              window.setInterval('<%= EVEN IF YOU ENCODE UNTRUSTED DATA YOU ARE XSSED HERE %>');
          </script>
         
        Specified by:
        encodeForJavaScript in interface Encoder
        Parameters:
        input - the untrusted data to output encode for JavaScript
        Returns:
        the untrusted data safely output encoded for use in a use in JavaScript
      • encodeForVBScript

        public java.lang.String encodeForVBScript​(java.lang.String input)
        Encode data for insertion inside a data value in a Visual Basic script. Putting user data directly inside a script is quite dangerous. Great care must be taken to prevent putting user data directly into script code itself, as no amount of encoding will prevent attacks there. This method is not recommended as VBScript is only supported by Internet Explorer
        Specified by:
        encodeForVBScript in interface Encoder
        Parameters:
        input - the untrusted data to output encode for VBScript
        Returns:
        the untrusted data safely output encoded for use in a use in VBScript
      • encodeForSQL

        public java.lang.String encodeForSQL​(Codec codec,
                                             java.lang.String input)
        Encode input for use in a SQL query, according to the selected codec (appropriate codecs include the MySQLCodec and OracleCodec). This method is not recommended. The use of the PreparedStatement interface is the preferred approach. However, if for some reason this is impossible, then this method is provided as a weaker alternative. The best approach is to make sure any single-quotes are double-quoted. Another possible approach is to use the {escape} syntax described in the JDBC specification in section 1.5.6. However, this syntax does not work with all drivers, and requires modification of all queries.
        Specified by:
        encodeForSQL in interface Encoder
        Parameters:
        codec - a Codec that declares which database 'input' is being encoded for (ie. MySQL, Oracle, etc.)
        input - the text to encode for SQL
        Returns:
        input encoded for use in SQL
        See Also:
        JDBC Specification, java.sql.PreparedStatement
      • encodeForOS

        public java.lang.String encodeForOS​(Codec codec,
                                            java.lang.String input)
        Encode for an operating system command shell according to the selected codec (appropriate codecs include the WindowsCodec and UnixCodec). Please note the following recommendations before choosing to use this method: 1) It is strongly recommended that applications avoid making direct OS system calls if possible as such calls are not portable, and they are potentially unsafe. Please use language provided features if at all possible, rather than native OS calls to implement the desired feature. 2) If an OS call cannot be avoided, then it is recommended that the program to be invoked be invoked directly (e.g., System.exec("nameofcommand" + "parameterstocommand");) as this avoids the use of the command shell. The "parameterstocommand" should of course be validated before passing them to the OS command. 3) If you must use this method, then we recommend validating all user supplied input passed to the command shell as well, in addition to using this method in order to make the command shell invocation safe. An example use of this method would be: System.exec("dir " + ESAPI.encodeForOS(WindowsCodec, "parameter(s)tocommandwithuserinput");
        Specified by:
        encodeForOS in interface Encoder
        Parameters:
        codec - a Codec that declares which operating system 'input' is being encoded for (ie. Windows, Unix, etc.)
        input - the text to encode for the command shell
        Returns:
        input encoded for use in command shell
      • encodeForLDAP

        public java.lang.String encodeForLDAP​(java.lang.String input)
        Encode data for use in LDAP queries. Wildcard (*) characters will be encoded.
        Specified by:
        encodeForLDAP in interface Encoder
        Parameters:
        input - the text to encode for LDAP
        Returns:
        input encoded for use in LDAP
      • encodeForLDAP

        public java.lang.String encodeForLDAP​(java.lang.String input,
                                              boolean encodeWildcards)
        Encode data for use in LDAP queries. You have the option whether or not to encode wildcard (*) characters.
        Specified by:
        encodeForLDAP in interface Encoder
        Parameters:
        input - the text to encode for LDAP
        encodeWildcards - whether or not wildcard (*) characters will be encoded.
        Returns:
        input encoded for use in LDAP
      • encodeForDN

        public java.lang.String encodeForDN​(java.lang.String input)
        Encode data for use in an LDAP distinguished name.
        Specified by:
        encodeForDN in interface Encoder
        Parameters:
        input - the text to encode for an LDAP distinguished name
        Returns:
        input encoded for use in an LDAP distinguished name
      • encodeForXPath

        public java.lang.String encodeForXPath​(java.lang.String input)
        Encode data for use in an XPath query. NB: The reference implementation encodes almost everything and may over-encode. The difficulty with XPath encoding is that XPath has no built in mechanism for escaping characters. It is possible to use XQuery in a parameterized way to prevent injection. For more information, refer to this article which specifies the following list of characters as the most dangerous: ^&"*';<>(). This paper suggests disallowing ' and " in queries.
        Specified by:
        encodeForXPath in interface Encoder
        Parameters:
        input - the text to encode for XPath
        Returns:
        input encoded for use in XPath
        See Also:
        XPath Injection [ibm.com], Blind XPath Injection [packetstormsecurity.org]
      • encodeForXML

        public java.lang.String encodeForXML​(java.lang.String input)
        Encode data for use in an XML element. The implementation should follow the Character Encoding in Entities from W3C.

        The use of a real XML parser is strongly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parser, this method provides a safe mechanism to do so.

        Specified by:
        encodeForXML in interface Encoder
        Parameters:
        input - the text to encode for XML
        Returns:
        input encoded for use in XML
        See Also:
        Character Encoding in Entities
      • encodeForXMLAttribute

        public java.lang.String encodeForXMLAttribute​(java.lang.String input)
        Encode data for use in an XML attribute. The implementation should follow the Character Encoding in Entities from W3C.

        The use of a real XML parser is highly encouraged. However, in the hopefully rare case that you need to make sure that data is safe for inclusion in an XML document and cannot use a parse, this method provides a safe mechanism to do so.

        Specified by:
        encodeForXMLAttribute in interface Encoder
        Parameters:
        input - the text to encode for use as an XML attribute
        Returns:
        input encoded for use in an XML attribute
        See Also:
        Character Encoding in Entities
      • encodeForURL

        public java.lang.String encodeForURL​(java.lang.String input)
                                      throws EncodingException
        Encode for use in a URL. This method performs URL encoding on the entire string.
        Specified by:
        encodeForURL in interface Encoder
        Parameters:
        input - the text to encode for use in a URL
        Returns:
        input encoded for use in a URL
        Throws:
        EncodingException - if encoding fails
        See Also:
        URL encoding
      • decodeFromURL

        public java.lang.String decodeFromURL​(java.lang.String input)
                                       throws EncodingException
        Decode from URL. Implementations should first canonicalize and detect any double-encoding. If this check passes, then the data is decoded using URL decoding.
        Specified by:
        decodeFromURL in interface Encoder
        Parameters:
        input - the text to decode from an encoded URL
        Returns:
        the decoded URL value
        Throws:
        EncodingException - if decoding fails
      • encodeForBase64

        public java.lang.String encodeForBase64​(byte[] input,
                                                boolean wrap)
        Encode for Base64.
        Specified by:
        encodeForBase64 in interface Encoder
        Parameters:
        input - the text to encode for Base64
        wrap - the encoder will wrap lines every 64 characters of output
        Returns:
        input encoded for Base64
      • decodeFromBase64

        public byte[] decodeFromBase64​(java.lang.String input)
                                throws java.io.IOException
        Decode data encoded with BASE-64 encoding.
        Specified by:
        decodeFromBase64 in interface Encoder
        Parameters:
        input - the Base64 text to decode
        Returns:
        input decoded from Base64
        Throws:
        java.io.IOException
      • getCanonicalizedURI

        public java.lang.String getCanonicalizedURI​(java.net.URI dirtyUri)
                                             throws IntrusionException
        Get a version of the input URI that will be safe to run regex and other validations against. It is not recommended to persist this value as it will transform user input. This method will not test to see if the URI is RFC-3986 compliant. This will extract each piece of a URI according to parse zone as specified in RFC-3986 section 3, and it will construct a canonicalized String representing a version of the URI that is safe to run regex against.
        Specified by:
        getCanonicalizedURI in interface Encoder
        Parameters:
        dirtyUri -
        Returns:
        Canonicalized URI string.
        Throws:
        IntrusionException
      • buildUrl

        protected java.lang.String buildUrl​(java.util.Map<DefaultEncoder.UriSegment,​java.lang.String> parseMap)
        All the parts should be canonicalized by this point. This is straightforward assembly.
        Parameters:
        parseMap - The parts of the URL to put back together.
        Returns:
        The canonicalized URL.
      • splitQuery

        public java.util.Map<java.lang.String,​java.util.List<java.lang.String>> splitQuery​(java.net.URI uri)
                                                                                          throws java.io.UnsupportedEncodingException
        The meat of this method was taken from StackOverflow: http://stackoverflow.com/a/13592567/557153 It has been modified to return a canonicalized key and value pairing.
        Parameters:
        uri - The URI to analyze.
        Returns:
        a map of canonicalized query parameters.
        Throws:
        java.io.UnsupportedEncodingException