PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/koldstart/kode/cherrypy/lib/httpauth.py

https://github.com/Eckankar/HCI-koldskaal
Python | 363 lines | 337 code | 9 blank | 17 comment | 6 complexity | e32484af7815ee27f966097305544a52 MD5 | raw file
  1. """
  2. httpauth modules defines functions to implement HTTP Digest Authentication (RFC 2617).
  3. This has full compliance with 'Digest' and 'Basic' authentication methods. In
  4. 'Digest' it supports both MD5 and MD5-sess algorithms.
  5. Usage:
  6. First use 'doAuth' to request the client authentication for a
  7. certain resource. You should send an httplib.UNAUTHORIZED response to the
  8. client so he knows he has to authenticate itself.
  9. Then use 'parseAuthorization' to retrieve the 'auth_map' used in
  10. 'checkResponse'.
  11. To use 'checkResponse' you must have already verified the password associated
  12. with the 'username' key in 'auth_map' dict. Then you use the 'checkResponse'
  13. function to verify if the password matches the one sent by the client.
  14. SUPPORTED_ALGORITHM - list of supported 'Digest' algorithms
  15. SUPPORTED_QOP - list of supported 'Digest' 'qop'.
  16. """
  17. __version__ = 1, 0, 1
  18. __author__ = "Tiago Cogumbreiro <cogumbreiro@users.sf.net>"
  19. __credits__ = """
  20. Peter van Kampen for its recipe which implement most of Digest authentication:
  21. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302378
  22. """
  23. __license__ = """
  24. Copyright (c) 2005, Tiago Cogumbreiro <cogumbreiro@users.sf.net>
  25. All rights reserved.
  26. Redistribution and use in source and binary forms, with or without modification,
  27. are permitted provided that the following conditions are met:
  28. * Redistributions of source code must retain the above copyright notice,
  29. this list of conditions and the following disclaimer.
  30. * Redistributions in binary form must reproduce the above copyright notice,
  31. this list of conditions and the following disclaimer in the documentation
  32. and/or other materials provided with the distribution.
  33. * Neither the name of Sylvain Hellegouarch nor the names of his contributors
  34. may be used to endorse or promote products derived from this software
  35. without specific prior written permission.
  36. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  37. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  38. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  40. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  41. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  42. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  43. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  45. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  46. """
  47. __all__ = ("digestAuth", "basicAuth", "doAuth", "checkResponse",
  48. "parseAuthorization", "SUPPORTED_ALGORITHM", "md5SessionKey",
  49. "calculateNonce", "SUPPORTED_QOP")
  50. ################################################################################
  51. try:
  52. # Python 2.5+
  53. from hashlib import md5
  54. except ImportError:
  55. from md5 import new as md5
  56. import time
  57. import base64
  58. import urllib2
  59. MD5 = "MD5"
  60. MD5_SESS = "MD5-sess"
  61. AUTH = "auth"
  62. AUTH_INT = "auth-int"
  63. SUPPORTED_ALGORITHM = (MD5, MD5_SESS)
  64. SUPPORTED_QOP = (AUTH, AUTH_INT)
  65. ################################################################################
  66. # doAuth
  67. #
  68. DIGEST_AUTH_ENCODERS = {
  69. MD5: lambda val: md5(val).hexdigest(),
  70. MD5_SESS: lambda val: md5(val).hexdigest(),
  71. # SHA: lambda val: sha(val).hexdigest(),
  72. }
  73. def calculateNonce (realm, algorithm = MD5):
  74. """This is an auxaliary function that calculates 'nonce' value. It is used
  75. to handle sessions."""
  76. global SUPPORTED_ALGORITHM, DIGEST_AUTH_ENCODERS
  77. assert algorithm in SUPPORTED_ALGORITHM
  78. try:
  79. encoder = DIGEST_AUTH_ENCODERS[algorithm]
  80. except KeyError:
  81. raise NotImplementedError ("The chosen algorithm (%s) does not have "\
  82. "an implementation yet" % algorithm)
  83. return encoder ("%d:%s" % (time.time(), realm))
  84. def digestAuth (realm, algorithm = MD5, nonce = None, qop = AUTH):
  85. """Challenges the client for a Digest authentication."""
  86. global SUPPORTED_ALGORITHM, DIGEST_AUTH_ENCODERS, SUPPORTED_QOP
  87. assert algorithm in SUPPORTED_ALGORITHM
  88. assert qop in SUPPORTED_QOP
  89. if nonce is None:
  90. nonce = calculateNonce (realm, algorithm)
  91. return 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"' % (
  92. realm, nonce, algorithm, qop
  93. )
  94. def basicAuth (realm):
  95. """Challengenes the client for a Basic authentication."""
  96. assert '"' not in realm, "Realms cannot contain the \" (quote) character."
  97. return 'Basic realm="%s"' % realm
  98. def doAuth (realm):
  99. """'doAuth' function returns the challenge string b giving priority over
  100. Digest and fallback to Basic authentication when the browser doesn't
  101. support the first one.
  102. This should be set in the HTTP header under the key 'WWW-Authenticate'."""
  103. return digestAuth (realm) + " " + basicAuth (realm)
  104. ################################################################################
  105. # Parse authorization parameters
  106. #
  107. def _parseDigestAuthorization (auth_params):
  108. # Convert the auth params to a dict
  109. items = urllib2.parse_http_list (auth_params)
  110. params = urllib2.parse_keqv_list (items)
  111. # Now validate the params
  112. # Check for required parameters
  113. required = ["username", "realm", "nonce", "uri", "response"]
  114. for k in required:
  115. if not params.has_key(k):
  116. return None
  117. # If qop is sent then cnonce and nc MUST be present
  118. if params.has_key("qop") and not (params.has_key("cnonce") \
  119. and params.has_key("nc")):
  120. return None
  121. # If qop is not sent, neither cnonce nor nc can be present
  122. if (params.has_key("cnonce") or params.has_key("nc")) and \
  123. not params.has_key("qop"):
  124. return None
  125. return params
  126. def _parseBasicAuthorization (auth_params):
  127. username, password = base64.decodestring (auth_params).split (":", 1)
  128. return {"username": username, "password": password}
  129. AUTH_SCHEMES = {
  130. "basic": _parseBasicAuthorization,
  131. "digest": _parseDigestAuthorization,
  132. }
  133. def parseAuthorization (credentials):
  134. """parseAuthorization will convert the value of the 'Authorization' key in
  135. the HTTP header to a map itself. If the parsing fails 'None' is returned.
  136. """
  137. global AUTH_SCHEMES
  138. auth_scheme, auth_params = credentials.split(" ", 1)
  139. auth_scheme = auth_scheme.lower ()
  140. parser = AUTH_SCHEMES[auth_scheme]
  141. params = parser (auth_params)
  142. if params is None:
  143. return
  144. assert "auth_scheme" not in params
  145. params["auth_scheme"] = auth_scheme
  146. return params
  147. ################################################################################
  148. # Check provided response for a valid password
  149. #
  150. def md5SessionKey (params, password):
  151. """
  152. If the "algorithm" directive's value is "MD5-sess", then A1
  153. [the session key] is calculated only once - on the first request by the
  154. client following receipt of a WWW-Authenticate challenge from the server.
  155. This creates a 'session key' for the authentication of subsequent
  156. requests and responses which is different for each "authentication
  157. session", thus limiting the amount of material hashed with any one
  158. key.
  159. Because the server need only use the hash of the user
  160. credentials in order to create the A1 value, this construction could
  161. be used in conjunction with a third party authentication service so
  162. that the web server would not need the actual password value. The
  163. specification of such a protocol is beyond the scope of this
  164. specification.
  165. """
  166. keys = ("username", "realm", "nonce", "cnonce")
  167. params_copy = {}
  168. for key in keys:
  169. params_copy[key] = params[key]
  170. params_copy["algorithm"] = MD5_SESS
  171. return _A1 (params_copy, password)
  172. def _A1(params, password):
  173. algorithm = params.get ("algorithm", MD5)
  174. H = DIGEST_AUTH_ENCODERS[algorithm]
  175. if algorithm == MD5:
  176. # If the "algorithm" directive's value is "MD5" or is
  177. # unspecified, then A1 is:
  178. # A1 = unq(username-value) ":" unq(realm-value) ":" passwd
  179. return "%s:%s:%s" % (params["username"], params["realm"], password)
  180. elif algorithm == MD5_SESS:
  181. # This is A1 if qop is set
  182. # A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
  183. # ":" unq(nonce-value) ":" unq(cnonce-value)
  184. h_a1 = H ("%s:%s:%s" % (params["username"], params["realm"], password))
  185. return "%s:%s:%s" % (h_a1, params["nonce"], params["cnonce"])
  186. def _A2(params, method, kwargs):
  187. # If the "qop" directive's value is "auth" or is unspecified, then A2 is:
  188. # A2 = Method ":" digest-uri-value
  189. qop = params.get ("qop", "auth")
  190. if qop == "auth":
  191. return method + ":" + params["uri"]
  192. elif qop == "auth-int":
  193. # If the "qop" value is "auth-int", then A2 is:
  194. # A2 = Method ":" digest-uri-value ":" H(entity-body)
  195. entity_body = kwargs.get ("entity_body", "")
  196. H = kwargs["H"]
  197. return "%s:%s:%s" % (
  198. method,
  199. params["uri"],
  200. H(entity_body)
  201. )
  202. else:
  203. raise NotImplementedError ("The 'qop' method is unknown: %s" % qop)
  204. def _computeDigestResponse(auth_map, password, method = "GET", A1 = None,**kwargs):
  205. """
  206. Generates a response respecting the algorithm defined in RFC 2617
  207. """
  208. params = auth_map
  209. algorithm = params.get ("algorithm", MD5)
  210. H = DIGEST_AUTH_ENCODERS[algorithm]
  211. KD = lambda secret, data: H(secret + ":" + data)
  212. qop = params.get ("qop", None)
  213. H_A2 = H(_A2(params, method, kwargs))
  214. if algorithm == MD5_SESS and A1 is not None:
  215. H_A1 = H(A1)
  216. else:
  217. H_A1 = H(_A1(params, password))
  218. if qop in ("auth", "auth-int"):
  219. # If the "qop" value is "auth" or "auth-int":
  220. # request-digest = <"> < KD ( H(A1), unq(nonce-value)
  221. # ":" nc-value
  222. # ":" unq(cnonce-value)
  223. # ":" unq(qop-value)
  224. # ":" H(A2)
  225. # ) <">
  226. request = "%s:%s:%s:%s:%s" % (
  227. params["nonce"],
  228. params["nc"],
  229. params["cnonce"],
  230. params["qop"],
  231. H_A2,
  232. )
  233. elif qop is None:
  234. # If the "qop" directive is not present (this construction is
  235. # for compatibility with RFC 2069):
  236. # request-digest =
  237. # <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
  238. request = "%s:%s" % (params["nonce"], H_A2)
  239. return KD(H_A1, request)
  240. def _checkDigestResponse(auth_map, password, method = "GET", A1 = None, **kwargs):
  241. """This function is used to verify the response given by the client when
  242. he tries to authenticate.
  243. Optional arguments:
  244. entity_body - when 'qop' is set to 'auth-int' you MUST provide the
  245. raw data you are going to send to the client (usually the
  246. HTML page.
  247. request_uri - the uri from the request line compared with the 'uri'
  248. directive of the authorization map. They must represent
  249. the same resource (unused at this time).
  250. """
  251. if auth_map['realm'] != kwargs.get('realm', None):
  252. return False
  253. response = _computeDigestResponse(auth_map, password, method, A1,**kwargs)
  254. return response == auth_map["response"]
  255. def _checkBasicResponse (auth_map, password, method='GET', encrypt=None, **kwargs):
  256. # Note that the Basic response doesn't provide the realm value so we cannot
  257. # test it
  258. try:
  259. return encrypt(auth_map["password"], auth_map["username"]) == password
  260. except TypeError:
  261. return encrypt(auth_map["password"]) == password
  262. AUTH_RESPONSES = {
  263. "basic": _checkBasicResponse,
  264. "digest": _checkDigestResponse,
  265. }
  266. def checkResponse (auth_map, password, method = "GET", encrypt=None, **kwargs):
  267. """'checkResponse' compares the auth_map with the password and optionally
  268. other arguments that each implementation might need.
  269. If the response is of type 'Basic' then the function has the following
  270. signature:
  271. checkBasicResponse (auth_map, password) -> bool
  272. If the response is of type 'Digest' then the function has the following
  273. signature:
  274. checkDigestResponse (auth_map, password, method = 'GET', A1 = None) -> bool
  275. The 'A1' argument is only used in MD5_SESS algorithm based responses.
  276. Check md5SessionKey() for more info.
  277. """
  278. global AUTH_RESPONSES
  279. checker = AUTH_RESPONSES[auth_map["auth_scheme"]]
  280. return checker (auth_map, password, method=method, encrypt=encrypt, **kwargs)