This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm building a MVC application for managing a creative portfolio (Going to put it on git hub). I need something to secure the DB connections, basically I have one class to manage ALL DB transactions.
I need to either create a class or find a class that can protect all SQL queries from XXS or SQL Attacks. What suggestions do you have for securing PHP Database connections?
Using PDO's prepared statements to access databases makes queries immune to injection.
http://us2.php.net/manual/en/pdo.prepare.php
Using htmlspecialchars() makes output immune to xxs.
http://us2.php.net/manual/en/function.htmlspecialchars.php
just try to filter you POST,GET requests with this function
function protect($string)
{
if (ini_get('magic_quotes_gpc') == 'off') // check if magic_quotes_gpc is on and if not add slashes
{
$string = addslashes($string);
}
// move html tages from inputs
$string = htmlentities($string, ENT_QUOTES);
//removing most known vulnerable words
$codes = array("script","java","applet","iframe","meta","object","html", "<", ">", ";", "'","%");
$string = str_replace($codes,"",$string);
//return clean string
return $string;
}
you can easily apply it for the whole input using array_map function
$input = array_map('protect','$_POST');
$input = array_map('protect','$_GET');
Related
i have the function for prevent sql injection
is an excellent function, really function in prevent attacks but
begin showing problems with characters
the word is "controle de finanças"
in var_dump i see string(31) "controle de finanças"
i´m trying some methods and failing 2 days please help me
function Anti_Sql_Injection($string){
if(ini_get('magic_quotes_gpc') == 'off'){
$string = addslashes($string);
}
$string = htmlentities($string, ENT_QUOTES);
$codes = array("script","java","applet","iframe","meta","object","html","CONCAT","CHAR","FLOOR","RAND", "<", ">", ";", "'","%");
$string = str_replace($codes,"",$string);
return $string;
}
Try this;
function Anti_Sql_Injection($string){
if(ini_get('magic_quotes_gpc') == 'off') {
$string = addslashes($string);
}
$string = htmlspecialchars($string, ENT_QUOTES,"UTF-8");
$codes = array("script","java","applet","iframe","meta","object","html","CONCAT","CHAR","FLOOR","RAND", "<", ">", ";", "'","%");
$string = str_replace($codes,"",$string);
return $string;
}
I also would like to tell you about PDO. It has built-in SQL injection via prepared statements. Check out this tutorial to start with PDO. I know it is kinda old but still valid and well explained.
Why are you using a function named Anti_Sql_Injection() to prevent XSS attacks? You should be using Prepared Statements to stop SQL injection and an appropriate, separate strategy for stopping XSS attacks.
Don't try to kill two birds with one stone. You end up altering data.
XSS prevention made easy
Are you using a framework that offers context-sensitive XSS escaping?
Yes: Use that feature then. Prioritize autoescape blocks over manual escape filters (e.g. with Twig).
No: Do you need to allow the user to provide some HTML?
Yes: HTML Purifier
No: htmlspecialchars($string, ENT_QUOTES | ENT_HTML5, 'UTF-8');
SQL Injection prevention made easy
Use prepared statements. A library like EasyDB (which wraps PDO) can make it less painful to migrate.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The ultimate clean/secure function
After reading up on PHP security I have the feeling that anything I code is always insecure. So to combat the security issues of user input I have created a function that allows me to escape and strip user input for any usage situation.
I would just like to know if this is in fact secure and if I could make it more secure. Also what kind of attacks would this prevent? From what I can tell XSS by using _GET, HTML input and MYSQL injection would have been prevented?
function _INPUT($name,$tag,$sql,$url)
{
if ($_SERVER['REQUEST_METHOD'] == 'GET')
$filter = ($_GET[$name]);//Assign GET to filter variable
if ($tag == true)//Remove all HTML, PHP and JAVASCRIPT tags
{
$filter = strip_tags($filter);
}
if ($sql == true)//If MYSQL escaping is enabled
{
$filter = mysql_real_escape_string($filter);
}
if ($url == true)//If URL encoding is enabled
{
$filter = urlencode($filter);
}
return $filter;
}
$output = _INPUT('name',true,true,true);
I will be using prepared statements for MYSQL too, although I need to read up on them more to fully understand how it prevents injection.
Thank you for your time.
Once again, there is no universal escape function that just magically makes things "secure".
See this: https://stackoverflow.com/a/7810880/362536
Different escape methods are used for different things. You can't just run a bunch of data through a bunch of functions that are supposed to be used in specific contexts. You are creating garbage data, and are no more secure than you were with the raw user data in the first place.
No,
For SQL Injection prevention, you really want to be using prepared statements. This is a safer way to do this, instead of escaping quotes. You also want to use htmlspecialchars() for escaping HTML tags, instead of just stripping them away, but that's up to you.
This is kind of an eternal question, and the answers vary across wanted usage: for prepared queries, I believe it’s 100 % safe to use its own variables system and let it handle the input. For HTML output, stripping tags may not always be what you want; moreover, it’s kind of safer to do a whitelist of what to allow in input than blacklist, because you know, hackers have fantasy. For URL output, your solution should be fine, but be aware that some other platforms may do a little different URL-encoding (see the difference between a string URL-encoded by Java standard libraries and iOS/Mac libraries, i.e.).
I am creating a function for my $_POST inputs to prevent SQL Injection BEFORE adding the values into database. I use it on login/register and when a user needs to post an article. As far as I know, this does not secure it from XSS.
Should I create a different function when I output data or edit this?
Thank you.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
Try using prepared statements. They are designed to automatically escape things. They should also keep your queries cleaner in the source code.
http://www.ultramegatech.com/blog/2009/07/using-mysql-prepared-statements-in-php/
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/book.pdo.php
You talk about XSS and then SQL injection...
SQL
Use mysql_real_escape_string() or better still bind params with a library such as PDO.
If magic_quotes is a possibility, use...
function sqlEscape($str) {
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
Regarding your example, why do you need to use trim() to make data safe? Also, why use the error supressor on trim()?
XSS
Use htmlspecialchars($str, ENT_QUOTES) to prevent HTML special characters from having special meaning.
I use the following, which works just fine to prevent injections:
function clean($str) {
$value = mysql_escape_string(stripslashes(htmlspecialchars($str)));
return $value;
}
You shouldn't save values as encoded HTML to your database. Do that when outputting them, not when saving them (saving encoded HTML makes it harder to search in it, makes their size bigger, makes it harder to use them in formats other than HTML and generally just wrong - your database should store the actual text, not the text formatted to be displayed in a specific way).
Also, as Quamis said, you should probably look at PDO or some other DBAL that lets you use prepared statements instead of escaping it manually.
This question already has answers here:
How to escape strings in SQL Server using PHP?
(14 answers)
Closed 7 years ago.
Am wondering what is the equivalent in PHP for SQL Server escaping of strings?
Nice question, I don't know but you could use PDO::quote() with the PDO_DBLIB driver.
EDIT: Seems like this guy got it from StackOverflow:
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
Another option:
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
The best alternative is to use parameterised queries, then you don't have to escape strings.
If you still want to put the query together yourself, the proper way to escape a string literal for SQL Server (T-SQL) is to replace each apostrophe (') in the string with two apostrophes.
The short answer is: use whatever mechanism your connection libraries provide, it really has nothing to do with the database. If you're using ADO, you have parameterized queries, if you're using something else (I know nothing about PHP) then use whatever that library offers.
Rolling your own is probably a bad idea, because you're very likely to get something wrong, e.g. handling comment delimiters correctly.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best way to stop SQL Injection in PHP
I am creating a website using PHP that makes use of a MySQL database and handles forms and variables from the URL. The variables are being using to dynamically construct SQL query strings. So i need a robust solution to make sure nobody is trying a SQL injection, etc.. A friend of mine has said that really i should only use stored procedures to access the database but that's not really feasible because the host i'm using doesn't allow these.
Here is the code i'm using (it's part of a class to wrap DB commands):
...
public function Sanitize($Variable)
{
if(is_resource($this->ServerConnection))
{
$Variable = str_replace(";", "", $Variable);
if(get_magic_quotes_gpc())
{
if(ini_get('magic_quotes_sybase'))
{
$Variable = str_replace("''", "'", $Variable);
}
else
{
$Variable = stripslashes($Variable);
}
}
return mysql_real_escape_string($Variable, $this->ServerConnection);
}
else
{
$this->PrintError("The Sanitize function is not available as there is no server connection.");
}
}
...
Is this function robust enough? Should i be doing anything else?
Might be worth reading this post.
What is the best way of ...
There is no best way. It depends on the context.
.. sanitising POST/GET variables from ..
It is a flawed mode of thinking that data are good or bad. Data is just data. It's the context in which it's used that makes it malicious or not. Some words may be bad if you execute them unadorned on a database server. Some words are bad if you display them to minors. It's about context.