summaryrefslogtreecommitdiff
path: root/filter_plugins/crypto.py
blob: 54547a340afb64d1637b1dfe93dc9fbd2589750f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import hashlib
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))


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,
    }

    def filters(self):
        return self.filter_map