Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Security flaw in this code approach

Am wondering if there would be any security flaw in this approach. I am writing a piece of code which allows users to upload files and another set to download those files. These files can be anything.

  1. User uploads the file (any file including .php files), it is renamed to an md5 hash (extension removed) and stored on server. A corresponding mySQL entry is made.
  2. The user trying to download the file, uses say download.php to download the file where the md5 file is sent (with the original name).

Is there someway in which anyone can exploit the above scenario?

like image 863
Alec Smart Avatar asked Mar 18 '10 10:03

Alec Smart


1 Answers

Well, in theory no. There shouldn't be way to exploit that system. However, there are several things I would like to point out to you that you may not have thought of.

First, since the files are downloaded through a PHP file (assuming readfile() with appropriate headers), you should place the files in a place that is inaccessible to the users. On apache servers, generally the easiest approach is just to put a .htaccess file into the upload directory with "deny from all" in it to prevent external access. If users don't have access to the files externally in the first place, then there isn't really any worry about file extensions causing trouble (though, renaming for storage purposes is still a good idea)

Secondly, naming the files by the hash may not be such a brilliant idea, since you might get collisions eventually. What if two files happen to have the same hash? Not to mention, computing the hash is a bit on the slow side, especially for bigger files (if computed from the file contents, and not the name). Since you store an entry to the database, I would assume you have some sort of primary key there (like an auto_increment field). I would recommend simply using that ID number as the file name for storage to avoid collisions (in case you don't know, you can get the ID generated by last insert via mysql_last_insert_id())

Of course, there may always be problems with files containing viruses, which can infect the machine downloading the files, but that's really outside the scope of this question and doesn't affect the server itself in any way.

like image 163
Rithiur Avatar answered Oct 14 '22 03:10

Rithiur