Search code examples
javaregexsymbolsesapi

Pattern to allow Percentage symbol while using ESAPI


I am using RegEx ^[\\p{L}\\p{N}:\\-.\\s_&.,$()\\*%]*$ for validating one of the fields, using ESAPI.

If my input is 1234% or 1234%% or 1234%%% or %1 it's being considered as TRUE. But, if I may input %12 or 1234%12 or 1234%%12 it's failing.

My observation is it doesn't allow more than one character/number after % symbol.

May I know if there is any error in my RegEx? What should be the RegEx pattern to allow any number of % symbols followed or preceeded by any valid character?

Thanks in advance.


Solution

  • Good option would be to exclude the Percentage codec, if it is not really needed.

    To do that, one needs to write own customized encoder implementation that extends ESAPI provided org.owasp.esapi.reference.DefaultEncoder and register that to ESAPI.properties like

    ESAPI.Encoder=path.to.ESAPIDefaultEncoderImpl
    

    See below the implementation example.

    package path.to;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ESAPIDefaultEncoderImpl extends org.owasp.esapi.reference.DefaultEncoder
    {
    private static List<String> codecs;
    private static ESAPIDefaultEncoderImpl singletonInstance ;
    
    static
    {
        codecs = new ArrayList<String>();
        codecs.add("HTMLEntityCodec ");
        codecs.add("JavaScriptCodec");
        singletonInstance = new ESAPIDefaultEncoderImpl();
    }
    
    public static ESAPIDefaultEncoderImpl getInstance()
          {
            return singletonInstance;
          }
          private ESAPIDefaultEncoderImpl()
          {
             super(codecs);
          }
    }
    

    In this customized encoder, one should not register the Percentage Codec, but only the ones which are really needed. (To see all ESAPI codecs, visit ESAPI documentation).