would php code safe from sql inejction without using escape? - php

public function fetchUserData( $username, $noUpdate = false ) {
if ( DEBUG ) echo "DBInterface::fetchUserData( '$username' )\n";
$query = "SELECT * FROM logins WHERE username = '$username'";
$result = mysql_db_query( $this->database, $query, $this->dbc );
if ( $result && !$noUpdate ) {
mysql_db_query( $this->database, "UPDATE logins SET last_accessed = CURRENT_TIMESTAMP WHERE username = '$username' ", $this->dbc );
}
return $this->userData = mysql_fetch_assoc( $result );
}
public function verifyLogin( $username = null, $password = null ) {
if ( DEBUG ) echo "DBInterface::verifyLogin( '$username', '$password' )\n";
$success = ( $username && $password
&& $this->fetchUserData( $username )
&& $this->userData['password'] == $this->md5_base64( $password )
&& $this->setLoggedIn()
);
return $success;
}
Obviously, there's no escape function, so one might insert as ' or '1'='1 to make WHERE clause true, and fetchUserData will return all rows from the table. But verfiyLogin checks user input password with the query result from database which may not be same, hence authentication will fail. Attacker also cannot modify table since mysql_db_query executes only single sql statement. Am I right? Any thoughts?

Yes, it's very possible to do SQL injection with any SQL query that's built from user input.
You should use the escaping functions, or preferentially prepared statements to protect yourself from SQL injection. However, you can't use prepared statements if you're using the outdated and deprecated mysql_* functions. You need to switch to mysqli or PDO.
PDO example:
$myPDO = new PDO ('Connection options go here');
$stmt = $myPDO -> prepare ("SELECT * FROM table WHERE rowID = :rowID");
if ($stmt -> execute (array ('rowID' = $inputFromUntrustedSource))) {
while ($row = $stmt -> fetch ()) {
// do stuff with $row here
}
}

You can inject your own data into the result set using the UNION operation. So an attacker could supply his own $this->userData['password'] value that would be equal to the $this->md5_base64($password) value, for example:
' UNION SELECT 'admin', 'X03MO1qnZdYdgyfeuILPmQ==
So you should absolutely make sure you pass the values properly to your query.

Data validation is often confused with SQL formatting. This "escaping" you are talking about (whatever you mean under this vague term) belongs not to "injection" but to mere formatting. You need to escape strings not because of injections but because of string delimiters and some other reasons.
Data validation rules may change. SQL formatting rules are constant. You have to format any data you put in SQL string. Whatever you did to this data prior constructing the query - doesn't matter.

Related

Is this the right way to parameterize query? Is there any other way?

Well i learned how to parameterize queries in php but i just wanted to ask that is it now totally secure from sql injection or any other type of attacks and if it isnt what betternment can i do to secure it even more?
<?php
include 'db.php';
$name = "";
$pass = "";
if(isset($_POST['send'])) {
$name = $_POST['name'];
$sql_u = "SELECT * FROM users WHERE username='$name'";
$res_u = $connection->query($sql_u);
if (mysqli_num_rows($res_u) > 0) {
echo "Sorry Username already taken";
}
else {
$password = $_POST['pass'];
$hpass = password_hash($password, PASSWORD_DEFAULT);
$query=$connection->prepare("insert into users (username,password) values (?,?)");
$query->bind_param('ss',$name,$hpass);
if ($query->execute()) {
$query->close();
header('location:index.php');
} else {
header('location:not.php');
}
}
}
I want to know if their is a even more secure way than only parameterizing queries?
You're using parameters for the INSERT statement, but you skipped using parameters for the SELECT statement. Without parameterizing the SELECT, you still have an SQL injection vulnerability. You need to use parameters in all cases when you combine untrusted content with your SQL.
Parameters are a good way to prevent SQL injection when combining dynamic content as values in your SQL queries.
You asked if there were another way, so I will recommend that you use PDO if you're starting out with a new PHP project. It's a little bit easier than Mysqli. In my opinion, there's no reason to use Mysqli unless you're porting a legacy PHP application that had used the deprecated Mysql PHP extension.
Here's what it would look like using PDO:
$name = $_POST['name'];
$sql = "SELECT COUNT(*) FROM users WHERE username = ?";
$query = $connection->prepare($sql);
$query->execute([$name]);
$count = $query->fetchColumn();
if ($count > 0) {
echo "Sorry Username already taken";
}
else {
$password = $_POST['pass'];
$hpass = password_hash($password, PASSWORD_DEFAULT);
$sql = "insert into users (username, password) values (?, ?)";
$query = $connection->prepare($sql);
if ($query->execute([$name, $hpass])) {
header('location:index.php');
} else {
header('location:not.php');
}
}
I'm assuming that the PDO connection was made previously, and that it had been enabled with exceptions. If you don't enable exceptions, you should check return values from every prepare() and execute() call to make sure there are no errors.
The same is true for Mysqli, you can enable exceptions so you don't have to check for errors manually.
I also show in the example my preference to use SELECT COUNT(*) instead of SELECT *. It's probably a trivial optimization in this case, but if * refers to many columns or there are many rows matching username = $name then the fetch will need to transfer less data from the database.

SQL Prepared Statement Error on my Search form

I am finding it difficult to write a SQL prepared statement for my search form, can I get help on fixing it? Everything works great without a SQL prepared bind statement but am sure it's not so secure.
Here is my CODE:
<?php
// Define Database connection parameters
$dbserver = "localhost";
$username = "root";
$password = "";
$dbname = "student";
// Lets Connect to theDatabase Table, But if there is an Error lets tell before its too late to figured
$conn = mysqli_connect ( $dbserver, $username, $password, $dbname ) or die ( ' I can not connect to the database ' );
// Its time to Capture the varibles and user inpute from the form , also we need to sanitize the input to avoid SQL Injection
$study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);
/* Lets try to use bind Statement to reduce further hacking
I am also avoiding using "LIKE" Clause because IVariable direct Exact results so will be using the Direct Varible
*/
$sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
$sql->bind_param('s', $study_group);
$sql ->execute();
$results = mysqli_query ($conn, $sql);
$mysqlResults = mysqli_num_rows ($results);
if ( $mysqlResults > 0 )
{
while ( $row = mysqli_fetch_assoc ( $results ))
{
// Display results in table form
echo " <div>
<h4> ".$row['full_name']."</h4>
</div>";
}
} else {
echo " Please Ensure your Matric Number is correct, We can not find anything relting to your data";
}
if you use prepared statement you should not use mysqli_real_escape_string
Try comment the mysqli_real_escape_string row and use $_POST['matric_number'] directly in bind_param
// $study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);
/* Lets try to use bind Statement to reduce further hacking
I am also avoiding using "LIKE" Clause because IVariable direct Exact results so will be using the Direct Varible
*/
$sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
$sql->bind_param('s', $_POST['matric_number']);
$sql ->execute();
The binding param and prepared statement prevents SQL injection so you don't need mysqli_real_escape_string operation

How to authenticate users with credentials in MySQL database

On my form page, I have two textboxes with the names name and password.
When the user hits submit, it sends that data into two columns in a MySQL database named 'name' and 'password'.
After the data is recorded (which is the part I understand and don't need help with), I want the user to be at the sign-in page and type in his/her name and password and only be allowed into the site if the name and password data already exist in the database (part that I don't understand).
Would I use the following query :
SELECT * FROM tablename WHERE name & password = "'$_POST[name]', $_POST[password]'
You should use AND or && instead of just a single ampersand (&), and separate the variables to be binded accordingly to their column name.
You should also consider sanitizing your variables before using them to your queries. You can use *_real_escape_string() to prevent SQL injections.
$name = mysql_real_escape_string($_POST["name"]);
$password = mysql_real_escape_string($_POST["password"]);
"SELECT * FROM tablename WHERE name = '".$name."' AND password = '".$password."'"
But the best recommendation that I can give to you is to use prepared statement rather than the deprecated mysql_*
if($stmt = $con->prepare("SELECT * FROM tablename WHERE name = ? AND password = ?")){ /* PREPARE THE QUERY; $con SHOULD BE ESTABLISHED FIRST USING ALSO mysqli */
$stmt->bind_param("ss",$_POST["name"],$_POST["password"]); /* BIND THESE VARIABLES TO YOUR QUERY; s STANDS FOR STRINGS */
$stmt->execute(); /* EXECUTE THE QUERY */
$noofrows = $stmt->num_rows; /* STORE THE NUMBER OF ROW RESULTS */
$stmt->close(); /* CLOSE THE STATEMENT */
} /* CLOSE THE PREPARED STATEMENT */
For securing password, you could also look at password_hash().
Please Always use Prepared statement to execute SQL code with Variable coming from outside your code. Concatenating variable from user input into SQL code is dangerous ( consider SQL injection ), you could use prepared statement with mysqli or PDO ( recommended ).
Mysqli example:
$mysqli = new mysqli("example.com", "user", "password", "database");
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $user,$password);
$stmt->execute();
if($stmt->num_rows!=1) {
// check failed
}else{
// check success
}
PDO example (recommended )
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $dbh->prepare($query);
$stmt->bindParam(1,$user);
$stmt->bindParam(2,$password);
$stmt->execute();
if($sth->fetchAll()) {
// check success
}else{
// check failure
}
Additionally you should also consider using some form of 1-way password encryption ( password hashing ) before storing it in your database and compare it to the hash( the most accepted way to do it is using Bcrypt).
You can use something like
SELECT count(*) FROM tablename WHERE name = "'.$_POST[name].' AND password = "'. $_POST[password].'"
You should expect count to be exactly 1 - indicating valid user, 0 - indicating invalid user
Anything greater than 1 should be invalid scenario indicating some kind of inconsistency in your database...
You should assign the variables to name & pass subsequently.
You can try this:
$con = mysqli_connect("localhost","YOURUSER","YOURPASS","YOURDB");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
$user
= mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$query = "select * from tablename where user ='$user' AND password='$pass' ";
$run = mysqli_query($con,$query);
$check = mysqli_num_rows($run );
if($check == 0)
{
echo "<script> alert('Password or Email is wrong,try again!')</script>";
}
else
{
//get a session for user
$_SESSION['user']=$user;
// head to index.php; you can just put index.php if you like
echo"<script>window.open('index.php?login=Welcome to Admin Area!','_self')</script>";
}

how to check the result of the mysql query in php

I have a html form for the user to login to the website but i want to check if the following query retun true or false, I am using the PDO so I cant use the method mysql_num_rows();
<?php
$view = new stdClass();
$view->login = 'Homepage';
if(isset($_POST['firstName']) && isset($_POST['password']) )
{
$_firstName = $_POST['firstName'];
$password= $_POST['password'];
$user = new UserPassword(); $user->getLogin($_firstName, $passWord);
}
require_once('Views/login.phtml');
public function getLogin($userName,$passWord) {
$sqlQuerys = "SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $userName' AND password = '$password'";
echo $sqlQuerys;
$statement = $this->_dbHandle->prepare($sqlQuerys);
$statement->execute();
}
}
You are not actually executing any query. You are setting a variable, but not executing the code.
Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks. Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/php has examples to get you started, and this question has many examples in detail.
You execute the query and you fetch a row. If the result of that fetch is not empty, you have a valid user.
Very important: You need to salt and hash your passwords and use prepared statements to avoid sql injection.
try this solution
$query="SELECT `id`, `username`, `password`, `firstname`, `surename` FROM `sta177users` WHERE username = ' $_firstName' AND password = '$password'";
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
You wanna do something like this:
function emptyQuery($db) // assume $db is your PDO object
{
// your prepared sql statement with PDO::prepare()
$sql = $db->prepare("SELECT `id`,
`username`,
`password`,
`firstname`,
`surename`
FROM
`sta177users`
WHERE
username = ' $_firstName'
AND password = '$password'
");
// execute it with PDO::execute()
$sql->execute();
// return all the rows with PDO::fetchAll(), and then see if the array is empty().
return empty($sql->fetchAll());
}
?>
This should implement your specification. You can use count() for a count, etc.
Of course, do not forsake the documentation:
http://us2.php.net/pdo
Hope that helps!

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