An SQL injection against which prepared statements won't help
- A simple update helper
- The injection
- PDO::quote() - the wrong move
- String escaping - a disaster
- Adding backticks (still vulnerable)
- Escaping backticks
- Solution that's solid all around
- Comments (21)
A simple update helper
While toying with PDO, almost every PHP user ends up with sort of improvement for INSERT/UPDATE query, that accepts an associative array and creates a query with placeholders dynamically, which basically looks like this (a real code taken from a question on Stack Overflow):
$params = [];
$setStr = "";
foreach ($data as $key => $value)
{
if ($key != "id")
{
$setStr .= $key." = :".$key.",";
}
$params[':'.$key] = $value;
}
$setStr = rtrim($setStr, ",");
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);
It looks pretty good, as it can quickly produce a query out of any array which keys represent column names and values represent values to be used in the query. Given field names in HTML form are the same as table column names, it can greatly automate the form processing, letting you to use the same code to edit information in any table. Very convenient. But catastrophically vulnerable.
"How's that?" - you'd probably say - "placeholders are used and data is safely bound, therefore our query is safe". Yes, the data is safe. But in fact, what does this code do is taking user input and adding it directly to the query. Yes, it's a $key variable. Which goes right into your query untreated.
Which means you've got an injection.
The injection
Here is a little proof of concept code, which, as long as you have a table "users" and a row with id=1, will change the user name in the table to a result of SELECT query. And this query could be anything:
<form method=POST>
<input type=hidden name="name=(SELECT'hacked!')WHERE`id`=1#" value="">
<input type=hidden name="name" value="Joe">
<input type=hidden name="id" value="1">
<input type=submit>
</form>
<?php
if ($_POST) {
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', '');
$params = [];
$setStr = "";
foreach ($_POST as $key => $value)
{
if ($key != "id")
{
$setStr .= $key." = :".$key.",";
}
$params[$key] = $value;
}
$setStr = rtrim($setStr, ",");
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);
}
This code will produce a query like this
UPDATE users SET name=(SELECT'hacked!')WHERE`id`=1# = :name=(SELECT'1')WHERE`id`=1#,name = :name WHERE id = :id
Where everything past first # will be treated as a comment.
You can try it at home.
What happens in this code? We are forging a form, adding another field to it, and writing an SQL code in the name attribute. The aforementioned helper function will take this forged SQL and insert it into constructed query. As a result, instead of "Joe" the name will be set to "hacked!". Not too scaring, eh? But you have to understand that what is dangerous here is the fact of injection. While as long as it is possible, the amount of exploits is infinite. And not all of them are that harmless. We will see a more dangerous exploit below.
PDO::quote() - the wrong move
Ok, we need to protect our useful code (as well as any other code that cannot be protected with prepared statements).
The first thing an average PHP user would probably think of is a built-in PDO::quote() function, which seemingly does what we need - protects the data from SQL injection. But soon it will be clear that a function intended for string formatting is inapplicable for identifiers. It will add quotes around returned value and will make our code to produce a sequence like this:
'name'='joe'
which will result in a syntax error - quotes are illegal as field name delimiters in MySQL.
DON'T ever think of trimming quotes from the resulting string either, as it was suggested some time ago in a heavily upvoted comment (now deleted) under PDO::quote()'s entry in PHP manual: the very purpose of this function is to do a complete formatting, doing both character escaping and adding quotes. Take out one of these two actions and you'll have an injection.
In other words, if we strip surrounding quotes from PDO::quote() result, it will be as though we only applied the regular sting escaping. And let's see why it is wrong:
String escaping - a disaster
Another thing a PHP user would think of is a familiar escaping function, which "makes your data safe" as falsely stated PHP manual for ages. Unfortunately, it will help only if injection code contains quotes or other characters this function deals with. The bad news, all these characters are unnecessary for injection, proving this function useless for the case (and disproving this function's fictional protecting skills):
<form method=POST>
<input type=hidden name="name=(SELECT password from admins)WHERE`id`=1#" value="">
<input type=hidden name="name" value="Joe">
<input type=hidden name="id" value="1">
<input type=submit>
</form>
<?php
if ($_POST) {
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', '');
$params = [];
$setStr = "";
foreach ($_POST as $key => $value)
{
if ($key != "id")
{
$setStr .= addslashes($key)." = :".$key.",";
}
$params[$key] = $value;
}
$setStr = rtrim($setStr, ",");
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);
var_dump("UPDATE users SET $setStr WHERE id = :id", $_POST);
}
As you can see, there is not a single quote in the malicious query and thus neither addslashes() not various *_escape_string() can do anything here.
This time injection is more dangerous as it will reveal the admin's password to anyone.
Adding backticks (still vulnerable)
Ok, as we learned already, quotes won't help. May be adding backticks would help? Not a slightest:
<form method=POST>
<input type=hidden name="name`=(SELECT'hacked!')WHERE`id`=1#" value="">
<input type=hidden name="name" value="Joe">
<input type=hidden name="id" value="1">
<input type=submit>
</form>
<?php
if ($_POST) {
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', '');
$params = [];
$setStr = "";
foreach ($_POST as $key => $value)
{
if ($key != "id")
{
$setStr .= "`$key` = :$key,";
}
$params[$key] = $value;
}
$setStr = rtrim($setStr, ",");
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);
}
As you can see, adding backticks didn't help us at all: an attacker just adds another one to prematurely close the identifier and then proceed with malicious query. It happens because adding whatever delimiters around some literal is useless if we don't escape these delimiters inside - the lesson that we learned hard from conventional string-based injections. So let's escape our backticks!
Escaping backticks
So, what can be done to retain such a helpful function, but without a terrible breach?
As it was said before, escaping delimiters would help. Therefore, your first level of defense should be escaping delimiters (backticks) by doubling them. Assembling your query this way,
$setStr .= "`".str_replace("`", "``", $key)."` = :".$key.",";
you will get the injection eliminated.
If we try to inject, using the method above, it will result in a query execution error, which, although is surely better than a successful injection, is still not quite a desirable behavior.
This is why quoting/escaping field names is still not enough. And this is why you should be using a another level of defense:
Solution that's solid all around
There is one more thing to keep in mind: although quoting/escaping field names will eliminate the classical SQL injection, there is another possible attack vector. As we don't control which field names are used for update, it is possible for the user to amend the value they shouldn't have an access to. For example, imagine there is a field in a users table like admin which is set to 1 for admins and 0 for regular users. The function in question will let any script-kiddie to raise the privilege level for their account.
Assuming all the above, such a useful function should be always accepting an additional parameter with a list of allowed field names:
<form method=POST>
<input type=hidden name="name`=(SELECT'hacked!')WHERE`id`=1#" value="">
<input type=hidden name="name" value="Joe">
<input type=hidden name="id" value="1">
<input type=submit>
</form>
<?php
if ($_POST) {
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', '');
$allowed = ["name","surname","email"];
$params = [];
$setStr = "";
foreach ($allowed as $key)
{
if (isset($_POST[$key]) && $key != "id")
{
$setStr .= "`".str_replace("`", "``", $key)."` = :".$key.",";
$params[$key] = $_POST[$key];
}
}
$setStr = rtrim($setStr, ",");
$params['id'] = $_POST['id'];
var_dump("UPDATE users SET $setStr WHERE id = :id",$params, $_POST);
$pdo->prepare("UPDATE users SET $setStr WHERE id = :id")->execute($params);
}
With such an improvement our code will become solid all around!
Of course, examples above would work only if emulation mode is turned on. But you have to understand that whether SQL injection can be successfully exploited or not is a different question and a quite irrelevant one. You should not let an injection in the first place. Or the way to exploit it will be found, this day or another.
Related articles:
- (The only proper) PDO tutorial
- PDO Fetch Modes
- Fetching objects with PDO
- Simple yet efficient PDO wrapper
- A fair comparison of mysqli vs. PDO
- Authenticating a user using PDO and password_verify()
- Your first database wrapper's childhood diseases
- MCVE or How to debug database interactions with PDO
- A cargo cult prepared statement
- Whitelisting helper function
Comments:
Please, exemple with select and backtrik
Well, that's all if you're silly enough to pass $_POST to a db wrapper without checking.
I've been using the kind of INSERT wrapper you so badly decry for ages in various languages, without a single problem... because I write server-side validation code that reads the params that the application expects (and not any extra ones), and then calls the required inserts or updates passing an array with all the relevant values.
Works like a charm.
Do I understand it correctly that this inclusion bases on the method to just USE ANY KEY stored in $_POST.. to create an insert/update?
So doing it the old fashioned way to get each variable, check it sanitize it and only then putting it into the prepared statment is not vulnerable as the evil keys would just stay in the $_POST without doing any harm.
Or did i miss something?
I'm a little confused - why are you still escaping backticks on your own foreach ($allowed as $key)
? Seems like a bit of an old "tick" ;)
Anyway, good stuff. Made me go back and check some old code. It's an easy newbie mistake to make, because reading field names off a web form is a quick and dirty shortcut. Years ago, a thing I used to do was check the column names on a table before an update. What I do these days is generate the whole form as a PHP object from a SQL table of field names, descriptions, data types, etc, and render it. When the user submits, the PHP object is re-created from the database -- the same as if we were going to render it -- but instead the object is used to validate and of course provide the field names to insert/update.
I'm somewhat new to this and have been perusing articles on the SQL injection issue. Some claim that parameterized stored procedures (called using PDO) are not susceptible to the SQL injection. Is that true?
In reply:
PHP uses HTML inputs from users to manipulate data in the SQL database. Therefore, there is a relationship there, and one your answer isn't addressing.
Yes, SQL and HTML are separate languages. But PHP is the common link between them that the article represents, thus the whole reason for your article.
If we're sending data via the PDO from an HTML form to an SQL database, there is a risk of exploitation of malformed SQL (a process we call "injection" due to its capability to "inject" data into the SQL query and receive more information than was intended or in another way compromise the security of the database, site, etc.).
The whole article was written to address that process. That's therefore the context of the question I asked.
Reply:
Hello Vishwa.
That's a very good question.
What you have to understand is the data source doesn't matter at all. It could be HTML, a text file, a JSON file, whatever.
And the source is just irrelevant to SQL.
When dealing with a database, you must consider the destination of the data, not the source. It's only the destination that matters. Hence HTML just has nothing to do with the article about SQL.
I'm curious: what if someone was to use a hashtag as part of, say, a password string? Let's say they were going to do this as a part of the signup page, and wanted to attempt an injection there?
Wouldn't manual replacement combined with some function like
htmlentities()with theENT_SUBSTITUTE|ENT_HTML5flags and assuring the charset of the DSN asutf8mb4still be preferable in such a case, where greater character variety is preferable to restricting characters?Alternately, would use of
filter_var()make sense to further sanitize inputs?I hope my question makes sense. I'm asking, because I see a LOT of code which use these functions as a way to sanitize the inputs, rather than specifically restricting the database structure.
Is there an advantage to the way you do it, over these other two functions (or similar)?
Reply:
Hello Vishwa !
I am not sure I understand what injection you are talking about here.
Speaking of SQL injection, it has nothing to do with htmlentities() or any other HTML related stuff. SQL and HTML are completely different things that have nothing in common.
So just make your mind what injection you want to be protected from and then use a method dedicated for this injection only.
Thank you for the reply.
I am creating a stripe version for database CRUD operations. That is, a web developer defines the table and column names in data- attributes (eg. data-tablename, data-columname) for his/her form or input fields, adds a script tag to handle events and data collection. On the backend developer makes a curl call to my application (with api key) for authentication. In order to make this simple i am allowing table and column names to be defined in the data attributes. I add a csrf token on the user page and a hashed signature in the session storage for verifying integrity. Just wanted to know if this is a stupid idea. But, I find it frustrating that so many man hours are wasted trying to save forms or fields in database. There has to be an easier and secured way. Would love to hear your thoughts as an expert. Again, thank you for this article. It has helped me a lot.
For the SQL injection, what if you only allow letters and numbers for column, table and database names. can it still be prone to injection. I have an application where the users might add columns on the fly.
Reply:
Hello again.
Allowing only letters and numbers should be safe in terms of syntax injection, but there will be still a wast opportunity for all sorts of cheating.
I would question such an architecture as well. There should be no direct connection between user-defined data and the database structure. There is always the way to have a stable db structure and user defined columns. I encourage you to ask a question on Stack Overflow asking for the proper solution.
How come PDO doesn't provide a float/decimal/double parameter type for bind values?
Been looking in your articles, but you do not touch on this issue.
Reply:
Hello!
First of all, please differentiate decimal values from double/float. The only way to correctly handle a decimal value is to represent it as a string, due to its very nature.
As of the double/float, there is an RFC published a year ago, https://wiki.php.net/rfc/pdo_float_type but it seems there was no progress since then.
Personally I never encountered any problem related to float values. Although I am trying to avoid them as much as possible, when they are used, I have no problem binding them as strings
I think sanitization is the wrong way to tackle this, one should build the statement using a switch/case, with a list of predefined field names that are allowed. That's only 100% safe way to do something like this. Anything unexpected should throw an exception immediately. Additionally never use real DB field names in any inputs, but offer them as something meaningless, say options 1,2,3. Internally you can map this into constants to make it still readable in the code, but attacker will have hard time just guessing what field 2 is. And always notify admin when your sql starts dropping exceptions as even the best hacker will not figure it out on the first try (or first 10).
Hello, If I begin each of my php mysql scripts (wich get data from the user) by these lines :
Am I protected against sql injections ?
Reply:
Hello Roland!
It's far from it. Your approach is wrong on so many levels. Why only $_POST for starter? SQL injection could come through $_GET, $_COOKIE or $_SERVER as well? And what about second order injections?
Like I said above, it's better to be safe than spare yourself a "trouble" of typing an array of allowed fields.
In order to get around needing to manually write a list of allowed fields to insert into my generated SQL query string, I have been checking the table for the column names and creating that whitelist array from the result:
The {$table} is a string that I set in the class that implements this function, so it's not user data. What do you think, amidoinitrite?
Reply:
Hello Abraham!
It could be plausible, but just remember there cold be fields that a user should not be able to set. Order price or permissions or something like that.
In your place I would define the list of allowed fields in the same class. Take Laravel's Eloquent for example. Its model have
fillableandguardedproperties which define the list of fields open for the mass update or forbidden from that respectively. Without any of these fields set, it won't allow the mass assignment like that.The one thing about this is there is no sterilization in your samples, I use a combination of htmlentities( ,ENT_QUOTES) and all of my post stuff, I use direct variables instead of a loop. I also substitute the E and e characters for their heml entity number equivalent to prevent the "add the select in the html hole"
Reply:
Hello David!
Sorry to disappoint you but all this stuff has absolutely nothing to do with SQL injections.
What you are talking about is for HTML, not SQL. I have no idea though what danger is coming from E character. I feel you are overthinking here.
I have a quick question about injection vulnerability. Is injection, with prepared statements, something I need to be worried about even with selected options that are queried from database? "for example, drop down menus for filtering through categories and sub categories. Or is this only a concern with actual user input directly from the keyboard? I wasn't sure if there was someway to fake a $_POST injecting into selection $_POST variables or not. Thank you so much for all your awesome PDO content here. I've been finding it to be extremely helpful.
In your example of what's safe you mention you can be sure to only pass allowed parameters, but wouldn't you still be vulnerable to someone instead of using
they could use
Of course we could do some kind of filtering or escaping on the allowed $_POST parameters, but the question then is what's the right way to do that?
Reply:
Hello Eric!
With values the protection is much simpler: just use prepared statements, and you will never see an SQL injection through value.
The point of this article is to show the SQL injection through POST keys, because it is used less often. But protecting values is not a problem at all - just use prepared statements!
Hope it is clear now. If not, feel free to ask!
Hello, your advice is very useful.
Please, you could put the code of how to stay with the INSERT statement, thank you very much!
Reply:
Hello Gustavo!
This article is not a crash course on SQL injections. So I am not going to provide any examples other than those required to explain protection measures.
limit column privileges to root or the DB admin. Until you can hack the passwords for these users PDO will throw an exception.
Reply:
Hello Peter!
I am not sure I am getting what are you talking about.
Nice article. But I have a question. In your solution you use str_replace. Is it not enough isset($_POST[$key]) ?
Reply:
Hello!
Thank you for the good question. In theory - yes, it should be enough to use a white list only. But I decided to keep str_replace just for sake of completeness. It is not for protection but to make the formatting complete. When you have a delimiter, it should be escaped inside. So this code does.
But in practice - yes, I hardly can imagine a case where you would really need this escaping, given field names are already filtered out.
This is a reminder that great tools mean nothing if people don't know how to use them. This video clip sums it up: https://www.youtube.com/watch?v=nvwR74XpKUM
Reply:
Hello Anna!
Yes, the clip nails it!
Thank you for this eye opening tutorial, in the process of converting some old mySQL wrappers to PDO.
I wanted to make sure I understood the proper escaping of fieldnames if I used a routine to build queries from arrays, similar to the routine you presented above. Assuming whitelisting to filter the keys, should the final output look like this? I was a bit unclear on the escaping for the params.
Thanks in advance...
Reply:
Hello Mark!
Thank you for the good question. I see now it's my fault, because I didn't word it properly. You have to quote only identifiers, but not placeholders. So, the result should be like shown by the link above:
this is why you need to whitelist the key names: because, if used for the placeholder names, they are left totally unprotected.