validation.net-4.8

Can the properties of an uploaded file (HttpPostedFileBase) be spoofed?


Specifically, I am wondering if the ContentLength property of an HttpPostedFile can always be trusted, or if it is necessary/good practice to read the contents of the file and verify the length yourself.

The reason for this question is that other posts have mentioned that it may be a good idea to check the "magic numbers" of a file to confirm its MIME type, but I can't see why that would be necessary if HttpPostedFileBase provides a 100% reliable method of getting this information via the ContentType property. So either it is unnecessary to run these checks, or not all properties of HttpPostedFileBase can be trusted all the time.


Side note: I am aware that ASP.NET offers a maxRequestLength attribute in the httpRuntime element of Web.config, but I would like to treat it as defense-in-depth instead of solely relying on external configuration for internal validation.


Solution

  • The property HttpPostedFileBase.ContentLength can be spoofed since any derived class from HttpPostedFileBase can return any value for this property (useful for unit tests).

    The property HttpPostedFile.ContentLength cannot be spoofed, the client doesn't send the file size anyway (unlike the file name and content type).

    The property HttpPostedFileWrapper.ContentLength cannot be spoofed, since it is just a wrapper for a HttpPostedFile instance.