How to Restrict Upload File Types in Php
Assuasive file uploads by finish users, particularly if done without a full understanding of the risks associated with it, is akin to opening the floodgates for server compromise. Naturally, despite the security concerns surrounding the ability for end-users to upload files, information technology is an increasingly mutual requirement in modernistic web applications.
File uploads carry a meaning risk that not many are aware of, or how to mitigate confronting abuses. Worst still, several web applications contain insecure, unrestricted file upload mechanisms. This article volition nowadays eight common flawed methods of securing upload forms, and how easily an attacker could bypass such defenses.
No Validation
A simple file upload grade typically consists of an HTML form which is presented to the client and a server-side script that processes the file being uploaded. The post-obit case contains such an HTML form and a server-side script written in PHP.
<form enctype="multipart/form-data" activeness="uploader.php" method="POST"> <input type="hidden" proper name="MAX_FILE_SIZE" value="100000" /> Cull a file to upload: <input name="uploadedfile" type="file" /> <input blazon="submit" value="Upload File" /> </form> <?php $target_path = "uploads/"; $target_path = $target_path . basename($_FILES['uploadedfile']['name']); if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file " . basename($_FILES['uploadedfile']['name']) . " has been uploaded"; } else { echo "At that place was an error uploading the file, please try again"; } ?>
When the PHP interpreter receives an HTTP Postal service
method request of the multipart/form-data
encoding type, the script volition create a temporary file with a random name in a temporary directory on the server, for example, /var/tmp/php6yXOVs. The PHP interpreter volition too populate the global array $_FILES
with the information about the uploaded file as follows.
-
$_FILES['uploadedfile']['name']
: The original name of the file on the client auto -
$_FILES['uploadedfile']['type']
: The mime blazon of the file -
$_FILES['uploadedfile']['size']
: The size of the file in bytes -
$_FILES['uploadedfile']['tmp_name']
: The temporary filename in which the uploaded file was stored on the server
The move_uploaded_file()
PHP function will move the temporary file to a location provided past the user. In this case, the destination is below the server root. Therefore the files can be accessed using a URL such as http://www.example.com/uploads/uploadedfile.txt.
In this elementary example, no restrictions are imposed by the server-side script on what file types are allowed to be uploaded to the server. To such an extent, an attacker could easily upload a malicious PHP that could lead to server compromise.
MIME-type Validation
A mutual fault made when securing file upload forms is to only check the MIME-type returned by the application runtime. For example, with PHP, when a file is uploaded to the server, PHP will ready the variable $_FILES['uploadedfile']['blazon']
to the MIME-type provided past the spider web client.
Since an aggressor could easily command the MIME-type past sending the server a crafted HTTP Postal service
request, such validation is trivial for an attacker to bypass. To such an extent, an aggressor could hands upload a malicious PHP file with an allowed MIME-type that could lead to server compromise.
Blacklisting File Extensions
Another weak validation method that is widely used in file upload forms is to use a blacklist of types of files that take unsafe extensions. Upload forms using this mechanism would check the extension of the file that is being uploaded and compare its file extension to a listing of extensions that the application considers harmful.
While this could be somewhat effective against some file types, the choice of employing a blacklist is a poor one since practically impossible to compile a list of all possible file extensions that an attacker could abuse use, especially if the application is running inside an environment that allows a large number of scripting languages, such as Perl, Python, Cerise, and others – the list is countless. For example, the attacker may change the letters in the extension to their capital forms (.phP, .PhP, .pHP). A whitelisting approach in this utilise instance is by far more effective.
1 possible way an assailant could bypass a file extension blacklist on an Apache HTTP Server is to kickoff upload an .htaccess file with the following contents.
AddType awarding/x-httpd-php .jpg
The in a higher place configuration would instruct the Apache HTTP Server to execute JPEG images as though they were PHP scripts. An attacker would then proceed to upload a file with a .jpg extension (a file extension that is presumably allowed), which would incorporate PHP code instead of an image and this would allow for code execution.
The screenshot below shows an HTTP request to a JPEG file that contains PHP code that invokes the phpinfo()
function.
Double Extensions
Some other concept for bypassing file upload validation is for an aggressor to abuse double extensions where an application extracts file extensions by looking for the .
character in the filename, and extracting the string after the dot character. The method used to bypass this approach is similar to the method used to featherbed a file extension blacklist.
It's important to outset empathise how the target web server handles files with multiple extensions. In this example, it shall be assumed that the target server is the Apache HTTP Server. The post-obit is a quotation of the Apache HTTP Server documentation regarding files with multiple extensions.
Files can have more than i extension, and the guild of the extensions is normally irrelevant. For example, if the file welcome.html.fr maps onto content blazon
text/html
and linguistic communication French then the file welcome.fr.html will map onto exactly the same information. If more than than one extension is given which maps onto the aforementioned type of meta-information, and so the one to the right volition be used, except for languages and content encodings. For case, if .gif maps to the MIME-blazonimage/gif
and .html maps to the MIME-typetext/html
, and so the file welcome.gif.html volition be associated with the MIME-typetext/html
.
Therefore, a file named alphabetize.php.123 will exist interpreted as a PHP file by the Apache HTTP Server and it will exist executed. This, of class, will just work if the last extension (in this instance .123) is not specified in the list of MIME-types known to the web server. This bottom-known characteristic of the Apache HTTP Server could be very dangerous for a number of reasons. Knowing this, an attacker could upload a file containing malicious code (such as a web shell) and bypass the file upload form validation.
A far meliorate approach to securing file upload forms is to utilise a whitelisting approach. With this approach, but files that match a known and accepted file extension are allowed. Even so, in some cases, this approach volition non work as expected. For case, when the Apache HTTP Server is configured to execute PHP code, there are ii ways one can specify this: using the AddHandler
directive or using the AddType
directive. If the AddHandler
directive is used, all filenames containing the .php extension (.php, .php.jpg) volition exist executed as PHP scripts. Therefore, if an Apache HTTP Server configuration file contains the following, it may be vulnerable:
AddHandler php5-script .php
On an Apache HTTP Server with the above configuration, an attacker can upload a file named filename.php.jpg, featherbed the validation, and execute code.
Checking the Image Header
When epitome upload only is allowed, most web applications usually validate the image header by using a server-side function such as getimagesize()
in PHP. When called, this function volition return the size of an paradigm. If the file is non a valid prototype, meaning that the file header is non that of an image, the function will return Fake
. Therefore, several web applications typically check if the part returns Truthful
or False
and validate the uploaded file using this data.
If an attacker attempts to upload a uncomplicated PHP shell embedded in a JPEG file, the office will return simulated, finer stopping the set on. Nonetheless, even this approach tin can be hands bypassed if the Apache HTTP Server is using the AddHandler
directive described to a higher place. If an image file is opened in an image editor, such as GIMP, i can edit the image metadata to include a annotate. An assailant would insert some PHP lawmaking here as shown below.
The prototype will still have a valid header; therefore information technology bypasses the getimagesize()
cheque. Equally seen in the screenshot below, the PHP code inserted in the prototype comments still gets executed when the image is requested past a browser.
Protecting the Upload Binder with .htaccess
Another common method used to secure file upload forms is to restrict execution of scripts in an upload directory using .htaccess configuration that would typically contain the following:
AddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi Options –ExecCGI
The to a higher place is another type of blacklist approach, which in itself is not very secure. Furthermore, as warned in the PHP documentation, the move_uploaded_file()
function will overwrite any file if the destination file already exists. Because uploaded files can and will overwrite the existing ones, an attacker could easily supersede an existing .htaccess file with a modified 1. This will allows execution of specific scripts which can help compromise a server.
Client-Side Validation
Another common security measure in file upload forms is client-side validation of files to exist uploaded. Typically, such an arroyo is more than common in ASP.Net applications, since ASP.NET offers easy-to-apply validation controls.
These types of validation controls allow an application to do regular-expression checks upon the file that is being uploaded, to check that the extension of the file being uploaded is specified in the list of allowed extensions. Below is a sample lawmaking taken from Microsoft'southward website.
<asp:FileUpload ID="FileUpload1" runat="server" /><br /> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload File" /> <br /> <br /> <asp:Characterization ID="Label1" runat="server"></asp:Label> <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ErrorMessage="Only mp3, m3u or mpeg files are allowed!" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\west+)\$?)(\\(\w[\w].*)) +(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" ControlToValidate="FileUpload1"></asp:RegularExpressionValidator> <br /> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="This is a required field!" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
This ASP.NET code uses validation controls, so the terminate-user is only allowed to upload .mp3, .mpeg or .m3u files to the web server. If the file type does not lucifer any of the specified extensions, the validation command throws an exception and the file won't be uploaded.
Since this blazon of validation is washed on the client side, a malicious user tin can hands featherbed information technology. It is possible to write a brusk client-side script that will practice the validation instead of the script provided past the web application. Without using a spider web browser, the attacker can send HTTP POST
requests to the application in order to featherbed the client side validation and upload a malicious file.
Suggested Solution
The following is a list of all-time practices that should be enforced when file uploads are allowed on websites and web applications. These practices volition help avoid file upload vulnerabilities in web applications that are served using Apache HTTP Server, notwithstanding like rules could hands be applied to other servers both on Linux and Windows.
- Define an .htaccess file that will only permit access to files with immune extensions.
- Practise not place the .htaccess file in the same directory where the uploaded files will exist stored, instead, identify it in the parent directory. This way the .htaccess file can never be overwritten by an assailant.
- A typical .htaccess which allows only GIF, JPG, JPEG, and PNG files should include the following (this should be adapted equally necessary for specific requirements). The post-obit will besides forbid double extension attacks:
deny from all < files ~ "^w+.(gif|jpe?g|png)$"> order deny,let let from all </files>
- If possible, upload the files in a directory outside the server root.
- Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
- Create a whitelist of accustomed MIME-types (map extensions from these MIME-types).
- Generate a random file name and add the previously generated extension.
- Don't rely on client-side validation merely, since it is not plenty. Ideally, both server-side and client-side validation should be implemented.
Frequently asked questions
faulkhimakinecity.blogspot.com
Source: https://www.acunetix.com/websitesecurity/upload-forms-threat/
Post a Comment for "How to Restrict Upload File Types in Php"