This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I know i am not secure when i am using this code so anything i can add in my code?
I have tried my self sql injection they are somewhere working but not much as i dont have much knowledge about sql injection. but as hacker are more smart so they can really hack my website.
Url looks like this :
http://example.com/profile.php?userID=1
php
$userID = $_GET['userID'];
$userID = mysql_real_escape_string($userID);
$CheckQuery = mysql_query("SELECT * FROM tbl_user WHERE id='$userID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: tos.php");
}
I tried:
http://example.com/profile.php?userID=1'
which hide many things on site.
when i tried
http://example.com/profile.php?userID=1' UNION SELECT * FROM tbl_user; with havij it was hacked
Thanks :|
use mysqli::prepare or at least sprintf
mysql_query(sprintf("SELECT * FROM tbl_user WHERE id='%d'", $userID);
$db = new mysqli(<database connection info here>);
$stmt = $db->prepare("SELECT * FROM tbl_user WHERE id='?'");
$stmt->bind_param("id", $userID);
$stmt->execute();
$stmt->close();
Dont use mysql_* functionality at all.
Use PDO or mysqli.
http://php.net/PDO
http://php.net/mysqli
PDO will escape your data for you.
But for your current code:
$userID = $_GET['userID'];
$userID = mysql_real_escape_string($userID);
if(ctype_digit($userID))
{
$CheckQuery = mysql_query("SELECT * FROM tbl_user WHERE id='$userID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: tos.php");
}
} else {
// THE USER ID IS NOT ALL NUMBERS, CREATE AN ERROR
}
I know i am not secure when i am using this code
This statement is wrong.
As a matter of fact, this very code is pretty secure.
And none of the codes you provided below would do any harm. Why do you think it is not secure?
This way is not recommended, yes. And the way you are using to format your queries may lead to injection for some other query. But the present code is perfectly secure.
As long as you are enclosing every variable in quotes and escape special chars in it - it is safe to be put into query.
Only if you omit one these two rules (i.e. escape but don't quote or quote but don't escape) - you are in sure danger. But as long as you're following both, you're safe.
The only reason for "hacking" I can guess of is a single quote used in HTML context. In some circumstances it can "hide many things on the page". But for the SQL, with the code you posted here, it's harmless
Look, out of this link
http://example.com/profile.php?userID=1'
your code will produce such a query
SELECT * FROM tbl_user WHERE id='1\''
which is quite legit for mysql and will even return a record for id=1, as it will cast 1' to 1 and find the record. This is why there is no redirect to tos.php.
So, the problem is somewhere else.
either there is a code that does not follow the rules I posted above
or this problem is unrelated to SQL at all - so, you are barking wrong tree and thus still keep whatever vulnerability open
Most likely you have to echo your values out
u can try type casting the value
<?php
$CheckQuery = mysql_query("SELECT * FROM tbl_user WHERE id='".(int)$userID."'");
?>
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I have a table (core_customer_information) and I want to create a SQL query in php that uses the variable $code and updates the activated field in my table.
$code = mysqli_real_escape_string($conn, $_GET['code']);
$check = mysqli_query("SELECT * FROM core_customer_information WHERE activation_code='$code' AND activated='1' ");
if ( mysqli_num_rows($check) == 1)
{
die ('The account has already been activated');
}
else
{
$activate = mysqli_query("UPDATE core_customer_information SET activated='1' WHERE activation_code='$code'");
echo ('Your account has know been activated <br>');
echo $code;
}
First of all, I check whether the activated is equal to 1, in which case the account is classed as activated, and if not, I then create an UPDATE query to update the activated field of this class.
My problem is that the query isn't updating my table and I'm unsure where the problem is at.
I would appreciate if someone could take a look for me please.
I would recommend you use mysqli_real_escape_string as it escapes the string taking into account the current connection charset as stated by the page:
This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.
To prevent most mysql injection methods you should do the following:
$code = mysqli_real_escape_string($link, $_GET['code']);
If you should ever use an adapter like ADODB or some other, I'd recommend you use prepared statements and their methods of preventing SQL injection.
It's not totally clear from your question what language you will be using to launch the SQL queries (since the only tags are sql and mysql at the moment...)
But if the language is similar to Java then you can use something similar to Java's PreparedStatement. (See https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)
A PreparedStatement is safer than simple concatenation of dynamic variables into sql Strings.
I'm just trying to figure out something here. I'm looking into SQL injection, and I can't seem to delete this table no matter how much I try to, and I was wondering if maybe it just can't be done -
may I have some examples of how this table can be deleted?
<?php
$username = trim($_POST['username']);
$cxn = mysqli_connect($a,$b,$c,$d);
if ($cxn) {
$sql = "SELECT * FROM members WHERE logins = '{$username}';";
// tried sending: '; DROP TABLE members".' doesn't work...
$result = mysqli_query($cxn,$sql)
if (!$result) { echo 'Couldn\'t be done!'; } else { echo 'Query completed!'; }
}
?>
So, how would I delete table members using SQL injection - or is it web-safe? Thanks.
MySQLi doesn't allow multi-stacked queries, unless you're using mysqli_multi_query, so DELETE-ing or DROP-ping wouldn't be possible.
How ever, this code is still very insecure.
lets say $username getst the value
$username = "' or id > '1"
it would transfer into
SELECT * FROM members WHERE logins = '' or id > '1'
There is a fatal misunderstanding.
SQL injection is not equal to dropping a table. The latter action is just an example, quite vivid, but not too feasible in read circumstances. But injections aren't limited to just dropping tables!
So, even if this particular kind of injection isn't possible in your particular case, it doesn't make your code "web-safe"!
Instead of caring of numerous particular ways to exploit of injection, you have to mitigate all injections at once. By means of using prepared statements
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
I just found that my website is vunerable.
Since it's connected to a DB and have functions like: Register, Change Password, Notices, etc... and SUPOSING it's fully vulnerable.
What should I look for into the code in order to start making it safe?
I mean, I did some researches and everywhere, everyone says different things about security.
"Use PDO."
"Use mysql_real_escape_string."
"Use addslashes."
What exactly should I look for??
"$_POST" and "$_GET" variables??
"$_SESSION" variables?
SQL querys?
$sql = "select * from user";
$sql = "update user set user="new_user_name";
$sql = "insert into user (user) values ('userid')";
What should I do in each case?
Please, help me to know what and where I must go.
Thank you.
Following are the points to be considered for making safe php application.
USE PDO or mysqli
Never trust any inputs. Consider every variable viz $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER as if they were tainted. Use appropriate filtering measure for these variables.
To avoid XSS attack use php’s builtin functions htmlentities,
strip_tags, etc while inserting the user input data into the
database.
Disable Register Globals in PHP.INI
Disable “allow_url_fopen” in PHP.INI
Don’t allow user to input more data than required. Validate input to
allow max number of characters. Also validate each field for
relevant datatypes.
Disable error reporting after Development period. It might give
information about database that’ll be useful to hackers.
Use one time token while posting a form. If token exist and matches
the form post is valid otherwise invalid.
Use parametrized database queries
Use stored procedures
You can google for each point for more details.
HOpe this helps
What you should look for: Any data send from the client/user. Sanitize/escape this data.
PDO can sanitize queries (using PDO::prepare) and supports multiple SQL systems.
For MySQL, use MySQLi. mysqli_real_escape_string is the function to use for sanitizing data if you are using MySQL.
None of the SQL queries you provided are actually vulnerable to SQL injection.
SQL injection vulnerabilities happen because SQL input is not properly escaped.
For example:
$sql = "select * from users where user_id =" . $_GET['user_id'];
Consider if I passed in the following:
http://some_server.com/some_page.php?user_id=123%20or%201=1
The query when executed would end up being:
select * from users where user_id = 123 or 1=1
To fix this, use parameterized queries:
$query = "select * from users where user_id = ?"
When you bind the user_id value to the query, the data access layer will escape the input string properly and the following would be executed:
select * from users where user_id = '123 or 1=1' which would not return any rows, preventing the injection
If using PHP and the mysql extension:
$sql = "select * from users where user_id = '" . mysql_real_escape_string($_GET['user_id']) . "'";
Keep in mind you need to escape ALL input that is going into a SQL query:
$sql = "select id_column from some_table where id = 1";
$stmt = mysqli_query($conn, $sql);
if($stmt === false) die(mysqli_error($conn) . "\n");
while($row = mysqli_fetch_assoc($conn, $stmt) {
$sql = "update some_other_table set some_value = 'new value' where some_column = '" . mysqli_real_escape_string($conn, $row['id_column']) . "'";
....
}
This is because values you select from the database might include characters that are not safe for execution in a SQL statement, like the name "O'Hara" or example.
}
I've been using PDO.
An example for that in your case:
<?php
$stmt = $dbh->prepare("insert into user (user) values (?)");
$stmt->bindParam(1, $name);
$name = 'ValueHere';
$stmt->execute();
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Are mysql_real_escape_string() and mysql_escape_string() sufficient for app security?
So basically I have a qryName in the URL
eg: mysite.com/qryName=WHAT
if (isset($_GET['qryName']))
{
$qryName = mysql_real_escape_string(filter($_GET['qryName']));
}
$urldata = mysql_fetch_assoc(mysql_query("SELECT * FROM gangs WHERE ShortName = '" . $qryName . "' LIMIT 1"));
$urldata is the code so it pretty much selects from the database. Note that in the database, the qryName has no spaces, special chars etc..
Just wondering if that is exploitable?
It is safe since you properly escape the value - unless....
...you do not initialize the variable and have register_globals enabled. In that case someone can use a cookie or POST value to send you an arbitrary value for $qryName containing evil SQL statements.
But since you probably just posted a snipped and do initialize the variable before that if statement (you do, right?!), your code is safe. Consider using prepared statements (with PDO) though instead of escaping - they make your code more readable, too.
Why don't you add one extra piece of validation or take out the isset and check if it only contains letters for example
if(ctype_alpha($_GET['qryName'])) {
$qryName = mysql_real_escape_string(filter($_GET['qryName']));
}
http://php.net/manual/en/function.ctype-alpha.php
Have you considered using something like PDO? My understanding is that when using PDO and bound variables, SQL injection is not possible. There are also other advantages worth considering.
A similar PDO query would be:
$data=array($_GET['qryName']);
try {
$STH = $this->DBH->prepare('SELECT * FROM gangs WHERE ShortName = ? LIMIT 1');
$STH->execute($data);
while($row = $STH->fetch()) {
$var1=$row->FieldName;
}
}
catch(PDOException $e) {echo $e->getMessage();}
You add the variables to the array ($data) and they are bound in order to each question mark in the SQL statement.
I today i start to read different articles about SQLi and DoS/DdoS to know how to protect my site and i found this thing :
Link: link to the article
// DB connection
// $id = (int)$_GET['id'];
$id = $_GET['id'];
$result = mysql_query("SELECT id,name,pass FROM users WHERE id = $id")
or die("Error");
if($data = mysql_fetch_array($result))
$_SESSION['name'] = $data['name'];
if(preg_match('/(benchmark|sleep)/i', $id))
exit('attack'); // no timing
I want to know the use of this.Also after this the guy show how to bypass it and i want to know if PDO is secury?
if(preg_match('/(benchmark|sleep)/i', $id)) checks if the $id matches the strings benchmark or sleep (the i stands for case-insensitive).
In the context it's presented I'd say this makes no sense what so ever though... I'd rather do this, and be done with it:
$id = (int) $_GET['id'];
$result = mysql_query('SELECT id,name,pass FROM users WHERE id = '.$id);
Notice I cast the id to an int, so if it's anything else it should just end up being 0, which most likely doesn't match anything since id columns usually starts on 1 (from my experience anyways).
I want to know the use of this
That's quite silly and apparently useless attempt to detect a possible SQL injection which is supposed to run a resource-consuming query.
Also after this the guy show how to bypass it
No wonder.
Once you have a code open to injection, thaere are thousands methods to run it.
The only your concern should be injection in general.
Once you protected - no ddos injection would be possible.
i want to know if PDO is secury?
First, it is not PDO secure, but strict and constant use of prepared statements considered secure.
Second, nope, prepared statements helps only half the problem