You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

checkers.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # -*- test-case-name: twisted.cred.test.test_cred -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from __future__ import division, absolute_import
  5. import os
  6. from zope.interface import implementer, Interface, Attribute
  7. from twisted.logger import Logger
  8. from twisted.internet import defer
  9. from twisted.python import failure
  10. from twisted.cred import error, credentials
  11. class ICredentialsChecker(Interface):
  12. """
  13. An object that can check sub-interfaces of ICredentials.
  14. """
  15. credentialInterfaces = Attribute(
  16. 'A list of sub-interfaces of ICredentials which specifies which I may check.')
  17. def requestAvatarId(credentials):
  18. """
  19. @param credentials: something which implements one of the interfaces in
  20. self.credentialInterfaces.
  21. @return: a Deferred which will fire a string which identifies an
  22. avatar, an empty tuple to specify an authenticated anonymous user
  23. (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin).
  24. Alternatively, return the result itself.
  25. @see: L{twisted.cred.credentials}
  26. """
  27. # A note on anonymity - We do not want None as the value for anonymous
  28. # because it is too easy to accidentally return it. We do not want the
  29. # empty string, because it is too easy to mistype a password file. For
  30. # example, an .htpasswd file may contain the lines: ['hello:asdf',
  31. # 'world:asdf', 'goodbye', ':world']. This misconfiguration will have an
  32. # ill effect in any case, but accidentally granting anonymous access is a
  33. # worse failure mode than simply granting access to an untypeable
  34. # username. We do not want an instance of 'object', because that would
  35. # create potential problems with persistence.
  36. ANONYMOUS = ()
  37. @implementer(ICredentialsChecker)
  38. class AllowAnonymousAccess:
  39. credentialInterfaces = credentials.IAnonymous,
  40. def requestAvatarId(self, credentials):
  41. return defer.succeed(ANONYMOUS)
  42. @implementer(ICredentialsChecker)
  43. class InMemoryUsernamePasswordDatabaseDontUse(object):
  44. """
  45. An extremely simple credentials checker.
  46. This is only of use in one-off test programs or examples which don't
  47. want to focus too much on how credentials are verified.
  48. You really don't want to use this for anything else. It is, at best, a
  49. toy. If you need a simple credentials checker for a real application,
  50. see L{FilePasswordDB}.
  51. """
  52. credentialInterfaces = (credentials.IUsernamePassword,
  53. credentials.IUsernameHashedPassword)
  54. def __init__(self, **users):
  55. self.users = {x.encode('ascii'):y for x, y in users.items()}
  56. def addUser(self, username, password):
  57. self.users[username] = password
  58. def _cbPasswordMatch(self, matched, username):
  59. if matched:
  60. return username
  61. else:
  62. return failure.Failure(error.UnauthorizedLogin())
  63. def requestAvatarId(self, credentials):
  64. if credentials.username in self.users:
  65. return defer.maybeDeferred(
  66. credentials.checkPassword,
  67. self.users[credentials.username]).addCallback(
  68. self._cbPasswordMatch, credentials.username)
  69. else:
  70. return defer.fail(error.UnauthorizedLogin())
  71. @implementer(ICredentialsChecker)
  72. class FilePasswordDB:
  73. """
  74. A file-based, text-based username/password database.
  75. Records in the datafile for this class are delimited by a particular
  76. string. The username appears in a fixed field of the columns delimited
  77. by this string, as does the password. Both fields are specifiable. If
  78. the passwords are not stored plaintext, a hash function must be supplied
  79. to convert plaintext passwords to the form stored on disk and this
  80. CredentialsChecker will only be able to check IUsernamePassword
  81. credentials. If the passwords are stored plaintext,
  82. IUsernameHashedPassword credentials will be checkable as well.
  83. """
  84. cache = False
  85. _credCache = None
  86. _cacheTimestamp = 0
  87. _log = Logger()
  88. def __init__(self, filename, delim=b':', usernameField=0, passwordField=1,
  89. caseSensitive=True, hash=None, cache=False):
  90. """
  91. @type filename: C{str}
  92. @param filename: The name of the file from which to read username and
  93. password information.
  94. @type delim: C{str}
  95. @param delim: The field delimiter used in the file.
  96. @type usernameField: C{int}
  97. @param usernameField: The index of the username after splitting a
  98. line on the delimiter.
  99. @type passwordField: C{int}
  100. @param passwordField: The index of the password after splitting a
  101. line on the delimiter.
  102. @type caseSensitive: C{bool}
  103. @param caseSensitive: If true, consider the case of the username when
  104. performing a lookup. Ignore it otherwise.
  105. @type hash: Three-argument callable or L{None}
  106. @param hash: A function used to transform the plaintext password
  107. received over the network to a format suitable for comparison
  108. against the version stored on disk. The arguments to the callable
  109. are the username, the network-supplied password, and the in-file
  110. version of the password. If the return value compares equal to the
  111. version stored on disk, the credentials are accepted.
  112. @type cache: C{bool}
  113. @param cache: If true, maintain an in-memory cache of the
  114. contents of the password file. On lookups, the mtime of the
  115. file will be checked, and the file will only be re-parsed if
  116. the mtime is newer than when the cache was generated.
  117. """
  118. self.filename = filename
  119. self.delim = delim
  120. self.ufield = usernameField
  121. self.pfield = passwordField
  122. self.caseSensitive = caseSensitive
  123. self.hash = hash
  124. self.cache = cache
  125. if self.hash is None:
  126. # The passwords are stored plaintext. We can support both
  127. # plaintext and hashed passwords received over the network.
  128. self.credentialInterfaces = (
  129. credentials.IUsernamePassword,
  130. credentials.IUsernameHashedPassword
  131. )
  132. else:
  133. # The passwords are hashed on disk. We can support only
  134. # plaintext passwords received over the network.
  135. self.credentialInterfaces = (
  136. credentials.IUsernamePassword,
  137. )
  138. def __getstate__(self):
  139. d = dict(vars(self))
  140. for k in '_credCache', '_cacheTimestamp':
  141. try:
  142. del d[k]
  143. except KeyError:
  144. pass
  145. return d
  146. def _cbPasswordMatch(self, matched, username):
  147. if matched:
  148. return username
  149. else:
  150. return failure.Failure(error.UnauthorizedLogin())
  151. def _loadCredentials(self):
  152. """
  153. Loads the credentials from the configured file.
  154. @return: An iterable of C{username, password} couples.
  155. @rtype: C{iterable}
  156. @raise UnauthorizedLogin: when failing to read the credentials from the
  157. file.
  158. """
  159. try:
  160. with open(self.filename, "rb") as f:
  161. for line in f:
  162. line = line.rstrip()
  163. parts = line.split(self.delim)
  164. if self.ufield >= len(parts) or self.pfield >= len(parts):
  165. continue
  166. if self.caseSensitive:
  167. yield parts[self.ufield], parts[self.pfield]
  168. else:
  169. yield parts[self.ufield].lower(), parts[self.pfield]
  170. except IOError as e:
  171. self._log.error("Unable to load credentials db: {e!r}", e=e)
  172. raise error.UnauthorizedLogin()
  173. def getUser(self, username):
  174. if not self.caseSensitive:
  175. username = username.lower()
  176. if self.cache:
  177. if self._credCache is None or os.path.getmtime(self.filename) > self._cacheTimestamp:
  178. self._cacheTimestamp = os.path.getmtime(self.filename)
  179. self._credCache = dict(self._loadCredentials())
  180. return username, self._credCache[username]
  181. else:
  182. for u, p in self._loadCredentials():
  183. if u == username:
  184. return u, p
  185. raise KeyError(username)
  186. def requestAvatarId(self, c):
  187. try:
  188. u, p = self.getUser(c.username)
  189. except KeyError:
  190. return defer.fail(error.UnauthorizedLogin())
  191. else:
  192. up = credentials.IUsernamePassword(c, None)
  193. if self.hash:
  194. if up is not None:
  195. h = self.hash(up.username, up.password, p)
  196. if h == p:
  197. return defer.succeed(u)
  198. return defer.fail(error.UnauthorizedLogin())
  199. else:
  200. return defer.maybeDeferred(c.checkPassword, p
  201. ).addCallback(self._cbPasswordMatch, u)
  202. # For backwards compatibility
  203. # Allow access as the old name.
  204. OnDiskUsernamePasswordDatabase = FilePasswordDB