summaryrefslogtreecommitdiff
path: root/passlib/handlers/pbkdf2.py
blob: 5b0426d72301d414aecaba3806231692c1bdb345 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""passlib.handlers.pbkdf - PBKDF2 based hashes"""
#=========================================================
#imports
#=========================================================
#core
from binascii import hexlify, unhexlify
from base64 import b64encode
import re
import logging; log = logging.getLogger(__name__)
from warnings import warn
#site
#libs
from passlib.utils import adapted_b64_encode, adapted_b64_decode, ALL_BYTE_VALUES
from passlib.utils.handlers import ExtendedHandler
from passlib.utils.pbkdf2 import pbkdf2
#pkg
#local
__all__ = [
    "pbkdf2_sha1",
    "pbkdf2_sha256",
    "pbkdf2_sha512",
    "dlitz_pbkdf2_sha1",
    "grub_pbkdf2_sha512",
]

#=========================================================
#
#=========================================================
class Pbkdf2DigestHandler(ExtendedHandler):
    "base class for various pbkdf2_{digest} algorithms"
    setting_kwds = ("salt", "rounds")

    _ident = None #subclass specified identifier prefix
    _prf = None #subclass specified prf identifier

    #NOTE: max_salt_chars and max_rounds are arbitrarily chosen to provide sanity check.
    #      the underlying pbkdf2 specifies no bounds for either.

    #NOTE: defaults chosen to be at least as large as pbkdf2 rfc recommends...
    #      >8 bytes of entropy in salt, >1000 rounds
    #      increased due to time since rfc established

    default_salt_chars = 16
    min_salt_chars = 0
    max_salt_chars = 1024
    salt_charset = ALL_BYTE_VALUES

    default_rounds = 6400
    min_rounds = 1
    max_rounds = 2**32-1
    rounds_cost = "linear"

    @classmethod
    def identify(cls, hash):
        return bool(hash) and hash.startswith(cls._ident)

    @classmethod
    def from_string(cls, hash):
        if not hash:
            raise ValueError, "no hash specified"
        ident = cls._ident
        if not hash.startswith(ident):
            raise ValueError, "invalid %s hash" % (cls.name,)
        parts = hash[len(ident):].split("$")
        if len(parts) == 3:
            rounds, salt, chk = parts
        elif len(parts) == 2:
            rounds, salt = parts
            chk = None
        else:
            raise ValueError, "invalid %s hash" % (cls.name,)
        int_rounds = int(rounds)
        if rounds != str(int_rounds): #forbid zero padding, etc.
            raise ValueError, "invalid %s hash" % (cls.name,)
        raw_salt = adapted_b64_decode(salt)
        raw_chk = adapted_b64_decode(chk) if chk else None
        return cls(
            rounds=int_rounds,
            salt=raw_salt,
            checksum=raw_chk,
            strict=bool(raw_chk),
        )

    def to_string(self, withchk=True):
        salt = adapted_b64_encode(self.salt)
        if withchk and self.checksum:
            return '%s%d$%s$%s' % (self._ident, self.rounds, salt, adapted_b64_encode(self.checksum))
        else:
            return '%s%d$%s' % (self._ident, self.rounds, salt)

    def calc_checksum(self, secret):
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        return pbkdf2(secret, self.salt, self.rounds, self.checksum_chars, self._prf)

def create_pbkdf2_hash(hash_name, digest_size):
    "create new Pbkdf2DigestHandler subclass for a specific hash"
    name = 'pbkdf2_' + hash_name
    ident = "$pbkdf2-%s$" % (hash_name,)
    prf = "hmac-%s" % (hash_name,)
    base = Pbkdf2DigestHandler
    return type(name, (base,), dict(
        name=name,
        _ident=ident,
        _prf = prf,
        checksum_chars=digest_size,
        encoded_checksum_chars=(digest_size*4+2)//3,
        __doc__="""This class implements passlib's pbkdf2-%(prf)s hash, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`encrypt()` and :meth:`genconfig` methods accept the following optional keywords:

    :param salt:
        Optional salt bytes.
        If specified, the length must be between 0-1024 bytes.
        If not specified, a %(dsc)d byte salt will be autogenerated (this is recommended).

    :param rounds:
        Optional number of rounds to use.
        Defaults to %(dr)d, but must be within ``range(1,1<<32)``.
    """ % dict(prf=prf, dsc=base.default_salt_chars, dr=base.default_rounds)
    ))

#---------------------------------------------------------
#derived handlers
#---------------------------------------------------------
pbkdf2_sha1 = create_pbkdf2_hash("sha1", 20)
pbkdf2_sha256 = create_pbkdf2_hash("sha256", 32)
pbkdf2_sha512 = create_pbkdf2_hash("sha512", 64)

#=========================================================
#dlitz's pbkdf2 hash
#=========================================================
class dlitz_pbkdf2_sha1(ExtendedHandler):
    """This class implements Dwayne Litzenberger's PBKDF2-based crypt algorithm, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`encrypt()` and :meth:`genconfig` methods accept the following optional keywords:

    :param salt:
        Optional salt string.
        If specified, it may be any length, but must use the characters in the regexp range ``[./0-9A-Za-z]``.
        If not specified, a 16 character salt will be autogenerated (this is recommended).

    :param rounds:
        Optional number of rounds to use.
        Defaults to 10000, must be within ``range(1,1<<32)``.
    """

    #=========================================================
    #class attrs
    #=========================================================
    name = "dlitz_pbkdf2_sha1"
    setting_kwds = ("salt", "rounds")

    #NOTE: max_salt_chars and max_rounds are arbitrarily chosen to provide sanity check.
    #   underlying algorithm (and reference implementation) allow effectively unbounded values for both of these.

    default_salt_chars = 16
    min_salt_chars = 0
    max_salt_chars = 1024

    default_rounds = 10000
    min_rounds = 0
    max_rounds = 2**32-1
    rounds_cost = "linear"

    #=========================================================
    #formatting
    #=========================================================

    @classmethod
    def identify(cls, hash):
        return bool(hash) and hash.startswith("$p5k2$")

    #hash       $p5k2$c$u9HvcT4d$Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g
    #ident      $p5k2$
    #rounds     c
    #salt       u9HvcT4d
    #chk        Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g
    #rounds in lowercase hex, no zero padding

    _pat = re.compile(r"""
        ^
        \$p5k2
        \$(?P<rounds>[a-f0-9]*)
        \$(?P<salt>[A-Za-z0-9./]*)
        (\$(?P<chk>[A-Za-z0-9./]{32}))?
        $
        """, re.X)

    @classmethod
    def from_string(cls, hash):
        if not hash:
            raise ValueError, "no hash specified"
        m = cls._pat.match(hash)
        if not m:
            raise ValueError, "invalid dlitz_pbkdf2_crypt hash"
        rounds, salt, chk = m.group("rounds", "salt", "chk")
        if rounds.startswith("0"): #zero not allowed, nor left-padded with zeroes
            raise ValueError, "invalid dlitz_pbkdf2_crypt hash"
        rounds = int(rounds, 16) if rounds else 400
        return cls(
            rounds=rounds,
            salt=salt,
            checksum=chk,
            strict=bool(chk),
        )

    def to_string(self, withchk=True):
        if self.rounds == 400:
            out = '$p5k2$$%s' % (self.salt,)
        else:
            out = '$p5k2$%x$%s' % (self.rounds, self.salt)
        if withchk and self.checksum:
            out = "%s$%s" % (out,self.checksum)
        return out

    #=========================================================
    #backend
    #=========================================================
    def calc_checksum(self, secret):
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        salt = self.to_string(withchk=False)
        result = pbkdf2(secret, salt, self.rounds, 24, "hmac-sha1")
        return adapted_b64_encode(result)

    #=========================================================
    #eoc
    #=========================================================

#=========================================================
#grub
#=========================================================
class grub_pbkdf2_sha512(ExtendedHandler):
    """This class implements Grub's pbkdf2-hmac-sha512 hash, and follows the :ref:`password-hash-api`.

    It supports a variable-length salt, and a variable number of rounds.

    The :meth:`encrypt()` and :meth:`genconfig` methods accept the following optional keywords:

    :param salt:
        Optional salt bytes.
        If specified, the length must be between 0-1024 bytes.
        If not specified, a 64 byte salt will be autogenerated (this is recommended).

    :param rounds:
        Optional number of rounds to use.
        Defaults to 10000, but must be within ``range(1,1<<32)``.
    """
    name = "grub_pbkdf2_sha512"
    setting_kwds = ("salt", "rounds")

    _ident = "grub.pbkdf2.sha512."

    #NOTE: max_salt_chars and max_rounds are arbitrarily chosen to provide sanity check.
    #      the underlying pbkdf2 specifies no bounds for either,
    #      and it's not clear what grub specifies.

    default_salt_chars = 64
    min_salt_chars = 0
    max_salt_chars = 1024
    salt_charset = ALL_BYTE_VALUES

    default_rounds = 10000
    min_rounds = 1
    max_rounds = 2**32-1
    rounds_cost = "linear"

    @classmethod
    def identify(cls, hash):
        return bool(hash) and hash.startswith(cls._ident)

    @classmethod
    def from_string(cls, hash):
        if not hash:
            raise ValueError, "no hash specified"
        ident = cls._ident
        if not hash.startswith(ident):
            raise ValueError, "invalid %s hash" % (cls.name,)
        parts = hash[len(ident):].split(".")
        if len(parts) == 3:
            rounds, salt, chk = parts
        elif len(parts) == 2:
            rounds, salt = parts
            chk = None
        else:
            raise ValueError, "invalid %s hash" % (cls.name,)
        int_rounds = int(rounds)
        if rounds != str(int_rounds): #forbid zero padding, etc.
            raise ValueError, "invalid %s hash" % (cls.name,)
        raw_salt = unhexlify(salt)
        raw_chk = unhexlify(chk) if chk else None
        return cls(
            rounds=int_rounds,
            salt=raw_salt,
            checksum=raw_chk,
            strict=bool(raw_chk),
        )

    def to_string(self, withchk=True):
        salt = hexlify(self.salt).upper()
        if withchk and self.checksum:
            return '%s%d.%s.%s' % (self._ident, self.rounds, salt, hexlify(self.checksum).upper())
        else:
            return '%s%d.%s' % (self._ident, self.rounds, salt)

    def calc_checksum(self, secret):
        #TODO: find out what grub's policy is re: unicode
        if isinstance(secret, unicode):
            secret = secret.encode("utf-8")
        return pbkdf2(secret, self.salt, self.rounds, 64, "hmac-sha512")

#=========================================================
#eof
#=========================================================