Open Filestream For Writing - Force Manipulation Path

Looking for a Path Manipulation solution to allow file opening:

public FileStream OpenFile(string directory, string filename)
{
    FileStream fs = null;
    string pathname = string.Empty;
    pathname = Path.Combine(directory, filename);
    fs = new FileStream(pathname , FileMode.OpenOrCreate);
    return (fs);
}

      

This code runs in a .NET application but is NOT written to the virtual directory.

The Fortify hint / assertion states that it whitelists valid directories, but this is tantamount to hard-coding directories in the application. It may be safe, but it is not good programming practice.

Thank you in advance

+3


source to share


1 answer


@James Nix provided the reason why Fortify discovered the vulnerability (in a comment):

You get this output because this method takes a "user-supplied path" and a filename. If the attacker were to send this method to parameters directory=C:\Windows

and filename=notepad.exe

, they could overwrite notepad.exe

something malicious if your application had write permissions to this file. - James Nix January 6 at 5:17 pm

If you are interested in fixing vulnerabilities, you need to:



  • If possible, change the method signature from general to specific.
  • Provide a fixed prefix for the provided file path (for example, "D: \ Temp \" or Application ("files_root") that you can add to your application configuration.
  • Do not allow "/" or "\" or ".." or ":" in the filename argument. Or just limit something like 8.3 if needed.
  • Do not allow ".." or ":" in the path argument. Or, just limit the valid character range (e.g. az).
  • Do not return an open FileStream object. You lose control over whether it is closed (Denial of Service vulnerability). Instead, get the data you want and close the FileStream before returning from the method.

If you need more focused advice to correct the situation, you need to describe what your application should do with this method.

+1


source







All Articles