Page 1 of 1

Password resetting help

Posted: Wed Aug 17, 2011 9:58 am
by stijn22
Hi, I am using the following code to reset a password for a member (just found it via google):

Code: Select all

<?php
/**
 * ShuttleCMS - A basic CMS coded in PHP.
 * Password Reset - Used for allowing a user to reset password
 * 
 * @author Dan <dan@danbriant.com>
 * @version 0.0.1
 * @package ShuttleCMS
 */
define('IN_SCRIPT', true);
// Start a session
session_start();

//Connect to the MySQL Database
include 'connect.php';

//this function will display error messages in alert boxes, used for login forms so if a field is invalid it will still keep the info
//use error('foobar');
function error($msg) {
    ?>
    <html>
    <head>
    <script language="JavaScript">
    <!--
        alert("<?=$msg?>");
        history.back();
    //-->
    </script>
    </head>
    <body>
    </body>
    </html>
    <?
    exit;
}

//This functions checks and makes sure the email address that is being added to database is valid in format. 
function check_email_address($email) {
  // First, we check that there's one @ symbol, and that the lengths are right
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
     if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
    }
  }  
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}


if (isset($_POST['submit'])) {
	
	if ($_POST['forgotpassword']=='') {
		error('Vul je e-mail in.');
	}
	if(get_magic_quotes_gpc()) {
		$forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword']));
	} 
	else {
		$forgotpassword = htmlspecialchars($_POST['forgotpassword']);
	}
	//Make sure it's a valid email address, last thing we want is some sort of exploit!
	if (!check_email_address($_POST['forgotpassword'])) {
  		error('Email niet geldig, het moet iets zijn als: voorbeeld@voorbeeld.nl');
	}
    // Lets see if the email exists
    $sql = "SELECT COUNT(*) FROM fgusers2 WHERE email = '$forgotpassword'";
    $result = mysql_query($sql)or die('Could not find member: ' . mysql_error());
    if (!mysql_result($result,0,0)>0) {
        error('Email niet gevonden!');
    }

	//Generate a RANDOM MD5 Hash for a password
	$random_password=md5(uniqid(rand()));
	
	//Take the first 8 digits and use them as the password we intend to email the user
	$emailpassword=substr($random_password, 0, 8);
	
	//Encrypt $emailpassword in MD5 format for the database
	$newpassword = md5($emailpassword);
	
        // Make a safe query
       	$query = sprintf("UPDATE `fgusers2` SET `password` = '%s' 
						  WHERE `email` = '$forgotpassword'",
                    mysql_real_escape_string($newpassword));
					
					mysql_query($query)or die('Updaten mislukt: ' . mysql_error());

//Email out the infromation
$subject = "Uw nieuwe wachtwoord"; 
$message = "Uw nieuwe wachtwoord:
---------------------------- 
Password: $emailpassword
---------------------------- 
Dit wachtwoord is gecodeerd opgeslagen in onze database.

Deze email is automatisch gegenereerd."; 
                       
          if(!mail($forgotpassword, $subject, $message,  "Van: dht-clan")){ 
             die ("Het verzenden is mislukt. Neem contact op met de sitebeheerder."); 
          }else{ 
                error('Nieuw wachtwoord is verzonden!');
         } 
		
	}
	
else {
?>
      <form name="forgotpasswordform" action="" method="post">
        <table border="0" cellspacing="0" cellpadding="3" width="100%">
          <caption>
          <div>Wachtwoord vergeten</div>
          </caption>
          <tr>
            <td>E-mailadres:</td>
            <td><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td>
          </tr>
          <tr>
            <td colspan="2" class="footer"><input type="submit" name="submit" value="Aanvragen" class="mainoption" /></td>
          </tr>
        </table>
      </form>
      <?
}
?>
Everything works except one thing. When I fill in the email on my site, it says that an email it send with the new password. But when I use that new password it doesn't work, and the old one does. So I think that there's something wrong with the update query, but I don't know what.

I am sure that the database and column names are right.

I hope someone can help me!

Re: Password resetting help

Posted: Wed Aug 17, 2011 10:48 am
by phphelpme
It might be wise to show us a mysql dump so we can see your tables and database etc.

It seems allot of code to accomplish a forgot password script.

Best wishes

Re: Password resetting help

Posted: Wed Aug 17, 2011 10:49 am
by stijn22
Why do you want that? Or do you suggest that I should search another script?

Re: Password resetting help

Posted: Wed Aug 17, 2011 10:52 am
by Apollo
1. Why use md5 instead of a decent hash, md5 is broken. (I mean to hash the password in the database, not to generate a random alphanumeric password, it's OK to use md5 for that purpose).

2. You are mysql_real_escape_string'ing $newpassword, even though it contains only hexadecimal characters, but you're inserting the email address $forgotpassword (which is direct user input and therefore unsafe) in the query without escaping it? (well, actually, you're applying htmlspecialchars on it, why??)

3. That check_email_address function seems ridiculously overcomplicated. Someone tried to reinvent a wheel, with all kinds of hairs and strings attached (same goes for the rest of the scripts btw, it feels rather messy). Email validation can be done with a single regular expression, or better yet, with php's built-in filter_var($email, FILTER_VALIDATE_EMAIL) function.

Anyway, to debug this, try to print the actual $query string it generates, and see if there's anything odd in there.

Re: Password resetting help

Posted: Wed Aug 17, 2011 10:53 am
by Apollo
stijn22 wrote:Or do you suggest that I should search another script?
Yes, highly recommended. The one above is utter crap.

Re: Password resetting help

Posted: Wed Aug 17, 2011 10:57 am
by phphelpme
Well, that is exactly what I was thinking Apollo... lol

You just did not hold back with it...

Very nice analysis by the way..

I agree with scrapping this code because its a total mess.

Best wishes

Re: Password resetting help

Posted: Wed Aug 17, 2011 4:22 pm
by stijn22
Ok, thanks. I will search for another code :P

Re: Password resetting help

Posted: Wed Aug 17, 2011 7:37 pm
by Apollo
stijn22 wrote:Ok, thanks. I will search for another code :P
Good luck, and also keep in mind you shouldn't be emailing the new password at all (see nr.2 of golden rules of online security)

Re: Password resetting help

Posted: Thu Aug 18, 2011 11:56 am
by stijn22
Thanks for the tip. I now have a script that mails an activationcode in a link, and with that link users can reset their password.

Re: Password resetting help

Posted: Thu Aug 18, 2011 3:56 pm
by phphelpme
Nice one, why dont you share the script on here so we can see what you instead. That way we can advice you on that one also.

Best wishes