How to make a safe file upload script in php? - php

i check the file for its extension, and mime type - is there anything else i can be doing to help make file uploads safer?
its for an avatar (so all the images are in one folder). i was thinking about using htaccess to forbid any php execution just incase some php file found its way in there. what do you think?

Neither file extension nor mime type can give you 100% security that you are dealing with a image file. But as long as you're not going to execute the file (e.g. by using include()), that is not a problem and you do not need to check for PHP code or anything else. The only security breach imaginable using a forged image file would be something that exploits the browser's rendering engine. This is impossible to protect effectively against from server side and is the browser vendor's responsibility.
So, as long as you make sure you use is_uploaded_file() and move_uploaded_file() when handling the upload, you should be fine, at least on the image format front. Make sure you read #bobince's post below and follow the link, it contains a bunch of great information on other security aspects when dealing with files.
You could however, to provide totally maximum security, of course copy the image into a new image container using GD's imagecopy. This would erase any ID3 and other header information contained in the file, and probably destroy any exploit attempts (GD would probably choke on such a file and return an error). This works for GIF, JPEG, and PNG only, of course, and you may run into some issues like alpha channel and colour profile problems.

Never use user-submitted filenames at all; make up new ones like «random number».jpeg. ‘Sanitising’ filenames is harder than you think, especially if the app needs to be able to run on a Windows server.
For images, use the PHP getimagesize function to determine the filetype of an image, rather than looking at the highly-unreliable filename and mimetype submissions. Disallow uploads that don't parse as images.
For files that are intended to be downloaded, use the Content-Disposition: attachment header to stop IE sniffing for HTML content and displaying it in the browser.
For files that must display inline you'll have to serve them from a different hostname to your main site, otherwise HTML content inside them can cross-site-script into your security context.
Making a file upload feature secure is hard. More discussion.

Related

Are there risks of exploit with uploading a file this way?

I have a simple form in PHP that make the conversion of a file from XML to SQL or vice versa. In this form, there is an input where the user can upload a file with xml or sql extension. I do various check (extension of the file and file size), I read the file using the value tmp_name of the global array $_FILES, I do some operation for the conversion, and then I save the modified file in my server (compressed in gz) with the original name of the file in the client machine in order to give the link to the user and download it.
My question are: There are risks of exploit with the steps that I listed above? In general, there are risks of exploit with uploading a file? Or risks, to upload the file with the original name in the client machine?
Thanks.
There are always risks of exploit when allowing users to upload files, so it's good to be worried.
You say "I do some operation for the conversion", so while I cannot comment specifically on the safety of this operation, there could be risks here depending on the operation and the content provided to it (e.g. buffer overruns, invalid data).
I'm assuming you are saving your file with a .gz extension.
Saving with the client filename could pose compatibility problems if you do not clean the filename at all. There are differences in disallowed (or problem) characters between filesystems, such as & in Unix or : on Windows. Sometimes if you simply save a file, and simply read it again your code won't "find" it, unless you escape or strip all these characters properly.
The client filename could possibly pose a risk, if the name could have for example a path embedded into it. A presented filename such as "../../../../home/user/file" could possibly trick your program into overwriting a file, as long as the permissions were very badly implemented and you are simply concatenating paths. At worst I'd say this would be an annoyance or DoS attack - limited to overwriting gzip files and "breaking" them.
The client filename could possibly overwrite another user's files? I'm not sure what your namespacing is, but a clever attacker could try to trick another user into downloading their xml/sql file by naming it cleverly.
Also if you could guess someone else's filename, you could guess the resulting URLs and war-dial through them looking for content.
All of these risks would go away, if you used a nice GUID to name the file. Or mapped it to each user's session (e.g. file1.gz is only valid to that user's session).
I generally don't use client names, or seriously validate and clean them before re-presenting them.
The main risk of uploading files with php (and other interpreted languages, as a matter of fact) is that user can upload a .php file and if it's stored inside a web-root, then execute it.
From your question, it seems you only allow certain non .php extensions. Make sure you do this check on server-side, not just on the client. Also, if you don't need to serve the uploaded file on web afterwards, store it outside of your web-root. If you force the filename and extension after upload (not keeping the original one), then you can have even more control over what's going on in your part of the system.
Other file types can also be exploited (images for example, see https://imagetragick.com/) so it's a good idea to check specifically for the file-types you want uploadable.

PHP file renamed to JPG and uploaded to server a threat?

We have a server that has been compromised that is running WordPress and Magento and is running them on about 5 domains all on the same server.
The hacker has been uploading there malicious scripts through all the file-system in hundreds of locations. It is a nightmare at this stage and I am still unable to find the entry point.
I did just notice that one of our AJAX image upload fields allows me to rename a PHP file as a .jpg and upload the file to the server.
When I access the PHP .jpg file in the browser is serves a broken image.
So I am not sure if the hacker would be able to upload a PHP file here and access it as a PHP file or if it would just serve it as a broken image fore like it did for me in the browser?
Any ideas on how much of a security threat this could be? Could it potentially be my entry point where hacker gained initial access? Or is the fact it serves as a broken image instead of processing the PHP file when I load in my browser mean that its somewhat secure?
Any help appreciated, thank you
Hard to say if the hacker has done something without actually checking what's there.
Regarding how to secure future image uploads I would advice using a function like finfo in PHP http://php.net/manual/en/function.finfo-file.php to find if a file belongs to any of the approved mime types, which btw, you should restrict to only a limited type of image types.
Also you should consider not allowing the use of the original image, but instead an adjusted version of it, to avoid that users end up downloading huge images or things like that.
Answer:
Usually (depending on the web server configuration) no one can execute a PHP file if it has a different extension, they could have upload it, but they can't run it, at least in any common configuration.
So, in theory you should not have to worry for that specific thing, but do be worry that someone is spending time in trying to hack you and that means you should expend time protecting the site and server.
I would recommend searching for articles on how to protect your specific server and configuration and to make sure you update your software, OS and such to the latest security updates.
Being able to upload a file with .jpeg file extension but PHP content is not a vulnerability in itself. However:
if the attacker is writing all over the file system you might have an upload function with a directory traversal vulnerability which will need fixing, ideally by not letting the uploader choose their own filename at all;
there are other problems to do with cross-site-scripting when you let users upload content to be served from the same hostname as the site;
it may be worth checking an uploaded file using something like getimagesize() to ensure that you have a JPEG file and non-ridiculous dimensions, but given the possibility of ‘chameleon’ files that can be interpreted as multiple different types this is not necessarily watertight, so this is a ‘defense-in-depth’ measure at best.
Getting a web server to run a .jpeg file as PHP code could happen by:
being able to write to server configuration to associate .jpeg with the PHP handler. Typically this would happen because another vulnerable file upload feature allowed an attacker to write a .htaccess file in the same directory for Apache to pick up.
a PHP script with a Local File Inclusion security hole. Typically this would be code like:
include("include/$variable");
where an attacker can get content into $variable, to point to something.jpeg. Generally include/require should never be used with variables unless those variables are explicitly limited to a few known-good values.
The other likely possibility if you have a load of malicious pages uploaded to your server is that your server login is compromised.

Safe way to upload GIF

I'm implementing image upload solution.
Now that everything works fine, I started thinking about security.
After researching much on internet, I found that safest way to upload image it recreate it.
For that I use GD Image Editor, which gets image size and resizes it to -1px from every side.
The problem which rose is that I cant recreate GIF image, as it becomes static (and ugly).
My question is, if anyone has done something and what options I have? Maybe some other solution to safely allow users to upload GIF imagies?
First and most important thing is to assign your own filename and extension to any uploaded image. Since your webserver decides on what to do with your file depending on it's extension, you should make damn sure it is '.gif'.
Renaming the whole file and not only it's extension ensures noone finds a ways break your extension safety and inject his own extension.
Never rely on any mime type sent to determine file type. Mime types can be manipulated and are not reliable. If you HAVE to check your file, use something like getimagesize(). But again, this is not necessary if you set the filename and extension anyways.
http://www.php.net/manual/en/function.getimagesize.php
You should also ensure file size is not to large to avoid your server running out of space.
Ensuring a login before uploading and only allowing a reasonable number of uploads per user is also a nice safety agains running out of space.
So, in short:
Set filename and extension
Dont rely on sent filename
Dont rely on sent mime type
check maximum filesize
ensure user can not spam files

Securing files in PHP site

I've got a site that accepts user-uploaded files (images, pdfs, word docs, etc.) then allows other users to download them.
I realize this presents a security risk, since malicious users could upload scripts etc. that masquerade as useful files.
My question is this-- is it enough to check the mime type of the file being uploaded using PHP (mime_content_type or finfo) and set the file to read only (non-executable), or must I also store the uploaded files in a directory that is outside the web root? I would think this would eliminate most of the risk from the uploaded file, but I'm not sure. Performing a virus scan on uploaded files is not possible in this situation.
Thanks for input.
A common practice is to upload files outside the document root, and typically using randomized filenames which are then mapped to the correct item/object/post in the database. If additional permissions are needed to access the files, make sure you check them before allowing downloads, and of course you'll have only authenticated users uploading.
Fileinfo finfo_ is useful for validating most mimetypes, at least to verify that something called ".txt" is actually a text file and not a binary blob, or that a ".jpg" really appears to be a jpeg based on its first few or last few bytes. It may require some extra work sorting out MS Office mimetypes, as if I recall correctly, they all come out as application-msword. But you can then use the file extension to figure out what it is really supposed to be (xls, ppt, doc, etc).
A PHP script then supplies the downloaded file, rather than the web server directly serving it. For that reason, you should store the mime type along with it, so that you can serve the appropriate headers.
header("Content-type: application-whatever");
header("Content-length: size-of-the-file-in-bytes");
I can recommend you use every tool at your disposal to test for the file type. But know that there are other ways a hacker can implant a dangerous file.
Your best bet is to have the files be uploaded to a different server. One that can only host files.
I would check the mime type of the file but I wouldn't rely on this. Even if the file is a full blown .gif and contains a comment in its id3 tag which is a php, it can be executed with a local file include. A safer approach would be store files in the database using a long blob datatype. However this kind of overhead is crap.
The best solution from the perspective of security, scalability and perforce would be to use a no-sql database like CouchDB.
A few things to keep in mind, don't trust $_FILES[]. $_FILES['type'] could be anything the attacker wants so there is no point in checking it from a security perspective. And $_FILES['name'] could have nasty input like ../../../. Its best to rename files to the primary key and then store information about that file in a relational database (like mysql).

Is this file uploading method secure via PHP?

I use the PHP language for file upload and want to know that the following method that I use is secure or not?
I am using simple method for file uploading,
I check the file name from $_FILES['userfile']['type']
and then if it's having an allowed file extension, I upload the file with some random number.
Like if it is abc.zip it may become 8w43x9d.zip.
Please tell me: is it a really bad method for file upload?
Randomly-generated safe filenames are definitely a good thing. However if you allowing the file extension through to the webroot you'll still need to ensure that the extension is something that won't cause any problems on the server, such as .php (OK, PHP handling should be disabled in the web server for upload directories, but still). There are also problems if you are on a Windows server, where trailing dots and spaces will confuse the filesystem; make sure you lock down the extension to a few ‘known good’ values.
Unfortunately the ['type'] property cannot be relied on at all. Some browsers won't fill a content-type in, others will put the wrong type because their OSes are set up badly (an infamously unhelpful one is that IE on Windows by default calls JPEG image/pjpeg), some will always say application/octet-stream or even text/plain.
Even the ['name'] property is unreliable; apart from browsers lying or obfuscating the value, there's always the chance a given type will have an unexpected file extension on that particular machine. Or, for Mac and Linux clients, it's entirely possible an uploaded file won't have an extension at all (or may even have the wrong extension for the type the OS sees it as).
So yeah, this is all a bit of a mess. Whilst sniffing for type from the Content-Type submission or filename extension can be useful to guess what default type a file should be, it's entirely unreliable, so it's a good thing to provide a manual method to choose the type of a file in addition. Alternatively, if you are serving the uploaded files as attachments (eg. through a PHP script setting Content-Disposition: attachment), you can often get away with just calling everything application/octet-stream and letting the user sort it out when they save it.
If you're not serving as an attachment, you may have a security problem. IE will happily sniff many filetypes you serve it for <html> tags and treat those files as HTML even if you tell it they're something else. Then it can display them inline in the browser, and lets them inject script into your security context. If you have anything significant in your security context, such as user accounts and cookies, that's a cross-site-scripting security hole. The workarounds for this are serving as attachment and/or serving from a different hostname that is not in your main site's security context (typically, a subdomain is used).
Allowing users you don't completely trust to upload files to your server turns out to actually be a much more difficult task than the trivial example code in PHP tutorials would lead you to believe. :-(
From the PHP Manual:
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
I wouldn't trust anything the user or user's browser sends me.
If you're trying to learn, I would take a look at existing secure sources, such as HTTP_Upload from PEAR. You might even consider using the Beta version.
Addition to above post, we are relying on FileInfo or SplFileInfo, so far it has proven to be the best option for our needs.
OK, in case of images we can use getimagesize($_FILES['userfile']['tmp_name']);
and can validate them but what in case of ZIP, RAR and PDF files?

Categories