Skip to content

Commit 36ffb05

Browse files
author
Josh Hoyt
committed
[project @ Server-generated and one-way nonces]
1 parent b45a322 commit 36ffb05

8 files changed

Lines changed: 230 additions & 171 deletions

File tree

‎openid/consumer/consumer.py‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@
197197
from openid import oidutil
198198
from openid.association import Association
199199
from openid.dh import DiffieHellman
200+
from openid.store.nonce import mkNonce, split as splitNonce
200201

201202
__all__ = ['AuthRequest', 'Consumer', 'SuccessResponse',
202203
'SetupNeededResponse', 'CancelResponse', 'FailureResponse',
@@ -412,6 +413,7 @@ class GenericConsumer(object):
412413
running.
413414
"""
414415

416+
TOKEN_LIFETIME = 60 * 5 # five minutes
415417
NONCE_LEN = 8
416418
NONCE_CHRS = string.ascii_letters + string.digits
417419

@@ -420,9 +422,14 @@ def __init__(self, store):
420422

421423
def begin(self, service_endpoint):
422424
nonce = self._createNonce()
425+
token = self._genToken(
426+
service_endpoint.identity_url,
427+
service_endpoint.getServerID(),
428+
service_endpoint.server_url,
429+
)
423430
assoc = self._getAssociation(service_endpoint.server_url)
424431
request = AuthRequest(service_endpoint, assoc)
425-
request.return_to_args['nonce'] = nonce
432+
request.return_to_args['nonce'] = mkNonce()
426433
return request
427434

428435
def complete(self, query, endpoint):
@@ -447,7 +454,7 @@ def complete(self, query, endpoint):
447454
return FailureResponse(endpoint, message)
448455
else:
449456
if response.status == 'success':
450-
return self._checkNonce(response, query.get('nonce'))
457+
return self._checkNonce(server_url, response)
451458
else:
452459
return response
453460
else:
@@ -460,28 +467,29 @@ def _checkNonce(self, response, nonce):
460467
for k, v in cgi.parse_qsl(query):
461468
if k == 'nonce':
462469
if v != nonce:
463-
return FailureResponse(response, 'Nonce mismatch')
470+
return FailureResponse(response.identity_url,
471+
'Nonce mismatch')
464472
else:
465473
break
466474
else:
467-
return FailureResponse(response, 'Nonce missing from return_to: %r'
475+
return FailureResponse(response.identity_url,
476+
'Nonce missing from return_to: %r'
468477
% (response.getReturnTo()))
469478

470479
# The nonce matches the signed nonce in the openid.return_to
471480
# response parameter
472-
if not self.store.useNonce(nonce):
481+
try:
482+
timestamp, salt = splitNonce(nonce)
483+
except ValueError:
484+
return FailureResponse(response.identity_url, 'Malformed nonce')
485+
if not self.store.useNonce(server_url, timestamp, salt):
473486
return FailureResponse(response,
474487
'Nonce missing from store')
475488

476489
# If the nonce check succeeded, return the original success
477490
# response
478491
return response
479492

480-
def _createNonce(self):
481-
nonce = cryptutil.randomString(self.NONCE_LEN, self.NONCE_CHRS)
482-
self.store.storeNonce(nonce)
483-
return nonce
484-
485493
def _makeKVPost(self, args, server_url):
486494
mode = args['openid.mode']
487495
body = urllib.urlencode(args)
@@ -835,7 +843,17 @@ def getReturnTo(self):
835843
"""
836844
return self.signed_args.get('openid.return_to', None)
837845

846+
def getNonce(self):
847+
"""Get the openid.nonce argument from this response.
848+
849+
This is useful for preventing replay attacks.
838850
851+
@returns: The nonce generated by the server, or C{None} if the
852+
response did not contain an C{openid.nonce} argument.
853+
854+
@returntype: str
855+
"""
856+
return self.signed_args.get('openid.nonce', None)
839857

840858
class FailureResponse(Response):
841859
"""A response with a status of FAILURE. Indicates that the OpenID

‎openid/store/dumbstore.py‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,7 @@ def removeAssociation(self, server_url, handle):
7070
"""
7171
return False
7272

73-
def storeNonce(self, nonce):
74-
"""
75-
This implementation does nothing.
76-
"""
77-
pass
78-
79-
def useNonce(self, nonce):
73+
def useNonce(self, server_url, timestamp, salt):
8074
"""
8175
In a system truly limited to dumb mode, nonces must all be
8276
accepted. This therefore always returns C{True}, which makes

‎openid/store/filestore.py‎

Lines changed: 18 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -407,49 +407,30 @@ def removeAssociation(self, server_url, handle):
407407
filename = self.getAssociationFilename(server_url, handle)
408408
return _removeIfPresent(filename)
409409

410-
def storeNonce(self, nonce):
411-
"""Mark this nonce as present.
410+
def useNonce(self, server_url, timestamp, salt):
411+
"""Return whether this nonce is valid.
412412
413-
str -> NoneType
413+
str -> bool
414414
"""
415-
filename = os.path.join(self.nonce_dir, nonce)
416-
nonce_file = file(filename, 'w')
417-
nonce_file.close()
415+
proto, rest = server_url.split('://', 1)
416+
domain = _filenameEscape(rest.split('/', 1)[0])
417+
url_hash = _safe64(server_url)
418+
salt_hash = _safe64(salt)
418419

419-
def useNonce(self, nonce):
420-
"""Return whether this nonce is present. As a side effect,
421-
mark it as no longer present.
420+
filename = '%08x-%s-%s-%s-%s' % (timestamp, proto, domain,
421+
url_hash, salt_hash)
422422

423-
str -> bool
424-
"""
425-
filename = os.path.join(self.nonce_dir, nonce)
423+
filename = os.path.join(self.nonce_dir, filename)
426424
try:
427-
st = os.stat(filename)
425+
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0200)
428426
except OSError, why:
429-
if why[0] == ENOENT:
430-
# File was not present, so nonce is no good
431-
return 0
427+
if why[0] == EEXIST:
428+
return False
432429
else:
433430
raise
434431
else:
435-
# Either it is too old or we are using it. Either way, we
436-
# must remove the file.
437-
try:
438-
os.unlink(filename)
439-
except OSError, why:
440-
if why[0] == ENOENT:
441-
# someone beat us to it, so we cannot use this
442-
# nonce anymore.
443-
return 0
444-
else:
445-
raise
446-
447-
now = time.time()
448-
nonce_age = now - st.st_mtime
449-
450-
# We can us it if the age of the file is less than the
451-
# expiration time.
452-
return nonce_age <= self.max_nonce_age
432+
os.close(fd)
433+
return True
453434

454435
def clean(self):
455436
"""Remove expired entries from the database. This is
@@ -463,21 +444,9 @@ def clean(self):
463444

464445
# Check all nonces for expiry
465446
for nonce in nonces:
466-
filename = os.path.join(self.nonce_dir, nonce)
467-
try:
468-
st = os.stat(filename)
469-
except OSError, why:
470-
if why[0] == ENOENT:
471-
# The file did not exist by the time we tried to
472-
# stat it.
473-
pass
474-
else:
475-
raise
476-
else:
477-
# Remove the nonce if it has expired
478-
nonce_age = now - st.st_mtime
479-
if nonce_age > self.max_nonce_age:
480-
_removeIfPresent(filename)
447+
if not checkTimestamp(nonce, now=now):
448+
filename = os.path.join(self.nonce_dir, nonce)
449+
_removeIfPresent(filename)
481450

482451
association_filenames = os.listdir(self.association_dir)
483452
for association_filename in association_filenames:

‎openid/store/nonce.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
__all__ = [
2+
'split',
3+
'mkNonce',
4+
'checkTimestamp',
5+
]
6+
7+
from openid import cryptutil
8+
from time import strptime, strftime, gmtime, time
9+
from calendar import timegm
10+
import string
11+
12+
NONCE_CHARS = string.letters + string.digits
13+
14+
# Keep nonces for five hours (allow five hours for the combination of
15+
# request time and clock skew). This is probably way more than is
16+
# necessary, but there is not much overhead in storing nonces.
17+
SKEW = 60 * 60 * 5
18+
19+
time_fmt = '%Y-%m-%dT%H:%M:%SZ'
20+
time_str_len = len('0000-00-00T00:00:00Z')
21+
22+
def split(nonce_string):
23+
"""Extract a timestamp from the given nonce string
24+
25+
@param nonce_string: the nonce from which to extract the timestamp
26+
@type nonce_string: str
27+
28+
@returns: A pair of a Unix timestamp and the salt characters
29+
@returntype: (int, str)
30+
31+
@raises ValueError: if the nonce does not start with a correctly
32+
formatted time string
33+
"""
34+
timestamp_str = nonce_string[:time_str_len]
35+
timestamp = timegm(strptime(timestamp_str, time_fmt))
36+
return timestamp, nonce_string[time_str_len:]
37+
38+
def checkTimestamp(nonce_string, allowed_skew=SKEW, now=None):
39+
"""Is the timestamp that is part of the specified nonce string
40+
within the allowed clock-skew of the current time?
41+
42+
@param nonce_string: The nonce that is being checked
43+
@type nonce_string: str
44+
45+
@param allowed_skew: How many seconds should be allowed for
46+
completing the request, allowing for clock skew.
47+
@type allowed_skew: int
48+
49+
@param now: The current time, as a Unix timestamp
50+
@type now: int
51+
52+
@returntype: bool
53+
@returns: Whether the timestamp is correctly formatted and within
54+
the allowed skew of the current time.
55+
"""
56+
try:
57+
stamp, _ = split(nonce_string)
58+
except ValueError:
59+
return False
60+
else:
61+
if now is None:
62+
now = time()
63+
64+
# Time after which we should not use the nonce
65+
past = now - allowed_skew
66+
67+
# Time that is too far in the future for us to allow
68+
future = now + allowed_skew
69+
70+
# the stamp is not too far in the future and is not too far in
71+
# the past
72+
return past < stamp < future
73+
74+
def mkNonce(when=None):
75+
"""Generate a nonce with the current timestamp
76+
77+
@param when: GMT time tuple representing the issue time of the
78+
nonce. Defaults to the current time.
79+
@type when: time tuple
80+
81+
@returntype: str
82+
@returns: A string that should be usable as a one-way nonce
83+
84+
@see: time
85+
"""
86+
salt = cryptutil.randomString(6, NONCE_CHARS)
87+
if when is None:
88+
when = gmtime()
89+
time_str = strftime(time_fmt, when)
90+
return time_str + salt

0 commit comments

Comments
 (0)