How to protect php and folder files from unauthorized access? - php

I want to block direct access to different php files (by writing let's say http://testpage.com/login_verif.php), for example the login verification one (that authentificates users).
Is it possible for an user to access the config.php file that connects him to the mysql database (and has the password written in it)?
Also, how can you configure your uploads folder, so that an user can only see the image for which he has the URL?

Exit the file if there is no data POSTed to the file, and/or place the file in a more controlled area.
You should not have a config.php file - they are very much not safe, but instead environment variables.
You may look into rewriting to disallow direct access, but allow referencing on the domain.

Related

File Download Login Protection with Session

I'd like to protect some files with a session Authentication. Some files can be viewed by users, some not.
I've impelemented a solution with mod_rewrite and readfile(). My problem is that this function will use a lot of ram and the server goes down when more users download files.
I tried this:
1) Pass a file trough the php handler and use the prepend function. It doesn't work because when the prepend php file finished the handler process the file, and in my case the handler was blocked because of invalid ASCII chars. I couldn't manage to stop the handler from processing but output the file.
2) Put the session, ip and the folder name in a temporary file what I tried to check in my nginx.conf to exclude from rewriting. I failed because I was not able to extract only the folder name in nginx into a variable.
How can I solve this problem? Has anyone a suggestion?
Thanks
If I understand the question correctly, you are trying to create a system that only allows authorised users to view certain files, and other users to view other files.
If my understanding is correct, then I would personally store the files above the root or in a secure location, and then have an access script (such as fetch_file.php) with a unique identifier in the URL (e.g. fetch_file.php?uid=1234).
If the user is authorised to access the file with the unique id of 1234; provide the file from the location details within the database, otherwise deny the request.
This way, the user can not access the file without the correct permissions, as it is stored securely above the root which should not be accessible from the internets.

Secure storage of database connection credentials

Here's how I connect to my database:
create a "access.php" file that has the username and password of the database inside it.
create a "main.php" file in which I include access.php and then create MySQL connection and the rest.
How secure is this way of coding?
I'm just a bit scared that if someone could somehow donwload the access.php and get to know my user and pass.
Any suggestions?
Since your php file is under a web server, it cannot be downloaded as pure file, but will be served always compiled, so the source code cannot be visible to users.
To view your username and password stored in the file, a user should have access to the server's file system. So you can feel comfortable.
I have a .php file called "Connect" which is the database connection file.
Then I have a file I call "config.php" which contain the username, pass etc.
Then once the database connection has been initiated or whatever it is called (sorry I am not English), then you would "unset" the variables which contain the login info, eg: unset($config['mysql_pass']);
However you shouldn't be scared of people being able to download your access.php file, as it is executed server-side, and the content are not visible to any front-end users.
You could also put your access.php file in a folder just before your public_html folder, this way, it cannot be accessed for outside the server.
Hope it helps :)
Possible duplicate question. Check out this older post:
How to secure database passwords in PHP?
One additional "trick" is to use somewhat ambiguous names for config files.... don't use something like db_config.php.
I don't think people can't just download the access.php file. When people type the location of the file in browser, php interpreter executes the file, does not just send the file to the user.
However if you install some other malicious script it may read the file & do harmful things, like downloading the file

Forbid access to files in a simple PHP login system

I wrote this VERY simple PHP login system:
<?php
session_start();
$error = '';
if (isset($_POST['username']) && isset($_POST['password']))
{
if ($_POST['username'] == 'user' && $_POST['password'] == 'pass')
{
$_SESSION['client'] = 'ok';
Header ("location: /kit/kit/index.php");
}
else
{
$error = 'Usuario o contraseña incorrectos.';
}
}
?>
Don´t worry about the vulnerability issues, it´s not protecting anything valuable.
In every .php page i add:
<?php
session_start();
if (!isset($_SESSION['client']) || $_SESSION['client'] != 'ok')
{
Header ("location: /kit/index.php");
die();
}
?>
This protects the .php sessions just fine.
The problem is that this doesn´t protect the files.
I mean if go directly to:
something/other/file.zip
it will download it wether you have loged in or not.
I hope the question is clear enough, if not, please ask!
To stop a user from seeing the directory, all you need to do is create an index page in that folder. Ex: index.htm, index.html, default.htm, default.html.
To stop a user from entering the folder (e.g. stop anyone from viewing http://www.yoursite.com/myFolder/), you may need to access some features of your web host. Some hosts allow you to password protect files or folders. You can also create an .htaccess file/folder
An htaccess file is a simple ASCII file, such as you would create through a text editor like NotePad or SimpleText. Many people seem to have some confusion over the naming convention for the file, so let me get that out of the way.
.htaccess is the file extension. It is not file.htaccess or somepage.htaccess, it is simply named .htaccess
Create the file
In order to create the file, open up a text editor and save an empty page as .htaccess (or type in one character, as some editors will not let you save an empty page). Chances are that your editor will append its default file extension to the name (ex: for Notepad it would call the file .htaccess.txt). You need to remove the .txt (or other) file extension in order to get yourself htaccessing--yes, I know that isn't a word, but it sounds keen, don't it? You can do this by right clicking on the file and renaming it by removing anything that doesn't say .htaccess. You can also rename it via telnet or your ftp program, and you should be familiar enough with one of those so as not to need explaining.
htaccess files must be uploaded as ASCII mode, not BINARY. This makes the file usable by the server, but prevents it from being read by a browser, which can seriously compromise your security. (For example, if you have password protected directories, if a browser can read the htaccess file, then they can get the location of the authentication file and then reverse engineer the list to get full access to any portion that you previously had protected. There are different ways to prevent this, one being to place all your authentication files above the root directory so that they are not www accessible, and the other is through an htaccess series of commands that prevents itself from being accessed by a browser, more on that later)
JUST INCASE stop users from downloading your file
store all things that are downloadable ourside your document root. which means before the public_html file.
EDIT: updated the section below to show graphical representation of folder structure
how do you access them then?
work
downloadableFiles
downloadables
- memberOnlyFile.zip
- welcomePackage.zip
- memberhshipVideoVideo.mov
photos
- photo1.jpeg
- photo2.jpeg
publi c_html
- index.htm
About
- about.html
- about.gif
LogIn
- login.htm
- loginScreen.htm
- loginFancyButton.gif
Now anything in the public_html folder the world can see through your website.
Anything outside your public_html folder, will not be visible directly to the world through your website by typing the file name into the address bar in their browser. so thats a good thing as we are going to save all our files that we dont want to give access to outside of the public_html folder.
Now say if you want a certain user to be able to download a file, say maybe a logged in user, you can still make the file downloadable by having a link to that file.
If we are at the login Page, to access the loginScreen webpage you just write down the hyperlink like so:
login screen
since that page is on the same folder. now if you want to allow a user to be able to download a file from the downloadable files folder which is outside the public_html folder since it is not in that folder it self youjust reference to it like so:
How would we get to that folder if we are in the login folder as we are viewing the loginScreen.htm page, you go one folder back so we end up being in the public_html folder. then we go another folder back so we are in the work folder.
so it would look like this so far.
../../ which means two folders back.
then to access the memberonlypath.zip we then need to go into the downloadableFiles folder then we need to get into the downloadable files and then we can link it to the file membersOnlyFile.zip which is the file we were lookng for before.
so the full link now becomes
download file
This way the user cannot access the file by simply typing it on the address bar but can download it if you reference it yourself like the above.
Hope this helps
PK
Store all files you don't want downloaded outside the DocumentRoot.
You need .htaccess to deny access to the folder.
Just have a php download script like: this one that will get the file below the public_html folder.
"Static" files are served by the webserver, not PHP, so authentication is handled differently. There are two easy ways around this:
Handle all authentication in the webserver, e.g. with HTTP basic/digest authentication. Apache 2.2 has a helpful introduction.
Serve the files with PHP, e.g. with foo.php/path/to/file if you have "pathinfo" enabled (according to the PHP docs you set AcceptPathInfo=ON in the server config somewhere) or foo.php?path=path/to/file, which is pretty terrible, but oh well.
There is a more enterprisey solution:
Write an authentication module for your download server which understands authentication cookies from the other site. Many big sites do this (adcdownload.apple.com comes to mind), partly so they can stick the downloads on a CDN but still have some sort of access control.
There is a lazy workaround:
Stick everything in an "unguessable" directory name (e.g. some random base64 chars). Make sure you can't list the parent directory (the easiest way is to create an empty "index.html" file).

PHP - Question about uploading & uploaded image file

I have read the following tutorial "Uploading Files To the Server Using PHP"
and have several questions related to the topics.
Q1> The tutorial mentions that
"Note that PHP must have write access
to $uploadDir or else the upload will
fail"
For me, I only allow the user to upload the file after the user has login to the website.
If we set that $uploadDir permission as 777, then everyone can have written permission to that folder. How to avoid this problems?
Also I am using WAMP as my testing bed, can I simulate the same case as a real web server?
Q2> In order to prevent Preventing direct access, the tutorial mentions:
"A better approach is to move the
upload directory away from your web
root. For example, the web root for
this site is:
/home/arman198/public_html/ to prevent
direct listing i can set the upload
directory to /home/arman198/upload/."
Now my problem is that how can I display the uploaded images on other website pages. Since, the upload is not accessible directly anymore? I need to display the uploaded image save personal headshot dynamically on other website page. Is it possible?
Thank you
It's a common problem.
All modern computers have a temporary files directory. On Linux/Unix it's /tmp, on Windows it's usually c:\temp. The OS install will have set permissions on that directory so that anyone can write files there but only privileged users can delete files that don't belong to them. This is where PHP will want to put an uploaded file; your application then has to move it elsewhere (this is the purpose of the move_uploaded_file() function). PHP under Windows may need upload_tmp_dir actually set in the php.ini file.
Once you have an uploaded file, you can shift it whereever you like, including to where the webserver can read it to serve it. The biggest problem with that it is awfully easy to put this directory inside your codebase. Don't do that. As soon as you do anything beyond editing the files inside the directory they are served from, it will be problematic. Trust me: I've dealt with a few times this in code I've inherited. It's easy to let your webserver load files from a location outside your codebase.
The other alternative is to produce a download script. That way the file need not be servable by the webserver at all. One disadvantage is that you don't get to leverage the web server's MIME translation, but then, that lets you control which types of image files are permitted.
For the second question, you can use a PHP script intead of direct access to the directory. Lets name it image.php. Lets assume that it can take a parameter id, like image.php?id=image_id. In that file you can get the id using superglobal array $_GET. Then you can search for images with that Id and just send it as response.
First one I'm not sure, but maybe play with .htaccess file.
And for the first question, try setting your permissions to 775. That should allow PHP to write the file to the directory without giving the general public write access.

Authentication / Denying access to files in directory with php

I have a directory of files that logged-in users can upload to and access. Some of the files are public, and others are private - for internal access only. The filenames and access settings are saved in a database.
Can anybody give me some resources or show me an example of how i can use session data (and .htaccess?) to allow access of private files only to authorized users?
I'm thinking it might be easier to keep public documents in a seperate, unprotected directory, though i'd kind of like to keep everything together.
I'm not concerned about top-level security or encryption, as the files aren't terribly sensitive, but i want to keep them from being indexed on search engines, etc.
thanks!
I suppose I wouldn't use a .htaccess (or any kind of HTTP-authentication) for that : .htaccess / .htpasswd are great when you want to allow/deny access to a whole directory, and not to specific files.
Instead, I would :
Deny any access to the files -- i.e. use a .htaccess file, containing Deny from All
That way, no-one has access to the file
Which means everyone will have to use another way to get to the files, than a direct URL.
Develop a PHP script that would :
receive a file identifier (a file name, for instance ; or some identifier that can correspond to the file)
authenticate the users (with some login/password fields), against the data stored in the database
if the user is valid, and has access to the file (This is if different users don't have access to the same set of files), read the content of the file from your PHP script, and send it the the user.
The advantage is that your PHP script has access to the DB -- which means it can allow users to log-in, log-out, it can use sessions, ...
About the "send the file from PHP", here are a couple of questions that might bring some light :
Sending correct file size with PHP download script
Resumable downloads when using PHP to send the file?
forcing a file download with php
I'd create a custom index script in PHP -- something that would show the files dynamically. Use that to keep only the right files being listed -- afterwards, to further protect the files, fetch file contents dynamically -- Pascal MARTIN's links show you how to use PHP to control the file streaming, you can use that to block access from hidden files to users that aren't supposed to get to them.

Categories