| 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 |
|
|---|
| 77 |
|
|---|
| 78 |
DIGEST_AUTH_ENCODERS = { |
|---|
| 79 |
MD5: lambda val: md5.new (val).hexdigest (), |
|---|
| 80 |
MD5_SESS: lambda val: md5.new (val).hexdigest (), |
|---|
| 81 |
|
|---|
| 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 |
|
|---|
| 130 |
|
|---|
| 131 |
def _parseDigestAuthorization (auth_params): |
|---|
| 132 |
|
|---|
| 133 |
items = urllib2.parse_http_list (auth_params) |
|---|
| 134 |
params = urllib2.parse_keqv_list (items) |
|---|
| 135 |
|
|---|
| 136 |
|
|---|
| 137 |
|
|---|
| 138 |
|
|---|
| 139 |
required = ["username", "realm", "nonce", "uri", "response"] |
|---|
| 140 |
for k in required: |
|---|
| 141 |
if not params.has_key(k): |
|---|
| 142 |
return None |
|---|
| 143 |
|
|---|
| 144 |
|
|---|
| 145 |
if params.has_key("qop") and not (params.has_key("cnonce") \ |
|---|
| 146 |
and params.has_key("nc")): |
|---|
| 147 |
return None |
|---|
| 148 |
|
|---|
| 149 |
|
|---|
| 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 |
|
|---|
| 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 |
|
|---|
| 223 |
|
|---|
| 224 |
|
|---|
| 225 |
return "%s:%s:%s" % (params["username"], params["realm"], password) |
|---|
| 226 |
|
|---|
| 227 |
elif algorithm == MD5_SESS: |
|---|
| 228 |
|
|---|
| 229 |
|
|---|
| 230 |
|
|---|
| 231 |
|
|---|
| 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 |
|
|---|
| 238 |
|
|---|
| 239 |
|
|---|
| 240 |
qop = params.get ("qop", "auth") |
|---|
| 241 |
if qop == "auth": |
|---|
| 242 |
return method + ":" + params["uri"] |
|---|
| 243 |
elif qop == "auth-int": |
|---|
| 244 |
|
|---|
| 245 |
|
|---|
| 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 == "auth" or aop == "auth-int": |
|---|
| 279 |
|
|---|
| 280 |
|
|---|
| 281 |
|
|---|
| 282 |
|
|---|
| 283 |
|
|---|
| 284 |
|
|---|
| 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 |
|
|---|
| 294 |
elif qop is None: |
|---|
| 295 |
|
|---|
| 296 |
|
|---|
| 297 |
|
|---|
| 298 |
|
|---|
| 299 |
request = "%s:%s" % (params["nonce"], H_A2) |
|---|
| 300 |
|
|---|
| 301 |
return KD(H_A1, request) |
|---|
| 302 |
|
|---|
| 303 |
def _checkDigestResponse(auth_map, password, method = "GET", A1 = None, **kwargs): |
|---|
| 304 |
"""This function is used to verify the response given by the client when |
|---|
| 305 |
he tries to authenticate. |
|---|
| 306 |
Optional arguments: |
|---|
| 307 |
entity_body - when 'qop' is set to 'auth-int' you MUST provide the |
|---|
| 308 |
raw data you are going to send to the client (usually the |
|---|
| 309 |
HTML page. |
|---|
| 310 |
request_uri - the uri from the request line compared with the 'uri' |
|---|
| 311 |
directive of the authorization map. They must represent |
|---|
| 312 |
the same resource (unused at this time). |
|---|
| 313 |
""" |
|---|
| 314 |
|
|---|
| 315 |
if auth_map['realm'] != kwargs.get('realm', None): |
|---|
| 316 |
return False |
|---|
| 317 |
|
|---|
| 318 |
response = _computeDigestResponse(auth_map, password, method, A1,**kwargs) |
|---|
| 319 |
|
|---|
| 320 |
return response == auth_map["response"] |
|---|
| 321 |
|
|---|
| 322 |
def _checkBasicResponse (auth_map, password, method='GET', encrypt=None, **kwargs): |
|---|
| 323 |
|
|---|
| 324 |
|
|---|
| 325 |
try: |
|---|
| 326 |
return encrypt(auth_map["password"], auth_map["username"]) == password |
|---|
| 327 |
except TypeError: |
|---|
| 328 |
return encrypt(auth_map["password"]) == password |
|---|
| 329 |
|
|---|
| 330 |
AUTH_RESPONSES = { |
|---|
| 331 |
"basic": _checkBasicResponse, |
|---|
| 332 |
"digest": _checkDigestResponse, |
|---|
| 333 |
} |
|---|
| 334 |
|
|---|
| 335 |
def checkResponse (auth_map, password, method = "GET", encrypt=None, **kwargs): |
|---|
| 336 |
"""'checkResponse' compares the auth_map with the password and optionally |
|---|
| 337 |
other arguments that each implementation might need. |
|---|
| 338 |
|
|---|
| 339 |
If the response is of type 'Basic' then the function has the following |
|---|
| 340 |
signature: |
|---|
| 341 |
|
|---|
| 342 |
checkBasicResponse (auth_map, password) -> bool |
|---|
| 343 |
|
|---|
| 344 |
If the response is of type 'Digest' then the function has the following |
|---|
| 345 |
signature: |
|---|
| 346 |
|
|---|
| 347 |
checkDigestResponse (auth_map, password, method = 'GET', A1 = None) -> bool |
|---|
| 348 |
|
|---|
| 349 |
The 'A1' argument is only used in MD5_SESS algorithm based responses. |
|---|
| 350 |
Check md5SessionKey() for more info. |
|---|
| 351 |
""" |
|---|
| 352 |
global AUTH_RESPONSES |
|---|
| 353 |
checker = AUTH_RESPONSES[auth_map["auth_scheme"]] |
|---|
| 354 |
return checker (auth_map, password, method=method, encrypt=encrypt, **kwargs) |
|---|
| 355 |
|
|---|
| 356 |
|
|---|
| 357 |
|
|---|
| 358 |
|
|---|