Billy Moon
Billy Moon

Reputation: 58521

How can I calculate shadow password for sha-512 using php/shell

I created account sysadmin with password delme. I then want to calculate the sha-512 of the password using php.

I expected this should produce the same hash...

billy@iserve:~$ sudo cat /etc/shadow | grep sysadmin
sysadmin:$6$q5HxMEDr$VUPS0JrRFv5bohFtsscvjQ7t2fUhi0m2z8f0ObKtorwlSHqiGde8N9hprkqmnB9LOtEDorG.3yBSXYSAKcJmz.:15276:0:99999:7:::
billy@iserve:~$ php -r "echo crypt('delme','$6$rounds=5000$q5HxMEDr$').\"\n"\";"
=54Jjswxnfslg

I can not replicate the password in the shadow file... can you tell me how?

Upvotes: 1

Views: 2029

Answers (4)

sq7lqw
sq7lqw

Reputation: 1

Little update to Billy's answer:

function authenticate($user, $pass){
  $shad =  preg_split("/[$:]/",`cat /etc/shadow | grep "^$user\:"`);
  if (!isset($shad[2]) || !isset($shad[3])) return false;
  $mkps = preg_split("/[$:]/",crypt($pass, '$'.$shad[2].'$'.$shad[3].'$'));
  return ($shad[4] == $mkps[3]);
}

Upvotes: -1

Mark Engelmann
Mark Engelmann

Reputation: 1

There is simply an error in your PHP code. You must escape the $ symbol!

$ echo "<?php \$foo=crypt('delme', '\$6\$q5HxMEDr\$'); echo \$foo; ?>" | php5-cgi; echo ""
X-Powered-By: PHP/5.4.4-14+deb7u7
Content-type: text/html

$6$q5HxMEDr$VUPS0JrRFv5bohFtsscvJQ7tZfUhi0m2z8f0ObKtorwlSHqiGde8N9hprkqmnB9LOtEDorG.3yBSXYSAKcJmz.

Upvotes: 0

Billy Moon
Billy Moon

Reputation: 58521

I ended up doing this to solve my problem...

/*    Need to add www-data to group shadow (and restart apache)
        $ sudo adduser www-data shadow
        $ sudo /etc/init.d/apache2 restart
      Needs whois to be installed to run mkpasswd
        $ sudo apt-get install whois
      Assumes that sha-512 is used in shadow file
*/

function authenticate($user, $pass){
  // run shell command to output shadow file, and extract line for $user
  // then split the shadow line by $ or : to get component parts
  // store in $shad as array
  $shad =  preg_split("/[$:]/",`cat /etc/shadow | grep "^$user\:"`);
  // use mkpasswd command to generate shadow line passing $pass and $shad[3] (salt)
  // split the result into component parts and store in array $mkps
  $mkps = preg_split("/[$:]/",trim(`mkpasswd -m sha-512 $pass $shad[3]`));
  // compare the shadow file hashed password with generated hashed password and return
  return ($shad[4] == $mkps[3]);
}

// usage...
if(authenticate('myUsername','myPassword')){
  // logged in   
} else {
  // not valid user
}

I am not entirely confident about the security of this method, so will be asking a question about that.

Upvotes: 1

Chris Eberle
Chris Eberle

Reputation: 48765

That's because the real system is using a randomly generated salt (between the second $ and the third $). Are you using this same salt in your php code?

Upvotes: 1

Related Questions