Java


JAVA.HARDCODED.FNAME : Hardcoded Filename (Java)

Summary

A file name is provided as a hardcoded string.

This checker identifies problems with the use of the external resources of the application. These are resource files, scripts or XML configuration files.

Properties

Class Name Hardcoded Filename (Java)
Significance reliability
Mnemonic JAVA.HARDCODED.FNAME
Categories
CWE CWE:547 Use of Hard-coded, Security-relevant Constants
Availability Available for Java only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Hardcoded Filename (Java)"

Example

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Resources {

  public static void main(String[] args) throws FileNotFoundException {
      new File("hello.txt");                          // "Hardcoded Filename (Java)" warning issued here
      new FileInputStream("C:\\myfile.txt");          // "Hardcoded Filename (Java)" warning issued here
      new FileOutputStream("/home/spoto/myfile.bmp"); // "Hardcoded Filename (Java)" warning issued here
      if (args.length > 0)
          new File(args[0]);
  }
}

Aside from the security risks associated with hardcoded file names, it is worth noting that paths "C:\\myfile.txt" and "/home/spoto/myfile.bmp" are OS-dependent: this program will not work consistently across all operating systems.

In this example, the programmer should move the file names into configuration files, so that they can be modified and swapped for distinct operating systems. It is also good practice to use File.separatorChar() to split path components in a OS-independent way.

Resolution

Verify if the problem is real and the resource is actually used in an incorrect way. Avoid hardcoded file names: move them to a configuration file. Avoid OS-dependent resources and resource names.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.