Skip site navigation (1) Skip section navigation (2)

Re: PHP Username & Password Detection From PSQL Database

From: Andrew McMillan <andrew(at)catalyst(dot)net(dot)nz>
To: Yasmine Kedoo <yazkedoo(at)hotmail(dot)com>
Cc: pgsql-php(at)postgresql(dot)org
Subject: Re: PHP Username & Password Detection From PSQL Database
Date: 2004-04-07 19:18:01
Message-ID: 1081365481.522.74.camel@lamb.mcmillan.net.nz (view raw or flat)
Thread:
Lists: pgsql-php
On Thu, 2004-04-08 at 02:16, Yasmine Kedoo wrote:
> 
> The username 'yamkedoo' and password 'yasmine' will give Successful Login. 
> This works for all usernames and passwords in the database.
> 
> Though if a different password is used, Access Denied is printed as well as 
> an error,  Warning: Unable to jump to row 0 on PostgreSQL result index 2 in 
> /home/webpages/yamkedoo/Tests/brandnew.php on line 16, that I am unable to 
> solve. This applies for all incorrect passwords. Please view my code:

Note that your code is vulnerable to "SQL injection" exploit - what
happens if someone puts in a username of "'; DROP TABLE PatPerInfo;". 
The earlier code I sent you included calls to pg_escape_string() to
avoid this problem.  If that function is not implemented in your PHP
version (it's in 4.2 onwards, I think) you can implement something like
it yourself, fairly trivially:

function pg_escape_string($str) {
  $str = str_replace("'", "''", $str);
  $str = str_replace('\\', '\\\\', $str);
}


Also, see the error highlighted in your code below.


Regards,
					Andrew McMillan

> 
> <?php
>                 #Connects to the database
> 	$database = pg_Connect ("host=pgdbs.inf.brad.ac.uk dbname = yamkedoo user = 
> yamkedoo password = yamkedoo");
> 
> 	if(!$database)
>      	{
>         	echo "Connection Failed<BR>";
>      	}
> 
> 	else
> 	{
>                                 #assign formusername from html form to 
> $auth_user
>                                 #assign formpassword from html form to 
> $auth_pass
> 		$auth_user = trim($formusername);
> 		$auth_pass = trim($formpassword);
> 
> 		$query = "SELECT * FROM PatPerInfo WHERE trim(username) = '$auth_user' AND 
> trim(password) = '$auth_pass'";
> 		$result = pg_exec($database, $query);
> 		$row = pg_fetch_object($result, $rw);

Here, you always try and fetch a row. You should check the count of rows
returned, and only try and fetch if there is one:

if ( !$result ) {
  print "There was a problem accessing the database";
  # do something here to log the application problem
}
else if ( pg_numrows($result) != 1 ) {
  print "Access Denied";
  # Possibly do something here to log the unauthorised access attempt
}
else {
  $row = pg_fetch_object($result, 0);
  print "Successful Login";
}

> 
> 		if($row)
> 		{
> 			print "Successful Login\n";
> 		}
> 
> 		else
> 		{
> 			print "Access Denied\n";
> 		}
> 	}
> 
>     pg_close($database);

I never pg_close in my programs - the database will be closed
automatically when the page generation finishes, and that's fine.

> 
> ?>
> 
> If anyone can spot any mistakes, i will welcome suggestions ;-)
> 
> Thanx
> 
> 
> 
> 
> >From: Andrew McMillan <andrew(at)catalyst(dot)net(dot)nz>
> >To: Yasmine Kedoo <yazkedoo(at)hotmail(dot)com>
> >CC: pgsql-php(at)postgresql(dot)org
> >Subject: Re: [PHP] PHP Username & Password Detection From PSQL Database
> >Date: Wed, 07 Apr 2004 21:35:22 +1200
> >
> >On Wed, 2004-04-07 at 20:59, Yasmine Kedoo wrote:
> > > Hi.
> > >
> > > I am just beginning to work with PHP & PSQL so forgive me if i make 
> >simple
> > > mistakes. :-)
> > >
> > > I created my PSQL database via telnet on my university's database 
> >server. I
> > > have no problems retrieving and displaying certain data using PHP, but i 
> >am
> > > unable to recognise a username and password entered via a predefined
> > > authentication variable, $PHP_AUTH_USER.
> > >
> > > The script must recognise the username: 'yamkedoo', and password: 
> >'yasmine'.
> > > In the database, the username & password columns are spelt exactly as:
> > > 'username' & 'password'. The database name is 'yamkedoo', and the table 
> >name
> > > is 'PatPerInfo', as can be seen from the following code:
> >
> >The example in the PHP manual is:
> >
> ><?php
> >   if (!isset($_SERVER['PHP_AUTH_USER'])) {
> >     header('WWW-Authenticate: Basic realm="My Realm"');
> >     header('HTTP/1.0 401 Unauthorized');
> >     echo 'Text to send if user hits Cancel button';
> >     exit;
> >   } else {
> >     echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
> >     echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your
> >password.</p>";
> >   }
> >?>
> >
> >A couple of notes:
> >
> >1) You have <?PHP well down your page - you need this before the PHP
> >starts (like in the example above).  Lowercase is also a lot more normal
> >(although probably uppercase still works).
> >
> >2) The example above shows the syntax for more recent PHP versions, with
> >some security features enabled (i.e. use of $_SERVER['PHP_AUTH_USER']
> >rather than $PHP_AUTH_USER) whether the older syntax you have used below
> >will work will depend on how the installation was configured, to some
> >extent, as well as the version you are using.
> >
> >
> > >
> > > if(!isset($PHP_AUTH_USER))
> > > 		{
> > > 			Header("WWW-Authenticate: Basic realm=\"Authentication\"");
> > > 			Header( "HTTP/1.0 401 Unauthorized");
> > >
> > > 			echo "No Login\n";
> > > 			exit;
> > > 		}
> > > 		else
> > > 		{
> > > 			echo "User: $PHP_AUTH_USER<BR>";
> > > 			echo "Password: $PHP_AUTH_PW<BR>";
> > > 		}
> > > <?PHP
> > > 	$database = pg_connect("host=pgdbs.inf.brad.ac.uk dbname=yamkedoo
> > > user=yamkedoo password=yamkedoo");
> > >
> > > 		if(!$database)
> > >      		{
> > >         		print "Connection to database failed.";
> > >      		}
> > >
> > > 		else
> > >         	               {
> > >         	               $selectquery = "SELECT * FROM PatPerInfo";
> > >           	               $result = pg_exec($database, $selectquery);
> > >
> > > 		$maxrows = pg_numrows($result);
> > >            		$maxfields = pg_numfields($result);
> > >
> > >           		for ($rw = 0; $rw < $maxrows; $rw++)
> > >    	   		{
> >
> >Just as a suggestion you might want to consider:
> >
> >$row = pg_fetch_object($result, $rw);
> >if ( trim($_SERVER['PHP_AUTH_USER']) == trim($row->username)
> >            trim($_SERVER['PHP_AUTH_PW']) == trim($row->password) )
> >{
> >  ...
> >
> >Actually, though, you can get the database to do it:
> >
> >$auth_user = pg_escape_string(trim($_SERVER['PHP_AUTH_USER']));
> >$auth_pass = pg_escape_string(trim($_SERVER['PHP_AUTH_PW']));
> >$selectquery = "SELECT * FROM PatPerInfo
> >    WHERE trim(username) = '$auth_user'
> >      AND trim(password) = '$auth_pass'";
> >
> >$result = pg_exec( ...
> >
> >
> >Doing it this way you can simply see if you got back exactly one row,
> >and if you did then that should be the correct user record - no need for
> >PHP to inefficiently loop through all of the table looking.
> >
> >
> > >    				$username = pg_Result($result,$rw,0);
> > > 				$password = pg_Result($result,$rw,1);
> > >
> >
> >Aren't you missing a comparison on the line below?
> >
> > > 				if( trim($PHP_AUTH_USER) == trim($username) && (trim($PHP_AUTH_PW))
> > > 				{
> > > 		  		 	$auth = 1;
> > > 				}
> > >            		                 }
> > >
> > > 		     echo $auth;
> > > 		}
> > >
> > >       		 if($auth==0)
> > >      		 {
> > >      			print "Access Denied<BR>\n";
> > >      			exit;
> > >      		 }
> > >
> > >
> > > ?>
> > >
> > > After the username and password, i get the following error: Parse error:
> > > parse error in /home/webpages/yamkedoo/Tests/referrals2.php on line 44.
> > >
> > > Please view te following link:
> > > http://www.cyber.brad.ac.uk/~yamkedoo/Tests/referrals2.php to see what 
> >is
> > > happening.
> > > Only once has the authentication window appeared, and has not done so 
> >since.
> > > It only gives the error as seen at the link.
> >
> >Once you have provided the correct credentials to basic auth, your web
> >browser will repeatedly provide them each time until you exit the
> >browser or cancel them.
> >
> >Most sites don't use Basic Authentication like the above - generally
> >some form of session is maintained through URL rewriting or cookies
> >since that allows a lot more control (and graphical design) fitting the
> >login process more smoothly into the web page.
> >
> >Regards,
> >					Andrew.
> >
> >-------------------------------------------------------------------------
> >Andrew @ Catalyst .Net .NZ  Ltd,  PO Box 11-053,  Manners St,  Wellington
> >WEB: http://catalyst.net.nz/             PHYS: Level 2, 150-154 Willis St
> >DDI: +64(4)916-7201       MOB: +64(21)635-694      OFFICE: +64(4)499-2267
> >                http://survey.net.nz/ - any more questions?
> >-------------------------------------------------------------------------
> >
> >
> >---------------------------(end of broadcast)---------------------------
> >TIP 2: you can get off all lists at once with the unregister command
> >     (send "unregister YourEmailAddressHere" to majordomo(at)postgresql(dot)org)
> 
> _________________________________________________________________
> It's fast, it's easy and it's free. Get MSN Messenger today! 
> http://www.msn.co.uk/messenger
> 
> 
> ---------------------------(end of broadcast)---------------------------
> TIP 2: you can get off all lists at once with the unregister command
>     (send "unregister YourEmailAddressHere" to majordomo(at)postgresql(dot)org)
-------------------------------------------------------------------------
Andrew @ Catalyst .Net .NZ  Ltd,  PO Box 11-053,  Manners St,  Wellington
WEB: http://catalyst.net.nz/             PHYS: Level 2, 150-154 Willis St
DDI: +64(4)916-7201       MOB: +64(21)635-694      OFFICE: +64(4)499-2267
        The truth is rarely pure, and never simple. - Oscar Wilde
-------------------------------------------------------------------------


In response to

Responses

pgsql-php by date

Next:From: Chris SmithDate: 2004-04-07 23:07:27
Subject: Re: PHP Username & Password Detection From PSQL Database
Previous:From: Thom DysonDate: 2004-04-07 14:46:27
Subject: Re: PHP Username & Password Detection From PSQL Database

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group