checkers.py 11 KB

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