Link Search Menu Expand Document

Unrestricted File Upload in .NET

Play SecureFlag Play .NET Labs on this vulnerability with SecureFlag!

Vulnerability example

In the below example of a vulnerability, the filename is user controlled. It could be possible for an attacker to store the file in a different location from the one intended by the application. Moreover, the logic does not perform checks on the file type, allowing content of any kind - including malicious content - to be uploaded:

namespace Application.Utils
{
    public class FileUpload 
    {
        private string uploadedFile;
        private string fileContent;
        private string safeUploadFolder = @"C:\temp\secure";

        public String execute() {
            try {
                string completePathNewFile= safeUploadFolder + System.IO.Path.PathSeparator + uploadedFile;
                if (!File.Exists(completePathNewFile))
                {
                    using (StreamWriter sw = File.CreateText(completePathNewFile))
                    {
                        sw.WriteLine(fileContent);
                    }
                }
                return "SUCCESS";
            } catch (System.Exception e) {
                return "ERROR";
            }
        }
    }
}

Prevention

  1. Restrict the upload to specific file types by implementing an allow list on the extension. If the extension is permitted, implement checks based on the file contents (this depends on the type of files the application accepts).

     if (!validExtensions.contains(System.IO.Path.GetExtension(fileNameAndPath))) {
         logger.Error( "An attempt to upload a potentially malicious file was detected ");
         return "ERROR"
     }
    
  2. Restrict the upload path, and ensure it is outside of the webroot. Ensure the user cannot manipulate the upload path.

     string fileNameSanitized = getFileName(fileNameAndPathFromUser);
     string fileNameAndPathSecured =  safeUploadFolder + System.IO.Path.PathSeparator + fileNameSanitized;
        
     public static String getFileName(String fileNameAndPath) {
         string fileName = System.IO.Path.GetFileName(fileNameAndPath);
         return fileName;
     }
    

References

OWASP - File Upload