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