Trying to secure multimedia files - php

I made a database system with PHP and MYSQL. It has a lot of sensitive information so I'm trying to put the best security.
I have a question about video and audio files. I want only people that are logged in and that actually have permission to download the files to be able to download them, not anybody that just points to the folder where the media files are. How can I do that?! Thanks!

Call your files via a php wrapper, i.e. <img src="files/file.php?id=oj348jfoj" /> and in your file.php you output the file with image headers if the user has the rights to view the file. In you table, you have the real image URI that corresponds to your oj348jfoj token, and this is what you file.php loads and outputs as image to the requester. This way the real URI of your server files stays hidden and you get to check access rights for every image load.

You need to stream the file using PHP. Pass the name of the file using the query string and then write it to the page. You can check the permissions before you stream the file over.
Pseudo-code:
header("Content-Disposition: atachment; filename=$filename");
header("Content-Type: application/octet-stream");
header("Content-Length: ".filesize("$path/$filename"));
header("Pragma: no-cache");
header("Expires: 0");
$fp=fopen("$path/$filename","r");
print fread($fp,filesize("$path/$filename"));
fclose($fp);
exit();

So. The files have to be on the server, that's clear. Here's a suggestion: hide them somewhere. Then, when a user hits download, copy its contents to a temporary location and save into a MySQL table with expiring 10-30 minutes (could be more if HUGE files). Then the user could download from that link. Finally, run a cronjob every 10-30 minutes (the same amount) that deletes expired files.
This isn't 100% security as a non-logged in can download too, but only if a logged-in shares the URL, so then they could simply send that to them.

Related

Only allow file download to logged in users

Is there a way, and if so, how, to allow only logged in users to download a file using Joomla and PHP?
Here is the situation:
When users are logged in, they can click the product's download link to be brought to a download page. They click download, and are able to download the file. However, these users may be beta testers, or the file may be sensitive, so I need to, somehow, hide the direct link to the file. Be it a PHP file or something that checks if the user is logged in (I'm already familiar on how to do that) and send the file to them. (Rather than a link to a .zip file for instance, a link to a .php page that will push the file to them)
Link to a PHP file in which you check if the user is logged in, and then you can initiate the download using the correct headers:
<?php
header("Content-Disposition: attachment; filename= filename.ext");
header("Content-type: application/octet-stream");
and then pass the file's contents through using fpassthru()

Renaming a folder for each download

EDIT: We allow our product download after submitting a simple form.
To avoid the owners of "illegal websites" learning where our product downloads are located, I was thinking about renaming the download folder after every download.
How can I do this in PHP?
Instead, verify an authenticated session and then stream the download via PHP.
Then if any illegal website tries to download your file, they will find they need to be authenticated first.
Don't rename the directory. It will break if multiple users download the file simultaneously. Instead serve file via PHP like:
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
Yes, - you can do it by using rename PHP function, but what a strange approach? You better customize access settings for files which can be accessed via HTTP request and which can not. Let just registered users download files and identify real users from robots using user session cookies and, probably, add captcha if those file are so significant.
A possible solution might be to do a PHP system call to create a temporary softlink to your installer, and remove that softlink after a fixed amount of time.
But indeed, it seems you've got the wrong idea when it comes to safeguarding your installer.
A good way is to use a combination of .htaccess & key
.htaccess
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)/([a-z0-9]+/i)$ serve.php?file=$2&key=$1 [NC,L]
After someone purchases your file set a key and ip in there customer account in mySQL send them the link to download via email (http://yoursite.com/key1234567/your.pdf) note they can only download once
person clicks download
then with serve.php
you check the key against there ip in there account and mark as downloaded
sql check on ip and key match
if($allowedToDownload===true){
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('hidDen_ArEa/'.basename($_REQUEST['file']));
}
Nothing personal, but it's not most clever idea.
Check $_SERVER['HTTP_REFERER'] - if this variable is not empty and not contains address of pre-download page, redirect user to some your pre-download page.
edit: checking HTTP_REFERER is not 100% protection against bots, but other methods (such as authentication) can be more annoying for users.
Also, sessions or cookies (with temporary token) can be used.
Best solution so far is the following: http://www.devshed.com/c/a/PHP/Simple-and-Secure-PHP-Download-Script-with-Limits-Tutorial/.
Thanks to all of you for directing me to this approach.

How do you create a database log when a website user has downloaded a file through php?

I am required to create a small website that people access through a html login/password form where a session begins. I have completed this however I need to log when a user clicks a link and downloads a file.
I need to record which user has clicked to downloaded the file.
All I have at the moment is a link to a download.php as follows
link
download
file
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="somefile.pdf"');
readfile('somefile.pdf');
how would I go about logging who has actually downloaded a file?
It would be very trivial to record the session login details at the top of the download.php file. It's not necessary to redirect via another intermediary file.
If you want to stop people directly linking to download.php you should put some security check at the start of download.php.
You could create a table in your database for the logging, with the user id, dates etc.
In download.php simply have an if statement to determine whether they're logged in (i.e. session is set) and then insert a new row into your logging table, complete with the user id, dates and other data.
Ok two solutions:
First the easy one. Don't do anything! Yes, apache already logs all access to every file in access.log file. I know this is the lazy way but would it satisfy?
Second, ok let's say you need a better way. Does it need to be in the database or can it just be a file? If so, then in your down file open a database connection write to a table and close and then read the pdf file. Or you can write to a flat file if it can be simple as that.

Control Access to Filesystem with PHP

I previously posted here:
Controlling Access for Trial Subscription
Since this is a new question based on suggestions there, I thought I should start a new post. If this should have been an edit, please let me know for the future.
I think the solution I'm going with to control access will be to upload a file and hash the name. The file will be in the format:
/uploads/#############.pdf
A link will be sent to subscribers. The first time they come to the site, they'll be asked to create a "pin" and a "hint" to remember. Then can then access a landing page to list their items via an email address/pin combo.
My question is: I know I can control the access to the page that shows what items they can view, but is there a way to control the /uploads/[file] to only be download-able after some kind of programmatic check? I can't think of any way to do this....
Thanks again.
D.
Your pdf files don't have to be in a user viewable directory. They can be outside your web root. That way, noone can actually browse to www.yoursite.ext/uploads/2395wrfhgt.pdf to download it himself or share the link with others.
In order to download the pdf you'll have a dedicated script that will do all the access checks on the user that's requesting it, and if all ok it will set the appropriate headers, read the file from the filesystem, and print it out to the user.
So, lets say your site is at /var/www/site/htdocs/ and you upload every pdf into /var/www/site/uploads/ . You don't even need to hash the filenames but instead can keep them nicely named for easy organization.
Then, all the links to download a file will be made to point to www.yoursite.ext/download.php?id={fileid}
Your download.php will do all the access checks (properly logged in, has permissions to download the file etc), and then do the following:
$pathToPdf = '/var/www/site/uploads/some.pdf' ;
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($pathToPdf));
header('Content-Disposition: attachment; filename=' . 'some.pdf');
readfile($pathToPdf) ;
And that's pretty much it. Once you get this working you can look into improving a few things:
use mod_rewrite or similar to have the actual pdf filename in the link, which helps some browsers realize they should download it: www.yoursite.ext/download/{fileid}.pdf
consider using the web server instead of php to serve files, eg X-Sendfile header

Restricting file downloads

I'm currently creating a website for a client that will basically involve selling various files. This is obviously a really common thing to do, which is making me feel kind of foolish for not thinking of a method for doing it.
Once the purchase has been made the customer should be taken to a page containing the download link, as well as receiving emails that contain a download link and an email with information about an account that will be created for them (they will also be able to download from their account's control panel). What I'm trying to figure out is how I can hide/obscure the file's location on my server so that one person who buys it can't simply copy and paste the direct link to the file elsewhere. Even if I make the request to download a file a link of the format http://example.com/blah/download/454643, a URL which does not correspond to the actual location of the file, I think it might still be possible to locate the file on the server? I don't really understand too much about how permissions work on my server, which is why I ask. Thanks in advance :)
You basically don't give the users the direct URL to the file. Server based permissions have nothing to do here.
Say you have the required file(s) saved in /data/files/file.pdf (good practice to store files out of your web root).
You can provide the users a link to download which looks something like /download.php?auth=32
When a user clicks the link, download.php will check if the session/cookie is authenticated and if the download id is valid (in case you have time based download expiry)
Then download.php will read the required file from its location and send it to the browser with appropriate headers to force download.
Store the files out side your web root, but then be sure that the folder you store them in is in the "open_basedir" directive in your php.ini file, this will allow you to access them from a PHP script. Storing them outside the web root means that they wont ever be directly accessed via HTTP.
Have a PHP script, like the ones listed in these answers that can stream/read out a file. If its a large file you may need to change the "max_execution_time" to account for the extra time the script will take to read out the file. This script will allow you to authenticate the user and check that they have paid for the file.
Put a .htacces in the folder with the script that rewrites the file requested from that folder to a variable. That makes it appear as though they are directly accessing the file while that are not. Personally i would only put the single script in this folder just to keep things simple. So:
http://www.yourdomain.com/files/expensive_song.mp3
actually rewrites to:
http://www.yourdomain.com/files/download_file.php?filename=expensive_song.mp3
Good luck.
If you have access to running Lighttpd, you should definitely check out the Mod_SecDownload module. I've used this on a previous project that sold video and image files securely.
As the webserver doesn't know anything
about the permissions used in the app,
the resulting URL would be available
to every user who knows the URL.
mod_secdownload removes this problem
by introducing a way to authenticate a
URL for a specified time. The
application has to generate a token
and a timestamp which are checked by
the webserver before it allows the
file to be downloaded by the
webserver.
The generated URL has to have the
format:
<uri-prefix>/<token>/<timestamp-in-hex>/<rel-path>
which looks like
"yourserver.com/bf32df9cdb54894b22e09d0ed87326fc/435cc8cc/secure.tar.gz"
<token> is an MD5 of
a secret string (user supplied)
(starts with /)
<timestamp-in-hex>
As you can see, the token is not bound
to the user at all. The only limiting
factor is the timestamp which is used
to invalidate the URL after a given
timeout (secdownload.timeout).
You can have the URL be an authorization code for the buyer. You get her to log in again, check which file the code is for, then pipe the file to her. Here is an exemple of PHP code from osCommerce (I wrote that a long time ago).
// Now send the file with header() magic
header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: Application/octet-stream");
header("Content-disposition: attachment; filename=" . $downloads['orders_products_filename']);
if (DOWNLOAD_BY_REDIRECT == 'true') {
// This will work only on Unix/Linux hosts
tep_unlink_temp_dir(DIR_FS_DOWNLOAD_PUBLIC);
$tempdir = tep_random_name();
umask(0000);
mkdir(DIR_FS_DOWNLOAD_PUBLIC . $tempdir, 0777);
symlink(DIR_FS_DOWNLOAD . $downloads['orders_products_filename'], DIR_FS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename']);
if (file_exists(DIR_FS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename'])) {
tep_redirect(tep_href_link(DIR_WS_DOWNLOAD_PUBLIC . $tempdir . '/' . $downloads['orders_products_filename']));
}
}
Here is sample code of what I have done for something quite similar:
// $mimeType is the mime type of the file
header('Content-type: ' . $mimeType);
// this will get the size of the file
// (helps for giving the size to the browser so a percent complete can be shown)
header('Content-length: ' . (string) (filesize($path)));
// disposition is either attachment (for binary files that can't be read by the browser)
// or inline (for files that can be read by the browser
// some times you have play with this to get working so users get the download window in all browsers
// original filename is the name you want to users to see
// (shouldn't have any special characters as you can end up with weird issues)
header('Content-Disposition: ' . $disposition . '; filename=' . $originalFilename);
// the next 2 lines try to help the browser understand that the file can't be cached
// and should be downloaded (not viewed)
header('Pragma: Public');
header('Cache-control: private');
// this will output the file to browser
readfile($path);
You can of course add to this any login checking and logging to ensure it isn't downloaded too many times.
Also, as said earlier, ensure you put the file outside (or above) the web server document root so people can't figure out the path. Or you could even put a password on the directory so only internal people could access the file list more easily, but wouldn't recommend this. (Only do this if you can put something outside the doc root.)
Some webservers, such as Lighty and Nginx, implement the X-Sendfile header. Let's say you have a Django app, you can have your view return an X-Sendfile header which points to the file you want to ship out. lighttpd will then serve that file instead.
The file can be in a non web-accessible location (this is not a 301 redirect) and because your app is serving the header, you can do authorisation first.
This is much better than serving static files from your application. The webserver is optimised for static files and will be faster, and much lighter on resources. If you're handling more than a few requests you should consider using X-Sendfile.
There's quite a good blog post about it here:
http://blog.zacharyvoase.com/2009/09/08/sendfile/
Lighttpd/PHP instructions can be found here:
http://redmine.lighttpd.net/wiki/1/X-LIGHTTPD-send-file
NGINX instructions can be found here:
http://wiki.nginx.org/XSendfile
There also appears to be an early release Apache mod that does the same thing:
https://tn123.org/mod_xsendfile/
A lot of download urls I've seen that are based on purchase tend to use some guid and other dynamic information as part of the url to not make it as simple as guessing one id. You could end up with guid/datetimepurchased/id or something like that as part of the path.
An additional option would be to ensure the user is logged in before allowing the download to proceed which would given an additional layer of security.
Well, first, you definitely don't want to link directly to the file. You'll probably want to send the user a link to a service you've created (or even just a page) with a generated id argument that results in a file download, if certain criteria are met.
Those criteria are difficult, really, as you need to allow the user to download the file more than once (in case he fails to download the complete file the first time, or deletes it accidentally, etc.), but once a link works, it works until you kill it.
I'd suggest either using time or IP to filter your download requests.
Time: When someone purchases the file from you, inform them that they'll be able to download the file for 1 day only, or some such. Yes, other people can download the file during that day, but only for 1 day. You could also put a download limit on this, so they can only download it 5 times (this is normal).
IP: When someone purchases the file from you, inform them that they'll only be able to download the file from that IP. Your download service can certainly check this when they attempt to download the file.
It seems both are easily usable at the same time, as well.
In either case (or both), be prepared to handle customers who didn't download the file in time, or want to get it again after the time limit (or from another computer/IP (some people don't get static ones)). They won't want to pay again, and probably shouldn't have to.

Categories