Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/trunk/cherrypy/lib/httpauth.py

Revision 2034 (checked in by fumanchu, 2 months ago)

Typo in httpauth.py

  • Property svn:eol-style set to native
Line 
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, 1
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 nc MUST be present
145     if params.has_key("qop") and not (params.has_key("cnonce") \
146                                       and params.has_key("nc")):
147         return None
148
149     # If qop is not sent, neither cnonce nor nc can be present
150     if (params.has_key("cnonce") or params.has_key("nc")) and \
151        not params.has_key("qop"):
152         return None
153
154     return params
155
156
157 def _parseBasicAuthorization (auth_params):
158     username, password = base64.decodestring (auth_params).split (":", 1)
159     return {"username": username, "password": password}
160
161 AUTH_SCHEMES = {
162     "basic": _parseBasicAuthorization,
163     "digest": _parseDigestAuthorization,
164 }
165
166 def parseAuthorization (credentials):
167     """parseAuthorization will convert the value of the 'Authorization' key in
168     the HTTP header to a map itself. If the parsing fails 'None' is returned.
169     """
170
171     global AUTH_SCHEMES
172
173     auth_scheme, auth_params  = credentials.split(" ", 1)
174     auth_scheme = auth_scheme.lower ()
175
176     parser = AUTH_SCHEMES[auth_scheme]
177     params = parser (auth_params)
178
179     if params is None:
180         return
181
182     assert "auth_scheme" not in params
183     params["auth_scheme"] = auth_scheme
184     return params
185
186
187 ################################################################################
188 # Check provided response for a valid password
189 #
190 def md5SessionKey (params, password):
191     """
192     If the "algorithm" directive's value is "MD5-sess", then A1
193     [the session key] is calculated only once - on the first request by the
194     client following receipt of a WWW-Authenticate challenge from the server.
195
196     This creates a 'session key' for the authentication of subsequent
197     requests and responses which is different for each "authentication
198     session", thus limiting the amount of material hashed with any one
199     key.
200
201     Because the server need only use the hash of the user
202     credentials in order to create the A1 value, this construction could
203     be used in conjunction with a third party authentication service so
204     that the web server would not need the actual password value.  The
205     specification of such a protocol is beyond the scope of this
206     specification.
207 """
208
209     keys = ("username", "realm", "nonce", "cnonce")
210     params_copy = {}
211     for key in keys:
212         params_copy[key] = params[key]
213
214     params_copy["algorithm"] = MD5_SESS
215     return _A1 (params_copy, password)
216
217 def _A1(params, password):
218     algorithm = params.get ("algorithm", MD5)
219     H = DIGEST_AUTH_ENCODERS[algorithm]
220
221     if algorithm == MD5:
222         # If the "algorithm" directive's value is "MD5" or is
223         # unspecified, then A1 is:
224         # A1 = unq(username-value) ":" unq(realm-value) ":" passwd
225         return "%s:%s:%s" % (params["username"], params["realm"], password)
226
227     elif algorithm == MD5_SESS:
228
229         # This is A1 if qop is set
230         # A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd )
231         #         ":" unq(nonce-value) ":" unq(cnonce-value)
232         h_a1 = H ("%s:%s:%s" % (params["username"], params["realm"], password))
233         return "%s:%s:%s" % (h_a1, params["nonce"], params["cnonce"])
234
235
236 def _A2(params, method, kwargs):
237     # If the "qop" directive's value is "auth" or is unspecified, then A2 is:
238     # A2 = Method ":" digest-uri-value
239
240     qop = params.get ("qop", "auth")
241     if qop == "auth":
242         return method + ":" + params["uri"]
243     elif qop == "auth-int":
244         # If the "qop" value is "auth-int", then A2 is:
245         # A2 = Method ":" digest-uri-value ":" H(entity-body)
246         entity_body = kwargs.get ("entity_body", "")
247         H = kwargs["H"]
248
249         return "%s:%s:%s" % (
250             method,
251             params["uri"],
252             H(entity_body)
253         )
254
255     else:
256         raise NotImplementedError ("The 'qop' method is unknown: %s" % qop)
257
258 def _computeDigestResponse(auth_map, password, method = "GET", A1 = None,**kwargs):
259     """
260     Generates a response respecting the algorithm defined in RFC 2617
261     """
262     params = auth_map
263
264     algorithm = params.get ("algorithm", MD5)
265
266     H = DIGEST_AUTH_ENCODERS[algorithm]
267     KD = lambda secret, data: H(secret + ":" + data)
268
269     qop = params.get ("qop", None)
270
271     H_A2 = H(_A2(params, method, kwargs))
272
273     if algorithm == MD5_SESS and A1 is not None:
274         H_A1 = H(A1)
275     else:
276         H_A1 = H(_A1(params, password))
277
278     if qop in ("auth", "auth-int"):
279         # If the "qop" value is "auth" or "auth-int":
280         # request-digest  = <"> < KD ( H(A1),     unq(nonce-value)
281         #                              ":" nc-value
282         #                              ":" unq(cnonce-value)
283         #                              ":" unq(qop-value)
284         #                              ":" H(A2)
285         #                      ) <">
286         request = "%s:%s:%s:%s:%s" % (
287             params["nonce"],
288             params["nc"],
289             params["cnonce"],
290             params["qop"],
291             H_A2,
292         )
293     elif qop is None:
294         # If the "qop" directive is not present (this construction is
295         # for compatibility with RFC 2069):
296         # request-digest  =
297         #         <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
298         request = "%s:%s" % (params["nonce"], H_A2)
299
300     return KD(H_A1, request)
301
302 def _checkDigestResponse(auth_map, password, method = "GET", A1 = None, **kwargs):
303     """This function is used to verify the response given by the client when
304     he tries to authenticate.
305     Optional arguments:
306      entity_body - when 'qop' is set to 'auth-int' you MUST provide the
307                    raw data you are going to send to the client (usually the
308                    HTML page.
309      request_uri - the uri from the request line compared with the 'uri'
310                    directive of the authorization map. They must represent
311                    the same resource (unused at this time).
312     """
313
314     if auth_map['realm'] != kwargs.get('realm', None):
315         return False
316
317     response =  _computeDigestResponse(auth_map, password, method, A1,**kwargs)
318
319     return response == auth_map["response"]
320
321 def _checkBasicResponse (auth_map, password, method='GET', encrypt=None, **kwargs):
322     # Note that the Basic response doesn't provide the realm value so we cannot
323     # test it
324     try:
325         return encrypt(auth_map["password"], auth_map["username"]) == password
326     except TypeError:
327         return encrypt(auth_map["password"]) == password
328
329 AUTH_RESPONSES = {
330     "basic": _checkBasicResponse,
331     "digest": _checkDigestResponse,
332 }
333
334 def checkResponse (auth_map, password, method = "GET", encrypt=None, **kwargs):
335     """'checkResponse' compares the auth_map with the password and optionally
336     other arguments that each implementation might need.
337     
338     If the response is of type 'Basic' then the function has the following
339     signature:
340     
341     checkBasicResponse (auth_map, password) -> bool
342     
343     If the response is of type 'Digest' then the function has the following
344     signature:
345     
346     checkDigestResponse (auth_map, password, method = 'GET', A1 = None) -> bool
347     
348     The 'A1' argument is only used in MD5_SESS algorithm based responses.
349     Check md5SessionKey() for more info.
350     """
351     global AUTH_RESPONSES
352     checker = AUTH_RESPONSES[auth_map["auth_scheme"]]
353     return checker (auth_map, password, method=method, encrypt=encrypt, **kwargs)
354  
355
356
357
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets