SQL injection on INSERT - php

The SQL Injection on INSERT as described here doesn't seem to work with MySQL.
SQL injection on INSERT
When I use this statement:
INSERT INTO COMMENTS VALUES('122','$_GET[value1]');
With this as the 'value1' variable value:
'); DELETE FROM users; --
This error gets returned:
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 'DELETE FROM users; --')' at line 1
What's wrong???
PS: Someone suggested me to do an SQL injection with this as variable value:
',(SELECT group_concat(table_name) FROM information_schema.tables INTO OUTFILE '/var/www/tables.txt'))-- -
But it didn't work either, and returned a syntax error.

Your injection turns a single SQL statement (INSERT ...) into multiple SQL statements (INSERT ...; DELETE ...).
However, the PHP mysql API does not support multiple statements in a single query. (The underlying MySQL C API must be explicitly instructed to support this functionality, which your bindings do not do.)

As #pilcrow points out, mysql_query will only accept a single statement. Your example is actually two statements:
INSERT INTO COMMENTS VALUES('122','value');
and:
DELETE FROM users;
The PHP mysql API will reject this immediately, so you can't use that to test SQL injection.
Another problem with the statement is the use of comment characters. The MySQL Comment Syntax states that:
From a “-- ” sequence to the end of the line. In MySQL, the “-- ”
(double-dash) comment style requires the second dash to be followed by
at least one whitespace or control character (such as a space, tab,
newline, and so on). This syntax differs slightly from standard SQL
comment syntax, as discussed in Section 1.8.5.5, “'--' as the Start of
a Comment”.
So you have to have whitespace after the --. If you use # instead, no following whitespace is required.
A simpler and safer way to begin your SQL injection testing is to try a simple SELECT:
$value = "1' OR 1; -- ";
$sql = "SELECT * FROM mytable WHERE id = '$value'";
print "$sql\n";
// SELECT * FROM mytable WHERE id = '1' OR 1; #'
$result = mysql_query($sql,$con);
// Should return multiple rows (if your table has multiple rows):
while ($row = mysql_fetch_assoc($result)) {
print "{$row['id']}\n";
}
As the PHP mysql API rejects multiple statements, some of the more commonly used examples of SQL injection won't work, and that's a good thing. However, as you can see from the simple example above, it doesn't prevent other forms on SQL injection.
Think how a statement like this could be affected:
DELETE FROM mytable WHERE id = '1'
Also bear in mind that deleting data is probably not of much use to anyone other than a malicious hacker who just wants to cause disruption. Obtaining confidential data to which you are not supposed to have access, on the other hand, may be very useful.

Related

SQL Injection : VALUES with/without array [duplicate]

How do prepared statements help us prevent SQL injection attacks?
Wikipedia says:
Prepared statements are resilient against SQL injection, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
I cannot see the reason very well. What would be a simple explanation in an easy English and some examples?
The idea is very simple - the query and the data are sent to the database server separately.
That's all.
The root of the SQL injection problem is in the mixing of the code and the data.
In fact, our SQL query is a legitimate program.
And we are creating such a program dynamically, adding some data on the fly. Thus, the data may interfere with the program code and even alter it, as every SQL injection example shows it (all examples in PHP/Mysql):
$expected_data = 1;
$query = "SELECT * FROM users where id=$expected_data";
will produce a regular query
SELECT * FROM users where id=1
while this code
$spoiled_data = "1; DROP TABLE users;"
$query = "SELECT * FROM users where id=$spoiled_data";
will produce a malicious sequence
SELECT * FROM users where id=1; DROP TABLE users;
It works because we are adding the data directly to the program body and it becomes a part of the program, so the data may alter the program, and depending on the data passed, we will either have a regular output or a table users deleted.
While in case of prepared statements we don't alter our program, it remains intact
That's the point.
We are sending a program to the server first
$db->prepare("SELECT * FROM users where id=?");
where the data is substituted by some variable called a parameter or a placeholder.
Note that exactly the same query is sent to the server, without any data in it! And then we're sending the data with the second request, essentially separated from the query itself:
$db->execute($data);
so it can't alter our program and do any harm.
Quite simple - isn't it?
The only thing I have to add that always omitted in the every manual:
Prepared statements can protect only data literals, but cannot be used with any other query part.
So, once we have to add, say, a dynamical identifier - a field name, for example - prepared statements can't help us. I've explained the matter recently, so I won't repeat myself.
Here is an SQL statement for setting up an example:
CREATE TABLE employee(name varchar, paymentType varchar, amount bigint);
INSERT INTO employee VALUES('Aaron', 'salary', 100);
INSERT INTO employee VALUES('Aaron', 'bonus', 50);
INSERT INTO employee VALUES('Bob', 'salary', 50);
INSERT INTO employee VALUES('Bob', 'bonus', 0);
The Inject class is vulnerable to SQL injection. The query is dynamically pasted together with user input. The intent of the query was to show information about Bob. Either salary or bonus, based on user input. But the malicious user manipulates the input corrupting the query by tacking on the equivalent of an 'or true' to the where clause so that everything is returned, including the information about Aaron which was supposed to be hidden.
import java.sql.*;
public class Inject {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/postgres?user=user&password=pwd";
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='" + args[0] + "'";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
}
}
}
Running this, the first case is with normal usage, and the second with the malicious injection:
c:\temp>java Inject salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary'
salary 50
c:\temp>java Inject "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary' OR 'a'!='b'
salary 100
bonus 50
salary 50
bonus 0
You should not build your SQL statements with string concatenation of user input. Not only is it vulnerable to injection, but it has caching implications on the server as well (the statement changes, so less likely to get a SQL statement cache hit whereas the bind example is always running the same statement).
Here is an example of Binding to avoid this kind of injection:
import java.sql.*;
public class Bind {
public static void main(String[] args) throws SQLException {
String url = "jdbc:postgresql://localhost/postgres?user=postgres&password=postgres";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?";
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, args[0]);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
}
}
}
Running this with the same input as the previous example shows the malicious code does not work because there is no paymentType matching that string:
c:\temp>java Bind salary
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
salary 50
c:\temp>java Bind "salary' OR 'a'!='b"
SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).
This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.
More great info here:
Prepared statements and SQL Injection
I read through the answers and still felt the need to stress the key point which illuminates the essence of Prepared Statements. Consider two ways to query one's database where user input is involved:
Naive Approach
One concatenates user input with some partial SQL string to generate a SQL statement. In this case the user can embed malicious SQL commands, which will then be sent to the database for execution.
String SQLString = "SELECT * FROM CUSTOMERS WHERE NAME='"+userInput+"'"
For example, malicious user input can lead to SQLString being equal to "SELECT * FROM CUSTOMERS WHERE NAME='James';DROP TABLE CUSTOMERS;'
Due to the malicious user, SQLString contains 2 statements, where the 2nd one ("DROP TABLE CUSTOMERS") will cause harm.
Prepared Statements
In this case, due to the separation of the query & data, the user input is never treated as a SQL statement, and thus is never executed. It is for this reason, that any malicious SQL code injected would cause no harm. So the "DROP TABLE CUSTOMERS" would never be executed in the case above.
In a nutshell, with prepared statements malicious code introduced via user input will not be executed!
When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.
You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.
This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.
In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query.
Example of an SQL injection vulnerable statement.
string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";
Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:
select * from table where username='a' or 1=1 -- and password=asda
And the rest is commented after --, so it never gets executed and bypassed as using the prepared statement example as below.
Sqlcommand command = new sqlcommand("select * from table where username = #userinput and password=#pass");
command.Parameters.Add(new SqlParameter("#userinput", 100));
command.Parameters.Add(new SqlParameter("#pass", 100));
command.prepare();
So in effect you cannot send another parameter in, thus avoiding SQL injection...
The key phrase is need not be correctly escaped. That means that you don't need to worry about people trying to throw in dashes, apostrophes, quotes, etc...
It is all handled for you.
ResultSet rs = statement.executeQuery("select * from foo where value = " + httpRequest.getParameter("filter");
Let’s assume you have that in a Servlet you right. If a malevolent person passed a bad value for 'filter' you might hack your database.
The simple example:
"select * from myTable where name = " + condition;
And if user input is:
'123'; delete from myTable; commit;
The query will be executed like this:
select * from myTable where name = '123'; delete from myTable; commit;
Root Cause #1 - The Delimiter Problem
Sql injection is possible because we use quotation marks to delimit strings and also to be parts of strings, making it impossible to interpret them sometimes. If we had delimiters that could not be used in string data, sql injection never would have happened. Solving the delimiter problem eliminates the sql injection problem. Structure queries do that.
Root Cause #2 - Human Nature, People are Crafty and Some Crafty People Are Malicious And All People Make Mistakes
The other root cause of sql injection is human nature. People, including programmers, make mistakes. When you make a mistake on a structured query, it does not make your system vulnerable to sql injection. If you are not using structured queries, mistakes can generate sql injection vulnerability.
How Structured Queries Resolve the Root Causes of SQL Injection
Structured Queries Solve The Delimiter Problem, by by putting sql commands in one statement and putting the data in a separate programming statement. Programming statements create the separation needed.
Structured queries help prevent human error from creating critical security holes.
With regard to humans making mistakes, sql injection cannot happen when structure queries are used. There are ways of preventing sql injection that don't involve structured queries, but normal human error in that approaches usually leads to at least some exposure to sql injection. Structured Queries are fail safe from sql injection. You can make all the mistakes in the world, almost, with structured queries, same as any other programming, but none that you can make can be turned into a ssstem taken over by sql injection. That is why people like to say this is the right way to prevent sql injection.
So, there you have it, the causes of sql injection and the nature structured queries that makes them impossible when they are used.

How prepared statement protect again SQL injection in below statement

I have gone through various document (SO post as well) about how exactly Prepared statement of PDO protect user from SQL injection.
Although,I understand it protect user because in prepared statement,user record is directly not executing on server insted we are sending positional / named parameter ( ? / :name) and then we send actual data in execute statement, and because of that it saves us from SQL Injection.
Well, Now if I have below code for SQL :
$query = "select * from user where id = $user_input_id";
and user input id = 1
So query will be something like :
$query = "select * from user where id = 1";
This is perfect till now. But if user entre $id = "1; DROP TABLE users;" so query will be something like :
$query = "SELECT * FROM users where id=$id";
and hence ,it will execute
$query = "SELECT * FROM users where id=1; DROP TABLE users;";
It works and out user table will drop because this query directly execute:
Well,I have read that prepared statement can save user from this :
and prepared statement working like :
$data = "1; DROP TABLE users;"
$db->prepare("SELECT * FROM users where id=?");
$db->execute($data);
In execute statement as well,record with Drop table is passing,so how exactly it won't execute drop table statament ? execute also performing some part on server right ?
Anyone can please explain how exactly prepared statement here save user from SQL injection ?
Thanks
Without explicitly setting a type (see PDOStatement::bindValue() for an example), it will treat the passed value as a string, so it will do this effectively:
SELECT * FROM users where id='1; DROP TABLE users;'
Btw, this would actually happen if you're using emulated prepared statements (PDO::ATTR_EMULATE_PREPARES); without this, it will send the parametrised query first followed by the actual data.
That is why you can additionally set the type of binded data to the type you need.
$stm->bindParam(":id", $id, PDO:PARAM_INT)
Additionally, PDO does some escaping of the data, and the string you provided will not break the query at ;, but will be inserted as plain string in the db.
SQL injection is an attack against the SQL parsing step, not the statement execution step. In this, it has similarities to other parse attacks such as cross site scripting and XML injection attacks.
SQL injection works because the common (broken) technique of creating SQL statements by using string concatenation operators to combine both code and (untrusted) data in a single string allows for the possibility of a specially crafted string to violate the statement data protocol (typically by breaking out of a data context using string delimiters embedded in data), and allowing the attacker to manipulate the SQL parser into executing different code to that originally intended.
When one uses a prepared statement, one is telling the parser 'treat the statement purely as trusted code, and provide some slots into which I will insert the data for execution'.
When you drop the string '1; drop table users' into the data slot you created using the '?' placeholder, that string is not processed by the parser, and hence it has no opportunity to influence the parsing of the string : you made it impossible for the contents of the string to break out of a data context.
Using your example, the database will execute the equivalent statement to :
SELECT * FROM users where id="1; drop table users;"
This is a perfectly valid select statement, which may or may not return rows depending on the data in your tables, but which is almost certainly not going to work properly.
Nevertheless, the approach bypassed the attempt at SQL injection.
Be aware : using prepared statements is the ONLY generalised way to avoid SQL injection attacks. In general, attempts to filter untrusted input data are broken.

PHP: Understand SQL Injection

I'm working on old website and I found this error in log files:
Invalid SQL: SELECT COUNT(*) AS color_count FROM colors WHERE id IN (on,on) ;
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
'on,on) ' at line 1
The code php is like that :
$query = "SELECT COUNT(*) AS color_count FROM colors WHERE id IN ";
$ids = implode("','", $_GET['id_color']);
$query .= "('".$ids."') ";
I resolved this error by adding mysql_real_escape_string.
But I want to understand how an SQL injection can modify the query and remove the simple quotes ' from the query?
SQL injection can only add characters, it cannot remove characters from your SQL string. In other words, it's not "SQL suction". :-)
I can think of these possibilities:
The error in the log occurred on a date in the past, before your code did quoting. Perhaps it was originally designed to handle only integers, which aren't required to be quoted.
I recommend noting the date/time of the error in the log, then retrieve the version of code from your source control corresponding to that date.
The error was generated by a similar SQL query in another part of your code, where the code fails to quote the values.
I recommend searching all of your code for similar SQL queries.
Your code (or your framework) strips single-quotes out of the SQL string. I can't guess why it would do this, but in theory it's a possibility.
SQL injection is a danger (among other cases) anywhere you allow user input to be put directly into the statement. This is why bound statements are more secure and preferred.
The gist of it is, if I can tack on input to the end of your statement, there's nothing to stop me from adding a semicolon to end your current statement, and then a new statement in the same variable. So my string could be:
"11;Drop colors if exists cascade" which a naive execute would execute two statements, one of which completes as you expect, then the malicious one which deletes your table.
Now, a checkbox isn't likely to be a victim of injection, but it should always be a concern.
Do some more research on SQL injection, and really understand it. Then you can start building and modifying code to better combat it.
http://en.wikipedia.org/wiki/SQL_injection
It can be ' or '1'='1 if you want to break single quotes (http://en.wikipedia.org/wiki/SQL_injection).

Select keyword cant be inserted in to mysql table

I am using mysql database for an application. I get some user details. Once user uses select keyword in his answer, the Insert query causes problems in mysql. I am using nearly 300 insert queries in my over all application. Select keyword makes problem.
How to solve it in easy way?
Thanks in advance
UPDATED:
$query = "INSERT INTO `feedback_entry_mailactivity_log` ( `subject`, `body_text`, `to_mail_id`, `from_mail_id`, `cc_mail_id`, `created_user_id`, `created_date_time`, `last_updated_user_id`, `last_updated_date_time`, `feedback_entry_id`, `feedback_id`, `account_id`, `section_id`)
VALUES ('".$subject."', '".$body_text."','".$to_mail_id."','".$from_mail_id."','".$cc_mail_id."','".$assign_to_userid."', NOW(),'".$assign_to_userid."', NOW(),'".$feedback_entry_id."','".$feedback_id."','".$this->account_id."','".$temp_sectionid."' );";
$this->db->execute($query);
In this case if $subject="select a tag";
Thus when I use keyword select insert query doesn't works
The problem is the use of string-generated SQL statement -- this can lead to incorrect escaping and injection attacks (or mis-behaviors) leading to errors like above. Imagine if one of the input variables -- the one with 'SELECT' in it -- contains the SQL string-escape character such as Wish this would' SELECT FAIL. (This might not be the exact problem in this case and the real problem could lay with some other layer trying to "protect" the use of the bad access method(s).)
To fix this problem correctly use PDO (or similar) and prepared-statements. (Jeremiah Willcock suggested mysqli_prepare).
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
Note: Incorrect "solutions" include mysql_real_escape_string and similar. There are very few -- perhaps none for static DQL -- cases when "manual escaping with SQL string-building" approaches like this should be used.
Happy coding.

Are PHP MySQLi prepared queries with bound parameters secure?

Historically, I've always used
mysql_real_escape_string()
for all input derived from users that ends up touching the database.
Now that I've completely converted over to MySQLi and I'm using prepared queries with bound parameters, have I effectively eliminated the possibility of SQL injection attacks?
Am I correct in saying I no longer need
mysql_real_escape_string()?
This is my understanding and the basis of a project of mine:
http://sourceforge.net/projects/mysqldoneright/files/Base/MysqlDoneRight-0.23.tar.gz/download
This is not something I want to get wrong though as now that I've released it, it could affect others as well.
All user provided input will now end up in bind_parms.
The queries provided in the prepare phase are static.
Yes. Using the prepared query will escape parameters.
It's not so simple. You can use bound parameters instead of interpolating application variables into SQL expressions in place of literal values only:
$sql = "SELECT * FROM MyTable WHERE id = ".$_GET["id"]; // not safe
$sql = "SELECT * FROM MyTable WHERE id = ?"; // safe
But what if you need to make part of the query dynamic besides a literal value?
$sql = "SELECT * FROM MyTable ORDER BY ".$_GET["sortcolumn"]; // not safe
$sql = "SELECT * FROM MyTable ORDER BY ?"; // doesn't work!
The parameter will always be interpreted as a value, not a column identifier. You can run a query with ORDER BY 'score', which is different from ORDER BY score, and using a parameter will be interpreted as the former -- a constant string 'score', not the value in the column named score.
So there are lots of cases where you have to use dynamic SQL and interpolate application variables into the query to get the results you want. In those cases, query parameters can't help you. You still have to be vigilant and code defensively to prevent SQL injection flaws.
No framework or data-access library can do this work for you. You can always construct a SQL query string that contains a SQL injection flaw, and you do this before the data-access library sees the SQL query. So how is it supposed to know what's intentional and what's a flaw?
Here are the methods to achieve secure SQL queries:
Filter input. Trace any variable data that gets inserted into your SQL queries. Use input filters to strip out illegal characters. For instance, if you expect an integer, make sure the input is constrained to be an integer.
Escape output. Output in this context can be the SQL query which you send to the database server. You know you can use SQL query parameters for values, but what about a column name? You need an escaping/quoting function for identifiers, just like the old mysql_real_escape_string() is for string values.
Code reviews. Get someone to be a second pair of eyes and go over your SQL code, to help you spot places where you neglected to use the above two techniques.
When you bind parameters to a prepared statement, it escapes the data automatically, so you shouldn't escape it before you send it through. Double escaping is usually a bad thing. At the very least, it produces ugly results with extra escaped characters later on.

Categories