1

I have ActionResult to download a file in which i passed file name as parameter to download.

[HttpGet]
public ActionResult OpenFile(string fileName)
{
    try
    {
        /*Get the folder name from the config file*/
        string FolderName = Convert.ToString(WebConfigurationManager.AppSettings["DownloadAttachments"]);
        FolderName = (FolderName == null ? "DownloadAttachments" : FolderName);

        return File(new FileStream(Server.MapPath("~/" + FolderName + "/" + fileName), FileMode.Open), "application/octetstream", fileName);
    }
    catch (Exception ex)
    {                
    }

    return Content("<h1>File Not Found.</h1>", "text/html");
}   

But User can able to download web.config file of the application also by Passing web.config file name as parameter.

Its any better way to avoid this security breach other than this condition..

if (fileName != null && !fileName.ToLower().Contains("web.config")) 
Ninita
  • 1,081
  • 1
  • 16
  • 39
  • 2
    The best way is to keep files that you want to share in a common directory root and always start your file path build up from within that root. If you have a web.config file within that root exclude it manually or build a list of files to exclude if you have additional files that you wish never to share (ie. create a black list). – Igor Jan 13 '16 at 15:01
  • See this: http://stackoverflow.com/questions/275781/server-mappath-server-mappath-server-mappath-server-mappath – Maria Ines Parnisari Jan 13 '16 at 15:02
  • 1
    your method is fine as it will only look for the file in "DownloadAttachments" folder, and surely the web.config should not be in that folder. – Preet Singh Jan 13 '16 at 15:02
  • Or you can configure IIS to not serve certain file types like *.config. See http://serverfault.com/questions/27010/how-do-i-prevent-iis-from-serving-a-type-of-file – Georg Patscheider Jan 13 '16 at 15:24
  • @GeorgPatscheider - IIS doesn't serve web.config by default, the problem here is that his application code is going around the IIS serving, and there's no way for IIS to know which file is being served here. – Erik Funkenbusch Jan 13 '16 at 16:00

0 Answers0