-1

I have a issue.I have a login page made using Angular.js,PHP and MySQL.When user is typing the following credential ,it is able to login.

username-1' or '1' = '1' or '1
password- 1' or '1' = '1' or '1

I think this is the SQL query based injection.I am explaining my php code below.

login.php:

<?php 
require_once '../../include/dbconfig.php'; 
$dept_id = $_SESSION["admin_dept_id"];
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_pass=$request->user_pass;

$password =sha1(htmlspecialchars(trim($user_pass)));
$selquery = "SELECT * FROM db_user WHERE login_name='".$user_name."' and password='".$password."' and user_status='1'";
$selres = mysql_query($selquery); 
if(mysql_num_rows($selres ) > 0){
    $result=mysql_fetch_array($selres); 
    $_SESSION["admin_id"]=$result['user_id'];
    $_SESSION["admin_user_name"]=$result['first_name']." ".$result['last_name'];
    $_SESSION["admin_user_type"]=$result['user_type'];
    $_SESSION["admin_email_id"]=$result['email'];
    $_SESSION["admin_role_id"]=$result['role_id'];
    $_SESSION["admin_clg_id"]=$result['colg_id'];
    $_SESSION["admin_dept_id"]=$result['dept_id'];
    //$result['msg'] = 'Login successfull...';
}else{
    header("HTTP/1.0 401 Unauthorized");
    $result['msg'] = 'Invalid username or password, Please try again...';
}
echo json_encode($result);
?>

Here I need to prevent this credentials for login.Please help me to resolve this issue.

1 Answers1

0

I suggest you read:

How can I prevent SQL injection in PHP?

In your case the problem is right here:

$selquery = "SELECT * FROM db_user WHERE login_name='".$user_name."' and password='".$password."' and user_status='1'";

For a quick fix, change it to:

$selquery = "SELECT * FROM db_user WHERE login_name='".mysql_real_escape_string($user_name)."' and password='".mysql_real_escape_string($password)."' and user_status='1'";

For a long-term fix, convert your code to use PDO.

Community
  • 1
  • 1
Sasha Pachev
  • 5,162
  • 3
  • 20
  • 20
  • Do Not use MySQL. Its no longer support for php7 – Abdulla Nilam Nov 18 '15 at 04:45
  • @ Sasha Pachev: your line is working. for login purpose only is this ok or not ? –  Nov 18 '15 at 04:53
  • If you do not plan to upgrade PHP to something higher than 5.5 and do not anticipate any code changes, you can live with this code. However, be aware that you are using a deprecated extension. – Sasha Pachev Nov 18 '15 at 05:19