1 # -*- coding: utf-8 -*-
2 """Password hashing functions and constants for the mudpy engine."""
4 # Copyright (c) 2004-2013 Jeremy Stanley <fungi@yuggoth.org>. Permission
5 # to use, copy, modify, and distribute this software is granted under
6 # terms provided in the LICENSE file distributed with this software.
8 # convenience constants for indexing the supported hashing algorithms,
9 # guaranteed a stable part of the interface
11 SHA1 = 1 # hashlib.sha1
12 SHA224 = 2 # hashlib.sha224
13 SHA256 = 3 # hashlib.sha256
14 SHA384 = 4 # hashlib.sha385
15 SHA512 = 5 # hashlib.sha512
18 def _pack_bytes(numbers):
20 This is a wrapper around struct.pack, used to turn a list of integers
21 between 0 and 255 into a packed sequence akin to a C-style string.
25 for number in numbers:
27 assert 0 <= number <= 255
28 packed += struct.pack("B", number)
32 def _bytes_to_text(byte_sequence):
34 This is a wrapper around base64.b64encode with preferences
35 appropriate for encoding Unix-style passwd hash strings.
38 return base64.b64encode(
41 ).decode("ascii").rstrip("=")
44 def _generate_salt(salt_len=2):
46 This simply generates a sequence of pseudo-random characters (with
47 6-bits of effective entropy per character). Since it relies on base64
48 encoding (which operates on 6-bit chunks of data), we only generate
49 0.75 times as many bytes (rounded up) as the number of characters we
50 need and discard any excess characters over the specified length.
51 This ensures full distribution over each character of the salt.
56 for i in range(int(math.ceil(salt_len * 0.75))):
57 salt.append(random.randint(0, 255))
58 return _bytes_to_text(_pack_bytes(salt))[:salt_len]
61 def upgrade_legacy_hash(legacy_hash, salt, sep="$"):
63 This utility function is meant to provide a migration path for users
64 of mudpy's legacy account-name-salted MD5 hexdigest password hashes.
65 By passing the old passhash (as legacy_hash) and name (as salt)
66 facets to this function, a conforming new-style password hash will be
70 assert re.match("^[0-9a-f]{32}$",
71 legacy_hash), "Not a valid MD5 hexdigest"
74 # this needs to become a byte() call in 2to3
75 collapsed += bytes(legacy_hash[2 * i:2 * i + 2].decode("ascii"))
76 return "%s%s%s%s%s%s%s%s" % (
80 0, # 2**0 provides one round of hashing
84 _bytes_to_text(collapsed)
97 The meat of the module, this function takes a provided password and
98 generates a Unix-like passwd hash suitable for storage in portable,
99 text-based data files. The password is prepended with a salt (which
100 can also be specified explicitly, if the output needs to be
101 repeatable) and then hashed with the requested algorithm iterated as
102 many times as 2 raised to the power of the rounds parameter.
104 The first character of the text returned by this function denotes the
105 separator character used to identify subsequent fields. The fields in
108 1. the decimal index number indicating which algorithm was used,
109 also mapped as convenience constants at the beginning of this
112 2. the number of times (as an exponent of 2) which the algorithm
113 was iterated, represented by a decimal value between 0 and 16
114 inclusive (0 results in one round, 16 results in 65536 rounds,
115 and anything higher than that is a potential resource
116 consumption denial of service on the application anyway)
118 3. the plain-text salt with which the password was prepended
121 4. the resulting password hash itself, base64-encoded using . and
122 / as the two non-alpha-numeric characters required to reach 64
124 The defaults provided should be safe for everyday use, but something
125 more heavy-duty may be in order for admin users, such as::
127 create(password, algorithm=SHA256, rounds=12, salt_len=16)
131 # if a specific salt wasn't specified, we need to generate one
133 salt = _generate_salt(salt_len=salt_len)
135 # make sure the algorithm index number is coerced into integer form,
136 # since it could also be passed as text (in decimal) for convenience
137 algorithm = int(algorithm)
139 # the list of algorithms supported by this function corresponds to
140 # the convenience constants defined at the beginning of the module
144 SHA224: hashlib.sha224,
145 SHA256: hashlib.sha256,
146 SHA384: hashlib.sha384,
147 SHA512: hashlib.sha512,
150 # make sure the rounds exponent is coerced into integer form, since
151 # it could also be passed as text (in decimal) for convenience
154 # to avoid a potential resource consumption denial of service attack,
155 # only consider values in the range of 0-16
156 assert 0 <= rounds <= 16
158 # here is where the salt is prepended to the provided password text
159 hashed = salt + password
161 # iterate the hashing algorithm over its own digest the specified
163 for i in range(2 ** rounds):
164 hashed = algorithms[algorithm](hashed.encode("utf-8")).digest()
165 # TODO: remove this check after the switch to py3k
167 hashed = "".join(format(x, "02x") for x in bytes(hashed))
169 hashed = "".join(format(ord(x), "02x") for x in bytes(hashed))
171 # concatenate the output fields, coercing into text form as needed
172 return "%s%s%s%s%s%s%s%s" % (
173 sep, algorithm, sep, rounds, sep, salt, sep,
174 _bytes_to_text(hashed.encode("ascii"))
178 def verify(password, encoded_hash):
180 This simple function requires a text password and a mudpy-format
181 password hash (as generated by the create function). It returns True
182 if the password, hashed with the parameters from the encoded_hash,
183 comes out the same as the encoded_hash.
185 sep = encoded_hash[0]
187 algorithm, rounds, salt, hashed = encoded_hash.split(sep)[1:]
188 if encoded_hash == create(