Does your web application allow the user to upload anything? This is one of the most terrifying parts of secure web development. You’ve made a decision to permit users to upload files. Perhaps they’re image avatars? CSV lists for you to import? Whatever they are, you’re going to need to become extremely paranoid, very quickly.
Don’t trust the file name
Surely you can just grab the filename, combine it with your “user uploads” folder, and all will be well? Absolutely not! Consider the following piece of code:
string saveAs = Path.Combine(userUploads, postedFile.FileName);
File.WriteAllBytes(
saveAs,
new BinaryReader(postedFile.InputStream)
.ReadBytes(postedFile.ContentLength));
In most situations, this code will run well. Files will upload correctly into the user uploads folder, and things will tick over nicely. But the subtle problem here is that the FileName property is whatever the user’s browser specifies. In most modern browsers, it is purely the filename. For example, “me standing on beach.jpg”. But for some older browsers, it’s the fully qualified filename. For example, “c:\documents\me standing on beach.jpg”. So the code above can write into folders other than the user uploads folder.
At the very least, use Path.GetFileName to remove any possibility of a path being present in the name. Better yet, generate filenames yourself.
Don’t trust the filetype
This one’s easy, but embarassingly easy to overlook. Only allow users to upload files that end in the extension you’re expecting. If you’re only allowing images, then deny any upload that doesn’t end in “.jpg”, “.jpeg”, “.gif”, etc. Importantly, block the upload BEFORE you write any bytes to disk anywhere
Don’t trust the content
A more complicated problem is that of the actual content being uploaded. This is more of a problem that varies by context, so I can only give high level pointers. But essentially, you need to try and filter out content that is unexpected or invalid for the situation. An example would be a user trying to upload an avatar image that was 100mb, or a text file that contained binary data. You should always be thinking of what type of data you are expecting, and blocking or quarantining anything that is not right.
Recent Comments