1

In a web application to transform images I want to deny direct access to other user's images and I've achieve it adding this code at my main .htaccess file:

RewriteCond %{HTTP_COOKIE} !PHPSESSID=(.+) [OR,NC]
RewriteCond %{HTTP_COOKIE}:%{REQUEST_URI} ^PHPSESSID=(.*?);:(?!.*?/usuarios/\1).* [NC]
RewriteRule ^.*?/usuarios/.+?\.(gif|jpe?g|png|wbmp)$ - [R=403,L]

So, as users have their own folder to upload and transform images, this rule will check if you are looking for an image which directory matches with your id_session, and will throw a 403 response if it doesn't match.

It seems to work fine, but if any user attach an image and change the scr with other user's image (assuming he knows the path), it is showing that image.

How could I prevent it?

You can check at http://itransformer.es

Manolo
  • 24,020
  • 20
  • 85
  • 130
  • 1
    I would rather see this logic implemented in the application code instead of the web server. I mean, it works since the sessions don't need to be persistent (single use site), but I think it would be easier and more portable to implement it in the actual application. – David Houde Nov 07 '13 at 12:09
  • It's also implemented, but it doesn't avoid to change your own `img` tag and access to the image. – Manolo Nov 07 '13 at 12:23

1 Answers1

3

As says @David Houde, such logic should be implemented in the application, for instance in the following way:

  1. The images uploaded by your users will be stored outside of the web site root directory, so they cannot be accessed directly using a URL,

  2. You need to setup your website to handle virtual URLs (the most simple here being a rewrite rule internally passing the request URL as parameter to some PHP (or whatever) script),

  3. Then, in your script you will have full latitude to check whether the request match your policy,

  4. And if the request is legitimate, your script will be able to open the requested image file and send its content as web server answer.

WhiteWinterWolf
  • 239
  • 2
  • 10
  • But I need to show the image with a `img` tag. How could I do it if it is outside the document root? – Manolo Nov 07 '13 at 12:34
  • @ManoloSalsas Please read points #2; #3; and #4, not just #1. – Adi Nov 07 '13 at 12:41
  • @ManoloSalsas: The IMG tag refers to a URL, however in this scheme the URL is a virtual one: `/uploads/myuser/mypict.jpg` will not directly map to the image, but a rewrite rule will pass this URL as parameter to a `/uploads.php?url=myuser/mypict.jpg` script, and this script will have the ability to access and send the content of files outside of the web root directory (web server root directory does not apply to scripts' file handling functions). –  Nov 07 '13 at 12:41
  • Well, we would need to know what language you are using in order to give an example. This question might be better suited for StackOverflow.com – David Houde Nov 07 '13 at 13:13
  • @DavidHoude - I'm using PHP. – Manolo Nov 10 '13 at 15:21