AbbyS
AbbyS

Reputation: 117

Checking to see if the password matches the particular user- PostgreSQL and Java

I am trying to implement a section of code which checks that the hashed_password and user_name match. The code below first checks to see if the username is valid, then if valid the code will then check to see if the password matches the username. However, that is section of the code that is not working. I can enter the correct username from the database and the corresponding correct password from the database and it displays the correct message You can proceed!. But if I enter the correct username from the database but an incorrect password it still displays You can proceed!. Any help is appreciated!

public void letsLogin() throws SQLException
 {

  System.out.print("Enter your user name: ");
  username = in.next();


  sql = "SELECT " + "username " + "FROM" + " users_table" + " where username = "
        + "'" + username + "'";


  result = s.executeQuery(sql);

 // select hashed_password
  sql_hash = "SELECT " + "hashed_password = " + "crypt(" + "'"
                 + hashed_password + "'" + ","+ "hashed_password)" +
                 " as matched " + "from users_table" +  " where username = "
                 + "'" + username + "'";

 result2 = s2.executeQuery(sql_hash);

  if(result.next())
  {
        System.out.println("You are registered!");
         // ask user to enter password

        System.out.println("Enter your password: ");
        hashed_password = stdin2.next();

        // check to see if username and hashed_password match
        if(result2.next())
        {
           System.out.println("You can proceed!");
        }

        else
        {
           System.exit(0);
        }


  }

Upvotes: 0

Views: 1298

Answers (2)

AbbyS
AbbyS

Reputation: 117

To fix the issue, it is best to use PrepardStatement and to create separate function to check the username and password.

Upvotes: 0

krokodilko
krokodilko

Reputation: 36107

I am not going to analyze why this code is not working, because it must be rewritten from scratch due to SQL Injection vulnerability.

Consider what happens when someone will enter this username:

' or 1=1 or 'x' = '

The first query becomes:

SELECT username FROM users_table where username = '' or 1=1 or 'x' = '';

The second query becomes:

 SELECT hashed_password =  crypt('any string', anything) as matched 
 from users where username = '' or 1=1 or 'x' = '';

In this case both queries always return some rows.

Because your code checks only a result of resultset.next() call, all checks will always pass, and .... the attacker logs into the system knowing neither the username nor the password.

Upvotes: 1

Related Questions