Best way to prevent SQL injections in Joomla 3 - php

I'm working to create a function that call a field in joomla database.
Is that a good usage to prevent sql injection?
// Get std objects
if (strlen($urlparams)<5) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('params');
$query->from($db->quoteName('#__template_styles'));
$query->where($db->quoteName('id')." = ".$db->quote($urlparams));
$db->setQuery($query);
$row = $db->loadResult();
}
else {
echo 'Something is going worng.';
}
Thank you and best regards.

You current method is perfectly fine as it uses the most up to date Joomla coding standards.
The only thing I would do it use quoteName() in your select clause which is used to escape field names. So you would end up with the following:
$query->select($db->quoteName('params'));
If you are ever in doubt, have a look at Joomla's:
Secure Coding Guidelines and
Documentation for Accessing the Database

Related

Retrieving words from database with codeigniter

I have recently started using codeigniter and I am a bit stuck as it is all rather new to me.
I use to have a config file with database conection and this on it:
$qset = "select * from re_settings";
$rset = mysql_query($qset) or die(mysql_error());
$aset = mysql_fetch_array($rset);
and this would allow me to pull words from database by simply putting this on the site
<?=$aset['SiteTitle']?>
How can I do this in codeigniter? Do I need to have a controller to do this or is it something much simpler than that.
You'll need to become familiar with the concepts of MCV which is how Codeigniter is built on and your ORM framework.
There's a bunch of helpful resources on http://tutorialcodeigniter.com/ or the official docs http://ellislab.com/codeigniter/user-guide/database/examples.html
as an example
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['email'];
}
I strongly recommend to use Datamapper along with CodeIgniter.
You will be surprised on how it is easy to work with your MySQL database.
Say goodbye to "mysql_fetch_array" 's and such.
Have a look : http://datamapper.wanwizard.eu/pages/getadvanced.html

Escape SQL queries in PHP PostgreSQL

I have a website with lots of PHP files (really a lot...), which use the pg_query and pg_exec functions which do not
escape the apostrophe in Postgre SQL queries.
However, for security reasons and the ability to store names with
apostrophe in my database I want to add an escaping mechanism for my database input. A possible solution is to go
through every PHP file and change the pg_query and pg_exec to use pg_query_params but it is both time consuming
and error prone. A good idea would be to somehow override the pg_query and pg_exec to wrapper functions that would
do the escaping without having to change any PHP file but in this case I guess I will have to change PHP function
definitions and recompile it which is not very ideal.
So, the question is open and any ideas that would
allow to do what I want with minimum time consumption are very welcome.
You post no code but I guess you have this:
$name = "O'Brian";
$result = pg_query($conn, "SELECT id FROM customer WHERE name='{$name}'");
... and you'd need to have this:
$name = "O'Brian";
$result = pg_query_params($conn, 'SELECT id FROM customer WHERE name=$1', array($name));
... but you think the task will consume an unreasonable amount of time.
While it's certainly complex, what alternatives do you have? You cannot override pg_query() but it'd be extremely simple to search and replace it for my_pg_query(). And now what? Your custom function will just see strings:
SELECT id FROM customer WHERE name='O'Brian'
SELECT id FROM customer WHERE name='foo' OR '1'='1'
Even if you manage to implement a bug-free SQL parser:
It won't work reliably with invalid SQL.
It won't be able to determine whether the query is the product of intentional SQL injection.
Just take it easy and fix queries one by one. It'll take time but possibly not as much as you think. Your app will be increasingly better as you progress.
This is a perfect example of when a database layer and associated API will save you loads of time. A good solution would be to make a DB class as a singleton, which you can instantiate from anywhere in your app. A simple set of wrapper functions will allow you to make all queries to the DB go through one point, so you can then alter the way they work very easily. You can also change from one DB to another, or from one DB vendor to another without touching the rest of the app.
The problem you are having with escaping is properly solved by using the PDO interface, instead of functions like pg_query(), which makes escaping unnecessary. Seeing as you'll have to alter everywhere in your app that uses the DB, you may as well refactor to use this pattern at the same time as it'll be the same amount of work.
class db_wrapper {
// Singleton stuff
private $instance;
private function __construct() {
// Connect to DB and store connection somewhere
}
public static function get_db() {
if (isset($instance)) {
return $instance;
}
return $instance = new db_wrapper();
}
// Public API
public function query($sql, array $vars) {
// Use PDO to connect to database and execute query
}
}
// Other parts of your app look like this:
function do_something() {
$db = db_wrapper::get_db();
$sql = "SELECT * FROM table1 WHERE column = :name";
$params = array('name' => 'valuename');
$result = $db->query($sql, $params);
// Use $result for something.
}

would it be safe to use functions to access database values?

I am pretty new with PHP furthermore PDO so I am not fully aware of what to avoid (and include) when accessing databases apart from SQL injection. (FYI, in the example below the table "users" also include passwords), however would accessing the database using a function as below to get information from be safe? is it prone to attacks?
and if you don't understand why I've done this it's because I find it quicker and it will make it easier when linking tables :)
<?php
require("access/common.php");
function getval($username, $column, $table, $datab){
$query = "
SELECT
id,
username,
email
FROM ".$table."
WHERE
username = :username
";
$query_params = array(
':username' => $username,
);
try
{
$stmt = $datab->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die();
}
$row = $stmt->fetch();
if($row)
{
return $row[$column];
}
}
echo getval("USERNAME", "email", "users", $db);
?>
The question you ask is very open-ended. Your biggest vector for attack is always what you do with user input (anything that a user can submit to your application/website through $_GET or $_POST variables). Certainly there are not security threats with the PHP language constructs eg. functions.
In your example I can see that you are binding the ":username" parameter but not the ":table" parameter which might be a vector for injection if you accept unsanitized user input and use it as the "$table" value.
Always be careful how your use $_GET and $_POST values... and when this becomes tedious, look for a framework to make some of this automatic.
A function is no safer or less safe than code outside of a function. If it's something you're going to be using more than once or twice, definitely put it in a function. As long as you're using PDO properly you'll be fine.
That said, you might want to put all your database functions in a class, then instantiate a $db object of that class, from which you can then call any database functions you need. There's lots of ways to organize your code to make things easier to work with.

PHP Class best practices and class structures

I'm currently creating a simple CMS for my small website in PHP5. This is my first 'larger' project in PHP. First I'm creating the needed classes that would simplify me the work a little bit, and there I'm stuck. I need your opinions about the following function inside my UserInfo class:
public function setUser($id) {
if(!isset($id)) {
return false;
}
session_start();
$conn = new mysql($_SESSION['DBCONNINFO']);
$sql = "SELECT
usr.ID,
usr.USERNAME as TUSERNAME,
usr.FIRST_NAME,
usr.LAST_NAME,
usr.PHONE,
usr.MOBILE,
usr.EMAIL,
usr.ADDITIONAL_INFO,
usr.LAST_LOGIN_DATE,
usr.USER_GROUP_ID
FROM cms_users usr
WHERE usr.id = " . $id;
$result = $conn->query_cust($sql);
$conn=null;
foreach ($result as $row) {
$this->id = $row['usr']['ID'];
$this->username = $row['usr']['TUSERNAME'];
$this->firstname = $row['usr']['FIRST_NAME'];
$this->lastname = $row['usr']['LAST_NAME'];
$this->phone = $row['usr']['PHONE'];
$this->mobile = $row['usr']['MOBILE'];
$this->email = $row['usr']['EMAIL'];
$this->additional_info = $row['usr']['ADDITIONAL_INFO'];
$this->last_login_date = $row['usr']['LAST_LOGIN_DATE'];
$this->user_group = $row['usr']['USER_GROUP_ID'];
}
return true;
}
Am I doing it the right way, I'm not talking about the syntax, for now I focus on the class structure, design and best practices - any opinion would be appreciated.
Could I call the session_start(), for example, in the class constructor and use the vars inside it without calling it each time in a function !?
Should I close the DB connection via the close() function or is $conn=null acceptable !?
Is it a bad practice to store the database information in the session class !? If yes, where to store it as a 'global' variable - $_GLOBAL !?
If there is a 'PHP bes practice class structures in 5 minutes for dummies' please notify me :)
Thanks in advance.
Use define to define all of your constants.
For example:
define('DBCONNINFO', "something");
Also you only have to call session_start() once, it can be done anywhere in your script.
It doesn't make a lot of sense to fetch the data from the database for every request if you're using sessions anyway. In which case, why is session_start() being called inside the setUser() method?
And we can't really comment on the class structure when you've only provided a single method.
Also, since the representation of data leaving PHP should be appropriate to the substrate where that data is going (to prevent SQL injection, email header injection, CSS....) then it's good practice to defer changes to the representation of the data until just before the point where it leaves PHP. e.g.
$sql = "SELECT
....
WHERE usr.id = " . mysql_real_escape_string($id);
(or use bound parameters)
However since users are usually identify themselves by their username rather than their userid, it rather implies that $id came from somewhere other than user supplied data - in which case where? And why are you using this as the identifier when you've already got an identifier for the session (which is where this data should be getting stored).
Or do you want to use this class for processing data relating to users other than the user of the current session - in which case there is no way that there should be a session_start() in there.
Sorry - but this is not well thought out code and not a well presented question.
BTW, setting the connection to null does not close the database connection.

Doctrine - how to get the SQL INSERT query, in the postSave() event?

I would like to get the exact SQL INSERT query that Doctrine generates when an object's save() method is called.
Preferably, I would like to get it in the postSave() event of the model and log it in a txt file.
For instance:
<?php
$user = new User(); // A Doctrine Model with timestampable behavior enabled
$user->first_name = 'Manny';
$user->last_name = 'Calavera';
$user->save();
?>
I want to get/log the following SQL query:
INSERT INTO user (first_name, last_name, created_at, updated_at) VALUES ('Manny', 'Calavera', '2010-08-03 12:00:00', '2010-08-03 12:00:00');
The background for needing this, is that I wish to mass-import later the data by parsing the txt file.
I don't think there is any easy way to do this since the behaviour of save() varies depending on a few different things (if you're inserting/updating).
If you had created a doctrine query object, then you can call the getSqlQuery() method like this:
$q = Doctrine_Query::create()
->select('u.id')
->from('User u');
echo $q->getSqlQuery();
but the save() is a method, not an object so this won't work. I think you'll have to hack in some code to detect whether you're inserting or updating and build a query to log on the fly and then use save().
I know this suggestion is not ideal because it is not logging 'exactly' what save() is doing but for the purposes you stated it should still work just as well.
Why don't you try to see how the symfony developers do it? Check their WebDebug Toolbar for Doctrine here. The WebDebug Toolbar outputs all query that you do on a page.
There's a hook on DoctrineEvent, and I think you can modify the code to do what you want. Check the getDoctrineEvents and getSqlLogs method.
Hope this helps. If you need further explanation, please write it in comment, I'll try my best to explain.
Take a look here: http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-8-hooks-profiling-dql and go to the section headed Profiling with Doctrine and Creating a Profiler Hook. Altough this is for the use with the CodeIgniter framework, it can be easy adopted to your own environment since the code has no dependencies to the framework.
You basically want to set up a Connection Profiler and let it write all queries to a file. I suggest appending all queries to the file to have a better "log"-like feeling. Don't get confused by many framework talk inside the articles. The examples work very well (with a little understanding and copy&pasting) in other scenarios.
you can use the profiler from the sfDoctrineDatabase class. Use the getQueryExecutionEvents to grab all queries.
$databaseManager = sfContext::getInstance()->getDatabaseManager();
if ($databaseManager) {
foreach ($databaseManager->getNames() as $name) {
$database = $databaseManager->getDatabase($name);
if ($database instanceof sfDoctrineDatabase && $profiler = $database->getProfiler()) {
foreach ($profiler->getQueryExecutionEvents() as $event) {
$conn = $event->getInvoker() instanceof Doctrine_Connection ? $event->getInvoker() : $event->getInvoker()->getConnection();
$params = sfDoctrineConnectionProfiler::fixParams($event->getParams());
$query = $event->getQuery() ;
foreach ($params as $param) {
$param = htmlspecialchars($param, ENT_QUOTES, sfConfig::get('sf_charset'));
$query = join(var_export(is_scalar($param) ? $param : (string) $param, true), explode('?', $query, 2));
}
// log the $query here, or use the symfony's logger
// sfContext::getInstance()->getLogger()->debug(sprintf('Query Run !! %s ', $query));
}
}
}
}
dont forget to join the query with the parameters (so it will replace ? with the values )
:D
You can convert you DQL query to SQL by this function: http://tokarchuk.ru/2010/12/dql-query-to-raw-sql/

Categories