mysql php security - php

On my php pages, at the top i connect to the database like this
$db = mysql_connect("mysql.site.com","thedb", "pass");
mysql_select_db("dbase",$db);
Is this secure? Could someone somehow scan and view my code, therefore get access to the database?
UPDATE
Reason I ask is because a user was able to get access to my database, and im pretty sure it wasn't through sql injection.

It would be better if you move this snippet to an include file outside of your document root — this will prevent people reading it in case your webserver somehow gets misconfigured and starts serving PHP files as plain text. Although, just by itself, it is secure enough — it is unlikely that somebody will be able to misconfigure your server like this on purpose.

If someone did have access to your code, then yes, they would be able to read the password out.
There isn't a huge amount you can do about this, but ensuring that this code is a directory up from your web root would help.
(i.e. if you are serving your site from the folder /usr/htdocs/mysite, change it to /usr/htdocs/mysite/public, then put your includes in mysite rather than public.)

You should always apply multiple layers of defense:
Remove the credentials from the source code and place them outside the web server’s document root.
Restrict access to your database, possibly only via localhost or via socket.
Restrict the user’s privileges to only those necessary.

That's ok, the important thing I could say, go to your database and give to that user restricted permission, I mean only select, insert , update and delete the tables that it need.. beside that, create a file with that info and just include when you need it, that's my advice.
If someone go through your code will be able to see that info, but try to reduce always the damage impact

Related

Set up PDO connection without password

I'm trying to connect to my database, but I changed my database's root password in the interest of security. However, in order to connect to the database and use PDO, I apparently have to pass my password in the php, which obviously is not good for security:
$hsdbc = new PDO('mysql:dbname=hs database;host=127.0.0.1;charset=utf8', 'root','passwordgoeshere');
$hsdbc->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$hsdbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Am I being stupid and that because it's PHP no-one but the person who views the actual file will be able to see the password, or is there some way to do it without passing the password in the file.
Generally speaking it's not bad practice to have connection strings in files that are not user facing. If you don't want to have your personal password in the php file, then you can create a new mysql user for php.
You can also restrict the user's IP address in MySQL to the server hosting your php scripts. This way if a nefarious person browsing the web somehow was able to see the database password, they would have more difficulty accessing it.
People are not able to just go and read into your files. They should be safe on the place where you host it. They are only able to get into to files if they are able to get into the place when you host your stuff. Which should not be possible if they don't have the info to get there.(which should only be known to you).
This is not just for PDO. but also my mysql and mysqli to do it like this
Going to extend SupSon (SC2 Select fan?)'s answer:
PHP itself is server coded language.
There are only 3 ways (maybe more if someone want to add to it) that code can be shown to an outside user:
By having an unsecure .htaccess file that shows php file as text
file (then you should move servers at that point because normally
this doesn't happen)
Somehow your operating on debug mode and something in your page
triggers this mode and you get a whole bunch of PHP code gets shown
FTP/SSH access to your .php file (then you have more than a PDO
problem in your hands)
So if one of these cases is happening, coding into a .php file your username/password won't be a breach in security.
I have seen websites that expose PHP code, when the Apache type handler for PHP becomes unconfigured by accident. Then the code in .php files is displayed instead of executed. There's also an Apache type handler to display PHP source deliberately, though this is not usually configured.
To avoid this vulnerability, it's a good practice to put your sensitive PHP code outside your htdocs directory. Instead, put in your htdocs directory a minimal PHP script that loads the rest of the code using include() or require().
An alternative is to put your MySQL credentials in a config file instead of PHP code at all. For example, the file format used by /etc/my.cnf and $HOME/.my.cnf is readable by the PHP function parse_ini_file(). It's easy to store your MySQL password outside of your code this way.
For example, read user and password from the [mysql] or [client] sections of /etc/my.cnf:
$ini = parse_ini_file("/etc/my.cnf", true);
if (array_key_exists("mysql", $ini)) {
$connect_opts = array_merge($connect_opts, $ini["mysql"]);
} else if (array_key_exists("client", $ini)) {
$connect_opts = array_merge($connect_opts, $ini["client"]);
}
$pdo = new PDO($dsn, $connect_opts["user"], $connect_opts["password"]);
Yes it seems insecure at first, but once you get the hang of it and know how to manage your files to minimize potential security breaches, you can minimize the risks associated with having passwords stored in plain text in potentially publicly exposed spaces. Yet AFAIK PDO doesn't even let you form a connection without supplying a password. The solutions are a combination of what everyone has said and then some. Here's my quick guide for what I do.
Separate SQL users for separate purposes (minimizes damage from SQL injection or hacked accounts):
There should be a PHP-specific user for each table you need to access. That user will be granted only enough rights to handle as much of that table that he needs to, if it doesn't need to delete then don't grant it delete. If it doesn't need to select then don't grant it select. It seems fussy but very quickly you'll have a copy-paste template to make the users, give them the right(s) they need, and document it. If there's a joined table, you'll want to also grant the user access to that table also, naturally.
-- a single user account for a specific purpose:
CREATE USER 'usermanager'#'localhost' IDENTIFIED BY '5765FDJk545j4kl3';
-- You might not want to give access to all three here:
GRANT SELECT, UPDATE, INSERT ON db.users to 'usermanager'#'localhost';
The purpose of this is so that if you have a bug in your code that lets people SQL inject, they won't be able to cause any harm beyond the scope of what that role can do.
Stupid mistake can reveal PHP code and files if left in-directory, move them out:
Never mind revealing the source code, even just trying to access php files "out of order" can be destructive.
Move as many files to an out-of-scope directory as possible. Then call them like so:
require_once('../lib/sql_connectors.php');
This should escape your html / webdir and you should hopefully be able to store all sorts of fun stuff outside the scope of what a stupid admin mistake could reveal.
You can even have a php file that gets pictures and videos from outside your webdir, that's how streaming sites protect their resources and also conduct php-based authentication to file access. To learn how to do that you'll want to look up assigning your own etag headers to make sure browsers cache your php-retrieved files otherwise you'll have a very busy server, here's a short introduction.
Block wrongful access to PHP that are left in-directory:
All of your in-directory PHP files can be protected by checking that the $_SERVER['REQUEST_URI'] isn't itself. If it is, you can have a function called show404() that loads the 404.php page and dies there or just directly call your 404.php with an include. That way, even if you have hackers trying to brute force your php files they'll never see them because they'll get 404 errors (fools the bots) and they'll see the 404 page (fools the humans).
I avoid using .php in any publicly visible paths, to do that, I make rewrite rules in my .htaccess files that look like this:
RewriteEngine On
RewriteRule ^login$ login.php [L,QSA]
The L makes it stop running other rules.
The QSA preserves the $_GET tags.
The first lines of code for every file (consider prepending) could be:
// they should be connecting via a redirect, not directly:
$fileName = basename(__FILE__);
if ($_SERVER['REQUEST_URI'] === '/' . $fileName) {
error_log('Security Warning: [' . $_SERVER['REMOTE_ADDR'] . '] might be trying to scrape for PHP code. URI: [' . $_SERVER['REQUEST_URI'] . ']');
include('404.php'); // should point to your 404 ErrorDocument
exit();
}
// redirect to actual file
include('../hidden/php/' . $fileName);
In this example, assuming you have the redirect in your .htaccess, a login.php with the code above, and a login.php in your hidden directory, the user would experience the following two scenarios: attempt to connect to '/login' and see the hidden '/login.php' page; attempt to connect to the visible '/login.php' directly and get a 404 error.
Those are the 3 big things, lots of small limited accounts to minimize damage in case of security failure, keep all possible files outside the web directory, and make all in-directory php files produce an error letting only non-php links access them.

Passing an Ajax request to a file inside a protected folder?

I have a jQuery console that I'm writing and I'd like to keep a log of what people type in there at what time with their IP address, for security reasons. I don't want to make the log public, but the console itself is supposed to be a fun sort of thing and isn't in a protected folder.
I want to put the log into my protected admin folder, but can I send Ajax data to a PHP file inside the protected folder or it will still prompt for the username/password?
I've already tried outright making the log itself in the folder from an external PHP file, but it doesn't work, hence why I'm wondering if it will work if the PHP file is inside the protected folder.
On a similar note, do I even need to bother with keeping a log? Like I said, it's for security purposes, but I don't know if it's necessary. As far as I know, with the way I've coded the console, it doesn't accept any input outside of the commands I've written. I'm still worried about things like SQL injection and the like.
Sorry for the long-winded question, and thanks in advance.
Why not create a database to store this sort of data? That way the data is not accessible to the users, and it is also stored nicely for anything you want to do with it. With this approach you could have you PHP page in a publicly accessible place too.
I would suggest PHP Data Objects for security if you choose to take this approach.

Should I Make Database Connection With PHP Includes

I've been told that it is unsecure to make database connections inside a PHP includes. For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?
For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?
No.
Maybe the person who told you this was talking about something else - like including a file using a dynamic value coming from a GET parameter, or using remote http:// includes, or as #AlienWebguy mentions, having the password include inside the web root. But using includes in itself is not insecure.
It's only insecure if you are storing your passwords literally in your PHP files. They should be declared outside of the web root. That being said, the lack of security is not due to the use of the include() function.
In and of itself, no, it is not insecure. How it's implemented inside the include is of course a different story.
That's the way I've always done it. I make sure that the include is in a different directory that has open permisions and that the directory your writing in has locked permisions. Hopefully that makes sense.
This question is way too broad to get a good answer from anyone. Short answer is no, there's nothing inherently insecure about including a file that connects to a database. However, if you write code that isn't written properly, then yes it may be insecure to do this.
Since using "include('process.php')" is exactly the same as pasting 'process.php' into the code of the other file, that should not be, per se, a security issue. The insecurity could be in your code, not in the fact the you use the "include". In fact, it could maybe improve the safety of your code, due the reuse.

Security implications of writing files using PHP

I'm currently trying to create a CMS using PHP, purely in the interest of education. I want the administrators to be able to create content, which will be parsed and saved on the server storage in pure HTML form to avoid the overhead that executing PHP script would incur. Unfortunately, I could only think of a few ways of doing so:
Setting write permission on every directory where the CMS should want to write a file. This sounds like quite a bad idea.
Setting write permissions on a single cached directory. A PHP script could then include or fopen/fread/echo the content from a file in the cached directory at request-time. This could perhaps be carried out in a Mediawiki-esque fashion: something like index.php?page=xyz could read and echo content from cached/xyz.html at runtime. However, I'll need to ensure the sanity of $_GET['page'] to prevent nasty variations like index.php?page=http://www.bad-site.org/malicious-script.js.
I'm personally not too thrilled by the second idea, but the first one sounds very insecure. Could someone please suggest a good way of getting this done?
EDIT: I'm not in the favour of fetching data from the database. The only time I would want to fetch data from the database would be when the content is cached. Secondly, I do not have access to memcached or any PHP accelerator.
Since you're building a CMS, you'll have to accept that if the user wants to do evil things to visitors, they very likely can. That's true regardless of where you store your content.
If the public site is all static content, there's nothing wrong with letting the CMS write the files directly. However, you'll want to configure the web server to not execute anything in any directory writable by the CMS.
Even though you don't want to hit the database every time, you can set up a cache to minimize database reads. Zend_Cache works very nicely for this, and can be used quite effectively as a stand-alone component.
You should put your pages in a database and retrieve them using parameterized SQL queries.
I'd go with the second option but modify it so the files are retrieved using mod_rewrite rather than a custom php function.

Secure password list in PHP

I'm thinking about storing list of passwords for users (eventually more info about them) of small-scale (max. 20 users) app in PHP file in directory like public_html_root/system/config/
<?php if($calledByApp !== true) die();
$pwds['username1'] = 'hispassword';
$pwds['username2'] = 'herpassword';
$pwds['username3'] = 'anotheroned';
?>
Now. hispassword is actually hashed version
$hashedpasword = sha1($password.sha1($salt));
This way, if file is included, it checks for $calledByApp, which is set upon starting from entry point - i.e. index.php in root, so we could say it's safe this way. If it's called directly from browser - it won't get served as text file, but rather as PHP file - and it will die also, since $calledByApp will return null or false.
Also, if another user is stored/deleted, the file gets rebuilt, so it reflects all users. And after including this file, we have all users in pretty array, so if we call
if (is_string($pwds[$sanitized_username])
&& ($pwds[$sanitized_username] === $sanitized_sha1_userpassword))
we'll do login.
My question is: Is this safe enough?
Clarification: DB for users seems to be a bit overkill - another table for max 20 users. Also, while this doesn't check if user is real, it won't do anything with DB - looks like added security too.
If for some reason mod_php has a hiccup it could result in httpd showing the uninterpreted file; store the script outside of the document root in order to fix this.
I would rather place that file outside of document root instead of relying on the PHP interpreter not failing for any reason.
No - this is a really bad idea.
By making your souce code files writeable you open a whole avenue for attacking your system.
Embedding data into source code is a messy practice - not least because it will not scale.
What happens if the file is locked for an update when a script tries to include it?
What happens when the connection to the browser is lost part way through writing the file?
If you're quite sure that you'll only ever have a very small number of users and a low level of concurrency then abetter solution by far would be to have a seperate directory, with all http access denied, containing one file per user, named with the username (or a hash of it if you prefer) containing the hashed password.
C.
It's always safer to store the encrypted passwords in a database.
If you are using a database then I would store user data in there. If not then I would look to start using one.

Categories