could you please tell me why my SQL-Injection isn't working and how can I fix it. I tried to go after the example from Here, but value'); DROP TABLE table;-- or password 1=1 doesn' work. Im sorry to steal your time with these easy things, but I tried it many times and I didn't get it running and the other post didn't help me.
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: #cc0000;}
</style>
</head>
<body>
<h2>Einlogen</h2>
<form action="EasyExploit.php" method="post">
Vorname: <input type="text" name="vorname"><br>
<input type="submit">
<h2>Registrieren</h2>
<form action="EasyExploit.php" method="post">
Vorname: <input type="text" name="vorname"><br>
<input type="submit">
<?php
$connection = mysqli_connect('localhost', 'root','' ,'DB') or die(mysqli_error());
mysqli_select_db($connection ,'DB')or die(mysqli_error());
#$unsafe_variable = $_POST['vorname'];
mysqli_query($connection, "INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");
?>
</body>
</html>
Thank's in Advance
Making sql injection vulnerable code (for testing purposes):
In order to test SQL Injection with your code we need to make some few changes:
<?php
$connection = mysqli_connect('localhost', 'root','' ,'DB') or
die(mysqli_error($connection)); //1
mysqli_select_db($connection ,'DB') or die(mysqli_error($connection)); //2
$unsafe_variable = $_POST['vorname'];
mysqli_multi_query($connection, //3
"INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");
?>
//1 and //2: mysqli_error needs $connection parameter.
//3: Only mysqli_multi_query is able to execute more than one sentence at a time. For security reasons. mysqli_query just executes one to prevent sql injection.
Testing:
It's the time to test sql injection. We create a simple table t to check if we can drop it through sql injection:
create table t ( i int );
Time to attack, the killer string to inject sql is:
pepe'); DROP TABLE t;--
SQL with injected code:
"INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"
Explained:
SQL pattern is: "INSERT INTO Persons (Vorname) VALUES ('$unsafe_variable')"
"pepe');" replaces $unsafe_variable : "INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"
Remember -- means "comments from here", then the last quote and parenthesis is a comment.
After post this value to form:
mysql> select * from t;
ERROR 1146 (42S02): Table 's.t' doesn't exist
How to avoid SQL Injection?
Man, this is Internet, they are a lot of papers about it. Start your searching with Parameterized Queries.
Related
I am not a programmer (duh), I just need to make a really simple tool for populating sql database. First I have html with form:
<form action="http://localhost:8081/phpSearch.php" method ="post">
Enter code: <input type="text" name="search"><br>
<input type ="submit">
</form>
and then php that should connect to MYSQL, search for data according to input (code,name) in one table and then populate another table with the result. And I'm only mising what to put instead of question marks.
<?php
$search1 = $_POST['search'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT code,name FROM users WHERE code LIKE '%$search1%'";
$sql2 = "INSERT INTO newUsers (newCode,newName) VALUES ('$search1', ??????)";
$conn->close();
?>
I'm pretty sure this is easy for you experts, so thanks in advance.
You could actually do this in a single SQL query:
$search1 = "%".$_POST['search']."%";
$sql = "INSERT INTO newUsers (newCode, newName) SELECT code, name FROM users WHERE code LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $search1);
$stmt->execute();
This will insert all the results of the SELECT query directly into the other table, without needing any intermediate processing in PHP. More about the INSERT...SELECT query format can be found here.
Note I've used prepared statements and parameters - which both executes the query securely and reduces the risk of accidental syntax errors. You can get more examples of this here.
Also, in a real application you shouldn't log in as root from your web application - instead create a SQL account for the application which has only the privileges it actually needs.
I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.
I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.
<html>
<head>
</head>
<body>
<form action = "insertform.php" method = "post">
field: <input type = "text" name = "fielda">
field2: <input type = "text" name = "fieldb">
thedata: <input type = "text" name = "qdata">
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","user","password");
if (!$con){
die("cannot connect" . mysql_error());
}
mysql_select_db("stQutieria",$con);
$sql = "INSERT INTO qtable(fielda, fieldb, qdata) VALUES ("$_POST[fielda]","$_POST[fieldb]","$_POST[qdata]")";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
Edit: OK! so I changed my code, I played around with double quotes or ' around the $_POST areas. When I used double quotes I got errors saying fielda / fieldb wernt defined, I also got errors saying "syntax error, unexpected '$_POST' (T_VARIABLE)"... the code i am working with derives from the same page ass insertform.php. Here is the video I am watching http://www.youtube.com/watch?v=j4FUCoCxE8w. if anyone could help me on Skype / msn / teamview I would greatly appreciate it.
You're missing quotes around your $_POST keys: $_POST[fielda] should be $_POST['fielda'] etc. (actually not true)
You need a space after your table name and opening parenthesis qtable(fielda should be qtable (fielda
You're missing a quote after '$_POST[fielda] (should be '$_POST[fielda]') and after '$_POST[fieldb] (should be '$_POST[fieldb]')
You have no error handling. If you call mysql_error() after your query you would know exactly what your error is.
You are wide open to SQL injections
You are using an obsolete API
That means your query is failing. Likely because you have no space between the table name and the column names:
INSERT INTO qtable (fielda, fieldb, qdata)
replace Your SQL with:
$sql = "INSERT INTO qtable (fielda, fieldb, qdata) VALUES ('".$_POST['fielda']."','".$_POST['fieldb']."','".$_POST['qdata']."')";
but this is really unsafe...
Much more safer is to use something like this:
$values = array($_POST['fielda'], $_POST['fieldb'], $_POST['qdata']);
$st = $db->prepare('INSERT INTO qtable (fielda, fieldb, qdata) VALUES (?,?,?)');
$st->execute($values);
You are making mistake in coding the correct sql statement will be like this one
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES (".$_POST[fielda].",".$_POST[fieldb].",".$_POST[qdata].")";
Note this above sql statement is for those fields which are integer in database if fields are varchar then following will be code
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES ('".$_POST[fielda]."','".$_POST[fieldb]."','".$_POST[qdata]."')";
Thank You
So I've been trying to replicate a second order SQL Injection. Here's an example template of two php based sites that I've prepared. Let's just call it a voter registration form. A user can register and then you can check if you're a registered voter or not.
insert.php
<?php
$db_selected = mysql_select_db('canada',$conn);
if (!db_selected)
die("can't use mysql: ". mysql_error());
$sql_statement = "INSERT into canada (UserID,FirstName,LastName,Age,State,Town)
values ('".mysql_real_escape_string($_REQUEST["UserID"])."',
'".mysql_real_escape_string($_REQUEST["FirstName"])."',
'".mysql_real_escape_string($_REQUEST["LastName"])."',
".intval($_REQUEST["Age"]).",
'".mysql_real_escape_string($_REQUEST["State"])."',
'".mysql_real_escape_string($_REQUEST["Town"])."')";
echo "You ran the sql query=".$sql_statement."<br/>";
$qry = mysql_query($sql_statement,$conn) || die (mysql_error());
mysql_close($conn);
Echo "Data inserted successfully";
}
?>
select.php
<?php
$db_selected = mysql_select_db('canada', $conn);
if(!db_selected)
die('Can\'t use mysql:' . mysql_error());
$sql = "SELECT * FROM canada WHERE UserID='".addslashes($_POST["UserID"])."'";
echo "You ran the sql query=".$sql."<br/>";
$result = mysql_query($sql,$conn);
$row=mysql_fetch_row($result);
$sql1 = "SELECT * FROM canada WHERE FirstName = '".$row[1]."'";
echo "The web application ran the sql query internally=" .$sql1. "<br/>";
$result1 = mysql_query($sql1, $conn);
$row1 = mysql_fetch_row($result1);
mysql_close($conn);
echo "<br><b><center>Database Output</center></b><br><br>";
echo "<br>$row1[1] $row1[2] , you are a voter! <br>";
echo "<b>VoterID: $row[0]</b><br>First Name: $row[1]<br>Last Name: $row[2]
<br>Age: $row[3]<br>Town: $row[4]<br>State: $row[5]<br><hr><br>";
}
?>
So I purposely made this vulnerable to show how second order SQL Injection works, a user can type in a code into the first name section (where I am currently stuck, I've tried many different ways but it seems that I can't get it to do anything).
Then when a person wants to activate the code that he has inserted in the first name section, all he needs to do is just type in the userID and the code will be inserted.
For example:
I will type into the insert.php page as:
userid = 17
firstname = (I need to inject something here)
lastname = ..
age = ..
town = ..
state = ..
Then when I check for my details, and type in 17, the SQL script injected will be activated.
Can I get few examples on what sort of vulnerabilities I can show through this?
What is there to demonstrate?
Second order SQL injection is nothing more than SQL injection, but the unsafe code isn't the first line.
So, to demonstrate:
1) Create a SQL injection string that would do something unwanted when executed without escaping.
2) Store that string safely in your DB (with escaping).
3) Let some other piece of your code FETCH that string, and use it elsewhere without escaping.
EDIT: Added some examplecode:
A table:
CREATE TABLE tblUsers (
userId serial PRIMARY KEY,
firstName TEXT
)
Suppose you have some SAFE code like this, receiving firstname from a form:
$firstname = someEscapeFunction($_POST["firstname"]);
$SQL = "INSERT INTO tblUsers (firstname) VALUES ('{$firstname }');";
someConnection->execute($SQL);
So far, so good, assuming that someEscapeFunction() does a fine job. It isn't possible to inject SQL.
If I would send as a value for firstname the following line, you wouldn't mind:
bla'); DELETE FROM tblUsers; //
Now, suppose somebody on the same system wants to transport firstName from tblUsers to tblWhatever, and does that like this:
$userid = 42;
$SQL = "SELECT firstname FROM tblUsers WHERE (userId={$userid})";
$RS = con->fetchAll($SQL);
$firstName = $RS[0]["firstName"];
And then inserts it into tblWhatever without escaping:
$SQL = "INSERT INTO tblWhatever (firstName) VALUES ('{$firstName}');";
Now, if firstname contains some deletecommand it will still be executed.
Using a first name of:
' OR 1 OR '
This will produce a where clause in the second SQL of
WHERE FirstName = '' OR 1 OR ''
Therefore the result will be the first record in the table.
By adding a LIMIT clause, you can extract all rows from the table with:
' OR 1 ORDER BY UserID ASC LIMIT 0, 1 --
Obviously it will only extract 1 row at a time, so you would need to repeat that and increment the 0 in the LIMIT. This example uses a comment -- to terminate the remaining SQL which would otherwise cause the query to fail because it would add a single quote after your LIMIT.
The above is a simple example, a more complex attack would be to use a UNION SELECT which would give you access to the entire DB through the use of information_schema.
Also you are using addslashes() in one of your queries. That is not as secure as mysql_real_escape_string() and in turn: escaping quotes with either is not as secure as using prepared statements or parameterised queries for example in PDO or MySQLi.