Skip to main content

Inappropriate coding practices - Wildcard export

Need

Enforce explicit exports in code to avoid wildcard exports

Context

  • Usage of Java for building cross-platform applications
  • Usage of javax.servlet for Java web application development

Description

Non compliant code

package com.example;

import javax.servlet.*;

public class ExportAllServlet implements Servlet {
//...
}

// In another file
import com.example.*;

In the code snippet above, we have a Java Servlet class ExportAllServlet which is part of the com.example package. This class might contain several methods that are used to perform various operations.

Now, in another file, we have a wildcard import statement import com.example.*;. This statement imports all the classes and interfaces from the com.example package.

The vulnerability here is the use of the wildcard operator (*) in the import statement. This is considered inappropriate coding practice because it exports all the classes and interfaces from the com.example package, regardless of whether they are needed in the current context or not.

This could lead to several issues:

  1. Maintenance Difficulty: It can make the code harder to understand and maintain, as it's not clear which classes are actually being used.

  2. Name Conflicts: It could lead to name conflicts if two classes with the same name exist in different packages.

  3. Performance Issues: It could lead to performance issues as the JVM has to load all the classes, even if they are not used.

  4. Security Risks: It could potentially expose sensitive classes or methods that should not be accessible.

Therefore, it's recommended to avoid the use of wildcard imports and instead import only the specific classes that are required.

Steps

  • Avoid using wildcard imports
  • Explicitly import only the necessary classes or functions
  • Remove the wildcard import statement
  • Update the import statements to import specific classes or functions

Compliant code

package com.example;

import javax.servlet.Servlet;

public class ExportAllServlet implements Servlet {
//...
}

// In another file
import com.example.ExportAllServlet;

The vulnerability in the code was due to the use of wildcard imports. Wildcard imports, denoted by an asterisk (*), import all the classes or functions from a package. This can lead to potential issues such as naming conflicts and can make the code harder to read and maintain.

In the fixed code, we have removed the wildcard import and replaced it with an explicit import statement. Now, instead of importing all classes from the com.example package, we are only importing the ExportAllServlet class which is actually needed in this context.

This practice of explicit imports enhances the readability of the code, as it is clear at the top of the file which classes are being used. It also reduces the risk of naming conflicts and makes the code easier to maintain and debug.

References