Authentication with Dovecot, SHA512, and salts

dovecotpostfix

I have a database that has a username, password, and password salt in it. The password is hashed using SHA512.

The data in my users database looks like this:

user = testuser

password_hash = 4acf9dc364843d1adfadfadf42de7d5707b791cc3ee8a2013f15efa8bdb

password_salt = QYhZ47zsQA=

I'm trying to authenticate to this database using dovecot sql authentication and SSHA512. I've turned authentication debugs on and I see this in mail.log:

dovecot: auth-worker(8603): Debug: sql(testuser,22.22.22.22): query: SELECT username as user, password_hash as password, password_salt as salt FROM users WHERE username='testuser';
dovecot: auth-worker(8603): sql(testuser,22.22.22.22): Password mismatch
dovecot: auth-worker(8603): Debug: sql(testuser,22.22.22.22): SSHA512(testpassword) != '4acf9dc364843d1adfadfadf42de7d5707b791cc3ee8a2013f15efa8bdb'
dovecot: auth: Debug: client passdb out: FAIL#0111#011user=testuser#011salt=QYhZ47zsQA=
dovecot: auth: Debug: client in:   AUTH#0112#011PLAIN#011service=imap#011secured#011session=rZmPoRYOagBJ3Ukh#011lip=33.33.33.33#01    1rip=22.22.22.22#011lport=993#011rport=53098#011resp=AHJpY2hlZQBjY2NwdGFtdDNtcA== (previous base64 data may contain sensitive data)
dovecot: imap-login: Disconnected (auth failed, 2 attempts in 8 secs): user=<testuser>, method=PLAIN, rip=22.22.22.22, lip=33.33.33.33, TLS, session=<rZmPoRYOagBJ3Ukh>

I've also tried to do an auth test which fails too:

$ sudo doveadm auth test testuser testpassword
passdb: richee auth failed
extra fields:
  user=testuser
  salt=QYhZ47zsQA=

Unfortunately the dovecot documentation doesn't cover exactly how to authenticate against salted hashes. I feel like I need to tell dovecot that my password hash is hex Salted SHA512 and my salt is 8 bytes base64. However I have no idea how to tell dovecot to use the salt. How can I use salts when authenticating dovecot?

Best Answer

For SQL-lookup password, dovecot has additional documentation in here. For additional info you can read a thread on SO: How to securely generate SSHA256 or SSHA512 hashes in PHP?. In this answer I assume that you use MySQL for database.

In order to matching dovecot auth scheme and your custom auth scheme, one of the method is your query must be returned password field that contain

{SSHA512.HEX}HashofPasswordandSaltinHEXformatSaltinHEXformattoo

With string manipulation from SQL, we can construct a query like this

SELECT CONCAT("{SSHA512.HEX}", `hex_password`, HEX(FROM_BASE64(`salt`))) AS password FROM mytable WHERE userid = '%u'

Put above query to password_query parameter in dovecot-sql configuration file.

In the query above, we construct the special string via SQL concat. Of course because you have different format for salt and hash, then we must convert it by base-64 decoding then hex-encoding.


Looks like the discussion here has been reblogged on this page with more complete and comprehensive information.

Related Topic