http_auth_handler_digest.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
1// Copyright (c) 2010 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "net/http/http_auth_handler_digest.h" 6 7#include <string> 8 9#include "base/logging.h" 10#include "base/md5.h" 11#include "base/rand_util.h" 12#include "base/string_util.h" 13#include "base/stringprintf.h" 14#include "base/utf_string_conversions.h" 15#include "net/base/net_errors.h" 16#include "net/base/net_util.h" 17#include "net/http/http_auth.h" 18#include "net/http/http_request_info.h" 19#include "net/http/http_util.h" 20 21namespace net { 22 23// Digest authentication is specified in RFC 2617. 24// The expanded derivations are listed in the tables below. 25 26//==========+==========+==========================================+ 27// qop |algorithm | response | 28//==========+==========+==========================================+ 29// ? | ?, md5, | MD5(MD5(A1):nonce:MD5(A2)) | 30// | md5-sess | | 31//--------- +----------+------------------------------------------+ 32// auth, | ?, md5, | MD5(MD5(A1):nonce:nc:cnonce:qop:MD5(A2)) | 33// auth-int | md5-sess | | 34//==========+==========+==========================================+ 35// qop |algorithm | A1 | 36//==========+==========+==========================================+ 37// | ?, md5 | user:realm:password | 38//----------+----------+------------------------------------------+ 39// | md5-sess | MD5(user:realm:password):nonce:cnonce | 40//==========+==========+==========================================+ 41// qop |algorithm | A2 | 42//==========+==========+==========================================+ 43// ?, auth | | req-method:req-uri | 44//----------+----------+------------------------------------------+ 45// auth-int | | req-method:req-uri:MD5(req-entity-body) | 46//=====================+==========================================+ 47 48HttpAuthHandlerDigest::NonceGenerator::NonceGenerator() { 49} 50 51HttpAuthHandlerDigest::NonceGenerator::~NonceGenerator() { 52} 53 54HttpAuthHandlerDigest::DynamicNonceGenerator::DynamicNonceGenerator() { 55} 56 57std::string HttpAuthHandlerDigest::DynamicNonceGenerator::GenerateNonce() 58 const { 59 // This is how mozilla generates their cnonce -- a 16 digit hex string. 60 static const char domain[] = "0123456789abcdef"; 61 std::string cnonce; 62 cnonce.reserve(16); 63 for (int i = 0; i < 16; ++i) 64 cnonce.push_back(domain[base::RandInt(0, 15)]); 65 return cnonce; 66} 67 68HttpAuthHandlerDigest::FixedNonceGenerator::FixedNonceGenerator( 69 const std::string& nonce) 70 : nonce_(nonce) { 71} 72 73std::string HttpAuthHandlerDigest::FixedNonceGenerator::GenerateNonce() const { 74 return nonce_; 75} 76 77HttpAuthHandlerDigest::Factory::Factory() 78 : nonce_generator_(new DynamicNonceGenerator()) { 79} 80 81HttpAuthHandlerDigest::Factory::~Factory() { 82} 83 84void HttpAuthHandlerDigest::Factory::set_nonce_generator( 85 const NonceGenerator* nonce_generator) { 86 nonce_generator_.reset(nonce_generator); 87} 88 89int HttpAuthHandlerDigest::Factory::CreateAuthHandler( 90 HttpAuth::ChallengeTokenizer* challenge, 91 HttpAuth::Target target, 92 const GURL& origin, 93 CreateReason reason, 94 int digest_nonce_count, 95 const BoundNetLog& net_log, 96 scoped_ptr<HttpAuthHandler>* handler) { 97 // TODO(cbentzel): Move towards model of parsing in the factory 98 // method and only constructing when valid. 99 scoped_ptr<HttpAuthHandler> tmp_handler( 100 new HttpAuthHandlerDigest(digest_nonce_count, nonce_generator_.get())); 101 if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log)) 102 return ERR_INVALID_RESPONSE; 103 handler->swap(tmp_handler); 104 return OK; 105} 106 107HttpAuth::AuthorizationResult HttpAuthHandlerDigest::HandleAnotherChallenge( 108 HttpAuth::ChallengeTokenizer* challenge) { 109 // Even though Digest is not connection based, a "second round" is parsed 110 // to differentiate between stale and rejected responses. 111 // Note that the state of the current handler is not mutated - this way if 112 // there is a rejection the realm hasn't changed. 113 if (!LowerCaseEqualsASCII(challenge->scheme(), "digest")) 114 return HttpAuth::AUTHORIZATION_RESULT_INVALID; 115 116 HttpUtil::NameValuePairsIterator parameters = challenge->param_pairs(); 117 118 // Try to find the "stale" value. 119 while (parameters.GetNext()) { 120 if (!LowerCaseEqualsASCII(parameters.name(), "stale")) 121 continue; 122 if (LowerCaseEqualsASCII(parameters.value(), "true")) 123 return HttpAuth::AUTHORIZATION_RESULT_STALE; 124 } 125 126 return HttpAuth::AUTHORIZATION_RESULT_REJECT; 127} 128 129bool HttpAuthHandlerDigest::Init(HttpAuth::ChallengeTokenizer* challenge) { 130 return ParseChallenge(challenge); 131} 132 133int HttpAuthHandlerDigest::GenerateAuthTokenImpl( 134 const string16* username, 135 const string16* password, 136 const HttpRequestInfo* request, 137 CompletionCallback* callback, 138 std::string* auth_token) { 139 // Generate a random client nonce. 140 std::string cnonce = nonce_generator_->GenerateNonce(); 141 142 // Extract the request method and path -- the meaning of 'path' is overloaded 143 // in certain cases, to be a hostname. 144 std::string method; 145 std::string path; 146 GetRequestMethodAndPath(request, &method, &path); 147 148 *auth_token = AssembleCredentials(method, path, 149 *username, 150 *password, 151 cnonce, nonce_count_); 152 return OK; 153} 154 155HttpAuthHandlerDigest::HttpAuthHandlerDigest( 156 int nonce_count, const NonceGenerator* nonce_generator) 157 : stale_(false), 158 algorithm_(ALGORITHM_UNSPECIFIED), 159 qop_(QOP_UNSPECIFIED), 160 nonce_count_(nonce_count), 161 nonce_generator_(nonce_generator) { 162 DCHECK(nonce_generator_); 163} 164 165HttpAuthHandlerDigest::~HttpAuthHandlerDigest() { 166} 167 168// The digest challenge header looks like: 169// WWW-Authenticate: Digest 170// [realm="<realm-value>"] 171// nonce="<nonce-value>" 172// [domain="<list-of-URIs>"] 173// [opaque="<opaque-token-value>"] 174// [stale="<true-or-false>"] 175// [algorithm="<digest-algorithm>"] 176// [qop="<list-of-qop-values>"] 177// [<extension-directive>] 178// 179// Note that according to RFC 2617 (section 1.2) the realm is required. 180// However we allow it to be omitted, in which case it will default to the 181// empty string. 182// 183// This allowance is for better compatibility with webservers that fail to 184// send the realm (See http://crbug.com/20984 for an instance where a 185// webserver was not sending the realm with a BASIC challenge). 186bool HttpAuthHandlerDigest::ParseChallenge( 187 HttpAuth::ChallengeTokenizer* challenge) { 188 auth_scheme_ = HttpAuth::AUTH_SCHEME_DIGEST; 189 score_ = 2; 190 properties_ = ENCRYPTS_IDENTITY; 191 192 // Initialize to defaults. 193 stale_ = false; 194 algorithm_ = ALGORITHM_UNSPECIFIED; 195 qop_ = QOP_UNSPECIFIED; 196 realm_ = nonce_ = domain_ = opaque_ = std::string(); 197 198 // FAIL -- Couldn't match auth-scheme. 199 if (!LowerCaseEqualsASCII(challenge->scheme(), "digest")) 200 return false; 201 202 HttpUtil::NameValuePairsIterator parameters = challenge->param_pairs(); 203 204 // Loop through all the properties. 205 while (parameters.GetNext()) { 206 // FAIL -- couldn't parse a property. 207 if (!ParseChallengeProperty(parameters.name(), 208 parameters.value())) 209 return false; 210 } 211 212 // Check if tokenizer failed. 213 if (!parameters.valid()) 214 return false; 215 216 // Check that a minimum set of properties were provided. 217 if (nonce_.empty()) 218 return false; 219 220 return true; 221} 222 223bool HttpAuthHandlerDigest::ParseChallengeProperty(const std::string& name, 224 const std::string& value) { 225 if (LowerCaseEqualsASCII(name, "realm")) { 226 realm_ = value; 227 } else if (LowerCaseEqualsASCII(name, "nonce")) { 228 nonce_ = value; 229 } else if (LowerCaseEqualsASCII(name, "domain")) { 230 domain_ = value; 231 } else if (LowerCaseEqualsASCII(name, "opaque")) { 232 opaque_ = value; 233 } else if (LowerCaseEqualsASCII(name, "stale")) { 234 // Parse the stale boolean. 235 stale_ = LowerCaseEqualsASCII(value, "true"); 236 } else if (LowerCaseEqualsASCII(name, "algorithm")) { 237 // Parse the algorithm. 238 if (LowerCaseEqualsASCII(value, "md5")) { 239 algorithm_ = ALGORITHM_MD5; 240 } else if (LowerCaseEqualsASCII(value, "md5-sess")) { 241 algorithm_ = ALGORITHM_MD5_SESS; 242 } else { 243 DVLOG(1) << "Unknown value of algorithm"; 244 return false; // FAIL -- unsupported value of algorithm. 245 } 246 } else if (LowerCaseEqualsASCII(name, "qop")) { 247 // Parse the comma separated list of qops. 248 // auth is the only supported qop, and all other values are ignored. 249 HttpUtil::ValuesIterator qop_values(value.begin(), value.end(), ','); 250 qop_ = QOP_UNSPECIFIED; 251 while (qop_values.GetNext()) { 252 if (LowerCaseEqualsASCII(qop_values.value(), "auth")) { 253 qop_ = QOP_AUTH; 254 break; 255 } 256 } 257 } else { 258 DVLOG(1) << "Skipping unrecognized digest property"; 259 // TODO(eroman): perhaps we should fail instead of silently skipping? 260 } 261 return true; 262} 263 264// static 265std::string HttpAuthHandlerDigest::QopToString(QualityOfProtection qop) { 266 switch (qop) { 267 case QOP_UNSPECIFIED: 268 return ""; 269 case QOP_AUTH: 270 return "auth"; 271 default: 272 NOTREACHED(); 273 return ""; 274 } 275} 276 277// static 278std::string HttpAuthHandlerDigest::AlgorithmToString( 279 DigestAlgorithm algorithm) { 280 switch (algorithm) { 281 case ALGORITHM_UNSPECIFIED: 282 return ""; 283 case ALGORITHM_MD5: 284 return "MD5"; 285 case ALGORITHM_MD5_SESS: 286 return "MD5-sess"; 287 default: 288 NOTREACHED(); 289 return ""; 290 } 291} 292 293void HttpAuthHandlerDigest::GetRequestMethodAndPath( 294 const HttpRequestInfo* request, 295 std::string* method, 296 std::string* path) const { 297 DCHECK(request); 298 299 const GURL& url = request->url; 300 301 if (target_ == HttpAuth::AUTH_PROXY && url.SchemeIs("https")) { 302 *method = "CONNECT"; 303 *path = GetHostAndPort(url); 304 } else { 305 *method = request->method; 306 *path = HttpUtil::PathForRequest(url); 307 } 308} 309 310std::string HttpAuthHandlerDigest::AssembleResponseDigest( 311 const std::string& method, 312 const std::string& path, 313 const string16& username, 314 const string16& password, 315 const std::string& cnonce, 316 const std::string& nc) const { 317 // ha1 = MD5(A1) 318 // TODO(eroman): is this the right encoding? 319 std::string ha1 = MD5String(UTF16ToUTF8(username) + ":" + realm_ + ":" + 320 UTF16ToUTF8(password)); 321 if (algorithm_ == HttpAuthHandlerDigest::ALGORITHM_MD5_SESS) 322 ha1 = MD5String(ha1 + ":" + nonce_ + ":" + cnonce); 323 324 // ha2 = MD5(A2) 325 // TODO(eroman): need to add MD5(req-entity-body) for qop=auth-int. 326 std::string ha2 = MD5String(method + ":" + path); 327 328 std::string nc_part; 329 if (qop_ != HttpAuthHandlerDigest::QOP_UNSPECIFIED) { 330 nc_part = nc + ":" + cnonce + ":" + QopToString(qop_) + ":"; 331 } 332 333 return MD5String(ha1 + ":" + nonce_ + ":" + nc_part + ha2); 334} 335 336std::string HttpAuthHandlerDigest::AssembleCredentials( 337 const std::string& method, 338 const std::string& path, 339 const string16& username, 340 const string16& password, 341 const std::string& cnonce, 342 int nonce_count) const { 343 // the nonce-count is an 8 digit hex string. 344 std::string nc = base::StringPrintf("%08x", nonce_count); 345 346 // TODO(eroman): is this the right encoding? 347 std::string authorization = (std::string("Digest username=") + 348 HttpUtil::Quote(UTF16ToUTF8(username))); 349 authorization += ", realm=" + HttpUtil::Quote(realm_); 350 authorization += ", nonce=" + HttpUtil::Quote(nonce_); 351 authorization += ", uri=" + HttpUtil::Quote(path); 352 353 if (algorithm_ != ALGORITHM_UNSPECIFIED) { 354 authorization += ", algorithm=" + AlgorithmToString(algorithm_); 355 } 356 std::string response = AssembleResponseDigest(method, path, username, 357 password, cnonce, nc); 358 // No need to call HttpUtil::Quote() as the response digest cannot contain 359 // any characters needing to be escaped. 360 authorization += ", response=\"" + response + "\""; 361 362 if (!opaque_.empty()) { 363 authorization += ", opaque=" + HttpUtil::Quote(opaque_); 364 } 365 if (qop_ != QOP_UNSPECIFIED) { 366 // TODO(eroman): Supposedly IIS server requires quotes surrounding qop. 367 authorization += ", qop=" + QopToString(qop_); 368 authorization += ", nc=" + nc; 369 authorization += ", cnonce=" + HttpUtil::Quote(cnonce); 370 } 371 372 return authorization; 373} 374 375} // namespace net 376