Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 11KB

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