Saturday, July 21, 2007

Using the New File Upload Control

ASP.NET 2.0 includes a new File Upload Web Server control. It works like the HTML File Upload control does except it is object-oriented with Web control properties and you no longer have to manually set the enctype attribute on the form element. What is more significant in terms of security is that you now have a FileName property on the ASP.NET File Upload control. The ASP.NET File Upload control still has the PostedFile property, but you don't need to use it for obtaining the filename anymore. Because the FileName property returns only the filename, and not the full path, there is less opportunity for mishandling the file and opening any security holes:
// the only way to get a file name from an HTML control
string htmlFilePath = fupHtmlUpload.PostedFile.FileName;
// still supported in ASP.NET Web control
string aspNetFilePath = fupAspNetUpload.PostedFile.FileName;
// new FileName property in ASP.NET Web control
string filePath = fupAspNetUpload.FileName;
// use it like this
string fileName = Path.Combine(Server.MapPath("."), filePath);
fupAspNetUpload.SaveAs(fileName);
This discussion assumes that you have weighed the benefits of allowing file uploads and have determined that it is a requirement. Remember that allowing file uploads is another vector that attackers can use to cause Denial-of-Service attacks on your site. You still need to be careful about file permissions you give the ASP .NET user. For example, if you are saving to a directory with a configuration file, the user could upload a file named web.config and overwrite yours. To stop this, put a deny write on the web.config ACL for the ASP.NET user (or the NETWORK SECURITY user on Windows Server 2003). For a more thorough security review, examine the identity that a user is operating to ensure secure settings.

No comments: