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.
Related
I have read somewhere here that using prepared statements in PDO makes your app only immune to first order SQL injections, but not totally immune to second order injections.
My question is: if we used prepared statements in all queries inlcuding SELECT queries and not only in INSERT query, then how can a second order sql injection be possible?
For example in the following queries there is no chance for a 2nd order injection:
write:
INSERT INTO posts (userID,text,date) VALUES(?,?,?)
read:
SELECT * FROM posts WEHRE userID=?
delete:
DELETE FROM posts WHERE userID=?
What you have read is a plain rubbish. Someone who wrote it just have no clue.
You should use prepared statements not for the query but for the data. Every time you have to add a variable into query, you have to make it via placeholder only. So, your query separation theory makes no sense: it doesn't matter if it SELECT or ALTER or GRANT or whatever. The only thing that matters - if any variable goes into query or not.
Since most people sermonize “the user is evil” and “don’t trust user input”, one may get the impression that once the data is in the database it’s ‘trusted’.
But SQL injections is not about trusted and untrusted data. SQL injection is the failure of ensuring that an SQL statement is interpreted as intended.
And this is where prepared statements/parameterization comes in play as it’s a technique to ensure that the parameters are interpreted as intended, i. e., as data and not as SQL code. And this should be applied to any data, regardless of its origin or whether it’s seen as ‘trusted’ or ‘untrusted’, simply to ensure the data is interpreted as intended.
I'm very new to PHP and programming in general. I've come across an article about security, although not an issue yet in my case, I'm sure it will come up in the future at some point.
The article in question was about database input.
I'm using PDO most of the time while dealing with databases, however I'm confused about some parts. Perhaps someone can shed some light on a few things.
As I understand it, prepared statements in PDO for example:
SELECT <column> FROM <table name> WHERE <something>
Doesn't get execute right away(well, obviously) but only when execute(); is called. And gets interpreted as is.
So having something like
"SELECT <column> FROM <table name> WHERE" . <userinput> OR 1=1;
Lets say userinput is the username
And
<userinput> OR 1=1
is a user input variable via a form or whatever, will get interpreted exactly like that, meaning the username will be
userinput OR 1=1
And obviously no username OR 1=1 will exist in the database so an error will be returned.
That this mean that PDO is safe(a strong word, I know) from things like SQL injection? Or other 'hacking' methods?
What can I use/do to sanitize user input in general?
Yes it is safe, you can look at it as sandbox, if you have SQL like SELECT FROM books, it guaranties that input from user will not get out of boundaries (like modifying sql query), so it is safe from 1st order injection, but not from 2nd.
What i mean? Well PDO PREPARED statements(because you can use pdo without preparing statements in php) guaranties that you sql query is safe, but it doesn't filters the actual value.
Consider example: suppose we get some value from the form, the value will be 1); DROP TABLE books and we will save it in our database using our prepared statement INSERT INTO books VALUES(<value1>, ...),so the query will be executed successfully, value 1); DROP TABLE books will be saved in our database, but evil code will no be executed, no drop value. But if you then use our stored value in standard query, not prepared one. You will get hurt. But if you everywhere use PDO prepared statement your are safe. But i advice to filter values anyway.
Make use of Prepared Statements on PDO and you can stop worrying about SQL Injection.
I am sorry as this is the simplest answer i could give for this question.
Source
EDIT :
Found this answer on SO
Statement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
stmt.setString(1, user);
stmt.execute();
If "user" came from user input and the user input was
Robert'); DROP TABLE students; --
Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.
I'm currently writing a php framework with focus on security. I use a query builder to generate SQL-statements, so that it is not bound to MySQL. (Or SQL in general) I found certain posibilities that user could inject row names, so it has to escape them somehow. Because of how the query builder works, i sadly cannot use prepared statements. How can I fix this?
EDIT:
The system works for example like this: db::select()-from('Tablename')->that('rowname')->run(). And I'm afraid one user could do something like that($_GET['foo']) or something. I could live with that, but I thought there has to be a way to sanatize this
To escape backtick you have to double it. Here is a function from my class
private function escapeIdent($value)
{
if ($value)
{
return "`".str_replace("`","``",$value)."`";
} else {
$this->error("Empty value for identifier (?n) placeholder");
}
}
//example:
$db->query("UPDATE users SET ?u=?s", $_POST['field'], $_POST['value']);
So, it will create a syntactically correct identifier.
But it is always better to whitelist it, as there can be a field, though with correct name,to which a user have no access rights. (So, schema-based solution is still dangerous from this point of view. Imagine there is a role field with value admin for the query from my example)
I have 2 functions in my class for this purpose, both accepts an array of allowed values.
Because of how the query builder works, i sadly cannot use prepared statements. How can I fix this?
If you can't use query parameters, then change the query builder to apply escaping to its arguments before interpolating them into SQL expressions.
Lots of people correctly advocate for query parameters, but escaping is also safe IF you do it correctly and consistently.
Cf. mysqli::real_escape_string()
Re your comment, okay I see where you're going. I was confused because you said "row name" and that's not the correct terminology. You must mean column name.
Yes, you're right, there are no functions in any of the MySQL APIs to escape table or column identifiers correctly. The escaping functions are for string literals and date literals only.
The best way to protect SQL queries when untrusted input names a table or column is to use allowlisting. That is, test the argument against a list of known table names or column names, which you either code manually, or else discover it from DESCRIBE table.
See examples of allowlisting at my past answers:
escaping column name with PDO
PHP PDO + Prepare Statement
My presentation SQL Injection Myths and Fallacies
My book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.
somewhere while studying I juz found out something interesting.. It says something as follows:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
using the query like this instead of
$query="select firstname, lastname, address, age FROM friends
WHERE firstname='".$_RETURN['name1']."', lastname='".$_RETURN['name2']."'";
does this seem reasonable.. have u tried this coding ever.. and how it helps prevent any malicious attacks..
First off, what this is about is called is SQL-Injection. It's basically just the possibility to alter queries against the database via user input.
Let's look at an example:
Query:
SELECT temp1 FROM temp WHERE temp2 = 'VAR1';
Now we'll assign VAR1 the value of: '; DROP TABLE *; --
And we'll get:
SELECT temp1 FROM temp WHERE temp2 = ''; DROP TABLE *; --';
With mysql_real_escape_string it would look like this:
SELECT temp1 FROM temp WHERE temp2 = '\'; DROP TABLE *; --'
mysql_real_escape_string 'secures' a string for usage within a query.
But in the end, you should stop using the mysql_* altogether. They're deprecated and considered as insecure when it comes to preventing SQL injection or other means of tempering with the queries.
You should simply stop concatenating queries together like this and start using prepared statements, which not only are easier to use, prevent SQL Injection by default but also can improve the speed of your application.
For PHP there are two extensions which are designed to close the whole mysql_* opened:
mysqli
PDO
And I say it again: Please stop using mysql_*!
As far as I'm aware, mysql_real_escape_string is one of the better ways to prevent SQL injection, short of using prepared statements with mysqli or PDO.
Using formatting functions like sprintf is purely a matter of taste; the big advantage in the first example is that the function mysql_real_escape_string prevents all SQL injections (explained in one of the other answers); unlike the somewhat iffy magic_quotes_gpc feature in PHP, which many people rely on instead.
magic_quotes_gpc automatically escapes things you receive in requests from clients... but it cannot detect so-called second-level injections:
You get a malicious query from a client and store its contents in the database. magic_quotes_gpc prevents SQL injection; the malicious string gets stored correctly.
Later on, you fetch this string from the database and include it in another query. Now the string didn't come out of a request, so magic_quotes_gpc doesn't escape the string. Voilà, SQL injection; your data is now probably gone.
Using some means of escaping yourself, either something like mysql_real_escape_string or a database abstraction layer with a query builder (e.g. Adodb), is definitely superior to just hoping for the best.
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.