credentials.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. from __future__ import division, absolute_import
  10. from zope.interface import implementer, Interface
  11. import base64
  12. import hmac
  13. import random
  14. import re
  15. import time
  16. from binascii import hexlify
  17. from hashlib import md5
  18. from twisted.python.randbytes import secureRandom
  19. from twisted.python.compat import networkString, nativeString
  20. from twisted.python.compat import intToBytes, unicode
  21. from twisted.cred._digest import calcResponse, calcHA1, calcHA2
  22. from twisted.cred import error
  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.declarations.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(object):
  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, nonce, nc, cnonce, qop)
  120. return expected == response
  121. def checkHash(self, digestHash):
  122. """
  123. Verify that the credentials represented by this object agree with the
  124. credentials represented by the I{H(A1)} given in C{digestHash}.
  125. @param digestHash: A precomputed H(A1) value based on the username,
  126. realm, and password associate with this credentials object.
  127. """
  128. response = self.fields.get('response')
  129. uri = self.fields.get('uri')
  130. nonce = self.fields.get('nonce')
  131. cnonce = self.fields.get('cnonce')
  132. nc = self.fields.get('nc')
  133. algo = self.fields.get('algorithm', b'md5').lower()
  134. qop = self.fields.get('qop', b'auth')
  135. expected = calcResponse(
  136. calcHA1(algo, None, None, None, nonce, cnonce, preHA1=digestHash),
  137. calcHA2(algo, self.method, uri, qop, None),
  138. algo, nonce, nc, cnonce, qop)
  139. return expected == response
  140. class DigestCredentialFactory(object):
  141. """
  142. Support for RFC2617 HTTP Digest Authentication
  143. @cvar CHALLENGE_LIFETIME_SECS: The number of seconds for which an
  144. opaque should be valid.
  145. @type privateKey: L{bytes}
  146. @ivar privateKey: A random string used for generating the secure opaque.
  147. @type algorithm: L{bytes}
  148. @param algorithm: Case insensitive string specifying the hash algorithm to
  149. use. Must be either C{'md5'} or C{'sha'}. C{'md5-sess'} is B{not}
  150. supported.
  151. @type authenticationRealm: L{bytes}
  152. @param authenticationRealm: case sensitive string that specifies the realm
  153. portion of the challenge
  154. """
  155. _parseparts = re.compile(
  156. b'([^= ]+)' # The key
  157. b'=' # Conventional key/value separator (literal)
  158. b'(?:' # Group together a couple options
  159. b'"([^"]*)"' # A quoted string of length 0 or more
  160. b'|' # The other option in the group is coming
  161. b'([^,]+)' # An unquoted string of length 1 or more, up to a comma
  162. b')' # That non-matching group ends
  163. b',?') # There might be a comma at the end (none on last pair)
  164. CHALLENGE_LIFETIME_SECS = 15 * 60 # 15 minutes
  165. scheme = b"digest"
  166. def __init__(self, algorithm, authenticationRealm):
  167. self.algorithm = algorithm
  168. self.authenticationRealm = authenticationRealm
  169. self.privateKey = secureRandom(12)
  170. def getChallenge(self, address):
  171. """
  172. Generate the challenge for use in the WWW-Authenticate header.
  173. @param address: The client address to which this challenge is being
  174. sent.
  175. @return: The L{dict} that can be used to generate a WWW-Authenticate
  176. header.
  177. """
  178. c = self._generateNonce()
  179. o = self._generateOpaque(c, address)
  180. return {'nonce': c,
  181. 'opaque': o,
  182. 'qop': b'auth',
  183. 'algorithm': self.algorithm,
  184. 'realm': self.authenticationRealm}
  185. def _generateNonce(self):
  186. """
  187. Create a random value suitable for use as the nonce parameter of a
  188. WWW-Authenticate challenge.
  189. @rtype: L{bytes}
  190. """
  191. return hexlify(secureRandom(12))
  192. def _getTime(self):
  193. """
  194. Parameterize the time based seed used in C{_generateOpaque}
  195. so we can deterministically unittest it's behavior.
  196. """
  197. return time.time()
  198. def _generateOpaque(self, nonce, clientip):
  199. """
  200. Generate an opaque to be returned to the client. This is a unique
  201. string that can be returned to us and verified.
  202. """
  203. # Now, what we do is encode the nonce, client ip and a timestamp in the
  204. # opaque value with a suitable digest.
  205. now = intToBytes(int(self._getTime()))
  206. if not clientip:
  207. clientip = b''
  208. elif isinstance(clientip, unicode):
  209. clientip = clientip.encode('ascii')
  210. key = b",".join((nonce, clientip, now))
  211. digest = hexlify(md5(key + self.privateKey).digest())
  212. ekey = base64.b64encode(key)
  213. return b"-".join((digest, ekey.replace(b'\n', b'')))
  214. def _verifyOpaque(self, opaque, nonce, clientip):
  215. """
  216. Given the opaque and nonce from the request, as well as the client IP
  217. that made the request, verify that the opaque was generated by us.
  218. And that it's not too old.
  219. @param opaque: The opaque value from the Digest response
  220. @param nonce: The nonce value from the Digest response
  221. @param clientip: The remote IP address of the client making the request
  222. or L{None} if the request was submitted over a channel where this
  223. does not make sense.
  224. @return: C{True} if the opaque was successfully verified.
  225. @raise error.LoginFailed: if C{opaque} could not be parsed or
  226. contained the wrong values.
  227. """
  228. # First split the digest from the key
  229. opaqueParts = opaque.split(b'-')
  230. if len(opaqueParts) != 2:
  231. raise error.LoginFailed('Invalid response, invalid opaque value')
  232. if not clientip:
  233. clientip = b''
  234. elif isinstance(clientip, unicode):
  235. clientip = clientip.encode('ascii')
  236. # Verify the key
  237. key = base64.b64decode(opaqueParts[1])
  238. keyParts = key.split(b',')
  239. if len(keyParts) != 3:
  240. raise error.LoginFailed('Invalid response, invalid opaque value')
  241. if keyParts[0] != nonce:
  242. raise error.LoginFailed(
  243. 'Invalid response, incompatible opaque/nonce values')
  244. if keyParts[1] != clientip:
  245. raise error.LoginFailed(
  246. 'Invalid response, incompatible opaque/client values')
  247. try:
  248. when = int(keyParts[2])
  249. except ValueError:
  250. raise error.LoginFailed(
  251. 'Invalid response, invalid opaque/time values')
  252. if (int(self._getTime()) - when >
  253. DigestCredentialFactory.CHALLENGE_LIFETIME_SECS):
  254. raise error.LoginFailed(
  255. 'Invalid response, incompatible opaque/nonce too old')
  256. # Verify the digest
  257. digest = hexlify(md5(key + self.privateKey).digest())
  258. if digest != opaqueParts[0]:
  259. raise error.LoginFailed('Invalid response, invalid opaque value')
  260. return True
  261. def decode(self, response, method, host):
  262. """
  263. Decode the given response and attempt to generate a
  264. L{DigestedCredentials} from it.
  265. @type response: L{bytes}
  266. @param response: A string of comma separated key=value pairs
  267. @type method: L{bytes}
  268. @param method: The action requested to which this response is addressed
  269. (GET, POST, INVITE, OPTIONS, etc).
  270. @type host: L{bytes}
  271. @param host: The address the request was sent from.
  272. @raise error.LoginFailed: If the response does not contain a username,
  273. a nonce, an opaque, or if the opaque is invalid.
  274. @return: L{DigestedCredentials}
  275. """
  276. response = b' '.join(response.splitlines())
  277. parts = self._parseparts.findall(response)
  278. auth = {}
  279. for (key, bare, quoted) in parts:
  280. value = (quoted or bare).strip()
  281. auth[nativeString(key.strip())] = value
  282. username = auth.get('username')
  283. if not username:
  284. raise error.LoginFailed('Invalid response, no username given.')
  285. if 'opaque' not in auth:
  286. raise error.LoginFailed('Invalid response, no opaque given.')
  287. if 'nonce' not in auth:
  288. raise error.LoginFailed('Invalid response, no nonce given.')
  289. # Now verify the nonce/opaque values for this client
  290. if self._verifyOpaque(auth.get('opaque'), auth.get('nonce'), host):
  291. return DigestedCredentials(username,
  292. method,
  293. self.authenticationRealm,
  294. auth)
  295. @implementer(IUsernameHashedPassword)
  296. class CramMD5Credentials(object):
  297. """
  298. An encapsulation of some CramMD5 hashed credentials.
  299. @ivar challenge: The challenge to be sent to the client.
  300. @type challenge: L{bytes}
  301. @ivar response: The hashed response from the client.
  302. @type response: L{bytes}
  303. @ivar username: The username from the response from the client.
  304. @type username: L{bytes} or L{None} if not yet provided.
  305. """
  306. username = None
  307. challenge = b''
  308. response = b''
  309. def __init__(self, host=None):
  310. self.host = host
  311. def getChallenge(self):
  312. if self.challenge:
  313. return self.challenge
  314. # The data encoded in the first ready response contains an
  315. # presumptively arbitrary string of random digits, a timestamp, and
  316. # the fully-qualified primary host name of the server. The syntax of
  317. # the unencoded form must correspond to that of an RFC 822 'msg-id'
  318. # [RFC822] as described in [POP3].
  319. # -- RFC 2195
  320. r = random.randrange(0x7fffffff)
  321. t = time.time()
  322. self.challenge = networkString('<%d.%d@%s>' % (
  323. r, t, nativeString(self.host) if self.host else None))
  324. return self.challenge
  325. def setResponse(self, response):
  326. self.username, self.response = response.split(None, 1)
  327. def moreChallenges(self):
  328. return False
  329. def checkPassword(self, password):
  330. verify = hexlify(hmac.HMAC(password, self.challenge).digest())
  331. return verify == self.response
  332. @implementer(IUsernameHashedPassword)
  333. class UsernameHashedPassword:
  334. def __init__(self, username, hashed):
  335. self.username = username
  336. self.hashed = hashed
  337. def checkPassword(self, password):
  338. return self.hashed == password
  339. @implementer(IUsernamePassword)
  340. class UsernamePassword:
  341. def __init__(self, username, password):
  342. self.username = username
  343. self.password = password
  344. def checkPassword(self, password):
  345. return self.password == password
  346. @implementer(IAnonymous)
  347. class Anonymous:
  348. pass
  349. class ISSHPrivateKey(ICredentials):
  350. """
  351. L{ISSHPrivateKey} credentials encapsulate an SSH public key to be checked
  352. against a user's private key.
  353. @ivar username: The username associated with these credentials.
  354. @type username: L{bytes}
  355. @ivar algName: The algorithm name for the blob.
  356. @type algName: L{bytes}
  357. @ivar blob: The public key blob as sent by the client.
  358. @type blob: L{bytes}
  359. @ivar sigData: The data the signature was made from.
  360. @type sigData: L{bytes}
  361. @ivar signature: The signed data. This is checked to verify that the user
  362. owns the private key.
  363. @type signature: L{bytes} or L{None}
  364. """
  365. @implementer(ISSHPrivateKey)
  366. class SSHPrivateKey:
  367. def __init__(self, username, algName, blob, sigData, signature):
  368. self.username = username
  369. self.algName = algName
  370. self.blob = blob
  371. self.sigData = sigData
  372. self.signature = signature