Insecure File Management
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 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: Avoid Path Traversal Attacks
A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the expected directory. By manipulating variables that reference files with "dot-dot-slash (../
)" sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files.
References:
- OWASP: Path Traversal
- OS Command Injection, Path Traversal & Local File Inclusion Vulnerability - Notes
- Go through the issues that GuardRails identified in the PR.
- Look for patterns like this:
[RedirectingAction]
public ActionResult Download(string fileName)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
- Replace it with this:
private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars();
[RedirectingAction]
public ActionResult Download(string fileName)
{
if (fileName.IndexOfAny(InvalidFilenameChars) >= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
- 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 to the local file system.
References