Php - compare password with root password - php

Hopefully this is simple. I am trying to grant administrative power to the user if they are able to provide the 'root' password. Is there a way to compare this newly entered password with the root password? this is what my code looks like so far:
<form action='index.php?login=yes' method=POST>
Password: <input type=password name='pwd'><br />
<input type=submit value='Login' />
</form>
<?php
$pass=$_POST['pwd'];
$login=$_GET['Login'];
if($login=='yes') {
$con=mysql_connect('localhost','root','');
mysql_select_db('Login');
$get=mysql_query("SELECT count(id) FROM Login WHERE pwd = '$pass'");
$result=mysql_result($get, 0);
mysql_close($con);
if($result!=1)
echo"Login Failure!";
else {
echo"Login Success";
};
};
?>
</p>
Please be gentle because PHP is a lot different than i'm used to (i prefer java).
Thanks!

You should definitely consider hashing the password, with a salt. The md5() algorithm isn't really recommended for secure environments but it does at least make the job harder.
When saving your password in the database, you should do something like
$salt = 'dhg1d9h12h1029he01h2e1'; // Just have something random and long here
$hashedpassword = md5($salt.md5($password, true)); // Or any other combination you like here
Then, you can save $hashedpassword into the database like so:
mysql_query(sprintf("UPDATE Login SET pwd = '%s' WHERE username = '%s'",
mysql_real_escape_string($hashedpassword),
mysql_real_escape_string($username)
));
Then when you want to check if a password matches, do the exact same step as above to calculate the $hashedpassword value but pass in their test password and then compare that with what's in the DB, eg:
$result = mysql_query(sprintf("SELECT (pwd = '%s') AS authenticated FROM Login WHERE username = '%s'",
mysql_real_escape_string($hashedpassword),
mysql_real_escape_string($username)
));
$row = mysql_fetch_assoc($result);
if ($row['authenticated']) {
echo "Success!";
}
Aaaanyway, you look like you're just starting out, so I'd be very careful how you go with actual password verification. From what I understand bcrypt2 is what you want to use instead of md5, but I'll leave you to read up on how to do that in PHP; you should definitely read up on this stuff.
I'd also check the structure of your login table. You probably want more than a single user in it, otherwise why not just store the hash in the code itself, rather than the DB?
Also, you can determine if someone is submitting a form or getting the form by checking if $_SERVER['REQUEST_METHOD'] == 'POST', which is cleaner than using a get URL parameter (though I guess there's nothing wrong with the other approach...)

Related

Anyone able to help me with this bug in a login form?

So, I have a login form which is having a bit of trouble. It keepsechoing Incorrect password, please try again. whenever I try and access the restricted page. I have had a fiddle on myself, but I have not been able to find out what is wrong. The code is as follows:
<?php
//MySQL Database connect;
include "databaselogin.php";
//Checks if there is a login cookie
if(isset($_COOKIE["ID_my_site"]))
//If there is a cookie, the user is directed to a restricted page
{
$emailaddress = $_COOKIE["ID_my_site"];
$pass = $_COOKIE["Key_my_site"];
$check = mysql_query("SELECT * FROM Users WHERE EmailAddress='$emailaddress'") or die(mysql_error());
while($info = mysql_fetch_array( $check )) {
if ($pass != $info["password1"]) {
}
else {
header("location: restricted.php");
}
}
}
if (isset($_POST["submit"])) { //If the form has been submitted
//Make sure they filled it all in
if(!$_POST["emailaddress"] | !$_POST["password1"]) {
echo("You did not fill in all the required fields.");
}
//Checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST["emailaddress"] = addslashes($_POST["emailaddress"]);
}
$check = mysql_query("SELECT * FROM Users WHERE EmailAddress = '".$_POST["emailaddress"]."'") or die(mysql_error());
//Gives a message if the user doesn't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
echo ("The Email Address that you have entered is not in use, <a href='register.php'>click here</a> to register");
}
while($info = mysql_fetch_array( $check )) {
$_POST["password1"] = stripslashes($_POST["password1"]);
$info["Password"] = stripslashes($info["Password"]);
$_POST["password1"] = sha1($_POST["password1"]);
//Gives an error is the password is wrong
if ($_POST["password1"] != $info["Password"]) {
echo("Incorrect password, please try again.");
}
else {
//If the login is ok, a cookie is added
$_POST["EmailAddress"] = stripslashes($_POST["EmailAddress"]);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST["emailaddress"], $hour);
setcookie(Key_my_site, $_POST["password1"], $hour);
//Then they are redirected to a restricted area
header("location: restricted.php");
}
}
}
else {
//If they are not logged in
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Email Address:</td><td>
<input type="text" name="emailaddress" maxlength="40" placeholder="Email Address">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password1" maxlength="12" Placeholder="Password">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
?>
All help will be massively appreciated.
There are a couple of issues. First, mysql_query is a deprecated PHP function and should be replaced with mysqli_query. All functions in your code should use the mysqli prefix instead of mysql (so mysql_fetch_assoc should be changed to mysqli_fetch_assoc). This function also takes a parameter providing a connection to the database, which is done with mysqli_connect. So your code should have something like this:
$con = mysqli_connect($username, $password, $host, $db); // Fill in the variables with correct values
$check = mysqli_query($con, "SELECT * FROM Users WHERE EmailAddress='$emailaddress'");
$con only needs to be set once and can be used in other query calls in your code.
First of all the way you store your credentials in cookies is very dangerous. Anyone who has access to your computer or to your network if you're not using ssl can steal your cookies and log in to your account.
Secondly your problem lies in
while($info = mysql_fetch_array( $check )) {
this is an infinite loop. you should only call this once.
Your overall code could use some improvements such as:
update mysql to mysqli or PDO
use prepared statements
optimize code for speed (use || instead of |)
use a stronger hashing algorithm
Leave a comment if you want a more in depth instruction to improve your code
Hope this helped
Improvements
this is a great article about PDO. But PDO is object based and since you're new to PHP and i don't know your skill level you can better use mysqli for now. There're plenty of articles available on how you can do this.
PDO
in your code you use
if(!$_POST["emailaddress"] | !$_POST["password1"]) {
but if you use || instead of | the if condition skips the second argument if the first already failed.
You use sha1 for hashing your passwords. But this algorithm is a bad practice. You should use Bcrypt or at least use an individual salt for each password you encrypt with sha1 and store that next to the password in the database
SHA1 not safe anymore
You never store the user info in a session to retain the login on next requests, the way you're implementing it is called a remember me function and is considered hard to implement safely. it is easier to work with sessions first and if you really need it cookies later.
If you're using sessions you should also check if the session_id hasn't been set by an attacker in the clients browser. You can do this by setting a random cookie such as init
and when this is not set you call
session_regenerate_id();
You store both the email and the hashed password in a cookie. this can be very dangerous. You shouldn't store the password even if it is hashed in an cookie. The best practice is to hash a randomly created string of characters with a high entropy and store only that in the cookie and in the database. When the user logged in once with that cookie you should refresh the cookie with a new hash.
To fix your error you should remove the while loop around the mysql_fetch_array($check)
Tips for in the future
Your code looks a lot more organized if you start to learn to work with PHP objects. This can also make your project a lot easier to work with.
I don't know if you're going to use this code in a production website because I highly recommend against that. You can better use a safe and sound solution that somebody with more experience has created and when you have more experience you can start building your own.

How can you limit the access of unregistered users while giving registered users full access?

I'm trying to create a webpage with users and information that can only be accessed by registered users. Is it possible to limit the files an unregistered user can see? If so, how? I already have a MySQL database with a connection in index.php. Here's what I have so far:
<head></head>
<body>
<h3>Signup Here:</h3>
<form method="post" action="userindex.php">
Please enter user name: <input type="text" name="username" value="" /><br />
Please enter password: <input type="password" name="password" value="" />
<br />
<input type="submit" value="Submit"/>
</form>
</body>
<?php
include ("dbroutines.php");
if (isset($_POST['username'])) {
if ($_POST['username']>'' && $_POST['password']>'' ) {
$q="insert into users (Name, Password ) values ('".$_POST['username']."', '".$_POST['password']."')";
echo 'query='.$q;
$conn=db_connect();
$result=$conn->query($q);
echo '<br />xxx'.$conn->error."xxx";
unset($_POST['username']);
unset($_POST['password']);
} else {
echo 'Please enter both username AND password!';
}
}
$q="select Name, Password from users";
$conn=db_connect();
$result=$conn->query($q);
echo 'xxx'.$conn->error."xxx";
if ($result){
echo '<hr />';
for ($count=0; $row=$result->fetch_row(); ++$count ) {
echo $count." Name=".$row[0]." password=".$row[1].'<br />';
}
echo '<b style="color:red;">there are '.$count.' users in your database!'.'</b><hr />';
}
From this, can you specify what kind of user gets access to certain files like the userindex.php?
I think verifying user is not the fool proof solution . You have to keep a token in the Session to remember that this user is registered user. You have to create a common php page , called Security.php where you will put the following code , because a smart user can directly type the URL and reach to your confidential pages. You need to include this page at the top of each php page you want to secure.
if (!isset($_SESSION['AuthId'])) {
header('Location:Login.php');
exit;
}
Yes. Query your database for someone with the given username and password using a query that would look something like this:
select * from users where Name = 'john.doe' and Password = 'hunter2' limit 1
If it yields any rows, the user exists, and you should let them in. If there are no rows, then that com­bin­a­tion of username and password is invalid and you should not let them in.
That's the basics, but if you're actually going to put this into production, you'll want to make a few more changes:
Escape the data you're putting in the query appropriately or use prepared queries. As is, your code is vulnerable to an SQL injection attack. Say, for example, I tried to create an account with an apostrophe in the username or password. Your code would break. This could be leveraged for malicious means, too, so you really should patch that up.
The simplest way to patch it up would be to escape everything before you put it into the query, using, say, mysql_real_escape_string. That'll probably work, but even better (since the whole mysql_ family of functions is deprecated) would be to use prepared queries and PDO, as I've shown below.
Hash and salt your passwords so a database compromise (which could happen rather easily if the above vulnerability is left unpatched) will not reveal all the passwords.
Your code might then look like this:
// You'd probably want to put these in a separate configuration file.
$db = new PDO('mysql:dbname=test', 'my_mysql_user', 'hunter2');
// Make any errors throw an exception.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare('select * from users where Name = :name limit 1');
$query->bindValue(":name", $_POST['username'], PDO::PARAM_STR);
$row = $query->fetch(PDO::FETCH_ASSOC);
if($row === FALSE) {
// User not in the database; don't let them in.
}
$calculatedHash = hash("sha512", $row['PasswordSalt'] . $_POST['password']);
if($calculatedHash === $row['PasswordHash']) {
// Password's right. Let them in.
}else{
// Password's wrong. Keep them out.
}
Further improvements would be to use, say, bcrypt rather than salted SHA-512.
You can put the one extra field in the loggin table name 'Role'.
Each login time. Check if it is Master user,then It can access the more access.
If it is extra user then limited access.
You got my point? Or any Query?

PHP/AJAX Login taking very long

I've inherited a website that requires users to login too.
The login uses Ajax and PHP only this login procedure can take up to a minute to complete when there is only 4000 users registered.
Could this be due to the way the login is coded?
AJAX
<form name="login-form" onsubmit="return false">
<input type="text" id="the_username" value="Username" onfocus="emptyUsername(this);" onblur="clickrecall(this,'Username')" class="focusfield input push" />
<input type="password" id="the_password" value="Password" class="input" onfocus="emptyPassword(this);" onblur="clickrecall(this,'Password')" />
<span id="dialog-login-fail" title="Login failed"></span>
<input type="submit" onclick="javascript:void(0);" id="loginBtnBre" class="sign-in signin-submit-btn" value="Login Now" />
</form>
PHP
<?php
require 'config.inc.php';
foreach($_POST as $k=>$v)
{
$_POST[$k] = trim($v);
}
if(!isset($_POST['theusername']) or !isset($_POST['thepassword']))
{
print "Please use all fields";
}elseif(empty($_POST['theusername'])){
print "Please enter a username";
}elseif(empty($_POST['thepassword'])){
print "Please enter a password";
}elseif($_POST['theusername'] == "username" && $_POST['thepassword'] == "password")
{
print "Password & User cannot be the ones already listed";
}elseif(!preg_match("/^[a-z0-9]+$/i", $_POST['theusername']))
{
print "Please use only characters and numbers for username, no spaces, dashes or others!";
}else{
$password = md5($_POST['thepassword']);
$user = $_POST['theusername'];
$loginVar = $usersClass->login($user, $password);
if(is_array($loginVar))
{
$_SESSION['loggedIn'] = $loginVar;
#session_regenerate_id(true);
print "success";
}else{
print "Whoops, something went wrong! Try again.";
}
}
?>
Query
public function login($username, $password)
{
$rs = mysql_query("SELECT `id`,`active` from `$this->usersTable` WHERE
`username` = '".mysql_real_escape_string($username)."' AND
`password` = '".mysql_real_escape_string($password)."'");
if($rs) {
$row = #mysql_fetch_object($rs);
return $this->userInfo($row->id);
}else{
return false;
}
First change the browser to make sure that it's not a problem with the browser (rare, yet still happens sometimes).
Then try a PHP profiler to identify the "slow" backend code. There is even a nice tutorial at http://erichogue.ca/2011/03/linux/profiling-a-php-application/
You can use the firebug feature of the firefox to know if the correct information is being posted or not? I can see that there is no problem except a "login" function.
You can echo the query and copy it from firebug and run it to the database.
Track the time it takes to run that query and add some second on it. See if your database query takes lots of time or not.
If your query takes more time then you need to optimize your SQL query
You probably dont have an index on the username or password fields
Run:
alter table `TableName` add index `username` (`username`(500));
alter table `TableName` add index `password` (`password`(500));
From a mysql prompt, where TableName is the name of your table, then try again. If that speeds things up, adjust the indexes to be a more suitable length.
And you really shouldn't be storing passwords as clear text in the database. As bare minimum store them as hashed strings (MD5 etc) or better yet, store them as salted MD5 hashes.
I would change your select to just select based on the username (drop the password) then perform additional checks to make sure the password entered matches that of the returned row.

Need help making login page with salts

Alright, I'm trying to make a login page. It seems that all of the pages worked pretty good- until I added salts. I don't really understand them, but doing something as basic as I am shouldn't be to hard to figure out. Here's "loginusr.php":
<html>
<body>
<?php
//form action = index.php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$pass = $_POST['password'];
$salt = $pass;
$password = sha1($salt.$pass);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con)
{
die("Unable to establish connection with host. We apologize for any inconvienience.");
}
mysql_select_db("users", $con) or die("Can't connect to database.");
$select = "SELECT * FROM data WHERE usrname='$usrname' and password='$password'";
$query = mysql_query($select);
$verify = mysql_num_rows($query);
if($verify==1)
{
$_SESSION["valid_user"] = $usrname;
header("location:index.php");
}
else
{
echo "Wrong username or password. Please check that CAPS LOCK is off.";
echo "<br/>";
echo "Back to login";
}
mysql_close($con);
?>
</body>
</html>
I used the command echo $password; to show me if the password in the database matched with the script. They did. What am I doing wrong?
It seems like you've misunderstood salts, since you're setting $salt to be the password.
A salt should be a completely random string that's stored in a user record along with the password hash. A new unique salt should be generated for every user. So you need to add a new column to your database, called "password_salt" or similar.
Rather than trying to use the password in the SELECT query and see if you get any records, you actually need to just SELECT using the username/user_id in order to get the password hash and salt so that you can then use those to determine if the user entered the correct password.
When you sign up new users you should add the fields with values like this,
<?php
// This is registeruser.php
$salt = substr(sha1(uniqid(rand(), true)), 0, 20);
$pass = $_POST['password'];
$pass_to_store = hash("sha256", $salt.$pass);
// Then issue a DB query to store the $salt and $pass_to_store in the user record.
// Do not store $pass, you don't need it.
// e.g. INSERT INTO users ('username', 'password_salt', 'password_hash') VALUES (:username, :salt, :pass_to_store);
?>
Then to check the password is the same when logging in, you do something like this,
<?php
// This is loginuser.php
$user = // result from SQL query to retrieve user record
// e.g. SELECT password_hash, password_salt FROM users WHERE username='from_user'
$salt_from_db = $user['password_salt'];
$pass_from_db = $user['password_hash'];
if ($pass_from_db == hash("sha256", $salt_from_db.$_POST['password'])
{
// Password matches!
}
?>
Don't forget to sanitize user inputs and anything you're putting into your database. You might want to look into using prepared statements instead of having to remember to use mysql_real_escape_string all the time.
It looks like you're salting with the same password? Normally a salt would be a random key that is specific to your site that you prepend to the password input, which it looks like you're doing fine. Just make sure you're using that same salt for checking that you use when the password is created.
Also, to use sessions properly you need to have session_start before anything is output to the page:
<?php
session_start();
?>
<html>
<body>
...
A salt is a random value to prevent an attacker from just looking up the source of a hash in table generated based on common passwords. (Using the username as salt is obviously not a good idea as it only adds very little entropy).
So you need to store the salt in the database and read it from the database in order to calculate the salted password hash for comparison with the stored value.
You misspelled username a couple of times, is it misspelled in the database, too?

User Authentication (Using sha1)

I am creating a login form. I am learning how to use SHA-1 to encrypt passwords. I used SHA-1 to encrypt the password that the user created during registration. In the database I inputted pretend username and password data, to have something to work with. I'm having problems getting my login form to work.
// Database Connection
$con = getConnection();
$sqlQuery = mysql_query("SELECT count(*) from Customers
WHERE Email = '$email' and Password = sha1('$passLogin')")
// Executing query
$result = $con->mysql_result($sqlQuery, "0");
if ($result == 0) {
echo "Can not login, try again.";
} else {
echo "Login Good!";
}
I am learning how to use sha1 to
encrypt passwords.
... use sha1 to hash passwords. Hashing is different from encryption. Encryption is reversible, hashing isn't. (or shouldn't be). Now, ...
You have to make sure the passwords in the database are hashed.
Usually you do the hashing on the PHP side.
You should use salting to make rainbow table attacks unfeasible. Read Just Hashing is Far from Enough for Storing Password
That said, I would do the authentication part like this:
$hashedAndSalted = sha1($passLogin . $yourSalt);
$sqlQuery = mysql_query("SELECT Email FROM Customers WHERE Email = '$email' AND Password = '$hashedAndSalted'");
if (mysql_num_rows($sqlQuery) == 1) {
echo 'Login successful';
} else {
echo 'Could not login';
}
Replace your query with this:
$sqlQuery = mysql_query("SELECT count(*) from Customers
WHERE Email = '".$email."' and Password = '".sha1($passLogin)."'");
Remember to always concatenate strings and variables manually, don't rely on PHP to do it for you. Also, you forgot the semicolon ; after that line. Every line must be appended with a semicolon in PHP.
On a separate note if you have not sanitized your form inputs you are wide open for SQL injection.
If user enters the following for Email field:
' or '1'='1
They will be logged in :)
You should be using mysql_real_escape_string to escape $email and $passLogin or even better use prepared statements.

Categories