Defense Against File Upload Vulnerabilities
The core idea of preventing File Upload vulnerabilities is to ensure that the uploaded files are not parsed into executable scripts by the server, which leads to unexpected consequences of deviating from the function design.
Restrict File Upload types
(1) blacklists often cause omissions or case-insensitive bypassing. Therefore, whitelists are usually used to restrict the security of file types, such
Image:. jpg,. png,. gif,. bmp
Documentation:. doc,. pdf,. txt
Compressed package:. rar,. zip
(2) The type restriction cannot only be applied to the front-end, and the js restriction can be easily bypassed. The latter-end restriction can be considered in the following aspects:
Check the extension. Note the % 00 truncation or the file name contains spaces or other special characters.
If necessary, rename the user-uploaded file to prevent file name attacks during upload.
MIME type detection. Malicious Code uses valid extensions for camouflage.
For image uploads, you can consider secondary rendering/compression. It is not difficult to embed the script into a completely legal image. However, secondary rendering can completely destroy malicious code.
Restrict the size of uploaded files
(1) restrict the size of uploaded files to prevent Dos caused by memory and disk depletion.
(2) You can configure the maximum Post size allowed by the web server.
(3) The size of the uploaded file can be obtained at the code level and further filtered based on different file types.
Ensure that the uploaded files are correctly returned according to the functional design when accessed.
(1) set the File Upload directory to a static resource directory to prevent parsing as a script for execution.
(2) Use the proxy page to hide the real path of the file, such as/attachment/getfile. php? Fileid = 1, 123
(3) when using the preceding method, ensure that the Content-Type is consistent with the actual file Type.
(4) If the file cannot be displayed on the page and can only be downloaded, set Content-disposition: attachment
Others
(1) Ensure that the uploaded files are placed in a safe path. If necessary, the uploaded files can be stored on a remote server other than the web server.
(2) ensure that the web server version is up-to-date and prevent accidental File Parsing due to web server Vulnerabilities
(3) Some File Upload attacks work with the local file inclusion (LFI) vulnerability. Therefore, make sure that the web Service does not have the LFI vulnerability.