Password not right but still right? - php

I'm busy with creating a login for on my website, I'm stuck with this problem:
Logging in with the right or wrong password still delivers me a succesfull login...
$sql = "SELECT *
FROM `players`
WHERE `username` = '" . $_POST['username']
. "' AND `password` = '" . sha1($_POST['password'])
. "' LIMIT 1";
$result = $mysqli->query($sql);
$get = $result->fetch_object();
if (empty($_POST['username']) || empty($_POST['password'])) {
$message = "You can't leave something blank...";
}
if (!$result) {
$message = "Nope, not that one...";
}

As previously stated in comments, your script is highly prone to sql injection which is extremely dangerous ESPECIALLY when handling passwords.
Please read: Prepared statements and stored procedures
I will provide you working code that I use for my registrations and logins. I hope this helps you in what you are looking for. A couple things to note is that I use AJAX/JSON to pass some data back and forth between my front and back ends which I will comment my code below as to not confuse you.
<?php
// starts the session
session_start();
// call on db connection file to execute queries below
require 'dbconfig.php';
// register logic
if(isset($_POST['newusername']) && isset($_POST['newpassword'])) {
$query = $conn->prepare("SELECT username FROM users WHERE username = :username");
$query->bindValue(':username', $_POST['newusername']);
$query->execute();
$check = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
// check if the username exists, if not then create the new user, else, send to front end and notify the user
if($check['username'] === $_POST['newusername']) {
header('Content-Type: application/json');
echo json_encode($check);
} else {
$query = $conn->prepare("INSERT INTO users (username, password) VALUES (:newuser, :newpassword)");
$query->bindValue(':newuser', $_POST['newusername']);
$query->bindValue(':newpassword', password_hash($_POST['newpassword'], PASSWORD_BCRYPT)); // using the prepared statements to prevent injection and optimizing PASSWORD_BCRYPT for passwords
if($query->execute()) {
// log to my log db
$registerLog = "New user was registered: " . $_POST['newusername'];
$query = $conn->prepare("INSERT INTO logs (website, entry) VALUES ('contacts', :entry)");
$query->bindValue(':entry', $registerLog);
$query->execute();
}
$query->closeCursor();
}
}
// login logic
if(isset($_POST['username']) && isset($_POST['password'])) {
$query = $conn->prepare("SELECT userid, username, password, pwreset, userlvl FROM users WHERE username = :username");
$query->bindValue(':username', $_POST['username']);
$query->execute();
$auth = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
// check for username and verify the password
if(count($auth > 0) && password_verify($_POST['password'], $auth['password'])) {
// if successful, initiate $_SESSION variables
$_SESSION['userid'] = $auth['userid'];
$_SESSION['userlvl'] = $auth['userlvl'];
$_SESSION['username'] = $auth['username'];
$loginLog = "User: " . $_POST['username'] . " logged in.";
$query = $conn->prepare("INSERT INTO logs (website, entry) VALUES ('contacts', :entry)");
$query->bindValue(':entry', $loginLog);
$query->execute();
$query->closeCursor();
$redirect = true;
header('Content-Type: application/json');
echo json_encode($redirect);
exit;
} else {
// if username and/or password do not match or don't exist, destroy the session.
session_unset();
session_destroy();
exit;
}
}
?>
You have to unset and destroy the session if a login attempt fails or else it will just let you in every time because the script just sees that you have set the session and beyond that, it doesn't care if it really failed, it will let the user in.
I hope this provides you with an answer you need.

Related

Login page keeps showing error PHP and MySQL

I am having issues getting some simple (or it seems simple) coding to cooperate. I've tried stripping it completely and typing everything out. Here is the code:
<?php
session_start();
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
include('includes/admin.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 0) {
echo '<p>Incorrect login.<br>Return to Login Page</p>';
} else {
$_SESSION['user'] = $username;
echo '<p>Login successful.<br>Go to Admin Page</p>';
}
}
?>
The goal is to have it redirect to the login page if unsuccessful and to redirect to another admin page if successful. I keep getting the "Incorrect Login" error, even when I type in the correct username and password.
Side Note: I know to redirect, I need to use header('Location: link.php'), it is not included for testing purposes.
If you didn't save your password as MD5 hash in your database you will never match it, cause in the line above you hash the password via MD5 before using in the query.
MD5 isn't secure! Use the PHP internal functions (password_hash(), password_verify()) to create and check passwords!
Use prepared statements!
Example code:
<?php
// Save a new user password in DB
$username = 'Max User';
$password = 'My_Secr3t_Pa5sw0rd';
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare("INSERT INTO `users` (`username`, `password`) VALUES(?, ?)");
$stmt->bind_param("ss", $username, $passwordHash);
$stmt->execute();
// Check user password
$stmt = $mysqli->prepare("SELECT `password` FROM `users` WHERE `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (password_verify($password, $row['password']) {
echo "Password correct";
} else {
echo "Password incorrect!";
}
?>

PHP script is saying "invalid password" when I know it's correct

I'm building an intentionally flawed application for presentation purposes for work. It's left vulnerable to demonstrate improper practices and possibly encourage those who would exploit it to do so. There is ample logging on the server so we're able to see when people poke around. I just need a simple login page that uses a PHP script to connect to the SQL database. I can verify connectivity through the SQL server logs, however, the script returns and says "invalid password" when I know the password and username I'm inputting are correct.
I have tried swapping bits of code from other resources / what I know and I get internal error 500
// POST variables
$user=$_POST['user'];
$pass=$_POST['pass'];
// MD5 hash
//$pass=md5($pass);
$sql = "SELECT * FROM login WHERE user = '$user' AND pass = '$pass'";
// Query Login
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Login validation
if(sqlsrv_has_rows($stmt)) {
header('Location: landing.html');
}
else {
echo "Wrong username or password!";
}
I expect the connection to work, instead, it just throws up my "Wrong username or password!" statement
The way that your scripts is written is incorrect. To check for a correct username and password, I wouldn't check if there are rows. I understand this isn't real and it's meant to show bad scripting/coding/etc however, this is really bad. The reason why it keeps giving you "Wrong username or password!" is because there are no rows being returned. Try rewriting your script like this:
<?php
// Connect to Database Server
$server = "serverName\sqlexpress";
$connectionInfo = array("Database" => "dbName", "UID" => "username", "PWD" => "password");
$conn = sqlsrv_connect($server, $connectionInfo);
// POST variables
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = 'SELECT * FROM login WHERE `user` = "' . $user . '" AND `pass` = "' . $pass . '"';
// Query Login
$statement = sqlsrv_query($conn, $query);
if ($statement) {
$rows = sqlsrv_has_rows($statement);
if ($rows === true && $rows >= 1) {
header('Location: landing.html');
} else {
echo "Wrong username or password!";
}
} else {
die(print_r(sqlsrv_errors(), true));
}

"Cant process the request", dealing with basic parameterized queries

I am trying something I found online (Extremely new to this) and none of it works. It's some random science project I decided to learn more about yet I am stuck on part 2 of the "procedures". https://www.sciencebuddies.org/science-fair-projects/project-ideas/Cyber_p008/cybersecurity/sql-injection#procedure
I watched videos but they only consist of just a user_ID and not a username and password. NOTE: Only the code dealing with login.php is causing problems.
<?php
include("global.php");
include("db.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password are sent in the form
$username = $_POST['username'];
$password = $_POST['password'];
// Check if the username and password exist in the database
$sql = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$stmt = msqli_stmt_init($db);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL Statement Failed";
} else {
mysqli_stmt_bind_param($stmt, "ss", $username, $password );
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);}
// If username and password matched then there is one row in the result
if ($count != 0) {
$_SESSION['login_user'] = strtolower($username);
header("location: search.php");
}
else {
$error = "Your Username or Password is invalid";
}
}
?>
It should have prevented a basic " 'or''=' " injection attack but it decided not to work entirely.
If you use query parameters — which is definitely a good idea — you must leave placeholders in your query. Use ? as the placeholder.
Like this:
$sql = "SELECT username FROM users WHERE username = ? AND password = ?";
You later bind variables to those parameters. You must bind the same number of variables as the number of parameter placeholders.
You got the error you described because you tried to bind variables to a query that had no parameter placeholders.

Invalid sql statment

I'm trying to conduct an experiment using a pre-coded project which inside this link here.
I'm using xampp as a web server with mysql. Whenever I run through the authentication page which has this code:
<?php
include_once("zSessionStart.php");
include_once("zConfig.php");
include_once("zDB.php");
$password = $_REQUEST["password"];
$userID = $_REQUEST["userID"];
$isAdmin = false; //is administrator or not
$askDemo = false;
//authenticate the login data from login.php
$query="select userID, isAdmin, askDemo from $_usersTable where (password= '$password') and (userID='$userID');";
$rs=mysql_query($query) or die ("Invalid sql.");
if ( mysql_num_rows($rs) > 0 ) //correct password
{
$array = mysql_fetch_array($rs);
if(strcmp($array["isAdmin"], "y")==0){
$isAdmin=true;
}
if(strcmp($array["askDemo"], "y")==0){
$askDemo=true;
}
if(!$isAdmin){
$query="select userID from usertests where userID='" . $userID . "'";
$rs2=mysql_query($query) or die ("Invalid sql.");
if(mysql_num_rows($rs2) > 0){ //already take test
$array2 = mysql_fetch_array($rs2);
echo "<h2> You have already taken the task. Please contact your administrator if you " .
" feel you need to re-take this task again.</h2>";
die();
}
}
$_SESSION['userID'] = $array["userID"];
session_unregister('loginErr');
if($isAdmin){
header("Location: transfer.php?" . SID);
}else{
if($askDemo){
header("Location:demo.php?" . SID);
}else{
header("Location: index.php?" . SID);
}
}
}
else
{
$_SESSION['loginErr'] = "true";
header("Location: login.php");
}
mysql_close($db);
?>
I receive an error that says "Invalid sql.". Inside my database I have a table called users which has credentials such as userID and password. I've already set the username to be admin and password to be pass. However, I haven't had any luck figuring out what the issue might be.
Your Query is invalid because you are using wrong table name that is even no variable syntax i.e. $_usersTable. And also you are ending your query with multiple semi colons and even single/double quotes are not properly used.
You need to update your select query like below to resolve your issue:
$query="select userID, isAdmin, askDemo from usersTable where password = '".$password."' and userID ='".$userID."';
I strongly recommend you to use MySqli Prepared Statement Query to make it more Secure like below:
$mysqli = mysqli_connect($host, $username, $password, $db);
$query = "SELECT userID, isAdmin, askDemo from `usersTable` WHERE userID=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $userID);
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_all();
To learn more about it, follow link http://php.net/manual/en/mysqli.prepare.php

login with username or email address in php

I am trying to create a login with username or email
My code is:
$username=$_REQUEST['login'];
$email=$_REQUEST['login'];
$password=$_REQUEST['password'];
if($username && $password) {
$query="select * from user_db where username='$username' and password='$password'";
} else if ($email && $password) {
$query="select * from user_db where email='$email' and password='$password'";
}
Login with username is success but login with email is not working. Please help me!
The login parameter is the same for both email and username. Not exactly incorrect if you have a single login box that accepts either.
You could put the condition in the query itself if you're not sure if it's an email or username.
$login=$_REQUEST['login'];
$query = "select * from user_db where ( username='$login' OR email = '$login') and password='$password'"
Edit:
A PDO-like solution is much more preferred nowadays as the above is subject to SQL injection. The logic stays the same, but you'd have it look something like this:
$query = "
SET #username = :username
SELECT * FROM user_db
WHERE ( username = #username OR email = #username)
AND password = :password
";
$statement = $pdoObject->prepare($query);
$statement->bindValue(":username", $login, PDO::PARAM_STR);
$statement->bindValue(":password", $password, PDO::PARAM_STR);
$statement->execute();
You are setting the same value to two variables, and then using an if/else. Both if statements are equivalent.
You need to figure out if $_REQUEST[login] contains a valid email address, and if so use the email field of the database. Otherwise, use the username field.
Also, you should not be putting variables directly into the query. Use prepared statements.
Well i know this is an old post but i've found that some people are still going to view it so i wanted to put a easy way to allow both email and username on the same input
my code is as follows
if
(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $name_of_same_input) )
{
$un_check = mysql_query("SELECT uname FROM eusers WHERE uname = '' ") or die(mysql_error());
echo "loging in with username"; //code
}
elseif
(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $name_of_same_input) )
{
$un_check = mysql_query("SELECT umail FROM eusers WHERE umail = '' ") or die(mysql_error());
echo "loging in with email"; //code
}
<?php
require "connectdb.php";
$email =$_POST["email"];
$mobile = $_POST["mobile"];
$password =$_POST["password"];
//Test variables
//$email = "admin#xyz.com";
//$mobile = "9876543210";
//$password ="#!b7885a$";
$sql_query = "SELECT email FROM RegisterUser WHERE `email` LIKE '$email' OR `mobile` LIKE '$mobile' AND `password` LIKE '$password';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result) > 0 )
{
$row = mysqli_fetch_assoc($result);
$email = $row["email"];
echo "Login Successful...Welcome ".$email;
}
else
{
echo "Login Failed...Incorrect Email or Password...!";
}
?>
Hi, for me works something like this:
if ( !isset($_POST['emailuser'], $_POST['userPass']) ) {
// Could not get the data that should have been sent.
die ('Please fill both the username and password field!');
}
$emailuser = ($_POST['emailuser']);
$emailuser = trim($emailuser);
if ($stmt = $con->prepare('SELECT userEmail or userName, userPass FROM users WHERE userEmail = ? or userName = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bind_param('ss', $emailuser, $emailuser);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($userName, $userPass);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if (password_verify($_POST['userPass'], $userPass)) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['name'] = $emailuser;
$_SESSION['emailuser'] = $userName;
header('location: /menu.php');
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close(); } ?>
$username=$_REQUEST['login'];
$email=$_REQUEST['login'];
This is wrong, you are using $_REQUEST['login'] for both email and username. Why don't you just use email?
If $_REQUEST['login'] doesn't have email address, of course this wont return you anything.
Also, both of your if statements will always execute, unless the fields are empty. right?
Take the login out, enforce the users to login with email addresses. also, take md5 of the password. who stores raw passwords these days?
$username=$_REQUEST['username'];//I'm assuming your code here was wrong
$email=$_REQUEST['email'];//and that you have three different fields in your form
$password=$_REQUEST['password'];
if (validate_username($username)) {
$query="select * from user_db where username='".$username".' and password='".validate_password($password)."'";
} else if (validate_email($email)) {
$query="select * from user_db where email='".$email."' and password='".validate_password($password)."'";
}
//... elsewhere...
function validate_username(&$username) {
if (strlen($username) <= 1) { return false; }
//return false for other situations
//Does the username have invalid characters?
//Is the username a sql injection attack?
//otherwise...
return true;
}
function validate_email(&$email) {
//same deal as with username
}
function validate_password(&$password) {
//same deal as with username
}
Note, if you have only two fields (login and password), then the distinction between email and username is meaningless. Further note that you should really be using PHP PDO to construct and execute your queries, to prevent security breaches and make your life waaay easier.
if (validate_username($username)) {
$query="select * from user_db where username='".$username".' and password='".validate_password($password)."'";
} else if (validate_email($email)) {
$query="select * from user_db where email='".$email."' and password='".validate_password($password)."'";
}

Categories