Added a fake_login_attempt utility.
[mediagoblin.git] / mediagoblin / auth / lib.py
CommitLineData
6755f50e
CAW
1# GNU Mediagoblin -- federated, autonomous media hosting
2# Copyright (C) 2011 Free Software Foundation, Inc
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import os
18
c15c9843 19import random
6755f50e
CAW
20
21
22def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None):
23 """
24 Check to see if this password matches.
25
26 Args:
27 - raw_pass: user submitted password to check for authenticity.
28 - stored_hash: The hash of the raw password (and possibly extra
29 salt) to check against
30 - extra_salt: (optional) If this password is with stored with a
31 non-database extra salt (probably in the config file) for extra
32 security, factor this into the check.
33
34 Returns:
35 True or False depending on success.
36 """
37 if extra_salt:
38 raw_pass = u"%s:%s" % (extra_salt, raw_pass)
39
40 hashed_pass = bcrypt.hashpw(raw_pass, stored_hash)
41
42 # Reduce risk of timing attacks by hashing again with a random
43 # number (thx to zooko on this advice, which I hopefully
44 # incorporated right.)
45 #
46 # See also:
47 rand_salt = bcrypt.gensalt(5)
48 randplus_stored_hash = bcrypt.hashpw(stored_hash, rand_salt)
49 randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt)
50
51 return randplus_stored_hash == randplus_hashed_pass
52
53
54def bcrypt_gen_password_hash(raw_pass, extra_salt=None):
55 """
56 Generate a salt for this new password.
57
58 Args:
59 - raw_pass: user submitted password
60 - extra_salt: (optional) If this password is with stored with a
61 non-database extra salt
62 """
63 if extra_salt:
64 raw_pass = u"%s:%s" % (extra_salt, raw_pass)
65
e0bc23d3 66 return unicode(bcrypt.hashpw(raw_pass, bcrypt.gensalt()))
c15c9843
CAW
67
68
69def fake_login_attempt():
70 """
71 Pretend we're trying to login.
72
73 Nothing actually happens here, we're just trying to take up some
74 time.
75 """
76 rand_salt = bcrypt.gensalt(5)
77
78 hashed_pass = bcrypt.hashpw(str(random.random()), rand_salt)
79
80 randplus_stored_hash = bcrypt.hashpw(str(random.random()), rand_salt)
81 randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt)
82
83 randplus_stored_hash == randplus_hashed_pass