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.

credentials.py 16KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. # -*- test-case-name: twisted.cred.test.test_cred-*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module defines L{ICredentials}, an interface for objects that represent
  6. authentication credentials to provide, and also includes a number of useful
  7. implementations of that interface.
  8. """
  9. import base64
  10. import hmac
  11. import random
  12. import re
  13. import time
  14. from binascii import hexlify
  15. from hashlib import md5
  16. from zope.interface import Interface, implementer
  17. from twisted.cred import error
  18. from twisted.cred._digest import calcHA1, calcHA2, calcResponse
  19. from twisted.python.compat import nativeString, networkString
  20. from twisted.python.deprecate import deprecatedModuleAttribute
  21. from twisted.python.randbytes import secureRandom
  22. from twisted.python.versions import Version
  23. class ICredentials(Interface):
  24. """
  25. I check credentials.
  26. Implementors I{must} specify the sub-interfaces of ICredentials
  27. to which it conforms, using L{zope.interface.implementer}.
  28. """
  29. class IUsernameDigestHash(ICredentials):
  30. """
  31. This credential is used when a CredentialChecker has access to the hash
  32. of the username:realm:password as in an Apache .htdigest file.
  33. """
  34. def checkHash(digestHash):
  35. """
  36. @param digestHash: The hashed username:realm:password to check against.
  37. @return: C{True} if the credentials represented by this object match
  38. the given hash, C{False} if they do not, or a L{Deferred} which
  39. will be called back with one of these values.
  40. """
  41. class IUsernameHashedPassword(ICredentials):
  42. """
  43. I encapsulate a username and a hashed password.
  44. This credential is used when a hashed password is received from the
  45. party requesting authentication. CredentialCheckers which check this
  46. kind of credential must store the passwords in plaintext (or as
  47. password-equivalent hashes) form so that they can be hashed in a manner
  48. appropriate for the particular credentials class.
  49. @type username: L{bytes}
  50. @ivar username: The username associated with these credentials.
  51. """
  52. def checkPassword(password):
  53. """
  54. Validate these credentials against the correct password.
  55. @type password: L{bytes}
  56. @param password: The correct, plaintext password against which to
  57. check.
  58. @rtype: C{bool} or L{Deferred}
  59. @return: C{True} if the credentials represented by this object match the
  60. given password, C{False} if they do not, or a L{Deferred} which will
  61. be called back with one of these values.
  62. """
  63. class IUsernamePassword(ICredentials):
  64. """
  65. I encapsulate a username and a plaintext password.
  66. This encapsulates the case where the password received over the network
  67. has been hashed with the identity function (That is, not at all). The
  68. CredentialsChecker may store the password in whatever format it desires,
  69. it need only transform the stored password in a similar way before
  70. performing the comparison.
  71. @type username: L{bytes}
  72. @ivar username: The username associated with these credentials.
  73. @type password: L{bytes}
  74. @ivar password: The password associated with these credentials.
  75. """
  76. def checkPassword(password):
  77. """
  78. Validate these credentials against the correct password.
  79. @type password: L{bytes}
  80. @param password: The correct, plaintext password against which to
  81. check.
  82. @rtype: C{bool} or L{Deferred}
  83. @return: C{True} if the credentials represented by this object match the
  84. given password, C{False} if they do not, or a L{Deferred} which will
  85. be called back with one of these values.
  86. """
  87. class IAnonymous(ICredentials):
  88. """
  89. I am an explicitly anonymous request for access.
  90. @see: L{twisted.cred.checkers.AllowAnonymousAccess}
  91. """
  92. @implementer(IUsernameHashedPassword, IUsernameDigestHash)
  93. class DigestedCredentials:
  94. """
  95. Yet Another Simple HTTP Digest authentication scheme.
  96. """
  97. def __init__(self, username, method, realm, fields):
  98. self.username = username
  99. self.method = method
  100. self.realm = realm
  101. self.fields = fields
  102. def checkPassword(self, password):
  103. """
  104. Verify that the credentials represented by this object agree with the
  105. given plaintext C{password} by hashing C{password} in the same way the
  106. response hash represented by this object was generated and comparing
  107. the results.
  108. """
  109. response = self.fields.get("response")
  110. uri = self.fields.get("uri")
  111. nonce = self.fields.get("nonce")
  112. cnonce = self.fields.get("cnonce")
  113. nc = self.fields.get("nc")
  114. algo = self.fields.get("algorithm", b"md5").lower()
  115. qop = self.fields.get("qop", b"auth")
  116. expected = calcResponse(
  117. calcHA1(algo, self.username, self.realm, password, nonce, cnonce),
  118. calcHA2(algo, self.method, uri, qop, None),
  119. algo,
  120. nonce,
  121. nc,
  122. cnonce,
  123. qop,
  124. )
  125. return expected == response
  126. def checkHash(self, digestHash):
  127. """
  128. Verify that the credentials represented by this object agree with the
  129. credentials represented by the I{H(A1)} given in C{digestHash}.
  130. @param digestHash: A precomputed H(A1) value based on the username,
  131. realm, and password associate with this credentials object.
  132. """
  133. response = self.fields.get("response")
  134. uri = self.fields.get("uri")
  135. nonce = self.fields.get("nonce")
  136. cnonce = self.fields.get("cnonce")
  137. nc = self.fields.get("nc")
  138. algo = self.fields.get("algorithm", b"md5").lower()
  139. qop = self.fields.get("qop", b"auth")
  140. expected = calcResponse(
  141. calcHA1(algo, None, None, None, nonce, cnonce, preHA1=digestHash),
  142. calcHA2(algo, self.method, uri, qop, None),
  143. algo,
  144. nonce,
  145. nc,
  146. cnonce,
  147. qop,
  148. )
  149. return expected == response
  150. class DigestCredentialFactory:
  151. """
  152. Support for RFC2617 HTTP Digest Authentication
  153. @cvar CHALLENGE_LIFETIME_SECS: The number of seconds for which an
  154. opaque should be valid.
  155. @type privateKey: L{bytes}
  156. @ivar privateKey: A random string used for generating the secure opaque.
  157. @type algorithm: L{bytes}
  158. @param algorithm: Case insensitive string specifying the hash algorithm to
  159. use. Must be either C{'md5'} or C{'sha'}. C{'md5-sess'} is B{not}
  160. supported.
  161. @type authenticationRealm: L{bytes}
  162. @param authenticationRealm: case sensitive string that specifies the realm
  163. portion of the challenge
  164. """
  165. _parseparts = re.compile(
  166. b"([^= ]+)" # The key
  167. b"=" # Conventional key/value separator (literal)
  168. b"(?:" # Group together a couple options
  169. b'"([^"]*)"' # A quoted string of length 0 or more
  170. b"|" # The other option in the group is coming
  171. b"([^,]+)" # An unquoted string of length 1 or more, up to a comma
  172. b")" # That non-matching group ends
  173. b",?"
  174. ) # There might be a comma at the end (none on last pair)
  175. CHALLENGE_LIFETIME_SECS = 15 * 60 # 15 minutes
  176. scheme = b"digest"
  177. def __init__(self, algorithm, authenticationRealm):
  178. self.algorithm = algorithm
  179. self.authenticationRealm = authenticationRealm
  180. self.privateKey = secureRandom(12)
  181. def getChallenge(self, address):
  182. """
  183. Generate the challenge for use in the WWW-Authenticate header.
  184. @param address: The client address to which this challenge is being
  185. sent.
  186. @return: The L{dict} that can be used to generate a WWW-Authenticate
  187. header.
  188. """
  189. c = self._generateNonce()
  190. o = self._generateOpaque(c, address)
  191. return {
  192. "nonce": c,
  193. "opaque": o,
  194. "qop": b"auth",
  195. "algorithm": self.algorithm,
  196. "realm": self.authenticationRealm,
  197. }
  198. def _generateNonce(self):
  199. """
  200. Create a random value suitable for use as the nonce parameter of a
  201. WWW-Authenticate challenge.
  202. @rtype: L{bytes}
  203. """
  204. return hexlify(secureRandom(12))
  205. def _getTime(self):
  206. """
  207. Parameterize the time based seed used in C{_generateOpaque}
  208. so we can deterministically unittest it's behavior.
  209. """
  210. return time.time()
  211. def _generateOpaque(self, nonce, clientip):
  212. """
  213. Generate an opaque to be returned to the client. This is a unique
  214. string that can be returned to us and verified.
  215. """
  216. # Now, what we do is encode the nonce, client ip and a timestamp in the
  217. # opaque value with a suitable digest.
  218. now = b"%d" % (int(self._getTime()),)
  219. if not clientip:
  220. clientip = b""
  221. elif isinstance(clientip, str):
  222. clientip = clientip.encode("ascii")
  223. key = b",".join((nonce, clientip, now))
  224. digest = hexlify(md5(key + self.privateKey).digest())
  225. ekey = base64.b64encode(key)
  226. return b"-".join((digest, ekey.replace(b"\n", b"")))
  227. def _verifyOpaque(self, opaque, nonce, clientip):
  228. """
  229. Given the opaque and nonce from the request, as well as the client IP
  230. that made the request, verify that the opaque was generated by us.
  231. And that it's not too old.
  232. @param opaque: The opaque value from the Digest response
  233. @param nonce: The nonce value from the Digest response
  234. @param clientip: The remote IP address of the client making the request
  235. or L{None} if the request was submitted over a channel where this
  236. does not make sense.
  237. @return: C{True} if the opaque was successfully verified.
  238. @raise error.LoginFailed: if C{opaque} could not be parsed or
  239. contained the wrong values.
  240. """
  241. # First split the digest from the key
  242. opaqueParts = opaque.split(b"-")
  243. if len(opaqueParts) != 2:
  244. raise error.LoginFailed("Invalid response, invalid opaque value")
  245. if not clientip:
  246. clientip = b""
  247. elif isinstance(clientip, str):
  248. clientip = clientip.encode("ascii")
  249. # Verify the key
  250. key = base64.b64decode(opaqueParts[1])
  251. keyParts = key.split(b",")
  252. if len(keyParts) != 3:
  253. raise error.LoginFailed("Invalid response, invalid opaque value")
  254. if keyParts[0] != nonce:
  255. raise error.LoginFailed(
  256. "Invalid response, incompatible opaque/nonce values"
  257. )
  258. if keyParts[1] != clientip:
  259. raise error.LoginFailed(
  260. "Invalid response, incompatible opaque/client values"
  261. )
  262. try:
  263. when = int(keyParts[2])
  264. except ValueError:
  265. raise error.LoginFailed("Invalid response, invalid opaque/time values")
  266. if (
  267. int(self._getTime()) - when
  268. > DigestCredentialFactory.CHALLENGE_LIFETIME_SECS
  269. ):
  270. raise error.LoginFailed(
  271. "Invalid response, incompatible opaque/nonce too old"
  272. )
  273. # Verify the digest
  274. digest = hexlify(md5(key + self.privateKey).digest())
  275. if digest != opaqueParts[0]:
  276. raise error.LoginFailed("Invalid response, invalid opaque value")
  277. return True
  278. def decode(self, response, method, host):
  279. """
  280. Decode the given response and attempt to generate a
  281. L{DigestedCredentials} from it.
  282. @type response: L{bytes}
  283. @param response: A string of comma separated key=value pairs
  284. @type method: L{bytes}
  285. @param method: The action requested to which this response is addressed
  286. (GET, POST, INVITE, OPTIONS, etc).
  287. @type host: L{bytes}
  288. @param host: The address the request was sent from.
  289. @raise error.LoginFailed: If the response does not contain a username,
  290. a nonce, an opaque, or if the opaque is invalid.
  291. @return: L{DigestedCredentials}
  292. """
  293. response = b" ".join(response.splitlines())
  294. parts = self._parseparts.findall(response)
  295. auth = {}
  296. for (key, bare, quoted) in parts:
  297. value = (quoted or bare).strip()
  298. auth[nativeString(key.strip())] = value
  299. username = auth.get("username")
  300. if not username:
  301. raise error.LoginFailed("Invalid response, no username given.")
  302. if "opaque" not in auth:
  303. raise error.LoginFailed("Invalid response, no opaque given.")
  304. if "nonce" not in auth:
  305. raise error.LoginFailed("Invalid response, no nonce given.")
  306. # Now verify the nonce/opaque values for this client
  307. if self._verifyOpaque(auth.get("opaque"), auth.get("nonce"), host):
  308. return DigestedCredentials(username, method, self.authenticationRealm, auth)
  309. @implementer(IUsernameHashedPassword)
  310. class CramMD5Credentials:
  311. """
  312. An encapsulation of some CramMD5 hashed credentials.
  313. @ivar challenge: The challenge to be sent to the client.
  314. @type challenge: L{bytes}
  315. @ivar response: The hashed response from the client.
  316. @type response: L{bytes}
  317. @ivar username: The username from the response from the client.
  318. @type username: L{bytes} or L{None} if not yet provided.
  319. """
  320. username = None
  321. challenge = b""
  322. response = b""
  323. def __init__(self, host=None):
  324. self.host = host
  325. def getChallenge(self):
  326. if self.challenge:
  327. return self.challenge
  328. # The data encoded in the first ready response contains an
  329. # presumptively arbitrary string of random digits, a timestamp, and
  330. # the fully-qualified primary host name of the server. The syntax of
  331. # the unencoded form must correspond to that of an RFC 822 'msg-id'
  332. # [RFC822] as described in [POP3].
  333. # -- RFC 2195
  334. r = random.randrange(0x7FFFFFFF)
  335. t = time.time()
  336. self.challenge = networkString(
  337. "<%d.%d@%s>" % (r, t, nativeString(self.host) if self.host else None)
  338. )
  339. return self.challenge
  340. def setResponse(self, response):
  341. self.username, self.response = response.split(None, 1)
  342. def moreChallenges(self):
  343. return False
  344. def checkPassword(self, password):
  345. verify = hexlify(hmac.HMAC(password, self.challenge, digestmod=md5).digest())
  346. return verify == self.response
  347. @implementer(IUsernameHashedPassword)
  348. class UsernameHashedPassword:
  349. deprecatedModuleAttribute(
  350. Version("Twisted", 21, 2, 0),
  351. "Use twisted.cred.credentials.UsernamePassword instead.",
  352. "twisted.cred.credentials",
  353. "UsernameHashedPassword",
  354. )
  355. def __init__(self, username, hashed):
  356. self.username = username
  357. self.hashed = hashed
  358. def checkPassword(self, password):
  359. return self.hashed == password
  360. @implementer(IUsernamePassword)
  361. class UsernamePassword:
  362. def __init__(self, username, password):
  363. self.username = username
  364. self.password = password
  365. def checkPassword(self, password):
  366. return self.password == password
  367. @implementer(IAnonymous)
  368. class Anonymous:
  369. pass
  370. class ISSHPrivateKey(ICredentials):
  371. """
  372. L{ISSHPrivateKey} credentials encapsulate an SSH public key to be checked
  373. against a user's private key.
  374. @ivar username: The username associated with these credentials.
  375. @type username: L{bytes}
  376. @ivar algName: The algorithm name for the blob.
  377. @type algName: L{bytes}
  378. @ivar blob: The public key blob as sent by the client.
  379. @type blob: L{bytes}
  380. @ivar sigData: The data the signature was made from.
  381. @type sigData: L{bytes}
  382. @ivar signature: The signed data. This is checked to verify that the user
  383. owns the private key.
  384. @type signature: L{bytes} or L{None}
  385. """
  386. @implementer(ISSHPrivateKey)
  387. class SSHPrivateKey:
  388. def __init__(self, username, algName, blob, sigData, signature):
  389. self.username = username
  390. self.algName = algName
  391. self.blob = blob
  392. self.sigData = sigData
  393. self.signature = signature