How to delete a table with SQL injection - php

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

Related

Is there a way to demonstrate SQL injection with mysqli?

I want to make a quick and easy demonstration about how SQL injection work. And I've solved some of my problems. I have a table with random usernames, passwords and emails in, and I'm able to "inject" SQL code to view all of the users in a search with this injection:
' OR '1'='1
This is how my PHP code looks for searching for "members":
if (isset($_POST['search'])) {
$searchterm = $_POST['searchterm'];
echo $searchterm . '<br>';
/* SQL query for searching in database */
$sql = "SELECT username, email FROM Members where username = '$searchterm'";
if ($stmt = $conn->prepare($sql)) {
/* Execute statement */
$stmt->execute();
/* Bind result variables */
$stmt->bind_result($name, $email);
/* Fetch values */
while ($stmt->fetch()) {
echo "Username: " . $name . " E-mail: " . $email . "<br>";
}
}
else {
die($conn->error);
}
}
Now I want to demonstrate some more fatal problems, like someone truncating your whole table. So I tried this code in the search bar:
'; TRUNCATE TABLE Members; --
But I get this error message:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'TRUNCATE TABLE Members; -- '' at line 1
It seems like I get an extra ', but I don't know how to get rid of it, though the -- would comment that out. First I thought that the problem was that I had no whitespace behind the -- but adding a whitespace didn't make any difference.
I have tried switching to PDO, because I thought there was a problem with mysqli not accepting multiple queries, but then I somewhere read that PDO doesn't support that either, but I don't know.
Is there a way I can make it work?
I later found that PDO supports multi-querying by default, but when I tried it it didn't work. Maybe I bound the parameters wrong. But I couldn't even make a simple select query to work.
mysqli_query() does not support multi-query by default. It has a separate function for that: mysqli_multi_query().
SQL injection is not only about running multiple statements, the famous XKCD cartoon notwithstanding.
Your code has a bad SQL injection vulnerability. Do you think that using prepare() somehow makes a query safe, even though you interpolate content from your $_POST request data directly into the SQL string?
Your code is this:
$searchterm = $_POST['searchterm'];
$sql = "SELECT username, email FROM Members where username = '$searchterm'";
if ($stmt = $conn->prepare($sql)) {
/* execute statement */
$stmt->execute();
...
It's easy for unsafe input to make SQL injection mischief this way. It might even be innocent, but still result in problems. Suppose for example the search is: O'Reilly. Copying that value directly into your SQL would result in a query like this:
SELECT username, email FROM Members where username = 'O'Reilly'
See the mismatched ' quotes? This won't do anything malicious, but it'll just cause the query to fail, because unbalanced quotes create a syntax error.
Using prepare() doesn't fix accidental syntax errors, nor does it protect against copying malicious content that modifies the query syntax.
To protect against both accidental and malicious SQL injection, you should use bound parameters like this:
$searchterm = $_POST['searchterm'];
$sql = "SELECT username, email FROM Members where username = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $searchterm);
/* execute statement */
$stmt->execute();
...
Bound parameters are not copied into the SQL query. They are sent to the database server separately, and never combined with the query until after it has been parsed, and therefore it can't cause problems with the syntax.
As for your question about mysqli::query(), you may use that if your SQL query needs no bound parameters.
Re your comment:
... vulnerable to injection, so I can show the students how much harm a malicious attack may [do].
Here's an example:
A few years ago I was an SQL trainer, and during one of my trainings at a company I was talking about SQL injection. One of the attendees said, "ok, show me an SQL injection attack." He handed me his laptop. The browser was open to a login screen for his site (it was just his testing site, not the real production site). The login form was simple with just fields for username and password.
I had never seen his code that handles the login form, but I assumed the form was handled by some code like most insecure websites are:
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM accounts WHERE user = '$user' AND password = '$password'";
// execute this query.
// if it returns more than zero rows, then the user and password
// entered into the form match an account's credentials, and the
// client should be logged in.
(This was my educated guess at his code, I had still not seen the code.)
It took me 5 seconds to think about the logic, and I typed a boolean expression into the login form for the username, and for the password, I typed random garbage characters.
I was then logged into his account — without knowing or even attempting to guess his password.
I won't give the exact boolean expression I used, but if you understand basic boolean operator precedence covered in any Discrete Math class, you should be able to figure it out.
Did you try something like this ?
'(here put something);
in this way you are going to close the query with ' and add other stuff to it, when you add ; everything else is going to be discarded

Protect generic sql query statements

Any way to prevent malicious sql statements without using prepared statements and parameterized queries?
Example after simplify:
<?php
$con = mysqli_connect($_POST['db_server'], $_POST['db_user'],
$_POST['db_password'], $_POST['db_database']) or die(mysql_error());
$result = mysqli_query($con, $_POST['query_message']);
?>
Is it possible to check out the parameter $_POST['query_message'] is safe or not?
You should always build your queries within your code and then sanitise any variables you're going to use within them. NEVER pass the query or the database connection variables in via $_POST unless your user is querying the database via that form, in which case I'd recommend you just install phpMyAdmin.
As for sanitising your variables, if you really don't want to use PDO's prepared statements, you can sanitise incoming integers as follows:
$id = (isset($_POST['id']) ? (int)$_POST['id'] : null);
if ($id) {
$sql = "SELECT *
FROM `table`
WHERE `id` = {$id}";
}
And for strings use this:
$username = (isset($_POST['username']) ? mysqli_real_escape_string($con, $_POST['username']) : null);
if ($username) {
$sql = "SELECT *
FROM `table`
WHERE `username` = {$username}";
}
You can also call real_escape_string() directly on your $con object as follows:
$username = (isset($_POST['username']) ? $con->real_escape_string($con, $_POST['username']) : null);
However, as with #Shankar-Damodaran above, I highly suggest you do use PDO prepared statements to query your database.
Why you don't wanna use Prepared Statements ? That is really weird. I strongly suggest you should go for it.
You could make use of mysqli::real_escape_string for escaping quotes that is commonly used for SQL Injection Attacks.
Something like...
OOP Style
$message = $mysqli->real_escape_string($_POST['query_message']);
Procedural Style
$message = mysqli_real_escape_string($link,$_POST['query_message']);
other way is using:
htmlentities($query);
as an extra you could use preg_match() regular expressions to avoid
the inclusion of certain words (SELECT, DROP, UNION .......)
Example:
try{
$query = sprintf("SELECT * FROM users WHERE id=%d", mysqli_real_escape_string($id));
$query = htmlentities($query);
mysqli_query($query);
}catch(Exception $e){
echo('Sorry, this is an exceptional case');
}
There are real world cases where prepared statements are not an option.
For a simple example, a web page page where you can do a search on any number of any columns in the database table. SAy that table has 20 searchable columns. you would need a huge case statement that has all 20 single column queries, all 19+18+17+16+15+14+13+... 2 column queries, all possible 3 column queries... that's a LOT of code. much less to dynamically construct the where clause. That's what the OP means by prepared statements being less flexible.
Simply put, there is no generic case. If there was, php would have it already.
real_escape_string can be beaten. a common trick is to % code the character you are trying to escape so real_escape_string doesn't see it. then it gets passed to mysql, and decoded there. So additional sanitizing is still required. and when all characters used in injection are valid data, it's a PITA, because you can't trust real_escape_string to do it.
If you are expecting an integer, it's super easy.
$sanitized=(int)$unsanitized;
done.
If you are expecting a small text string, simply truncating the string will do the trick. does't matter that it's not sanitized if there's not enough room to hold your exploit
But there is no one size fits all generic function that can sanitize arbitrary data against sql injection yet. If you write one, expect it to get put into php. :)

How i can make my code secure from SQL Injection [duplicate]

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."'");
?>

What is the use of preg_match('/(benchmark|sleep)/i', $id)

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

PHP (int) for variables in MySQL query. Secure?

I am using following method for MySQL queries:
$sql = "SELECT * FROM mytable WHERE `myTableId`=" . (int)$myId;
Is this a completely safe method or is there a way to inject some sql into the database with this method?
Any better alternative?
It can lead to unintended consequences, e.g.
$myId = 'blahblahblah';
would result in
... WHERE myTableId=0
maybe not such a big deal in this case, but if (say) you're doing a permissions systme and "super-duper-ultra-high-level-user-with-more-power-than-god" has permission level 0, then it's a nice way to bypass security.
If you truly want to avoid SQL injection, your best bet is to use PDO and prepared statements. check out http://www.php.net/pdo and http://www.php.net/manual/en/pdo.prepare.php
Thís should be perfectly save, without any drawbacks, as long as the input can be casted to int.
make it like this
$sql="select `username` from `users` where id='$newid';";
mysql_query($sql);
here $newid is the int value.
The symbol used before and after username, to get this you have to press the key just below esc .
I would probably use sprintf instead - but I dont see that it is much different from what you are doing. Placing the integer in quotes may also help.
$sql = sprintf("SELECT * FROM mytable WHERE `myTableId`='%d'", $myId);
Should probably add that you may want to deal with the case when conversion to integer fails. So dont have a table zero.
No need for the Int if you are just worrying about the mysql injection.
To prevent mysql injection you can use mysql_real_escape_string.
What you have right now will block all mysql injection if your mysql condition is only for int but if the situation is like this:
$username = $_GET["username"];
SELECT * FROM customers WHERE username = '$username'
if the $username value is *\' OR 1* your in trouble or i should say your dead
if the $username value is *\'; DELETE FROM customers WHERE 1 or username = * your very dead + doomed
To prevent this from happening use mysql_real_escape_string
$username = mysql_real_escape_string($_GET["username"]);

Categories