simple PHP $_GET sanitization question - php

I have a record edit link that GETs a 7 character alphanumeric text string which is always ZZZZ111 in structure and is then used in a MySQL query to pull all related data for that record id.
Is mysql_real_escape_string() all I need in terms of sanitizing this $_GET['id'] ? Or are there more steps to take to protect my database?

mysql_real_escape_string() will escape any malicious characters. In addition, you can use a regex like /^[A-Za-z]{4}\d{3}$/ to make sure that the user indeed entered a valid input.

To make input safe for an SQL query, mysql_real_escape_string() should be sufficient, though I suggest switching to PDO and prepared statements. They tend to be a little nicer to use, and a little more efficient (the statement is only parsed once, and the query can be re-used).
However, you also should make sure your pages are immune to cross-site scripting by (e.g.) filtering HTML from fields based on a whitelist.

If you plan on showing you data to users you would like to remove any HTML tags aswell. Maybe someone inserted a malicious javascript in a guestbook post for example?
this can be done with http://php.net/manual/en/function.htmlentities.php
Or you can use a inputfilter class to allow certain tags etc.
I found this one very useful http://www.phpclasses.org/browse/package/2189.html

mysql_real_escape_string() is a good start, and I would agree that using prepared statements would be a pretty good choice. Zend_Db is nice if you want to look into some DB abstraction which can make PDO easier to work with.
I'd also take this as an opportunity to write some sort of RegEx validator for your input. A sample regex that could get you started is:
[A-Z]{4}[0-9]{3}
More info on PHP and regex can be found here: http://www.regular-expressions.info/php.html

mysql_real_escape_string should do the job for $_GET['id']. Also, take a look at prepared statements via PDO.

Related

Is PDO-DEBUG secure? [duplicate]

Does execute($input_parameter) protect from sql injections just like bindParam/bindValue?
If the answer is yes, bindParam()/bindValue()/execute() are invulnerable to any sql-inject attack? Or I need to take measures to prevent such attacks?.
Thanks for help!.
As far as execute($input_parameters) being as safe as separate bindParam/bindValue/execute steps, the answer would appear to be basically, yes.
However, you might still need to take further measures depending on how you constructed the query string that you pass to your PDO::prepare call. It is not always possible to parameter-ize everything in the prepared query string. For example, you can't use a parameter for a table or column name. If you allow user data or any external data into that query string you must still sanitize that data before passing the string to prepare.
Refer to these stackoverflow questions for more details:
how safe are PDO prepared statements
Are PDO prepared statements sufficient to prevent SQL injection?
In general you should be filtering all input data anyway, so if you wanted to be extra safe you could sanitize any input data that is destined for SQL-type stuff using the filters appropriate for your needs, or even writing a FILTER_CALLBACK custom function if you wish.
In the case of table or column names coming from user-provided data, a common validation technique is to check the values against arrays of allowable names.
Hope this helps. Good luck. Stay safe! ;)
Yes, it does the same thing. I cannot say that it is invulnerable, because the underlying SQL engine could itself be vulnerable. But that really isn't in your hands anymore.
So for all practical reasons, yes, its safe.
EDIT: Look at the PHP Documentation (1st and second example). One is with bindParam() and the other uses execute().

Strip_tags or mysql_real_escape_string or add_magic_quotes in php

i reading about php security these days and i'm dizzy, please explain clear!
i know i should use strip_tags() or htmlentities() for XSS attacks. but if i need some where html tags, same as blog post, what should i do!?
but where should i use mysql_real_escape_string() and add_magic_quotes()?
are these same?
an other question is, should i use mysql_real_escape_string() for every SQL query? (INSERT, UPDATE,SELECT, DELETE, etc.)? can this function has bad effect on my data (for example, on a blog post that has html tags or ', "")?
i know i should use strip_tags() or htmlentities() for XSS attacks. but if i need some where html tags, same as blog post, what should i do!?
If you don't trust the users, then parse the HTML, run all the elements and attributes through a whitelister, then serialise the document back to HTML.
but where should i use mysql_real_escape_string() and add_magic_quotes()? are these same?
They aren't the same, and you should, generally speaking, avoid them. Use bound parameters instead.
an other question is, should i use mysql_real_escape_string() for every SQL query?
You should escape all user input before passing it to a dabtas.
Forget about magic_quotes. It was a lazy way to automatically escape certain control characters found within user input. Continue learning about newer and more efficient methods to filter/sanitize user input and you'll discover why magic_quotes has been deprecated.
can this function has bad effect on my data (for example, on a blog
post that has html tags or ', "")?
You shouldn't have any problems because the data isn't stored in the database with the extra slashes. If it is, there's a good chance magic_quotes is enabled and needs to be turned off.
should i use mysql_real_escape_string() for every SQL query?
User input needs to be filtered/sanitized before using it to make a query. Use that function, or prepared statements.
If you need to allow HTML within a blog post, you should whitelist tags and attributes, but you should not attempt this yourself. Instead, use HTMLPurifier. Use if before storing in the database as it is heavy and slow, but very safe.
http://htmlpurifier.org/
Magic quotes should not be used at all. Ever. mysql_real_escape_string() should be used on every single argument provided in the query. It is all that is needed to prevent SQL injections. Of course, making sure the connection expects the character encoding you are actually sending is a prerequisite.
The idea of a generic sanitation function is a broken concept.
There is one right sanitation method for every purpose. Running a generic sanitation method on a string will often break it - escaping a piece of HTML code for a SQL query will break it for use in a web page, and vice versa. Sanitation should be applied right before using the data:
mysql_real_escape_string() for functional mysql_* calls (or parametrized queries)
htmlspecialchars() for safe HTML output
preg_quote() for use in a regular expression
escapeshellarg() / escapeshellcmd() for use in an external command
etc. etc.
Using a "one size fits all" sanitation function is like using five kinds of highly toxic insecticide on a plant that can by definition only contain one kind of bug - only to find out that your plants are infested by a sixth kind, on which none of the insecticides work.
Always use that one right method, ideally straight before passing the data to the function. Never mix methods unless you need to.

php: clear input data before inserting it into mysql database

I'm wondering what's the best way to celar input data before inserting it into a mysql database.
There are a lot of function: trim, addslashes, mysql_real_escape_string and so on.
At this moment i'm using this simple function:
function filter($var){
$data = preg_replace('/[^a-zA-Z0-9]/','',$var);
$data = trim(addslashes($data));
return $data;
}
What's the best way to do it? Thanks
to be on the safe side, when dealing with mysql, mysql_real_escape_string() -- always use this. always.
Using mysql_real_escape_string() is enough for security reasons. Another way to do it is using prepared statements.
But you should check what information in what type you want in your database. There are several functions and language constructs you could use: Typecasts, filter_*() functions, int_val(), abs(), trim(), and a whole lot more.
I suggest you take a look at prepared statements that pretty much protect you against all form of SQL Injection.
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).
The best thing is to do multiple things:
Validate data
Clean data
escape date
The validation is to check whether the data you've got makes any sense. For instance if you expect a birth date you check whether the format is correct and maybe even whether the date amkes sense. This not only has security benefits but also prevents some (not all) errors of wrong data. The tools there depend on the case, regular expression (preg_match) are often a good choice.
Cleaning data is often not really needed, but nice, for instance if a user types in some value use trim() to split of some whitespaces, which might be mistakes from copy and paste or such. This has no security benefit but improves the overall quality of your data. Which is good.
Both of these things should be done early in your script. While "early" depends on your achitecture. Sometimes it makes sense to clean first an validate then or doing it at once (preg_replace)
Then when sending data of to a database or putting it in HTML or any of these things oyu have to escape it accordingly to the system you are using. You should do that for all data, even when you verfied the format beforehand to be on the safe side. When talking to mysql these are the real_escape_string functions for instance, for HTML it is htmlentities() or htmlspecialchars(). with databases it is also a good idea too look into prepared statements, either PDO->prepare + execute() or mysqli->prepare() +execute()

Is FILTER_SANITIZE_STRING enough to avoid SQL injection and XSS attacks?

I'm using PHP 5 with SQLite 3 class and I'm wondering if using PHP built-in data filtering function with the flag FILTER_SANITIZE_STRING is enough to stop SQL injection and XSS attacks.
I know I can go grab a large ugly PHP class to filter everything but I like to keep my code as clean and as short as possible.
Please advise.
The SQLite3 class allows you to prepare statements and bind values to them. That would be the correct tool for your database queries.
As for XSS, well that is entirely unrelated to your use of SQLite.
It's never wise to use the same sanitization function for both XSS and SQLI. For XSS you can use htmlentities to filter user input before output to HTML. For SQLI on SQLite you can either use prepared statements (which is better) or use escapeString to filter user input before constructing SQL queries with them.
If you don't trust your own understanding of the security issues enough to need to ask this question, how can you trust someone here to give you a good answer?
If you go down the path of stripping out unwanted characters sooner or later you're going to be stripping out characters that users want to type. It's better to encode for the specific context that the data is used.
Check out OWASP ESAPI, it contains plenty of encoding functions. If you don't want to pull in that big of a library, check out what the functions do and copy the relevant parts to your codebase.
If you are just trying to build a simple form and dont want to introduce any heavy or even light frameworks, then go with php filters + and use PDO for the database. This should protect you from everything but cross site request forgeries.
FILTER_SANITIZE_STRING will remove HTML tags not special characters like &. If you want to convert a special character to entity code prevent malicious users to do anything.
filter_input(INPUT_GET, 'input_name', FILTER_SANITIZE_SPECIAL_CHARS);
OR
filter_input($var_name, FILTER_SANITIZE_SPECIAL_CHARS);
If you want to encode everything it's worth using for
FILTER_SANITIZE_ENCODED
For more info:
https://www.php.net/manual/en/function.filter-var.php
I think its good enough to secure your string data inputs, but there are many other options available which you can choose. e.g. other libraries would increase your application process time but will help you to process/parse other types of data.

PHP: Is mysql_real_escape_string sufficient for cleaning user input?

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.

Categories