UNIX SHA-512 Passwords & Python

Well today I spent a bit of time looking up how /etc/shadow created their shadow passwords.

I found a good source for the method at http://www.akkadia.org/drepper/SHA-crypt.txt , and if you take some time to review it you will notice the steps are a bit involved

Lucky for us Python has a Crypt module that works nicely.

First off I started by creating a dummy user with the password of test on one of my Linux computers:

# cat /etc/shadow | grep dummy
dummy:$6$JJ1sbaL/$2P4ZcZ10VjIa9f5.8N/GJukYCg.RJVBTP2h30v2mnh0Q5izqc2rtKZ6qtI0Ewiyji
      0hX9zIVfftOVuJTIsBSKQ/:15310:0:99999:7:::

And like that we have a password we can attempt to validate.

Next I will need to define our salt in Python. A good article explaining the format of /etc/shadow can be found on cyberciti.biz. Like the article says the salt is found between the $ after the username and before the password hash. For comparison I will also extract the hash:

>>> salt = 'JJ1sbaL/'
>>> hash = '2P4ZcZ10VjIa9f5.8N/GJukYCg.RJVBTP2h30v2mnh0Q5izqc2rtKZ6qtI0Ewiyj0hX9zIVfftOVuJTIsBSKQ/'

Now that we have our salt we can create a hash of our password using that salt and verify it matches the hash shown in /etc/shadow :

>>> import crypt
>>> output = crypt.crypt('test', '$6$%s$' % salt)
>>> print output
$6$JJ1sbaL/$2P4ZcZ10VjIa9f5.8N/GJukYCg.RJVBTP2h30v2mnh0Q5izqc2rtKZ6qtI0Ewiyj0hX9zIVfftOVuJTIsBSKQ/

And lastly lets compare the new hash with the one found in /etc/shadow :

>>> newhash = output.split('$')[-1]
>>> print newhash
'2P4ZcZ10VjIa9f5.8N/GJukYCg.RJVBTP2h30v2mnh0Q5izqc2rtKZ6qtI0Ewiyj0hX9zIVfftOVuJTIsBSKQ/'
>>>
>>> newhash == hash
True