[CalendarServer-changes] [1518] CalendarServer/trunk
source_changes at macosforge.org
source_changes at macosforge.org
Tue May 8 11:10:10 PDT 2007
Revision: 1518
http://trac.macosforge.org/projects/calendarserver/changeset/1518
Author: cdaboo at apple.com
Date: 2007-05-08 11:10:10 -0700 (Tue, 08 May 2007)
Log Message:
-----------
Support multi-process digest authentication where each process can share a database of nonces/client ips etc.
Modified Paths:
--------------
CalendarServer/trunk/conf/caldavd-test.plist
CalendarServer/trunk/conf/caldavd.plist
CalendarServer/trunk/twistedcaldav/cluster.py
CalendarServer/trunk/twistedcaldav/config.py
CalendarServer/trunk/twistedcaldav/directory/digest.py
CalendarServer/trunk/twistedcaldav/tap.py
Added Paths:
-----------
CalendarServer/trunk/twistedcaldav/directory/test/test_digest.py
Modified: CalendarServer/trunk/conf/caldavd-test.plist
===================================================================
--- CalendarServer/trunk/conf/caldavd-test.plist 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/conf/caldavd-test.plist 2007-05-08 18:10:10 UTC (rev 1518)
@@ -68,6 +68,10 @@
Data Store
-->
+ <!-- Data root -->
+ <key>DataRoot</key>
+ <string>data/</string>
+
<!-- Document root -->
<key>DocumentRoot</key>
<string>twistedcaldav/test/data/</string>
@@ -217,8 +221,6 @@
<string>md5</string>
<key>Qop</key>
<string></string>
- <key>Secret</key>
- <string></string>
</dict>
<!-- Kerberos/SPNEGO -->
Modified: CalendarServer/trunk/conf/caldavd.plist
===================================================================
--- CalendarServer/trunk/conf/caldavd.plist 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/conf/caldavd.plist 2007-05-08 18:10:10 UTC (rev 1518)
@@ -66,6 +66,10 @@
Data Store
-->
+ <!-- Data root -->
+ <key>DataRoot</key>
+ <string>/Library/CalendarServer/Data</string>
+
<!-- Document root -->
<key>DocumentRoot</key>
<string>/Library/CalendarServer/Documents</string>
@@ -164,8 +168,6 @@
<string>md5</string>
<key>Qop</key>
<string></string>
- <key>Secret</key>
- <string></string>
</dict>
<!-- Kerberos/SPNEGO -->
Modified: CalendarServer/trunk/twistedcaldav/cluster.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/cluster.py 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/twistedcaldav/cluster.py 2007-05-08 18:10:10 UTC (rev 1518)
@@ -95,7 +95,6 @@
'-o', 'BindSSLPorts=%s' % (','.join(map(str, self.sslPorts)),),
'-o', 'PIDFile=None',
'-o', 'ErrorLogFile=None',
- '-o', 'SharedSecret=%s' % (config.SharedSecret,),
'-o', 'MultiProcess/ProcessCount=%d' % (
config.MultiProcess['ProcessCount'],)])
Modified: CalendarServer/trunk/twistedcaldav/config.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/config.py 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/twistedcaldav/config.py 2007-05-08 18:10:10 UTC (rev 1518)
@@ -63,7 +63,8 @@
#
# Data store
#
- "DocumentRoot": "/Library/CalendarServer/Documents",
+ "DataRoot" : "/Library/CalendarServer/Data",
+ "DocumentRoot" : "/Library/CalendarServer/Documents",
"UserQuota" : 104857600, # User quota (in bytes)
"MaximumAttachmentSize": 1048576, # Attachment size limit (in bytes)
@@ -94,7 +95,6 @@
"Enabled": True,
"Algorithm": "md5",
"Qop": "",
- "Secret": "",
},
"Kerberos": { # Kerberos/SPNEGO
"Enabled": False,
@@ -173,10 +173,6 @@
# processes.
"ControlSocket": "/var/run/caldavd.sock",
- # A secret key (SHA-1 hash of random string) that is used for internal
- # crypto operations and shared by multiple server processes
- "SharedSecret": "",
-
# Support for Content-Encoding compression options as specified in
# RFC2616 Section 3.5
"ResponseCompression": True,
Modified: CalendarServer/trunk/twistedcaldav/directory/digest.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/digest.py 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/twistedcaldav/directory/digest.py 2007-05-08 18:10:10 UTC (rev 1518)
@@ -16,20 +16,250 @@
# DRI: Cyrus Daboo, cdaboo at apple.com
##
+from twistedcaldav.sql import AbstractSQLDatabase
from twisted.web2.auth.digest import DigestCredentialFactory
+from zope.interface import implements, Interface
+
+import cPickle as pickle
+from twisted.cred import error
+from twisted.web2.auth.digest import DigestedCredentials
+import time
+import os
+
"""
Overrides twisted.web2.auth.digest to allow specifying a qop value as a configuration parameter.
+Also adds an sqlite-based credentials cache that is multi-process safe.
"""
+class IDigestCredentialsDatabase(Interface):
+ """
+ An interface to a digest credentials database that is used to hold per-client digest credentials so that fast
+ re-authentication can be done with replay attacks etc prevented.
+ """
+
+ def has_key(self, key):
+ """
+ See whether the matching key exists.
+
+ @param key: the key to check.
+ @type key: C{str}.
+
+ @return: C{True} if the key exists, C{False} otherwise.
+ """
+ pass
+
+ def set(self, key, value):
+ """
+ Store per-client credential information the first time a nonce is generated and used.
+
+ @param key: the key for the data to store.
+ @type key: C{str}
+ @param value: the data to store.
+ @type value: any.
+ """
+ pass
+
+ def get(self, key):
+ """
+ Validate client supplied credentials by comparing with the cached values. If valid, store the new
+ cnonce value in the database so that it can be used on the next validate.
+
+ @param key: the key to check.
+ @type key: C{str}.
+
+ @return: the value for the corresponding key, or C{None} if the key is not found.
+ """
+ pass
+
+ def delete(self, key):
+ """
+ Remove the record associated with the supplied key.
+
+ @param key: the key to remove.
+ @type key: C{str}
+ """
+ pass
+
+ def keys(self):
+ """
+ Return all the keys currently available.
+
+ @return: a C{list} of C{str} for each key currently in the database.
+ """
+ pass
+
+class DigestCredentialsMap:
+
+ implements(IDigestCredentialsDatabase)
+
+ def __init__(self, *args):
+ self.db = {}
+
+ def has_key(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ return self.db.has_key(key)
+
+ def set(self, key, value):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ self.db[key] = value
+
+ def get(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ if self.db.has_key(key):
+ return self.db[key]
+ else:
+ return None
+
+ def delete(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ if self.db.has_key(key):
+ del self.db[key]
+
+ def keys(self):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ return self.db.keys()
+
+class DigestCredentialsDB(AbstractSQLDatabase):
+
+ implements(IDigestCredentialsDatabase)
+
+ """
+ A database to maintain cached digest credentials.
+
+ SCHEMA:
+
+ Database: DIGESTCREDENTIALS
+
+ ROW: KEY, VALUE
+
+ """
+
+ dbType = "DIGESTCREDENTIALSCACHE"
+ dbFilename = ".db.digestcredentialscache"
+ dbFormatVersion = "1"
+
+ def __init__(self, path):
+ db_path = os.path.join(path, DigestCredentialsDB.dbFilename)
+ if os.path.exists(db_path):
+ os.remove(db_path)
+ super(DigestCredentialsDB, self).__init__(db_path, DigestCredentialsDB.dbFormatVersion)
+ self.db = {}
+
+ def has_key(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ for ignore_key in self._db_execute(
+ "select KEY from DIGESTCREDENTIALS where KEY = :1",
+ key
+ ):
+ return True
+ else:
+ return False
+
+ def set(self, key, value):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ self._delete_from_db(key)
+ pvalue = pickle.dumps(value)
+ self._add_to_db(key, pvalue)
+ self._db_commit()
+
+ def get(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ for pvalue in self._db_execute(
+ "select VALUE from DIGESTCREDENTIALS where KEY = :1",
+ key
+ ):
+ return pickle.loads(str(pvalue[0]))
+ else:
+ return None
+
+ def delete(self, key):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ self._delete_from_db(key)
+ self._db_commit()
+
+ def keys(self):
+ """
+ See IDigestCredentialsDatabase.
+ """
+ result = []
+ for key in self._db_execute("select KEY from DIGESTCREDENTIALS"):
+ result.append(str(key[0]))
+
+ return result
+
+ def _add_to_db(self, key, value):
+ """
+ Insert the specified entry into the database.
+
+ @param key: the key to add.
+ @param value: the value to add.
+ """
+ self._db_execute(
+ """
+ insert into DIGESTCREDENTIALS (KEY, VALUE)
+ values (:1, :2)
+ """, key, value
+ )
+
+ def _delete_from_db(self, key):
+ """
+ Deletes the specified entry from the database.
+
+ @param key: the key to remove.
+ """
+ self._db_execute("delete from DIGESTCREDENTIALS where KEY = :1", key)
+
+ def _db_type(self):
+ """
+ @return: the collection type assigned to this index.
+ """
+ return DigestCredentialsDB.dbType
+
+ def _db_init_data_tables(self, q):
+ """
+ Initialise the underlying database tables.
+ @param q: a database cursor to use.
+ """
+
+ #
+ # DIGESTCREDENTIALS table
+ #
+ q.execute(
+ """
+ create table DIGESTCREDENTIALS (
+ KEY text,
+ VALUE text
+ )
+ """
+ )
+
class QopDigestCredentialFactory(DigestCredentialFactory):
"""
See twisted.web2.auth.digest.DigestCredentialFactory
"""
- def __init__(self, algorithm, qop, secret, realm):
+ def __init__(self, algorithm, qop, realm, db_path):
"""
@type algorithm: C{str}
@param algorithm: case insensitive string that specifies
@@ -41,25 +271,43 @@
the qop to use
- @type secret: C{str}
- @param secret: specifies a secret key to be used for opaque value hashing
-
@type realm: C{str}
@param realm: case sensitive string that specifies the realm
portion of the challenge
+
+ @type db_path: C{str}
+ @param db_path: path where the credentials cache is to be stored
"""
super(QopDigestCredentialFactory, self).__init__(algorithm, realm)
self.qop = qop
- if secret:
- self.privateKey = secret
+ self.db = DigestCredentialsDB(db_path)
def getChallenge(self, peer):
"""
+ Generate the challenge for use in the WWW-Authenticate header
Do the default behavior but then strip out any 'qop' from the challenge fields
if no qop was specified.
+
+ @param peer: The L{IAddress} of the requesting client.
+
+ @return: The C{dict} that can be used to generate a WWW-Authenticate
+ header.
"""
- challenge = super(QopDigestCredentialFactory, self).getChallenge(peer)
+ c = self.generateNonce()
+
+ # Make sure it is not a duplicate
+ if self.db.has_key(c):
+ raise AssertionError("nonce value already cached in credentials database: %s" % (c,))
+
+ # The database record is a tuple of (client ip, nonce-count, timestamp)
+ self.db.set(c, (peer.host, 0, time.time()))
+
+ challenge = {'nonce': c,
+ 'qop': 'auth',
+ 'algorithm': self.algorithm,
+ 'realm': self.realm}
+
if self.qop:
challenge['qop'] = self.qop
else:
@@ -73,7 +321,130 @@
if no qop was specified.
"""
- credentials = super(QopDigestCredentialFactory, self).decode(response, request)
- if not self.qop and credentials.fields.has_key('qop'):
- del credentials.fields['qop']
- return credentials
+ """
+ Decode the given response and attempt to generate a
+ L{DigestedCredentials} from it.
+
+ @type response: C{str}
+ @param response: A string of comma seperated key=value pairs
+
+ @type request: L{twisted.web2.server.Request}
+ @param request: the request being processed
+
+ @return: L{DigestedCredentials}
+
+ @raise: L{error.LoginFailed} if the response does not contain a
+ username, a nonce, an opaque, or if the opaque is invalid.
+ """
+ def unq(s):
+ if s[0] == s[-1] == '"':
+ return s[1:-1]
+ return s
+ response = ' '.join(response.splitlines())
+ parts = response.split(',')
+
+ auth = {}
+
+ for (k, v) in [p.split('=', 1) for p in parts]:
+ auth[k.strip()] = unq(v.strip())
+
+ username = auth.get('username')
+ if not username:
+ raise error.LoginFailed('Invalid response, no username given.')
+
+ if 'nonce' not in auth:
+ raise error.LoginFailed('Invalid response, no nonce given.')
+
+ # Now verify the nonce/cnonce values for this client
+ if self.validate(auth, request):
+
+ credentials = DigestedCredentials(username,
+ request.method,
+ self.realm,
+ auth)
+ if not self.qop and credentials.fields.has_key('qop'):
+ del credentials.fields['qop']
+ return credentials
+ else:
+ raise error.LoginFailed('Invalid nonce/cnonce values')
+
+ def validate(self, auth, request):
+ """
+ Check that the parameters in the response represent a valid set of credentials that
+ may be being re-used.
+
+ @param auth: the response parameters.
+ @type auth: C{dict}
+ @param request: the request being processed.
+ @type request: L{twisted.web2.server.Request}
+
+ @return: C{True} if validated.
+ @raise LoginFailed: if validation fails.
+ """
+
+ nonce = auth.get('nonce')
+ clientip = request.remoteAddr.host
+ nonce_count = auth.get('nc')
+
+ # First check we have this nonce
+ if not self.db.has_key(nonce):
+ raise error.LoginFailed('Invalid nonce value: %s' % (nonce,))
+ db_clientip, db_nonce_count, db_timestamp = self.db.get(nonce)
+
+ # Next check client ip
+ if db_clientip != clientip:
+ self.invalidate(nonce)
+ raise error.LoginFailed('Client IPs do not match: %s and %s' % (clientip, db_clientip,))
+
+ # cnonce and nonce-count MUST be present if qop is present
+ if auth.get('qop') is not None:
+ if auth.get('cnonce') is None:
+ self.invalidate(nonce)
+ raise error.LoginFailed('cnonce is required when qop is specified')
+ if nonce_count is None:
+ self.invalidate(nonce)
+ raise error.LoginFailed('nonce-count is required when qop is specified')
+
+ # Next check the nonce-count is one greater than the previous one and update it in the DB
+ try:
+ nonce_count = int(nonce_count, 16)
+ except ValueError:
+ self.invalidate(nonce)
+ raise error.LoginFailed('nonce-count is not a valid hex string: %s' % (auth.get('nonce-count'),))
+ if nonce_count != db_nonce_count + 1:
+ self.invalidate(nonce)
+ raise error.LoginFailed('nonce-count value out of sequence: %s should be one more than %s' % (nonce_count, db_nonce_count,))
+ self.db.set(nonce, (db_clientip, nonce_count, db_timestamp))
+ else:
+ # When not using qop the stored nonce-count must always be zero.
+ # i.e. we can't allow a qop auth then a non-qop auth with the same nonce
+ if db_nonce_count != 0:
+ self.invalidate(nonce)
+ raise error.LoginFailed('nonce-count was sent with this nonce: %s' % (nonce,))
+
+ # Now check timestamp
+ if db_timestamp + DigestCredentialFactory.CHALLENGE_LIFETIME_SECS <= time.time():
+ self.invalidate(nonce)
+ raise error.LoginFailed('Digest credentials expired')
+
+ return True
+
+ def invalidate(self, nonce):
+ """
+ Invalidate cached credentials for the specified nonce value.
+
+ @param nonce: the nonce for the record to invalidate.
+ @type nonce: C{str}
+ """
+ self.db.delete(nonce)
+
+ def cleanup(self):
+ """
+ This should be called at regular intervals to remove expired credentials from the cache.
+ """
+ keys = self.db.keys()
+ oldest_allowed = time.time() - DigestCredentialFactory.CHALLENGE_LIFETIME_SECS
+ for key in keys:
+ ignore_clientip, ignore_cnonce, db_timestamp = self.db.get(key)
+ if db_timestamp <= oldest_allowed:
+ self.invalidate(key)
Copied: CalendarServer/trunk/twistedcaldav/directory/test/test_digest.py (from rev 1517, CalendarServer/branches/users/cdaboo/digest-1510/twistedcaldav/directory/test/test_digest.py)
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_digest.py (rev 0)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_digest.py 2007-05-08 18:10:10 UTC (rev 1518)
@@ -0,0 +1,420 @@
+
+
+from twisted.cred import error
+from twisted.internet import address
+from twisted.trial import unittest
+from twisted.web2.auth import digest
+from twisted.web2.test.test_server import SimpleRequest
+from twisted.web2.dav.fileop import rmdir
+from twistedcaldav.directory.digest import QopDigestCredentialFactory
+import os
+import md5
+
+class FakeDigestCredentialFactory(QopDigestCredentialFactory):
+ """
+ A Fake Digest Credential Factory that generates a predictable
+ nonce and opaque
+ """
+
+ def __init__(self, *args, **kwargs):
+ super(FakeDigestCredentialFactory, self).__init__(*args, **kwargs)
+
+ def generateNonce(self):
+ """
+ Generate a static nonce
+ """
+ return '178288758716122392881254770685'
+
+
+clientAddress = address.IPv4Address('TCP', '127.0.0.1', 80)
+
+challengeOpaque = ('75c4bd95b96b7b7341c646c6502f0833-MTc4Mjg4NzU'
+ '4NzE2MTIyMzkyODgxMjU0NzcwNjg1LHJlbW90ZWhvc3Q'
+ 'sMA==')
+
+challengeNonce = '178288758716122392881254770685'
+
+challengeResponse = ('digest',
+ {'nonce': challengeNonce,
+ 'qop': 'auth', 'realm': 'test realm',
+ 'algorithm': 'md5',})
+
+cnonce = "29fc54aa1641c6fa0e151419361c8f23"
+
+authRequest1 = (('username="username", realm="test realm", nonce="%s", '
+ 'uri="/write/", response="%s", algorithm="md5", '
+ 'cnonce="29fc54aa1641c6fa0e151419361c8f23", nc=00000001, '
+ 'qop="auth"'),
+ ('username="username", realm="test realm", nonce="%s", '
+ 'uri="/write/", response="%s", algorithm="md5"'))
+
+authRequest2 = (('username="username", realm="test realm", nonce="%s", '
+ 'uri="/write/", response="%s", algorithm="md5", '
+ 'cnonce="29fc54aa1641c6fa0e151419361c8f23", nc=00000002, '
+ 'qop="auth"'),
+ ('username="username", realm="test realm", nonce="%s", '
+ 'uri="/write/", response="%s", algorithm="md5"'))
+
+authRequest3 = ('username="username", realm="test realm", nonce="%s", '
+ 'uri="/write/", response="%s", algorithm="md5"')
+
+namelessAuthRequest = 'realm="test realm",nonce="doesn\'t matter"'
+
+
+class DigestAuthTestCase(unittest.TestCase):
+ """
+ Test the behavior of DigestCredentialFactory
+ """
+
+ def setUp(self):
+ """
+ Create a DigestCredentialFactory for testing
+ """
+ self.path1 = self.mktemp()
+ self.path2 = self.mktemp()
+ os.mkdir(self.path1)
+ os.mkdir(self.path2)
+
+ self.credentialFactories = (QopDigestCredentialFactory(
+ 'md5',
+ 'auth',
+ 'test realm',
+ self.path1
+ ),
+ QopDigestCredentialFactory(
+ 'md5',
+ '',
+ 'test realm',
+ self.path2
+ ))
+
+ def tearDown(self):
+ rmdir(self.path1)
+ rmdir(self.path2)
+
+ def getDigestResponse(self, challenge, ncount):
+ """
+ Calculate the response for the given challenge
+ """
+ nonce = challenge.get('nonce')
+ algo = challenge.get('algorithm').lower()
+ qop = challenge.get('qop')
+
+ if qop:
+ expected = digest.calcResponse(
+ digest.calcHA1(algo,
+ "username",
+ "test realm",
+ "password",
+ nonce,
+ cnonce),
+ algo, nonce, ncount, cnonce, qop, "GET", "/write/", None
+ )
+ else:
+ expected = digest.calcResponse(
+ digest.calcHA1(algo,
+ "username",
+ "test realm",
+ "password",
+ nonce,
+ cnonce),
+ algo, nonce, None, None, None, "GET", "/write/", None
+ )
+ return expected
+
+ def test_getChallenge(self):
+ """
+ Test that all the required fields exist in the challenge,
+ and that the information matches what we put into our
+ DigestCredentialFactory
+ """
+
+ challenge = self.credentialFactories[0].getChallenge(clientAddress)
+ self.assertEquals(challenge['qop'], 'auth')
+ self.assertEquals(challenge['realm'], 'test realm')
+ self.assertEquals(challenge['algorithm'], 'md5')
+ self.assertTrue(challenge.has_key("nonce"))
+
+ challenge = self.credentialFactories[1].getChallenge(clientAddress)
+ self.assertFalse(challenge.has_key('qop'))
+ self.assertEquals(challenge['realm'], 'test realm')
+ self.assertEquals(challenge['algorithm'], 'md5')
+ self.assertTrue(challenge.has_key("nonce"))
+
+ def test_response(self):
+ """
+ Test that we can decode a valid response to our challenge
+ """
+
+ for ctr, factory in enumerate(self.credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ creds = factory.decode(clientResponse, _trivial_GET)
+ self.failUnless(creds.checkPassword('password'))
+
+ def test_multiResponse(self):
+ """
+ Test that multiple responses to to a single challenge are handled
+ successfully.
+ """
+
+ for ctr, factory in enumerate(self.credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ creds = factory.decode(clientResponse, _trivial_GET)
+ self.failUnless(creds.checkPassword('password'))
+
+ clientResponse = authRequest2[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000002"),
+ )
+
+ creds = factory.decode(clientResponse, _trivial_GET)
+ self.failUnless(creds.checkPassword('password'))
+
+ def test_failsWithDifferentMethod(self):
+ """
+ Test that the response fails if made for a different request method
+ than it is being issued for.
+ """
+
+ for ctr, factory in enumerate(self.credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ creds = factory.decode(clientResponse,
+ SimpleRequest(None, 'POST', '/'))
+ self.failIf(creds.checkPassword('password'))
+
+ def test_noUsername(self):
+ """
+ Test that login fails when our response does not contain a username,
+ or the username field is empty.
+ """
+
+ # Check for no username
+ for factory in self.credentialFactories:
+ e = self.assertRaises(error.LoginFailed,
+ factory.decode,
+ namelessAuthRequest,
+ _trivial_GET)
+ self.assertEquals(str(e), "Invalid response, no username given.")
+
+ # Check for an empty username
+ e = self.assertRaises(error.LoginFailed,
+ factory.decode,
+ namelessAuthRequest + ',username=""',
+ _trivial_GET)
+ self.assertEquals(str(e), "Invalid response, no username given.")
+
+ def test_noNonce(self):
+ """
+ Test that login fails when our response does not contain a nonce
+ """
+
+ for factory in self.credentialFactories:
+ e = self.assertRaises(error.LoginFailed,
+ factory.decode,
+ 'realm="Test",username="Foo",opaque="bar"',
+ _trivial_GET)
+ self.assertEquals(str(e), "Invalid response, no nonce given.")
+
+ def test_checkHash(self):
+ """
+ Check that given a hash of the form 'username:realm:password'
+ we can verify the digest challenge
+ """
+
+ for ctr, factory in enumerate(self.credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ creds = factory.decode(clientResponse, _trivial_GET)
+
+ self.failUnless(creds.checkHash(
+ md5.md5('username:test realm:password').hexdigest()))
+
+ self.failIf(creds.checkHash(
+ md5.md5('username:test realm:bogus').hexdigest()))
+
+ def test_invalidNonceCount(self):
+ """
+ Test that login fails when the nonce-count is repeated.
+ """
+
+ credentialFactories = (
+ FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.path1),
+ FakeDigestCredentialFactory('md5', '', 'test realm', self.path2)
+ )
+
+ for ctr, factory in enumerate(credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse1 = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ clientResponse2 = authRequest2[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000002"),
+ )
+
+ factory.decode(clientResponse1, _trivial_GET)
+ factory.decode(clientResponse2, _trivial_GET)
+
+ if challenge.get('qop') is not None:
+ self.assertRaises(
+ error.LoginFailed,
+ factory.decode,
+ clientResponse2,
+ _trivial_GET
+ )
+
+ challenge = factory.getChallenge(clientAddress)
+
+ clientResponse1 = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+ del challenge['qop']
+ clientResponse3 = authRequest3 % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000002"),
+ )
+ factory.decode(clientResponse1, _trivial_GET)
+ self.assertRaises(
+ error.LoginFailed,
+ factory.decode,
+ clientResponse3,
+ _trivial_GET
+ )
+
+ def test_invalidNonce(self):
+ """
+ Test that login fails when the given nonce from the response, does not
+ match the nonce encoded in the opaque.
+ """
+
+ credentialFactories = (
+ FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.path1),
+ FakeDigestCredentialFactory('md5', '', 'test realm', self.path2)
+ )
+
+ for ctr, factory in enumerate(credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+ challenge['nonce'] = "noNoncense"
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ self.assertRaises(
+ error.LoginFailed,
+ factory.decode,
+ clientResponse,
+ _trivial_GET
+ )
+
+ def test_incompatibleClientIp(self):
+ """
+ Test that the login fails when the request comes from a client ip
+ other than what is encoded in the opaque.
+ """
+
+ credentialFactories = (
+ FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.path1),
+ FakeDigestCredentialFactory('md5', '', 'test realm', self.path2)
+ )
+
+ for ctr, factory in enumerate(credentialFactories):
+ challenge = factory.getChallenge(address.IPv4Address('TCP', '127.0.0.2', 80))
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ self.assertRaises(
+ error.LoginFailed,
+ factory.decode,
+ clientResponse,
+ _trivial_GET
+ )
+
+ def test_oldNonce(self):
+ """
+ Test that the login fails when the given opaque is older than
+ DigestCredentialFactory.CHALLENGE_LIFETIME_SECS
+ """
+
+ credentialFactories = (
+ FakeDigestCredentialFactory('md5', 'auth', 'test realm', self.path1),
+ FakeDigestCredentialFactory('md5', '', 'test realm', self.path2)
+ )
+
+ for ctr, factory in enumerate(credentialFactories):
+ challenge = factory.getChallenge(clientAddress)
+ clientip, nonce_count, timestamp = factory.db.get(challenge['nonce'])
+ factory.db.set(challenge['nonce'], (clientip, nonce_count, timestamp - 2 * digest.DigestCredentialFactory.CHALLENGE_LIFETIME_SECS))
+
+ clientResponse = authRequest1[ctr] % (
+ challenge['nonce'],
+ self.getDigestResponse(challenge, "00000001"),
+ )
+
+ self.assertRaises(
+ error.LoginFailed,
+ factory.decode,
+ clientResponse,
+ _trivial_GET
+ )
+
+ def test_incompatibleCalcHA1Options(self):
+ """
+ Test that the appropriate error is raised when any of the
+ pszUsername, pszRealm, or pszPassword arguments are specified with
+ the preHA1 keyword argument.
+ """
+
+ arguments = (
+ ("user", "realm", "password", "preHA1"),
+ (None, "realm", None, "preHA1"),
+ (None, None, "password", "preHA1"),
+ )
+
+ for pszUsername, pszRealm, pszPassword, preHA1 in arguments:
+ self.assertRaises(
+ TypeError,
+ digest.calcHA1,
+ "md5",
+ pszUsername,
+ pszRealm,
+ pszPassword,
+ "nonce",
+ "cnonce",
+ preHA1=preHA1
+ )
+
+
+
+_trivial_GET = SimpleRequest(None, 'GET', '/')
Modified: CalendarServer/trunk/twistedcaldav/tap.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/tap.py 2007-05-08 16:59:23 UTC (rev 1517)
+++ CalendarServer/trunk/twistedcaldav/tap.py 2007-05-08 18:10:10 UTC (rev 1518)
@@ -16,16 +16,10 @@
# DRI: David Reid, dreid at apple.com
##
-try:
- from hashlib import sha1
-except ImportError:
- import sha
- sha1 = sha.new
import random
import os
import stat
import sys
-import copy
from zope.interface import implements
@@ -233,11 +227,6 @@
log.msg("WARNING: changing umask from: 0%03o to 0%03o" % (
oldmask, config.umask,))
- # Generate a shared secret that will be passed to any slave processes
- if not config.SharedSecret:
- c = tuple([random.randrange(sys.maxint) for _ in range(3)])
- config.SharedSecret = sha1('%d%d%d' % c).hexdigest()
-
def checkDirectory(self, dirpath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
if not os.path.exists(dirpath):
raise ConfigurationError("%s does not exist: %s" % (description, dirpath,))
@@ -445,17 +434,11 @@
)
elif scheme == 'digest':
- secret = schemeConfig['Secret']
- if not secret and config.SharedSecret:
- log.msg("Using master process shared secret for Digest authentication")
- secret = config.SharedSecret
- else:
- log.msg("No shared secret for Digest authentication")
credFactory = QopDigestCredentialFactory(
schemeConfig['Algorithm'],
schemeConfig['Qop'],
- secret,
- realm
+ realm,
+ config.DataRoot,
)
elif scheme == 'basic':
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20070508/167b2f63/attachment.html
More information about the calendarserver-changes
mailing list