Debian Codegraph @

flufl/password/schemes.py

raw
1 # Copyright (C) 2011-2014 by Barry A. Warsaw
2 #
3 # This file is part of flufl.password
4 #
5 # flufl.password is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation, version 3 of the License.
8 #
9 # flufl.password is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
12 # License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with flufl.password. If not, see <http://www.gnu.org/licenses/>.
16
17 """Password hashing and verification schemes.
18
19 Represents passwords using RFC 2307 syntax (as best we can tell).
20 """
21
22 from __future__ import absolute_import, print_function, unicode_literals
23
24 __metaclass__ = type
25 __all__ = [
26 'ClearTextPasswordScheme',
27 'NoPasswordScheme',
28 'PBKDF2PasswordScheme',
29 'PasswordScheme',
30 'SHAPasswordScheme',
31 'SSHAPasswordScheme',
32 ]
33
34
35 import os
36 import hmac
37 import hashlib
38
39 from array import array
40 from base64 import urlsafe_b64decode as decode
41 from base64 import urlsafe_b64encode as encode
42 from functools import partial
43
44 from flufl.password._registry import register
45 from flufl.password._utils import BadPasswordFormatError
46
47
48 SALT_LENGTH = 20 # bytes
49 ITERATIONS = 2000
50
51
52
53 class PasswordScheme:
54 """Password scheme base class."""
55 TAG = ''
56
57 @staticmethod
58 def make_secret(password):
59 """Return the hashed password.
60
61 :param password: The clear text password.
62 :type password: bytes or utf-8 encoded string.
63 :return: The encrypted password.
64 :rtype: bytes
65 """
66 raise NotImplementedError
67
68 @classmethod
69 def check_response(cls, hashed, cleartext, scheme=None):
70 """Check a hashed password against a clear text response.
71
72 :param hashed: The user's stored hashed password, without the scheme
73 prefix (i.e. strip off the *{SCHEME}* part first).
74 :type hashed: bytes
75 :param cleartext: The clear text password entered by the user for
76 authentication.
77 :type cleartext: bytes or utf-8 encoded string.
78 :param scheme: The scheme tag i.e. the *{SCHEME}* part without the
79 braces. This can be omitted when called on the class directly,
80 unless the scheme puts some additional information in there. It
81 is always provided by the `verify()` API.
82 :type response: bytes or utf-8 encoded string.
83 :return: True if the clear text matches the hash
84 :rtype: bool
85 """
86 return hashed == cls.make_secret(cleartext)
87
88
89
90 @register
91 class NoPasswordScheme(PasswordScheme):
92 """A password scheme without passwords."""
93
94 TAG = 'NONE'
95
96 @staticmethod
97 def make_secret(password):
98 """See `PasswordScheme`."""
99 return b''
100
101 @classmethod
102 def check_response(cls, hashed, cleartext, scheme=None):
103 """See `PasswordScheme`."""
104 return False
105
106
107
108 @register
109 class ClearTextPasswordScheme(PasswordScheme):
110 """A password scheme that stores clear text passwords."""
111
112 TAG = 'CLEARTEXT'
113
114 @staticmethod
115 def make_secret(password):
116 """See `PasswordScheme`."""
117 return password
118
119
120
121 @register
122 class SHAPasswordScheme(PasswordScheme):
123 """A password scheme that encodes the password using SHA1."""
124
125 TAG = 'SHA'
126
127 @staticmethod
128 def make_secret(password):
129 """See `PasswordScheme`."""
130 h = hashlib.sha1(password)
131 return encode(h.digest())
132
133
134
135 @register
136 class SSHAPasswordScheme(PasswordScheme):
137 """A password scheme that encodes the password using salted SHA1."""
138
139 TAG = 'SSHA'
140
141 @staticmethod
142 def _make_salted_hash(password, salt):
143 h = hashlib.sha1(password)
144 h.update(salt)
145 return encode(h.digest() + salt)
146
147 @staticmethod
148 def make_secret(password):
149 """See `PasswordScheme`."""
150 salt = os.urandom(SALT_LENGTH)
151 return SSHAPasswordScheme._make_salted_hash(password, salt)
152
153 @classmethod
154 def check_response(cls, hashed, cleartext, scheme=None):
155 """See `PasswordScheme`."""
156 # The salt is always 20 bytes and always tacked onto the end.
157 decoded = decode(hashed)
158 salt = decoded[20:]
159 return hashed == cls._make_salted_hash(cleartext, salt)
160
161
162
163 def _bytes_of(array_obj):
164 # Avoid DeprecationWarnings in Python 3.
165 try:
166 return array_obj.tobytes()
167 except AttributeError:
168 return array_obj.tostring()
169
170
171 # Basic algorithm given by Bob Fleck
172 @register
173 class PBKDF2PasswordScheme(PasswordScheme):
174 """RFC 2989 password encoding scheme."""
175
176 # This is a bit nasty if we wanted a different prf or iterations. OTOH,
177 # we really have no clue what the standard LDAP-ish specification for
178 # those options is.
179 TAG = 'PBKDF2 SHA {0}'.format(ITERATIONS)
180
181 @staticmethod
182 def _pbkdf2(password, salt, iterations):
183 """From RFC2898 sec. 5.2. Simplified to handle only 20 byte output
184 case. Output of 20 bytes means always exactly one block to handle,
185 and a constant block counter appended to the salt in the initial hmac
186 update.
187 """
188 # We do it this way because the array() constructor takes a 'native
189 # string'. You can't use unicodes in Python 2 or bytes in Python 3.
190 array_of_signedints = partial(array, str('i'))
191 h = hmac.new(password, None, hashlib.sha1)
192 prf = h.copy()
193 prf.update(salt + b'\x00\x00\x00\x01')
194 T = U = array_of_signedints(prf.digest())
195 while iterations:
196 prf = h.copy()
197 prf.update(_bytes_of(U))
198 U = array_of_signedints(prf.digest())
199 T = array_of_signedints((t ^ u for t, u in zip(T, U)))
200 iterations -= 1
201 return _bytes_of(T)
202
203 @staticmethod
204 def make_secret(password):
205 """See `PasswordScheme`.
206
207 From RFC2898 sec. 5.2. Simplified to handle only 20 byte output
208 case. Output of 20 bytes means always exactly one block to handle,
209 and a constant block counter appended to the salt in the initial hmac
210 update.
211 """
212 salt = os.urandom(SALT_LENGTH)
213 digest = PBKDF2PasswordScheme._pbkdf2(password, salt, ITERATIONS)
214 return encode(digest + salt)
215
216 @classmethod
217 def check_response(cls, hashed, cleartext, scheme):
218 """See `PasswordScheme`."""
219 parts = scheme.split()
220 if (len(parts) != 3 or
221 parts[0].upper() != 'PBKDF2' or
222 parts[1].upper() != 'SHA'
223 ):
224 raise BadPasswordFormatError(scheme)
225 try:
226 iterations = int(parts[2])
227 except ValueError:
228 raise BadPasswordFormatError(scheme)
229 decoded = decode(hashed)
230 salt = decoded[20:]
231 secret = decoded[:20]
232 return secret == cls._pbkdf2(cleartext, salt, iterations)