Justin Gardner
Justin Gardner

Reputation: 625

Python with etc/Shadow

so I'm writing this program that needs to check the password hash in etc/shadow and compare it to the password the user entered. I tried encrypting the password with hashlib.sha512, but the result was not the same. I think it's salted some how, but I don't know if it uses a universal salt or how I can get the salt each time.

tldr; I need a way for a user to enter a password, then have the program hash it and check it against the etc/shadow. Any ideas?

Upvotes: 0

Views: 4600

Answers (3)

MarrekNožka
MarrekNožka

Reputation: 443

>>> import crypt
>>> line = 'bob:$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.:15965:0:99999:7:::'
>>> encript = line.split(':')[1]
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'

>>> i = encript.rfind('$')
>>> salt = encript[:i]
>>> salt
--> '$1$qda8YAO9'

>>> crypt.crypt('bob_password',salt)
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'
>>> encript
--> '$1$qda8YAO9$rBiov9uVJlH1/97cbcyEt.'

Upvotes: 3

eri
eri

Reputation: 3514

Try this https://pypi.python.org/pypi/pam . First link in google by python pam. Look at distribution package manager for python-pam if exists. Else install with pip or easy_install.

Small example:

>>> import pam
>>> pam.authenticate('fred', 'fredspassword')
False

Upvotes: 5

abarnert
abarnert

Reputation: 365845

The passwd field is not just a SHA-512 hash of the password.*

This is explained in the crypt manpage. The format is $id$salt$hash, where id specifies the hash method (1 for MD5, 2a for Blowfish, 5 for SHA-256, 6 for SHA-512), salt specifies the salt to use with that algorithm, and hash specifies what the result should be.

As the manpage implies, you can actually pass the whole $id$salt$ to the crypt function in place of the salt, and it will automatically use the appropriate algorithm. This wouldn't be too hard to do via, say, ctypes.


At any rate, what you're doing is almost certainly a bad idea. You'll need to run as root in order to have access to /etc/shadow, and you'll need to simulate more than just password verification if you actually want to verify that the user can log in, and of course you'll need to handle secure input and make sure you don't end up saving the password in plaintext somewhere and so on. It's a lot simpler and safer to just let PAM do the work for you.


* I believe that in theory, it can be—if it doesn't start with a $ it's interpreted as some legacy format… presumably meaning it's interpreted as POSIX crypt using the DES algorithm.

Upvotes: 2

Related Questions