from __future__ import (absolute_import, division, print_function) __metaclass__ = type import hashlib import passlib from binascii import hexlify from passlib.utils.binary import Base64Engine, HASH64_CHARS, BCRYPT_CHARS from ansible.module_utils._text import to_bytes, to_text from ansible import errors def _hash64_salt(seed, length): h = hashlib.new('sha256') e = Base64Engine(HASH64_CHARS) h.update(to_bytes(seed, errors='surrogate_or_strict')) return to_text(e.encode_bytes(h.digest()[0:length])) def apr_md5_crypt_salt(seed): ''' generate salt for apr_md5_crypt algorithm based on seed-value ''' try: return _hash64_salt(seed, 6) except Exception as e: raise errors.AnsibleFilterError("apr_md5_crypt_salt(): %s" % str(e)) def sha2_crypt_salt(seed): ''' generate salt for sha256/sha512_crypt algorithms based on seed-value ''' try: return _hash64_salt(seed, 12) except Exception as e: raise errors.AnsibleFilterError("sha2_crypt_salt(): %s" % str(e)) def bcrypt_salt(seed): ''' generate salt for bcrypt algorithm based on seed-value ''' try: h = hashlib.new('sha256') e = Base64Engine(BCRYPT_CHARS) h.update(to_bytes(seed, errors='surrogate_or_strict')) return to_text(e.encode_bytes(h.digest()[0:16])) except Exception as e: raise errors.AnsibleFilterError("bcrypt_salt(): %s" % str(e)) def wifi_80211r_key(seed): ''' generate keys 802.11r r0kh and r1kh keys based on seed-value ''' try: h = hashlib.new('sha256') h.update(to_bytes(seed, errors='surrogate_or_strict')) return to_text(hexlify(h.digest())) except Exception as e: raise errors.AnsibleFilterError("wifi_80211r_key(): %s" % str(e)) def mosquitto_passwd_hash(password, seed): ''' generate password hash for use by mosquitto mqtt server ''' try: h = hashlib.new('sha512') h.update(to_bytes(seed, errors='surrogate_or_strict')) salt = h.digest()[0:12] digest = passlib.hash.pbkdf2_sha512.using(salt=salt).hash(password).replace('pbkdf2-sha512', '7').replace('.', '+') return digest + '==' except Exception as e: raise errors.AnsibleFilterError("mosquitto_passwd_hash(): %s" % str(e)) class FilterModule(object): ''' crypto helpers ''' filter_map = { 'apr_md5_crypt_salt': apr_md5_crypt_salt, 'sha256_salt': sha2_crypt_salt, 'sha512_salt': sha2_crypt_salt, 'bcrypt_salt': bcrypt_salt, 'wifi_80211r_key': wifi_80211r_key, 'mosquitto_passwd_hash': mosquitto_passwd_hash, } def filters(self): return self.filter_map