checkers.py 11 KB

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