how to work php sql injection and use in site? [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
1. how to work php sql injection and use in site ?
my site login process easily login any person with out username & password.plz describe how to safe login process.
example :
$logindetail = "select * from tablename where username = '".$_REQUEST['username']."' and password = '".$_REQUEST['password']."' ";
$sqlrun = mysql_query($logindetail);
$recordcount = mysql_num_rows($sqlrun);
in this login process how would sql injection be used?

It's not clear whether you're asking for someone to explain how to prevent SQL injection, or how someone might use SQL injection to get into your site.
To prevent SQL injection, use parameterised queries. This has already been well explained in this question: How can I prevent SQL injection in PHP?
If someone realised your site was vulnerable to SQL injection, they could log on to your site as any known username, by entering this into the username box
admin' OR 1=1 --
This makes the SQL that is executed on the database server:
"select * from tablename where username = 'admin' OR 1=1 -- and password = '' "
The OR 1=1 will evaluate to true and the -- comments out the rest of the SQL string and prevent the password check.
I'm not going to get into password hashing, as I assume this is a small example.

use mysqli or PDO preprared statements to execute a query. mysql is deprecated.Something like this:-
<?php
$con = new mysqli('host','user','pass','db');
if(!$con)
die();
$stmt = $con->prepare("select * from tablename where username = ? and password =?");
$stmt->bind_param('ss',$_REQUEST['username'],$_REQUEST['password']);
$stmt->execute();
$stmt->close();
This can be a more safer way to stop SQL injection. Learn more from Here

Change first line to:
$logindetail = "select * from tablename where username = '".mysql_real_escape_string($_REQUEST['username'])."' and password = '".mysql_real_escape_string($_REQUEST['password'])."' ";

Use prepared statements and parameterized queries.
Can achieve this by using msqli
http://php.net/manual/en/book.mysqli.php
quick tutorial. http://www.phphaven.com/article.php?id=65
example code
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'DATABASE_NAME';
$DB_HOST = 'DATABASE_HOST';
$DB_USER = 'DATABASE_USER';
$DB_PASS = 'DATABASE_PASSWORD';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// A QUICK QUERY ON A FAKE USER TABLE
$query = "SELECT * FROM `users` WHERE `status`='bonkers'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo stripslashes($row['username']);
}
}
else {
echo 'NO RESULTS';
}
// CLOSE CONNECTION
mysqli_close($mysqli);
?>

Related

Is this code safe from SQL injection and other types of attack? (If it is why?) [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
I was wondering Is this code safe form SQL injection and other types of exploits? If it is safe can anyone explain it to me how? And if isn't can anyone make corrections
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form";
//Requesting values form form.html
$a = $_REQUEST['fname'];
$b = $_REQUEST['lname'];
$c = $_REQUEST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " .$conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare ("INSERT INTO my_db (fname, lname, email)
VALUES (?, ?, ?)");
$stmt->bind_param("sss",$a,$b,$c);
$stmt->execute();
echo "new record created successfully";
$stmt->close();
$conn->close();
?>
Yes, it's safe from SQL Injection, but it can be still improved security wise.
SQL Injection is when you concatenate sql query with user parameters, this gives malicious user a chance to inject data or perform dangerous actions in your database.
Assuming you have a code:
$query = 'select * from user where id = ' + $_GET['id'];
Now assume a hacker send the id param as 1 or 1 = 1, so your query becomes
select * from user where id = 1 or 1 = 1
This will return all users.There are also other ways to inject
Since you are using prepared statement and bind all parameters, it's not possible to concatenate sql query.
Security wise,
your code accept $_REQUEST, this includes both GET and POST. This is not a good practice. You should restrict CRUD to POST only.
You are using root (even in develop environment, you shouldn't use root)

Prevent SQL Injection to Login Page in PHP and MySQL [duplicate]

This question already has answers here:
Preventing SQL Injection in Login Page in PHP [duplicate]
(3 answers)
Closed 6 years ago.
Below is my PHP code for login page.
if(!$_POST["username"] || !$_POST["password"])
{
echo "Username and Password fields are mandatory.";
}
else
{
$query="select user_id from users where user_name='".$_POST["username"]."' and password='".md5($_POST["password"])."' ";
.....
.....
}
I think, this is vulnerable code for SQL Injection. What should I modify in this code to prevent SQL Injection to my MYSQL database?
I am using following code to connect to my MySQL database:
function connect_database()
{
$con = mysqli_connect("servername", "username", "", "dbname");
if (!$con)
{
$con = "";
echo("Database connection failed: " . mysqli_connect_error());
}
return $con;
}
I am trying to use mysqli_prepare, but getting errors:
$unsafe_username = $_POST["username"];
$unsafe_password = md5($_POST["password"]);
$query=mysqli_prepare("select user_id from users where user_name= ? and password= ? ");
$query->bindParam("ss", $unsafe_username, $unsafe_password);
$query->execute();
I got following error:
Warning: mysqli_prepare() expects exactly 2 parameters, 1 given
Fatal error: Call to a member function bindParam() on null
use prepared statement,
http://php.net/manual/en/pdo.prepared-statements.php
$stmt = mysqli->prepare("select user_id from users where user_name= ? and password= ?");
$stmt->bindParam("ss",$username,$pass);
$stmt->execute();
You want to escape the strings that can be inputted into your query. Considering you are using the mysqli driver you can do this:
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$query="select user_id from users where u.user_name='".$username."' and u.password='".md5($password)."' ";
Official documentation can be found here. You can also use prepared statements.

How to prevent weird user inputs from breaking things in queries?

Is there a good standard solution to deal with characters like ' and " from being used in user inputs on a web platform?
I'm using php for a webpage and if I have, for example, a search bar which have the following query behind it.
$sql = "select * from aTable where aColumn like '%".$searchedKeyword."%'";
If I search for like Greg's icecream the ' will break the script. Also, I'm guessing if I search for something like 1' or ID>0 my script will have a false effect.
What is the common solution here? Do you usually filter away undesired characters, or is there maybe some method or similiar built-in to php?
You can us PDO and prepared statements to prevent SQL injection.
http://php.net/manual/en/pdo.prepared-statements.php
$searchedKeyword = "mykeyword";
//Database details
$db = 'testdb';
$username = 'username';
$password = 'password';
//Connect to database using PDO (mysql)
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db, $username, $password);
} catch (PDOException $e) {
var_dump("error: $e");
}
//Prepared SQL with placeholder ":searchedKeyword"
$sql = "select * from aTable where aColumn like '%:searchedKeyword%'";
$sth = $dbh->prepare($sql);
//Bind parameter ":searchedKeyword" to variable $searchedKeyword
$sth->bindParam(':searchedKeyword', $searchedKeyword);
//Execute query
$sth->execute();
//Get results
$result = $sth->fetchAll(); //fetches all results where there's a match

Is it necessary to use my 'sql_real_escape_string' when selecting in MySQL? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 8 years ago.
I'm following a tutorial, Creating a Secure Login System the Right Way, about how to create a login system. In the code they use mysql_real_escape_string on the username field before passing it to the database as a query, that is,
$username = mysql_real_escape_string($username);
Is this necessary since I am not adding anything to the database, I am simply checking if this user already exists?
The reason I am not just leaving it in anyway is when I use the above code, it renders my text blank and so is sending an empty string to the database. I don't know why this is, so I thought, if I could leave it out, I would.
Below is for advice about database connection being open from a commenter (passwords, etc. been changed):
function dbConnect(){
$connection = mysql_connect('localhost', 'username', 'password');
$database=mysql_select_db('database', $connection);
return $connection;
}
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);
$username = mysql_real_escape_string($username);
$query = mysql_query("SELECT *
FROM members
WHERE username = '$username'
AND password = '$password'",dbConnect());
You may want to use PDO with prepared statements. Prepared statements are like placeholders in an SQL query and you're later on shipping the data that will then be inserted on those places. This makes escaping strings obsolete.
As I've already mentioned in the comments above: every SQL query with user input is vulnerable to SQL injection attacks.
The proper code is:
dbConnect();
$username = mysql_real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sql = "SELECT * FROM members WHERE username = '$username' AND password = '$password'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
Yes it is necessary because the username could contain special character not allowed in SQL that need to be escaped like ' or / for instance
Example:
Not escaping ' in the username McDonald's would lead to an illegal SQL statement:
select * from your_table where username = 'McDonald's'

Is mysql_real_escape_string() unsafe against hexadecimal encoded data?

We know that all user input must be escape by mysql_real_escape_string() function before executing on mysql in php script. And know that this function insert a \ before any ' or " character in user input. suppose following code:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
this code is safe.
But I find out if user enters her inputs with hexadecimal format then mysql_real_escape_string() can not do any thing and user can execute her sql injection easily. in bellow 27204f522027273d27 is same ' OR ''=' but in hex formated and sql execute without problem :
$_POST['username'] = 'aidan';
$_POST['password'] = "27204f522027273d27";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='".mysql_real_escape_string($_POST['username']."' AND password='".mysql_real_escape_string($_POST['password']."'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
But whether this is true and if answer is yes how we can prevent sql injection in this way?
If you are using mysql_real_escape_string(), odds are you would be better served using a prepared statement.
For your specific case, try this code:
/*
Somewhere earlier in your application, you will have to set $dbh
by connecting to your database using code like:
$dbh = new PDO('mysql:host=localhost;dbname=test', $DBuser, $DBpass);
*/
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
$user = $_POST['username'];
$password = $_POST['password'];
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user=? AND password=?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $user);
$stmt->bindParam(2, $password);
$stmt->execute();
This does require you to use PDO for your database interaction, but that's a good thing overall. Here's a question discussing the differences between PDO and mysqli statements.
Also see this StackOverflow question which is remarkably similar to yours and the accepted answer, from which I poached some of this answer.

Categories