Using the pg_escape_literal PHP function, I'm escaping my user input data as follows:
<?php
$dbconn = pg_connect('dbname=foo');
$escaped = pg_escape_literal($_GET['name']);
pg_query("INSERT INTO participants (name) VALUES ({$escaped})");
?>
Being new to PostgreSQL, my questions are:
Is there a way to achieve an SQL injection given this code?
Is there any other vulnerability that is left untreated in this code?
Using PHP 5.4 and PostgreSQL 9.2.
Since you do not trust any user input and you escape it accordingly, there is no injection in there.
Furthermore, you can use prepared statements to ensure you don't forget any escape, and you take correct data types for the sentence.
Remember that if you forget only 1 escape, your whole system is compromised despite it may be escaped all the rest.
That is the recomended method for escaping queries and ensuring sql injection attacks do not work.
If you are extra paranoid, or just want to be safe, you can also do regex to weed out unwanted characters and length checks of the data before you escape it.
Related
I'm using PHP PDO for my queries, everywhere, but I read that in very rare cases there could still be "second order injections" where an unsafe variable is stored then executed when used in another statement.
Will prepared statements still protect against this? As long as I make sure I always use them? Or do I have to take more precautions? Am I still vulnerable to XSS attacks?
I also have a couple more questions, just out of curiosity, if you all don't mind:
Is it possible to have an SQL Injection with only alphanumeric characters, spaces, and one dash? Like select * from something where name='$some_variable'. All the examples I've seen seem to require other characters like semicolons, quotes, or double dashes.
I've read many SQL examples where the unsafe variable could be set to form another statement, eg
$foo = "foo'); INSERT INTO users (name) VALUES ('hi";
$bar = ("INSERT INTO users (name) VALUES ('$foo')");
But I just tested and mysql_query doesn't even allow multiple statements. I know you can still have injections within 1 statement, but can I confirm that you won't have problems with multiple statements in PHP?
Not to beat a dead (or is it a very alive?) horse, but...
Injection can only happen when data is read by the SQL engine as commands. In a very simple case, if you allow unescaped " characters in your data, and your data is encapsulated by " characters in SQL, they you have enabled an SQL injection attack.
The key to preventing any SQL injection is to properly validate and escape incoming data EVERY time, at the time it goes into the SQL statement. An easy way to do this is to just use prepared statements, which take care of it for you, allowing you to safely pass parameters to an SQL statement.
Each database library has it's own way of escaping or using prepared statements. In MySQL and PHP, you have mysqli_real_escape_string(), which should be used EVERY TIME PERIOD, when you are using the mysqli library.
The PDO library has it's own way, but if I recall correctly, prepared statements were a big part of PDO -- use them 100% of the time, and you will be OK in that regard.
To prevent agains XSS attacks, use HTML Purifier, and never strip_tags(), see links below for more info, PDO prepared statements should be fine for SQL Injection prevention:
http://www.reddit.com/r/PHP/comments/nj5t0/what_everyone_should_know_about_strip_tags/
http://htmlpurifier.org/
Minus the whole addslashes() vs mysqli_real_escape_string() argumentation will stripping then adding slashes guarantee sql injection invulverability? Will this alter the data in anyway, for example displaying the string with double slashes after fetching it from the database?
so what you want to do is
$input='bla" SELECT * FROM blabla"';
$escaped=stripslashes(addslashes($input));
in that case
$input==$escaped is true
so no this would probably do nothing
thats why you should prefer mysql_real_escape_string
Escaping characters (addslashes()) may protect you from SQL Injection. I'm not an expert on how to sanitize inputs, and here's why:
I skipped the whole "sanitizing" thing and went straight to prepared statements. Sanitizing / escaping means you have to do the reverse on the output side, which means double the effort every time, and double the chances to mess up somewhere - allowing bad input in. If you just plop the PDO between every database query you do and the database itself, your worries are over.
That's not to say, of course, that the PDO protects you from attacks like CSRF or XSS, but the actual stored values are SQL-injection-safe, and you can strip html or whatever you need to do before you store it to protect from attacks like those.
NO
use: mysql_real_escape_string.
Why: you are not considering a ton of issues, mainly encoding of strings, etc...
No, having the right amount of slashes helps with some vulnerabilities, but you still need to check user input. There is no guarantee sql injection invulnerability, ever.
addslashes() will protect you in most cases. As for the getting the output, it depends how your submitting it, if you do
$input = addslashes("Bob's shoes")
you'll get Bob\'s shoes.
When you put this in your database
insert into tbl (txt) values (Bob\'s shoes)
The output of
select txt from tbl
will be Bob's shoes as you intended, the slashes are removed by the sql on insert.
If your anal about it you can say add other precautions, but if you want a quick and easy thing that's not a ridiculously secure website it should be fine. there's also built in php sanitize functions if you look them up
I'm new to PHP, and not yet familiar with how this works.
If I use mysqli_real_escape_string() and parameterize every variable in the SQL query, can I spare myself doing the validation with is_numeric(), etc.?
What is the best way to create a injection detection system? Simply validate the user's input with regex stuff and save it in the database?
Parametrizing your query is enough, you don't need anything else. You'll input the stuff they "inject" als a string, and there is nothing especially wrong with sql in a database... I suspect SO's database is full of SQL ;)
Escaping a value for MySQL simply adds a backslash in front of of the following characters: NULL \n \r \ ' " and 0x1A. It does nothing else.
An "escaped" value isn't magically safe for use in SQL. Escaping prevents special characters (such as quotes) from being misinterpreted. But if you insert an escaped value into an SQL query without surrounding it in quotes, then you've completely missed the point, and you are no more safe than you would have otherwise been.
Remember, the security procedure is quote and escape. You should always use those two together, since neither is safe without the other.
Also, if you can absolutely guarantee that your input value contains none of the above characters, then you also can be certain that your escaped string will always be identical to the unescaped one, and therefore escaping serves no additional purpose under those conditions.
But More Importantly:
Finally we have, in retrospect, realized that SQL was poorly designed from a security perspective, and relying on users properly quote and escape their data is just a really bad idea.
Parameterized queries are the solution, since it safely separates the data from the control structure. Parameterized queries are possible with mysqli by using prepare() followed by bind_param(). No escaping is necessary when using this method, and you can be confident that you are absolutely immune from SQL injection attacks.
Even if you have protected your variables against injection by using a parameterized query or mysql_real_escape_string() (not mysql_escape_string()), you should still validate them on the server side to ensure that they match the expected type of input. That way, if they do not, you can return an error message to your user with a request to retry those form fields.
If you use a parameterized query, such as offered by MySQLi as prepared statements, you needn't also escape the strings. However, if you don't use a parameterized query, it is essential to call mysql_real_escape_string() on every input parameter received by PHP.
This is a good question, and I think one of the best ways to avoid SQL injection is to learn about proper use of prepared statements
These will really help out the security of your application.
The issue with sql injection is the user inserting SQL data into a command and not validating that the data meets your business rules.
Making sure all user data is passed through mysqli_real_escape_string or used prepared statements is the best way to avoid problems.
What is the industry standard to filter input from users (both POST and GET) to avoid SQL injections and things of that nature. So far I am using filter_input() and mysql_real_escape_string() functions? Is that enough and if not, what other methods I should use?
An important rule to live by is FIEO. Filter Input Escape Output.
ANY information that you take and store from a user must be filtered server-side, in order to do this you should be using mysql_real_escape_string. It always should be the last thing you should before adding the value to the database. Validate the users input, ensure it is what you want, remove any symbols or tags if you need to using Regular Expressions, check its length and any other rules - do all this, then finally apply the MySQL function mysql_real_escape_string.
ANY information that you are displaying on your webpage that is dynamic - i.e. has come from a database of user-generated content or has directly come from user input must then be escaped. You must URL encode any symbols, remove (or encode) any HTML tags.
I highly recommend you watch this presentation on web security by expert Chris Shiflett:
http://www.slideshare.net/shiflett/evolution-of-web-security
Escaping to avoid SQL injection and filtering or validating inputs are two different things. You do not need to filter input to avoid SQL injection, and filtering input does not necessarily help against SQL injection.
To avoid SQL injection you escape the input so it won't mess up the syntax of your query, or you use prepared statements that avoid the problem entirely. It does not matter what this input contains, whether it's filtered or not. If you escape it once using the appropriate escaping function for your database or use prepared statements, you're done worrying about SQL injection.
You filter or validate input for different reasons, mostly because you do not want to allow certain values in the database. This is entirely separate from how these values are put into the database (which is where SQL injection could occur).
On output you need to escape the values according to your output medium as well, for the same reasons you escape them when putting them in an SQL query: to avoid messing up syntax, which may be exploited. I.e. when outputting to a webpage, you HTML escape your values. Again, it doesn't matter what value it is; if it's properly escaped, it can be anything.
i suggest you use database lib for saving data to database like pear db or cakephp orm
in this method you really sure noting can attack your db for injection
you may use PDO for database connection in php. PDO stands for PHP Data Object. It is better than mysql_connect. PDO is Objetc oriented and also it ensure much more protection.
http://www.php.net/manual/en/class.pdo.php
$link = new PDO ( $dsn, $user, $password, $options ) ;
use htmlspecialchars to encode characters that could cause problems. Validating the data is different, it depends on what you are expecting from the input field.
Is mysql_real_escape_string sufficient for cleaning user input in most situations?
::EDIT::
I'm thinking mostly in terms of preventing SQL injection but I ultimately want to know if I can trust user data after I apply mysql_real_escape_string or if I should take extra measures to clean the data before I pass it around the application and databases.
I see where cleaning for HTML chars is important but I wouldn't consider it necessary for trusting user input.
T
mysql_real_escape_string is not sufficient in all situations but it is definitely very good friend. The better solution is using Prepared Statements
//example from http://php.net/manual/en/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
Also, not to forget HTMLPurifier that can be used to discard any invalid/suspicious characters.
...........
Edit:
Based on the comments below, I need to post this link (I should have done before sorry for creating confusion)
mysql_real_escape_string() versus Prepared Statements
Quoting:
mysql_real_escape_string() prone to
the same kind of issues affecting
addslashes().
Chris Shiflett (Security Expert)
The answer to your question is No. mysql_real_escape_string() is not suitable for all user input and mysql_real_escape_string() does not stop all sql injection. addslashes() is another popular function to use in php, and it has the same problem.
vulnerable code:
mysql_query("select * from user where id=".mysql_real_escape_string($_GET[id]));
poc exploit:
http://localhost/sql_test.php?id=1 or sleep(500)
The patch is to use quote marks around id:
mysql_query("select * from user where id='".mysql_real_escape_string($_GET[id])."'");
Really the best approach is to use parametrized queries which a number of people ahve pointed out. Pdo works well, adodb is another popular library for php.
If you do use mysql_real_escape_string is should only be used for sql injection, and nothing else. Vulnerabilities are highly dependent on how the data is being used. One should apply security measures on a function by function basis. And yes, XSS is a VERY SERIOUS PROBLEM. Not filtering for html is a serious mistake that a hacker will use to pw3n you. Please read the xss faq.
To the database, yes. You'll want to consider adequately escaping / encoding data for output as well.
You should also consider validating the input against what you expect it to be.
Have you considered using prepared statements? PHP offers numerous ways to interact with your database. Most of which are better than the mysql_* functions.
PDO, MDB2 and the MySQL Improved should get you started.
What situations?
For SQL queries, it's great. (Prepared statements are better - I vote PDO for this - but the function escapes just fine.) For HTML and the like, it is not the tool for the job - try a generic htmlspecialchars or a more precise tool like HTML Purifier.
To address the edit: The only other layer you could add is data valdation, e.g. confirm that if you are putting an integer into the database, and you are expecting a positive integer, you return an error to the user on attempting to put in a negative integer. As far as data integrity is concerned, mysql_real_escape_string is the best you have for escaping (though, again, prepared statements are a cleaner system that avoids escaping entirely).
mysql_real_escape_string() is useful for preventing SQL injection attacks only. It won't help you with preventing cross site scripting attacks. For that, you should use htmlspecialchars() just before outputting data that was originally collected from user input.
There are two ways, one is to use prepared statements (as mentioned in other answers), but that will slow down your app, because you now have to send two requests to the Database, instead of one. If you can live with the reduced performance, then go for it; Prepared Statements makes your code prettier and easier to deal with.
If you chose to use mysql_real_escape_string, then make sure that you escape all the strings that are untrusted. An (mysql_real_escape_string) escaped string is SQL Injection secure. If you don't escape all the strings, then you are not secure. You should really combine mysql_real_escape_string with input validation; checking that a variable you expect to hold a number really is a number and within the expected range. Remember, never trust the user.
There are different types of "cleaning".
mysql_real_escape_string is sufficient for database data, but will still be evaluated by the browser upon display if it is HTML.
To remove HTML from user input, you can use strip_tags.
I would suggest you look into using PDO instead of regular MySQL stuff, as it supports prepared statements right out of the box, and those handle the escaping of invalid data for you.
You can try both, as in
function clean_input($instr) {
// Note that PHP performs addslashes() on GET/POST data.
// Avoid double escaping by checking the setting before doing this.
if(get_magic_quotes_gpc()) {
$str = stripslashes($instr);
}
return mysql_real_escape_string(strip_tags(trim($instr)));
}
The best way to go would be to use Prepared Statements
I thought I'd add that PHP 5.2+ has input filter functions that can sanitize user input in a variety of ways.
Here's the manual entry as well as a blog post [by Matt Butcher] about why they're great.