Page 1 of 2

bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-04 17:27
by facos79
Hello everyone, I have a problem to solve urgently: I created an application with appgini with which the user can upload some pdf documents to his own private area. These documents must be accessible only to the user who uploaded them. But there is a problem: these documents a vote saved on the server are also accessible to those who know the link and has not logged in. how do I block access to who knows the link?
Thank you.


---- in italiano ---

Ciao a tutti, ho un problema da risolvere urgentemente: ho creato un'aplicazione con appgini con la quale l'utente può caricare nella propria area riservata alcuni documenti pdf. Questi documenti devono essere accessibili solo all'utente che li ha caricati. C'è però un problema: questi documenti una vota salvati sul server sono accessibili anche a chi conosce il link e non ha eseguito l'accesso. come faccio a bloccare l'accesso a che conosce il link ?
Grazie.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-05 11:07
by a.gneady
Please don't post duplicate posts ... I removed the other duplicates of this post.

You could try adding this to an .htaccess file in the upload folder:

Code: Select all

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} \.mydomain\.com [NC]
RewriteRule \.pdf$ - [F,L]
Change 'mydomain\.com' to the domain name of your server -- note the slash before the dot.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-05 11:15
by facos79
Hello,
I apologize for the double post.
I had first published it incorrectly in another section.
Thank you for the information. From the middle of the year we have to respect the new European regulation on privacy and documents should only be accessible to those who have access to the database. So it is essential that the software blocks unwanted access not only to information entered in the fields but also to uploaded documents.

I try and let you know if it works.

Thank you.

Greetings


--------------------------
Ciao,
Mi scuso per il doppio post.
L'avevo pubblicato prima erroneamente in un'altra sezione.
Ti ringrazio per l'informazione. Da metà anno dobbiamo rispettare il nuovo regolamento europeo sulla privacy e i documenti dovrebbero essere accessibili solamente a chi possiede le credenziali di accesso al database. Quindi è fondamentale che il software blocchi l'accesso indesiderato non solo alle informazioni inserite nei campi ma anche ai documenti caricati.

Provo e ti faccio sapere se funziona.

Grazie.

Saluti

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-05 12:57
by facos79
a.gneady wrote:
2018-12-05 11:07
Please don't post duplicate posts ... I removed the other duplicates of this post.

You could try adding this to an .htaccess file in the upload folder:

Code: Select all

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} \.mydomain\.com [NC]
RewriteRule \.pdf$ - [F,L]
Change 'mydomain\.com' to the domain name of your server -- note the slash before the dot.

Hi, I created the .htaccess file in the upload folder. Knowing the link of the pdf and without having logged in as a user, the file also opens from a browser.

I tried to write in .htaccess this too:

Code: Select all

<Files ~ "^\.(htaccess|htpasswd)$">
deny from all
</Files>
Options Indexes
order deny,allow
So the file does not open but can not open even the user who has logged in to the database manager.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-05 13:09
by a.gneady
Hmm ... basic questions first:

1. Is mod rewrite enabled on your server? To check it, please follow the steps here: https://stackoverflow.com/a/10891317/1945185
2. Do you see any error reported in the server error_log after creating the .htaccess file?

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-06 12:40
by facos79
Hello,
yes the 'mod rewrite' is active. I am attaching the newly downloaded logs.
Here is an example of the link to which only registered users should log in. Instead knowing the link you can open the file (this is a test) you too:

https://fabiocostanzo.it/assistenza/ima ... e86c4a.pdf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2018-12-07 17:21
by facos79
Hi, how did I try to put this code in the .htaccess file:

Code: Select all

<Files ~ ".+"> 
Order allow,deny 
Deny from all 
Satisfy All 
</Files> 
the files in the pdf in the image folder are blocked and can not be opened from links. Only the user can open them by clicking on the file name in the application appgini and with the right mouse button selecting 'save as'.
Would it be possible to allow only users logged in to view files in the browser without having to save them?

appgini is an excellent application and would be very nice if it could generate secure code automatically even as regards the uploaded files (photos, images, zip pdf etc etc)

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-01-09 14:15
by a.gneady
Would it be possible to allow only users logged in to view files in the browser without having to save them?
Hmm .. once a file is viewable in the browser, there is no way to prevent users from saving it. You might find scripts for preventing right-clicking an object (to hide the 'Save as' option) but they can be very easily circumvented.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-01-16 08:57
by mghielmi
To protect download of PDF I've used this method.

2 files (in images folder, the folder where files are upload)
1 .htaccess
2. protect.php

.htaccess

Code: Select all

RewriteEngine on
RewriteRule .* protect.php
protect.php

Code: Select all

<?php

	define('PREPEND_PATH', '../');
	$hooks_dir = dirname(__FILE__);
	include("$hooks_dir/../defaultLang.php");
	include("$hooks_dir/../language.php");
	include("$hooks_dir/../lib.php");
	
	/* grant access to the groups 'Admins' and 'Other'*/
	$mi = getMemberInfo();
	if(!in_array($mi['group'], array('Admins', 'Other'))){
		header("location: /");
		exit;
	} else {
        //Check if user has right to access the file. If no, show access denied and exit the script.
        $path = $_SERVER['REQUEST_URI'];
        $paths = explode('/', $path);
        $lastIndex = count($paths) - 1;
        $fileName = $paths[$lastIndex];
        header('Content-type: application/pdf');
        header("Content-Disposition: inline; filename=$fileName");
        readfile($fileName);
    }

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-01-19 10:24
by a.gneady
Very nice tip @mghielmi. Thanks so much for sharing :)

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-01-29 21:09
by facos79
Excellent solution!
It works perfectly. Just what I was looking for.
Thanks thanks thanks!


--------

Ottima soluzione!
Funziona perfettamente. Proprio quello che stavo cercando.
Grazie, Grazie, Grazie!

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-10-29 14:06
by onoehring
Hi,

just want to post a little improvement / alternate solution:
An easy design so that an admin user can easily and quickly add / remove permissions to access files in the images folder (by click on an image or a direct link)

How:
Here I created a new AppGini table db_image_access (see image). This contains only two fields. Primary key (which is not utilized and the usergroup.
To have easy access to the groups I created a view in MySQL ( view_membership_users ) that simply pulls all entries from the membership_users table. Then I created a "pseudo"-table in Appgini with that same name view_membership_users. Now I created a simple lookup/dropdown to save the groupID into my new table.

Image of this table:
ec_prot02.png
ec_prot02.png (7.77 KiB) Viewed 52628 times
SQL for this table:

Code: Select all

CREATE TABLE `db_image_access` (
  `ID_image_access` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `groupID` int(11) NOT NULL,
  PRIMARY KEY (`ID_image_access`),
  KEY `groupID` (`groupID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now the code needed to be changed to access this table instead of using fixed groupnames. The new code for contains some more header information which should be easy to extend when needed:

Code: Select all

<?php
//initial source: https://forums.appgini.com/phpbb/viewtopic.php?t=2856#p9355
// version: 2019-10-29 15:00:00
// Olaf Noehring, https://datenbank-projekt.de

define('PREPEND_PATH', '../');
$hooks_dir = dirname(__FILE__);
include("$hooks_dir/../defaultLang.php");
include("$hooks_dir/../language.php");
include("$hooks_dir/../lib.php");

$sql = "SELECT Count(groupID) AS c FROM db_image_access WHERE groupID = " . getLoggedGroupID() . ";";
$result = sqlValue($sql);

if ($result == 0) {
    $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
    header("location: $actual_link");   //use absolute URL 
    die();
    exit;
} else {

    $path = $_SERVER['REQUEST_URI'];
    $paths = explode('/', $path);
    $lastIndex = count($paths) - 1;
    $fileName = $paths[$lastIndex];
    $extension = strtolower(substr(strrchr($path, "."), 1));

    $fname = __DIR__."/".$fileName;

    switch ($extension){
        case "pdf":
            header('Content-type: application/pdf');
            break;
        
        case "jpg":
            header('Content-Type: image/jpeg');
            break;

        case "jpeg":
            header('Content-Type: image/jpeg');
            break;            

        case "png":
            header('Content-Type: image/png');
            break;

        default:
            header('Content-type: application/pdf');
    }
    
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fname)).' GMT', true, 200);
    header('Content-Length: '. filesize($fname));
    header("Content-Disposition: attachment; filename=\"" .$fileName. "\"");
    readfile($fileName);
}
?>
Of course you still need to create a .htaccess file in your /images folder:

Code: Select all

RewriteEngine on
RewriteRule .* protect.php
Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2019-12-08 14:57
by onoehring
Hi,

just moving a site to 1and1 ... and the htaccess from above does not work there (at least in my case).
I needed to make an adjustment - so this is the .htaccess which works (for me) at 1and1 as well:

Code: Select all

RewriteEngine on
#If you have changes your uploads directory, change next line accoring
RewriteBase /images/
RewriteRule .* protect.php
Please note my hint, that, if you have changed your uploads directory (default /images) you will need to adjust the line in the .htaccess as well.

Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-06-21 13:02
by zibrahim
mghielmi wrote:
2019-01-16 08:57
To protect download of PDF I've used this method.

2 files (in images folder, the folder where files are upload)
1 .htaccess
2. protect.php

.htaccess

Code: Select all

RewriteEngine on
RewriteRule .* protect.php
protect.php

Code: Select all

<?php

	define('PREPEND_PATH', '../');
	$hooks_dir = dirname(__FILE__);
	include("$hooks_dir/../defaultLang.php");
	include("$hooks_dir/../language.php");
	include("$hooks_dir/../lib.php");
	
	/* grant access to the groups 'Admins' and 'Other'*/
	$mi = getMemberInfo();
	if(!in_array($mi['group'], array('Admins', 'Other'))){
		header("location: /");
		exit;
	} else {
        //Check if user has right to access the file. If no, show access denied and exit the script.
        $path = $_SERVER['REQUEST_URI'];
        $paths = explode('/', $path);
        $lastIndex = count($paths) - 1;
        $fileName = $paths[$lastIndex];
        header('Content-type: application/pdf');
        header("Content-Disposition: inline; filename=$fileName");
        readfile($fileName);
    }
Hi there,
Is there any solution if I want to also protect the image files such as .jpg or .png files as well?
How do I apply multiple Content-type in this case.
Thank you and have a nice day.

Zala.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-06-22 06:08
by onoehring
Hi Zala,

I do not understand. In my post above ( viewtopic.php?p=13800#p11378 ) there the script checks the filetype and arranges the header for download as needed.
Besides, the original ( posting.php?mode=reply&f=11&t=2856#pr9355 ) should work for all filetypes anyways - just giving a wrong header - which I believe - the browser will correct (and allow access to the file if the user is logged in).
You may try to remove the two header lines

Code: Select all

        header('Content-type: application/pdf');
        header("Content-Disposition: inline; filename=$fileName");
which should download an unspecified filetype.

Or ... try a combination of both:
protect.php (not tested):

Code: Select all

<?php
//initial source: https://forums.appgini.com/phpbb/viewtopic.php?t=2856#p9355
// version: 2019-10-29 15:00:00 (adjusted for admin group 2020-06-22)
// Olaf Noehring, https://datenbank-projekt.de

define('PREPEND_PATH', '../');
$hooks_dir = dirname(__FILE__);
include("$hooks_dir/../defaultLang.php");
include("$hooks_dir/../language.php");
include("$hooks_dir/../lib.php");

/* grant access to the groups 'Admins' and 'Other'*/
	$mi = getMemberInfo();
	if(!in_array($mi['group'], array('Admins', 'Other'))){
		header("location: /");
		exit;
	} else {

    $path = $_SERVER['REQUEST_URI'];
    $paths = explode('/', $path);
    $lastIndex = count($paths) - 1;
    $fileName = $paths[$lastIndex];
    $extension = strtolower(substr(strrchr($path, "."), 1));

    $fname = __DIR__."/".$fileName;

    switch ($extension){
        case "pdf":
            header('Content-type: application/pdf');
            break;
        
        case "jpg":
            header('Content-Type: image/jpeg');
            break;

        case "jpeg":
            header('Content-Type: image/jpeg');
            break;            

        case "png":
            header('Content-Type: image/png');
            break;

        default:
            header('Content-type: application/pdf');
    }
    
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fname)).' GMT', true, 200);
    header('Content-Length: '. filesize($fname));
    header("Content-Disposition: attachment; filename=\"" .$fileName. "\"");
    readfile($fileName);
}
?>
Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-06-25 08:57
by zibrahim
Hi Olaf,
Apologize for my ignorance and incompetency in coding.
I have reviewed and tested your codes and they work flawlessly.
This is very important to ensure the privacy or confidentiality of the attachments from being viewed without proper access.
Many thanks for your support and willingness to share your wisdom in this forum.

Zala.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-06-26 07:57
by onoehring
Hi Zala,

no need to apologize.
I am glad, that you were able to solve your problem (and the code works). Be assured - I see the unprotected "uploads" folder as a big problem as well.

Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-11-13 06:46
by onoehring
Hi,

just had the problem, that the "old" .htaccess did not work. After looking at error logs I was able to make it run again by introducind a new (here first) line:

Code: Select all

Options FollowSymLinks
RewriteEngine on
#If you have changes your uploads directory, change next line according
RewriteBase /images/
RewriteRule .* protect.php
Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-11-17 14:38
by SkayyHH
Does that work for you somehow with ag 5.92? For me, access is blocked and header is broken. With access from outside as well as when you are logged in....

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-11-17 14:51
by onoehring
Hi,

no, everything works. You might need to check server logs. I have encountered strange things on a 1&1 host once.

Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2020-11-17 21:26
by SkayyHH

Code: Select all

RewriteEngine on
#If you have changes your uploads directory, change next line according
RewriteBase /images/
RewriteRule .* protect.php
Works on domainfactory.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2021-08-11 06:48
by ltlow
Working on a linux server but not work in my Xampp windows.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2021-08-12 14:49
by SkayyHH
Hi, worked not with Xampp for me too.

Perhaps remove

Code: Select all

RewriteEngine on
.

But i don´t know if that works anymore when removed.

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2021-08-22 09:52
by onoehring
Hi SkyHH,

maybe it does not work as xampp is (probably) local?

just an idea.
Olaf

Re: bugs unauthorized users access pdf files knowing the link

Posted: 2022-04-29 11:58
by facos79
Hello,
the script with the new version appgini 2313 no longer works.
Downloads are blocked even if the user is logged in. Also it is not allowed to see the previews of the images (in this case I put .htaccess in the images folder. How can I solve it. It is important that no one can download a document or an image knowing the url link without being logged in.