Why is this important?
Any functionality related to file management requires careful usage. If attackers are able to influence the input to file access related APIs, then it can have a serious impact. For example, attackers could read the all files on your application server.
In other cases, this can allow attackers to include their own code, or files, that are then executed by the application at runtime.
Check out this video for a high-level explanation on local file inclusion issues:
Another high-level explanation on remote file inclusion issues:
Fixing Insecure File Management
Option A: Sanitize the Filename
The filename provided by the FileUpload API can be tampered with by the client to reference unauthorized files.
Therefore, such values should not be passed directly to the filesystem API. If acceptable, the application should generate its own file names and use those. Otherwise, the provided filename should be properly validated to ensure it's properly structured, contains no unauthorized path characters (e.g., / ), and refers to an authorized file.
- Go through the issues that GuardRails identified in the PR.
- A vulnerable example is shown below:
// This can contain dangerous characters String fileName = item.getName();
- Make sure that the filename is not taken from user input, but based on a unique id.
import java.util.UUID; UUID uuid2 = Generators.randomBasedGenerator().generate(); String fileName = uuid2;
- Test it
- Ship it 🚢 and relax 🌴
Option B: Migrate to Cloud Storage
Nowadays, there is rarely a need to allow users to interact with local files. A better alternative is storing files in dedicated systems, such as AWS S3. This way attackers can't get access the local file system.