Trouble in verifying hash password with the password user entered - php

i am trying to verify hash password stored in database with the password user enters to login. But i am unsuccessful with it. I am using password_verify to compare the passwords but its not giving the answer true even if i am entering correct password.
Please help me!!
<?php
print_r($_POST);
include('connect.php');
var_dump($_POST);
print_r($_POST);
$tbl_name = 'userC';
if(isset($_POST["USERNAME"]) && isset($_POST["USER_PASSWORD"]))
{
$username1 = $_POST["USERNAME"];
$password1 = $_POST["USER_PASSWORD"];
}
// To protect MySQL injection
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$stid = oci_parse($conn, "SELECT * FROM $tbl_name where
user_name='$username1'");
$result = oci_execute($stid);
//$re = oci_fetch_all($stid,$abc);
while(($row = oci_fetch_array($stid,OCI_BOTH)) != false )
{
$password = $row[6];
$username = $row[2];
$re = 1;
}
if(isset($password))
{
if (password_verify($password1, $password))
{
$re1=1;
}
else
{
$re1 = 0;
}
}
else
{
$re1 = 0;
}
// If result matched $username and $password, table row must be 1 row
if($re >= 1 && $re1 >= 1)
{
// Register $username, $password and redirect to file "login_success.php"
session_start();
$_SESSION["username"] = $username;
header("location:form.php");
}
if($re < 1) {
$failed = 1;
header("location:login.php?msg=failed");
}
if($re1 < 1) {
$failed = 1;
header("location:verify.php?msg1=failed");
}
?>

Remove the $password1 = stripslashes($password1); from your code. You shouldn't modify the entered password in any way before passing it to password_verify (or password_hash for the same matter).
By the way, stripslashes isn't protecting you from SQL-injection. Use prepared statements and oci_bind_by_name instead:
$stid = oci_parse($conn, "SELECT * FROM $tbl_name where user_name=:uname");
oci_bind_by_name($stid, ":uname", $username1);
$result = oci_execute($stid);

Related

Multiple User Type Login Through Single Login Page Issue

I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}

If and else statement , test on the user account status

I want to make test on the status of the user account.
If the account is active I redirect him to the user page
If the account is not active I redirect him to login page again with an error
Here’s my code
<?php
require('conexion.php');
$username = '';
$password = '';
if (isset($_POST['username']) || !empty($_POST['username']))
$username = $_POST['username'];
if (isset($_POST['password']) || !empty($_POST['password']))
$password = $_POST['password'];
$q1 = "select * from user where username='" . $username . "' and password='" . $password . "' ";
$r1 = $db->query($q1);
$i = 0;
echo $q1;
while ($d1 = $r1->fetch()) {
$i++;
//$id_perso = $d1['id_perso'];
$type = $d1['type'];
$nom = $d1['nom'];
$prenom = $d1['prenom'];
$statut = $d1['statut'];
$user_id = $d1['id_user'];
}
if ($i == 1) { // START IF
session_start ();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if ($statut = 'actif') {
if ($_SESSION['type'] == 'admin') {
$path = "admin/index.php";
}
if ($_SESSION['type'] == 'professeur') {
$path = "professeur/index.php";
}
if ($_SESSION['type'] == 'doctorant') {
$path = "doctorant/index.php";
}
header("Location:".$path);
} elseif ($statut = 'inactif') {
header("location:login.php?inactif");
}
} else {
header("location:login.php?error=1");
}
?>
Why don't you use a boolean, should be easier.
/*
1. Get Status from Database
2. When the user is active, you set the boolean true, else false. */
$booleanVar = false;
if($booleanVar) {
// user is active
} else {
// user is inactive
}
EDIT:
Redirecting with header works like this, I believe its Case Insensitive:
header('Location: somesite.php?abc');
Also you have to check values with "==" (for equal) or "===" (for identical)
You could simply get the same result if you do this with a simple query:
You check if the password and the username matches AND check if the account has been activated.
$sql = 'SELECT `id` FROM `user` WHERE `username` = '$username' AND `password` = '$password' AND `statut` = 1'
You then can run the query and check if number of rows is greater than 0.
$sql = $db->query($sql);
$results = $sql->fetch();
if (count($results) > 0) {
// Account is activated
} else {
header("location: login.php");
exit;
}
You are also vulnerable to SQL-injections by inserting your variables directly into your query, wich Edhurtig noticed! The best way to prevend SQL-injections is to use PDO prepared statements.
First and foremost: DO NOT STORE PASSWORDS IN PLAINTEXT. Do some research into secure hashing algorithms (not md5) or use a third party authentication service like Google, Facebook, Github, ect.
Second: This code is vulnerable to SQL injection via $_POST['username'] and $_POST['password']
Also it was a bit unclear what was being asked but I felt it was important to point out the aforementioned issues because they are so security critical.
Here is what I was able to cleanup. I would strongly recommend using a third party authentication service though
<?php
require('conexion.php');
$salt = "random_string";
$username='';
$password='';
if (isset($_POST['username'])||!empty($_POST['username'])) $username = $_POST['username'];
if (isset($_POST['password'])||!empty($_POST['password'])) $password = $_POST['password'];
$hashed_password = some_hashing_function_1000_times($password, $salt);
$q1="SELECT * FROM user WHERE `user`.`username` = '%s' AND `user`.`password` = '%s' LIMIT 1";
// I hope that $db has a prepare function, it prevents SQL injections from $_POST['username'] and $_POST['password']
$sql = $db->prepare($q1, $username, $hashed_password);
$r1= $db->query($q1);
$user = $r1->fetch();
if( $user ) { // START IF
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['type'] = $type;
$_SESSION['nom'] = $nom;
$_SESSION['prenom'] = $prenom;
$_SESSION['statut'] = $statut;
$_SESSION['user_id'] = $user_id;
if($statut == 'actif'){
if($_SESSION['type']=='admin') { $path="admin/index.php"; }
if($_SESSION['type']=='professeur'){ $path="professeur/index.php"; }
if($_SESSION['type']=='doctorant') { $path="doctorant/index.php"; }
header("Location: " . $path);
exit();
}
else if ($statut == 'inactif') {
header("Location: login.php?inactif");
exit();
}
}
header("Location: login.php?error=1");
exit();
// No Closing PHP tag at end of file

MySql Password_verify() not working?

during registration, the user's password is saved in the database as an encrypted BCRYPT password.
My question is: Why can't I verify the encrypted database password with the entered password?
CODE:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$veri_password' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY DECLARED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
?>
I'm receiving an error that says 'account does not exist' even when I enter valid information.
Thanks,
-Eugene
EDIT CHANGED TO THIS:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if($veri_password === true){
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY ESTABLISHED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
}
?>
change to:
$sql = "SELECT id, username FROM users WHERE email='$email'";
Also change:
$veri_password = password_verify($password, $user_pass);
to
if(!password_verify($password, $user_pass)){
echo 'invalid password';
exit;
}
anyway, your code is vulnerable to sql injection. please consider using prepared statements in your queries or escape input strings with mysql_real_escape_string. . And also it is recommended to use mysqli or pdo instead of procedural methods

Is it possible to select the exact password to a username in a database?

I have created a database with a table (UserPass) which essentially stores Usernames and Passwords.
Now in my form I want to ask a user to input his username and password and while testing this, I realized that I can input any username from the database and any password to login.
Is it possible to select in the SQL query the password that is in the same line as the username?
I tried something like:
$username = $_POST['username'];
$sql = "SELECT Password FROM UserPass WHERE Username = $username";
But the following mysqli_query failed:
$query = mysqli_query($cxn, $sql);
So here is the entire action.php script:
<?php
include "info.php";
include "god.php";
session_start();
if($_POST['god'] == $god)
{
header( "refresh:0;url=../web.html" );
}
else if(empty($_POST['god']))
{
}
else
{
echo "Can't you read: DON'T TRY!!!!!!!";
exit();
}
$cxn = mysqli_connect($host, $user, $password, $dbname) or die("Go");
//check username
$userI = $_POST["username"];
$userSql = "SELECT Username FROM UserPass ";
$result = mysqli_query($cxn, $userSql) or die("Query failed!");
while($line = mysqli_fetch_assoc($result))
{
extract($line);
foreach ($line as $key => $val)
{
if($_POST['username'] == $val)
{
//check for password
$username = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT Password FROM UserPass";
$passres = mysqli_query($cxn, $sql) or die("Request cannot be handled now.");
while ($passline = mysqli_fetch_assoc($passres))
{
extract($passline);
foreach ($passline as $k => $v)
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
}
else
{
session_destroy();
}
}
}
}
}
}
/*
if($userI == $line['Username'])
{
//check for password
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$res = mysqli_query($cxn, $sql) or die("Pass query failed");
$passline = mysqli_fetch_assoc($res);
if($pass == $passline['Password'])
{
header( "refresh:4;url=../web.html");
session_start();
echo "Login succesful, session started, session id: ";
}
}
*/
/*
if($_POST['username'] == $val)
{
//check for password
$b = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$passres = mysqli_query($cxn, $sql);
$passline = mysqli_fetch_row($passres);
foreach ($passline as $k => $v )
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
session_start();
}
}
}
*/
/*
else
{
print("Destroying Laptop...US Government...Destroying Laptop...\n");
exit();
}
*/
?>
You just need to check if there is a record that contains both username and password of the same user:
$password = mysqli_real_escape_string($password);
$username = mysqli_real_escape_string($username);
$sql = "SELECT Password FROM UserPass WHERE Username = '$username' AND Password = '$password'";
if there is 1 such result, it is OK.
BTW, you should not store passwords in plain text - instead use one-way hashing function and compare only the hashes of the passwords.
Your SQL query should contain an 'AND' like this:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM UserPass WHERE username = '{username }' AND password = '{$password}' LIMIT 1";
$query = mysqli_query($link, $sql);
if ($query && mysqli_num_rows($query)>0) {
//user is authenticated
}
?>
By using the logical operator AND your query must match two conditions to give you an answer. That conditions should be known only by the users.
Also please do not store the password field as clear text in database. It's not safe. You should use sha1 hash. For more information about this please take a look here http://en.wikipedia.org/wiki/SHA-1

Login suddenly stopped working

I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).

Categories