Catch the security flaw #6

If you can find the security issue with this piece of code, write about it by adding a comment to this blog post.

This is the scenario:-

1. There is a Web site that allows end users to upload their pictures.

2. On the Web server, the Web site is physically located at C:\Inetpub\wwwroot\sampleapp, which is obviously a virtual directory.

3. The uploaded pictures are stored on the file system in the following directory C:\Uploads\{username}. This is not a virtual directory. {username} is the logged in user’s username and can contain only alphabets and numbers.

This is what the page looks like to the end user.

fileupload

This is the code that gets executed. The code for the UploadPicture.aspx.cs file is this.

    1: public partial class UploadPicture : System.Web.UI.Page
    2: {
    3:     protected void Page_Load(object sender, EventArgs e)
    4:     {
    5:         lblUserName.Text = "Welcome " + User.Identity.Name;
    6:     }
    7:     protected void btnSubmit_Click(object sender, EventArgs e)
    8:     {
    9:         new UploadHelper().UploadFile(fileUploadControl, User.Identity.Name);
   10:     }
   11: }

The code for the UploadHelper.cs file is this:-

    1: public class UploadHelper
    2: {
    3:     private string uploadFolder;
    4:     public UploadHelper()
    5:     {
    6:         uploadFolder = @"C:\Uploads\";
    7:     }
    8:     
    9:     private void SetUpUploadFolder(string userName)
   10:     {
   11:         uploadFolder += userName + @"\";
   12:         if (!System.IO.Directory.Exists(uploadFolder))
   13:             System.IO.Directory.CreateDirectory(uploadFolder);
   14:     }
   15:     
   16:     public string UploadFile(FileUpload fp, string userName)
   17:     {
   18:         string extension = fp.PostedFile.FileName.Substring(fp.PostedFile.FileName.LastIndexOf("."));
   19:         if (extension.ToLower() == ".jpg" || extension.ToLower() == ".gif")
   20:         {
   21:             string strFileName = fp.PostedFile.FileName.Substring(fp.PostedFile.FileName.LastIndexOf("\\") + 1);
   22:             SetUpUploadFolder(userName);
   23:             string strFullPath = uploadFolder + strFileName;
   24:             fp.SaveAs(strFullPath);
   25:             return strFileName;
   26:         }
   27:         return null;
   28:     }
   29: }

If I login to the Web site as “varun” and upload a picture with name mypic.gif, it gets uploaded to this folder on the Web server:-

C:\Uploads\varun\mypic.gif

 

Happy Hunting!