Detailed explanation of application security protection ESAPI in one article

This article is shared from the Huawei Cloud Community " Application Security Protection ESAPI " by Uncle_Tom.

1. Introduction to ESAPI

OWASP Enterprise Security API (ESAPI) is a free, open source library of web application security controls that makes it easier for programmers to write lower-risk applications. The ESAPI library is designed to make it easier for programmers to retrofit existing applications for security. The ESAPI library is also a solid foundation for new developments.

Taking into account language-specific differences, all OWASP ESAPI versions have the same basic design:

  • There is a set of security control interfaces. For example, defines the parameter types passed to security control types.
  • Each security control has a reference implementation. For example: string-based input validation. For example, Java's ESAPI org.owasp.ESAPI.reference.FileBasedAuthenticator, while other reference implementations are mature enterprise-level reference implementations, such as org.oasp.ESAPI.reference.DefaultEncoder or org.owasp.ESAPI.reference.DefaultValidator .
  • Each security control has its own implementation (optional). These classes may contain application logic, which may be developed by or for your organization. For example: Enterprise Authentication.
  • In order to make this project as easy to spread as possible and enable more people to use it freely, the source code of this project uses the BSD license. Documentation for this project is licensed under a Creative Commons Attribution License. You are free to use, modify, and even include ESAPI in commercial products.

2. ESAPI framework

OWASP ESAPI has implemented the following security controls

  • Authentication
  • Access control
  • Input validation
  • Output encoding/escaping
  • password
  • Error handling and logging
  • communication safety
  • HTTP security
  • Security configuration

ESAPI framework

OWASP Top 10 covered by ESAPI

3. Use of ESAPI

3.1. ESAPI configuration in pom.xml

The latest version is: 2.5.3.1, which can be found directly in the Maven repository.

<!-- https://mvnrepository.com/artifact/org.owasp.esapi/esapi -->
<dependency>
  <groupId>org.owasp.esapi</groupId>
  <artifactId>esapi</artifactId>
  <version>2.5.3.1</version>
  <exclusions>
    <exclusion>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

3.2. Protection against injection problems

A large part of network security problems are caused by injection problems. This type of problem is mainly caused by improper transcoding during the use of external input, such as SQL injection, command injection, cross-site scripting, etc.

Encode (encoder interface) contains many methods for decoding input and encoding output so that the processed characters are safe for various interpreters.

3.2.1. Protection: XSS cross-site scripting attack

HTML encoder (encodeForHTML)

@Test
void testEncodeForHTML() {
    String input = "<a href='sdfs'></a> < script > alert('xss'); </ script >";
    String encodedString = ESAPI.encoder().encodeForHTML(input);

    LOG.info("EncodeForHTML: {}", encodedString);
}

Output:

EncodeForHTML: <a href='xss'></a> < script > alert('xss'); </ script >

URL encoder (encodeForURL)

@Test
void testEncodeForURL() {
    String input = "/?callback=<script>alert('xss')</script>";
    String encodedString;
    try {
        encodedString = ESAPI.encoder().encodeForURL(input);
        LOG.info("EncodeForURL: {}", encodedString);
    } catch (EncodingException e) {
        fail("Should not get exception:" + e.getMessage());
    }
}

Output:

EncodeForURL: %2F%3Fcallback%3D%3Cscript%3Ealert%28%27xss%27%29%3C%2Fscript%3E

3.2.2. Protection: SQL injection

@Test
void testEncodeForSQL() {
    String userId = "tom' or '1=1'";
    String sql = "select * from user where user='"
            + ESAPI.encoder().encodeForSQL(new MySQLCodec(MySQLCodec.Mode.STANDARD), userId) + "'";

    LOG.info("sql = {}", sql);
}

Output:

sql = select * from user where user='tom\' or \'1\=1\''

3.2.3. Protection: Command Injection

@Test
void testEncodeForOS() {
    String input = "dir & dir /s";
    String cmd = ESAPI.encoder().encodeForOS(new WindowsCodec(), input);

    LOG.info("cmd = {}", cmd);
}

Output:

cmd = dir^ ^&^ dir^ ^/s

3.3. Protection against input validation issues

The biggest threat to network security is external input, so verification of external input plays the greatest protective role in application security.

3.3.1. ESAPI input verification

ESAPI has an input validation configuration: validation.properties gives commonly used validations.

validation.properties

Validator.SafeString=^[.\\p{Alnum}\\p{Space}]{0,1024}$
Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$
Validator.IPAddress=^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Validator.URL=^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&;%\\$#_]*)?$
Validator.CreditCard=^(\\d{4}[- ]?){3}\\d{4}$
Validator.SSN=^(?!000)([0-6]\\d{2}|7([0-6]\\d|7[012]))([ -]?)(?!00)\\d\\d\\3(?!0000)\\d{4}$

Verification interface

/** 
  * Input verification 
  * 
  * @param context verification content 
  * @param input verification input   
  * @param type verification type, corresponding to the type in validation.properties 
  * @param maxLength input character maximum length verification 
  * @ param allowNull Input character Null value verification, false - not allowed; true - allowed 
  * @return Returns false if verification fails, returns true if verification succeeds 
  */ 
boolean ESAPI.validator().getValidInput(String context, String input, String type , int maxLength, boolean allowNull);
@Test
void testValidatorEmail() {
    String input = "xxxx.com";
    if (!ESAPI.validator().isValidInput("", input, "Email", 11, false)) {
        LOG.error("Email validate fail!");
    } else {
        LOG.info("Email is validate.");
    }
}

Output:

Email validate fail!

4. Common problems encountered during the use and upgrade of ESAPI

4.1. org.owasp.esapi.reference.DefaultEncoder CTOR threw exception caused by ExceptionInInitializerError

org.owasp.esapi.errors.ConfigurationException: java.lang.reflect.InvocationTargetException Encoder class (org.owasp.esapi.reference.DefaultEncoder) CTOR threw exception.
 at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:129)
 at org.owasp.esapi.ESAPI.encoder(ESAPI.java:101)
 at com.test.esapi.EsapiTest.testUpdateJulietInfo_good(EsapiTest.java:19)
 at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
 at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
Caused by: java.lang.reflect.InvocationTargetException

 at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:86)
 ... 71 more
Caused by: java.lang.ExceptionInInitializerError
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:375)
 at org.owasp.esapi.util.ObjFactory.loadClassByStringName(ObjFactory.java:158)
 at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:81)
 at org.owasp.esapi.ESAPI.logFactory(ESAPI.java:139)
 at org.owasp.esapi.ESAPI.getLogger(ESAPI.java:155)
 at org.owasp.esapi.reference.DefaultEncoder.(DefaultEncoder.java:85)
 at org.owasp.esapi.reference.DefaultEncoder.(DefaultEncoder.java:109)
 at org.owasp.esapi.reference.DefaultEncoder.getInstance(DefaultEncoder.java:68)
 ... 76 more
Caused by: org.owasp.esapi.errors.ConfigurationException: Unable to locate resource: esapi-java-logging.properties
 at org.owasp.esapi.logging.java.JavaLogFactory.readLoggerConfiguration(JavaLogFactory.java:128)
 at org.owasp.esapi.logging.java.JavaLogFactory.(JavaLogFactory.java:96)
 ... 85 more

This is the most common problem encountered when upgrading ESAPI to versions after 2.5.0.0.

2.5.0.0 is an important changed version of ESAPI. We can see from the version change information:

  • This version of ESAPI completely abandons support for Log4J, which is plagued by Log4J's constant vulnerabilities, and instead uses SLF4J. If your ESAPI.Logger property is set to use Log4J, obscure Exceptions or Errors will be thrown, usually ExceptionInInitializerError, if you do not change it.
  • AntiSamy has been upgraded to 1.7.0, and AntiSamy's customized AntiSamy-sapi.xml file is supported.
  • As from the previous version, this version only supports Java 8 or higher.

From here you can see that ExceptionInInitializerError should be caused by the change log component. Familiar friends will immediately think of the configuration file of ESAPI, ESAPI.properties, which gives the configuration of all components.

As you can see from lines 69 to 72 in the figure, line 69:

ESAPI.Logger=org.owasp.esapi.logging.java.JavaLogFactory

It still points to org.owasp.esapi.logging.java.JavaLogFactory. The following comments also remind us that we need to change it to line 71:

ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory

The problem is solved after modification.

4.2. java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest

java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
 at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
 at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3402)
 at java.base/java.lang.Class.getMethodsRecursive(Class.java:3543)
 at java.base/java.lang.Class.getMethod0(Class.java:3529)
 at java.base/java.lang.Class.getMethod(Class.java:2225)
 at org.owasp.esapi.util.ObjFactory.loadMethodByStringName(ObjFactory.java:196)
 at org.owasp.esapi.util.ObjFactory.findSingletonCreateMethod(ObjFactory.java:173)
 at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:84)
 at org.owasp.esapi.ESAPI.validator(ESAPI.java:192)
 at com.huawei.hwe.esapi.EsapiTest.testEsapi_encodeForURL(EsapiTest.java:23)
 at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
 at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)

Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:525)
 ... 79 more

This problem is obviously missing dependent libraries. We can view the Maven library's definition and dependency information about ESAPI.
https://mvnrepository.com/artifact/org.owasp.esapi/esapi/2.5.3.1

Compilation dependencies

Runtime dependencies

From the running dependencies, you can see the requirements: javax.servlet » javax.servlet-api.
Click on the version number: 3.1.0 to get the mvn dependency configuration of javax.servlet-api 3.1.0. Add this configuration to the project pom.xml file on it.

After adding javax.servlet-api configuration in pom.xml, the problem is solved.

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~

npm is abused - someone uploaded more than 700 Wulin Gaiden slice videos "Linux China" The open source community announced that it will cease operations Microsoft formed a new team to help rewrite the core Windows library with Rust JetBrain bundled AI assistant caused user dissatisfaction Deutsche Bahn is recruiting people familiar with MS - IT administrators of DOS and Windows 3.11 VS Code 1.86 will cause the remote development function to be unavailable. FastGateway: a gateway that can be used to replace Nginx. Visual Studio Code 1.86 is released . Seven departments including the Ministry of Industry and Information Technology jointly issued a document: Develop the next generation operating system and promote open source technology. , Building an open source ecosystem Windows Terminal Preview 1.20 released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4526289/blog/11029214