-1

I am having some MySQL issues and am super confused since this doesn't seem possible. Anyway, when I try to login, when I input the correct password I am sent to the screen that says that the username/password is incorrect.

Basically, my database looks like this:

USERNAME    PASSWORD       EMAIL
Xp10d3      Password12345  xp10d3@gmail.com
IiBlurBeriI Password33333  iiblurberii@gmail.com

I want to check if the user inputted their username and if the password matches, but I'm confused on how to do that. I got some help making the code, but it doesn't seem to work since any username can be inputted BEFORE it's verified (it's verified in the user's email) and once they inputted it the password doesn't have to match. Ex. WHAT I WANT: User inputs the username Xp10d3. User inputs the password Password1111. There is an error message saying the password doesn't match. User then inputs the password Password12345. It is valid and sets the $_SESSION variable to their username. WHAT IS HAPPENING NOW: User inputs Xp10d3 which is in the database. The password they input is Password12345 which is correct and they get sent to the screen that says that their password is incorrect.

I did some testing and logged all the variables. It all boiled down to the fact that $row["PASSWORD"] was incorrect. How do I fix this?

Some important notes: The variable $_SESSION['password_not'] is not a hashed password. However, all the other variables that I get except for that variable and the $password variable are hashed.

List of variables that are NOT hashed:

$_SESSION['password_not']
$password

Variables that ARE hashed:

$row["PASSWORD"]
Any passwords in the database

Code: login_check_update.php:

<!DOCTYPE HTML>
<html>
<head>
    <style>
        body {
            text-align: center;
            font-family: sans-serif;
        }
        a {
            text-decoration: none;
            color: blue;
        }
        #logout {
            margin: 0 auto;
            text-align: center;
            border: 1px solid;
            border-radius: 5px;
            max-width:1024px;;
            height: 800px;
        }
    </style>
</head>
<body>
    <div id="logout">
        <?php
            session_start();
            /* Sends an email to the user and adds the special key to another database */
            $username = $_GET['username']; /* Gets the username that was submitted in the HTML form. */
            $password = $_GET['password']; /* Gets the password that was submitted in the HTML form. */
            $servername = "localhost"; /* MySQL database. Change if needed! Most of the time its not localhost unless you're hosting on your computer. */
            $user = 'xxx'; /* MySQL username. Change if needed. */
            $pass = 'xxx'; /* MySQL password. Change if needed. */
            $dbname = 'vibemcform'; /* MySQL database name. Change if needed. */

            $bytes = random_bytes(10); /* Randomized code */
            $key = bin2hex($bytes); /* Makes the randomized code */

            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;

            $link = "live.php";

            $con = new mysqli($servername, $user, $pass, $dbname); /* Connects to the database */
            $query = "SELECT USERNAME FROM data WHERE USERNAME = '".$username."'";
            $result = $con->query($query);
            $row = $result->fetch_assoc();
            $selectTwo = "SELECT PASSWORD FROM data WHERE PASSWORD = '".$password."'";
            $result2 = $con->query($selectTwo);
            $row2 = $result->fetch_assoc();

            /* Delete after */
            $test = $row["USERNAME"];
            $testTwo = password_verify($_SESSION['password_not'], $row["PASSWORD"]);

            if ($username == $row["USERNAME"] && password_verify($_SESSION['password_not'], $row["PASSWORD"])) {
                    echo "Found data in the database! Visit the chat!";
                    echo "<form action='live.php' method='post'><a href='".$link."'><input type='submit' name='btn1' value='$username'/></a></form>";
                    echo "Session ID: ". session_id() . ". ";
            } else {
                echo "Username not found/password incorrect. Please try again!";
            }

            $conn = null;
            exit;
        ?>
        <a href="index.html">Home</a>
    </div>
</body>
</html>
Eltik
  • 71
  • 6
  • Why are the passwords in your database not hashed? – Robby Cornelissen Mar 06 '20 at 02:59
  • 1
    You can't use `password_verify()` against plain text passwords. You have to hash them first with `password_hash()`. – Funk Forty Niner Mar 06 '20 at 02:59
  • 1
    Don't store passwords in sessions, it's not a good idea. – Funk Forty Niner Mar 06 '20 at 02:59
  • Where did this code come from? It's absolutely **not** something to use. – tadman Mar 06 '20 at 03:00
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add any data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or data *of any kind* directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Mar 06 '20 at 03:01
  • **WARNING**: Writing an access control layer is not easy and there are many opportunities to get it severely wrong. Any modern [development framework](https://www.cloudways.com/blog/best-php-frameworks/) like [Laravel](http://laravel.com/) comes with an [authentication system](https://laravel.com/docs/master/authentication) built-in, and there are [authentication libraries](http://phprbac.net/) you can use. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text** or a weak hash like **SHA1 or MD5**. – tadman Mar 06 '20 at 03:01
  • If you're just getting started with PHP and want to build applications, I'd strongly recommend looking at various [development frameworks](https://www.cloudways.com/blog/best-php-frameworks/) to see if you can find one that fits your style and needs. They come in various flavors from lightweight like [Fat-Free Framework](https://fatfreeframework.com/) to far more comprehensive like [Laravel](http://laravel.com/). These give you concrete examples to work from and guidance on how to write your code and organize your project's files. What you have here is not sustainable in its current form. – tadman Mar 06 '20 at 03:02
  • Heck that's a lot of messages. Robby Cornelissen they are. I hash them before putting them into the database. Funk Forty Niner I need a way for the passwords/usernames to be global without using the POST/GET method since the passwords/usernames will immediately change the next time an user logs in. tadman yes I have used it but an super unfamiliar with it :/ I have looked at other security methods such as bcrypt and stuff but couldn't find a good tutorial to use. I prefer to use vanilla PHP instead of other such APIs or frameworks. I'll definitely take a look at the security link you sent tho – Eltik Mar 06 '20 at 03:07
  • I'm not sure whether you store the password plaintext or hashed, but if it is hashed, you cannot search for the password with pure SQL, because of the random salt. Instead you should search by username and load the password-hash, which can then be verified with `password_hash()`. Have a look at an [example](https://stackoverflow.com/a/38422760/575765) I wrote in another answer. – martinstoeckli Mar 06 '20 at 18:30
  • @martinstoeckli I have already tried verifying it with password_verify() since the password submitted to the database is hashed. Updated code: https://sourceb.in/6b0f742794 – Eltik Mar 06 '20 at 23:41
  • You missed the point, the second query cannot work if a hash is stored. Add the password field to the result columns of the first query, but don't use it in the where part, see the example. – martinstoeckli Mar 07 '20 at 07:51
  • Sorry, what do you mean by, "the second query cannot work if a hash is stored."? – Eltik Mar 07 '20 at 20:53
  • @Xp10d3 - A password hash contains a random salt, so if you only have the plain text password you cannot know how the stored hash looks, first you would have to read the hash and extract the salt. Have a look at my tutorial about [safe password storage](https://www.martinstoeckli.ch/hash/en/index.php). – martinstoeckli Mar 09 '20 at 23:21
  • Ok thanks :) I figured it out. Apparently my column for the PASSWORD was only about 60 for length instead of the 255 that is required for a hash. – Eltik Mar 09 '20 at 23:30

1 Answers1

1

This was just a stupid mistake. The reason that my code was not working was because the column PASSWORD was only 60 characters and since I was using password_hash() the database required at least 255 characters, thus cutting off more than half of the password.

Eltik
  • 71
  • 6