need help to prevent sql injection - php

hi i have the following statement
function count_rows($table_name, $condition = null, $debug = false)
{
$query_result = $this->query("SELECT count(*) AS count_rows FROM " . $this->db_prefix . $table_name . " " . $condition, $debug);
$count_rows = $this->sql_result($query_result, 0, 'count_rows');
return $count_rows;
}
i have been using sql inject me addon for firefox and it gives me the error
A Mysql error has occurred while running the script:
The query you are trying to run is invalid
Mysql Error Output: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2
SQL Query: SELECT count(*) AS count_rows FROM database_auctions a WHERE a.active=1 AND a.approved=1 AND a.deleted=0 AND a.list_in!='store' AND a.catfeat='1' AND a.closed=0 AND (a.category_id IN ())
how to sanitize this query against sql injection??

It looks like when you pass the $contidion you are forgetting something here a.category_id IN () between the parentesis should be values.
For avoid the SQL Injection check this

As you can see near this part of your query:
AND (a.category_id IN ())
You don't actually give it a subquery/list of values. You need to do so to determine if the result holds the category_id specified.
To help protect against sql injections, I suggest using the mysqli extension from PHP. I believe they support prepared statements. By using prepared statements, you are discarding the use of string concatenation, and the server "prepares" the sql statement, so the query is only sent to the server once, and then only parameters are sent when you actually execute the SQL query.
http://php.net/manual/en/class.mysqli-stmt.php
http://php.net/manual/en/mysqli-stmt.prepare.php

Related

Basic sql injection

I'm trying to learn SQL injections so I can protect myself in the future.
Here is the PHP code:
$req = mysql_query("INSERT INTO ip_change VALUES('', '".$_SESSION['id']."', '".$_POST['raison']."')") or die(mysql_error());
And the user has full control over $_POST['raison'] content.
When i use 'hello as $_POST['raison'] value I get
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'hello')' at line 1
When i use '); DELETE * FROM tabledetest;") or die(mysql_error());-- as $_POST['raison'] value I get
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'DELETE * FROM tabledetest;") or die(mysql_error());--')' at line
1
So I don't understand why my request isn't injected and I can't delete my tabledetest table.
Any help would be appreciated.
It is because you didn't do proper injection!
Here is the one you have done. The auto-format will hint you:
<?php
$_SESSION['id'] = "123"; //Just assume
$req = mysql_query("INSERT INTO ip_change VALUES('', '123', ''hello')") or die(mysql_error());
It didn't properly end the statement.
For the next one:
$req = mysql_query("INSERT INTO ip_change VALUES('', '123', ''); DELETE * FROM tabledetest;") or die(mysql_error());--')") or die(mysql_error());
From the manual:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
mysqli has support for multiple statements.
-- can't comment PHP code! PHP comment is // or #
Some of the links that might help you: [Similar to your question]
https://en.wikibooks.org/wiki/PHP_Programming/SQL_Injection_Attacks
http://roshanbh.com.np/2007/12/sql-injection-attack-examples-and-preventions-in-php.html
SQL injection test - mysql_query
To protect from SQL injection you should not inject the variables directly to query use Prepared Statements instead.

SQL error when deleting from MySQL

I am coming across a problem when deleting data from my SQL data. I have tried various versions of my statement but to no avail. Below is the error I am presented with and the statement I am using.
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= $user AND title= $check_value)";
//connect to database then execute the SQL statement.
$db->exec($sql);
and the error message is:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '#xml119.com AND
title= Luxurious Jamaican holidays | 40% Discount On Accommodati' at
line 1
I can see that the correct data is being passed but the syntax is wrong. Can anyone help?
$check_value is a string, so you have to enclose it in ' in your query like this:
title = '$check_value'
For security purposes, you should also use mysql_real_escape_string on all string parameters you have. Or even better, use prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
You need to put quotations around your variables. It doesn't like spaces.
Depending on the server you are using (MySQL or MSSQL) you have to use backticks, single quotes, or double quotes:
DELETE FROM saved_holidays WHERE (subscriberID="$user" AND title="$check_value")
Also, if you are using PDOs, you should consider using prepared statements:
$statment = $conn->prepare("DELETE FORM saved_holidays WHERE (subscriberID=? AND title=?)"); //$conn has to be your connection ceated by doing new PDO(...connection string...)
$statment->execute(array($user, $check_value));
Amit is correct your statement should look like this;
$sql = "DELETE FROM `saved_holidays` WHERE (subscriberID= '$user' AND title= '$check_value')";
the variable is a string so must be enclosed in single quotes.
This should then work for you.

Why do I get an SQL error when there is an apostrophe at the end of my URL?

Why do I get an error when I add ' to the end of a URL? For example : http://mywebsite.com/singel?id=24'
I get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' LIMIT 1' at line 1
This is shown everywhere if I put ' after any id in the query string.
What is wrong, and how it can be fixed?
Thank you.
You are inserting a non-escaped variable in an SQL query. And if this variable happens to contain SQL special chars, this can cause SQL syntax errors or worse.
You need to escape your variables before inserting them in your SQL queries.
Example:
$query = "SELECT * FROM users WHERE id = " . mysql_real_escape_string($id);
Instead of (this is WRONG, don't do this):
$query = "SELECT * FROM users WHERE id = $id LIMIT 1";
If $id is 24', the query becomes:
$query = "SELECT * FROM users WHERE id = 24' LIMIT 1";
As you can see, there is a ' after 24, which is a syntax error.
if a ' kills your query, you very obviously have an sql injection vulnerability. Read up on mysql_real_escape_string(), bobby-tables, and consider switching to PDO prepared statements.
Look here
http://www.codeproject.com/KB/database/SqlInjectionAttacks.aspx
You should learn something about SQL injection. Your Script is injectable now
This error usually means you are open to sql injections. This function is a bit more complicated than mysql_real_escape_string(), because it also does a PHP configuration test, to make sure you do not escape the data twice and to add Various PHP version support! (as per PHP Manual 1)
Just run this little nifty function on each of the submitted items, for inserts, updates or where statements:
function sql_injection($value){
$value = trim($value);
if(get_magic_quotes_gpc())
$value = stripslashes($value);
if(function_exists("mysql_real_escape_string")){
$value = mysql_real_escape_string($value);
}else
$value = addslashes($value);
return $value;
}
Ex:
$q = 'SELECT `blah` FROM `users` WHERE `id`='.sql_injection($_POST['id']);
This function does NOT replace server side validation, and everything should be validated before using it, always assume the worst :)

mysql_real_escape_string() not sanitizing variable

I'm working on an existing website trying to prevent SQL injections. Before $_GET['ID'] was unsanitized.
$ID=mysql_real_escape_string($_GET['ID']);
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID=$ID AND s1.MERCHANT_ID=me.MERCHANT_ID");
If I put a ' at the end of the url, with mysql_real_escape_string() I get this from mysql_error():
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
with out mysql_real_escape_string() I get:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
I'm not sure whats up with it? Any help would be greatly appreciated.
If it is an id, numerical I assume, why don't you just cast it to an integer?
$ID = (int) $_GET['ID'];
The best advice I can give you is to check out PDO and use bound parameters.
mysql_real_escape_string escapes, but doesn't quote.
Try:
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID='$ID' AND s1.MERCHANT_ID=me.MERCHANT_ID");
More generally, I tend to wrap both of these in a function, like:
function quoteValue($value) {
return "'" . mysql_real_escape_string($value) . "'";
}
This is useful, because you may find down the line that you want more refined quoting behavior (especially when it comes to handling Unicode, control characters, etc.)
It's because you're not quoting the variable.
Here's your query given the following inputs
$_GET['ID'] = "1";
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1 ...
$_GET['ID'] = "1'"
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1\' ...
$_GET['ID'] = "1'"
SELECT ... where s1.MERCHANT_ID=1' ...
Phil Brown is right, but you shoul forget about old fashioned mysql_real_escape_string or mysql_connect() as they are very old and move to php`s PDO() where you cand use prepared statements, binds, fetch object any many many more functions.
I suggest read PDO documentation at http://php.net/manual/en/book.pdo.php if you want next generation dabatase manipulation and security from SQL Injection .

PHP PDO prepared query refuses to execute properly - escaping problem?

I'm having a problem with a query prepared in PHP with PDO. The code:
$link = new PDO("mysql:dbname=$dbname;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT locality_name FROM :passedday GROUP BY locality_name ORDER BY locality_name DESC");
$query->bindParam(":passedday",$day); //Where day is, well, a day passed to the script elsewhere
$query->execute();
$result = $query->fetchAll();
$link = null;
//Do things with the $result.
The error message I am getting is:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''05_26_09' GROUP BY locality_name ORDER BY locality_name DESC' at line 1
When I execute the query on the server directly, it returns the appropriate result set without any problem. Any ideas what I'm doing wrong?
TIA.
Edit:
$day is passed as a GET argument. So, http://127.0.0.1/day.php?day=05_26_09 leads to $day = $_GET['day'];.
If 05_26_09 is supposed to bet the table's name, then I guess you've an escaping problem. Is your local operating system different from the live server?
I don't think you can use bindValue()/bindParam() for something else than values (eg. table name, field name). So I'm a bit suprised, that it works on your local system.
PDO uses mysql's C-API for prepared statements.
http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-prepare.html says:The markers are legal only in certain places in SQL statements. [...] However, they are not allowed for identifiers (such as table or column names)As a rule of thumb I use: "if you can't wrap it in single-quotes in an ad-hoc query string you can't parametrize it in a prepared statement"

Categories