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  std::string realm;
118
119  // Try to find the "stale" value, and also keep track of the realm
120  // for the new challenge.
121  while (parameters.GetNext()) {
122    if (LowerCaseEqualsASCII(parameters.name(), "stale")) {
123      if (LowerCaseEqualsASCII(parameters.value(), "true"))
124        return HttpAuth::AUTHORIZATION_RESULT_STALE;
125    } else if (LowerCaseEqualsASCII(parameters.name(), "realm")) {
126      realm = parameters.value();
127    }
128  }
129  return (realm_ != realm) ?
130      HttpAuth::AUTHORIZATION_RESULT_DIFFERENT_REALM :
131      HttpAuth::AUTHORIZATION_RESULT_REJECT;
132}
133
134bool HttpAuthHandlerDigest::Init(HttpAuth::ChallengeTokenizer* challenge) {
135  return ParseChallenge(challenge);
136}
137
138int HttpAuthHandlerDigest::GenerateAuthTokenImpl(
139    const string16* username,
140    const string16* password,
141    const HttpRequestInfo* request,
142    CompletionCallback* callback,
143    std::string* auth_token) {
144  // Generate a random client nonce.
145  std::string cnonce = nonce_generator_->GenerateNonce();
146
147  // Extract the request method and path -- the meaning of 'path' is overloaded
148  // in certain cases, to be a hostname.
149  std::string method;
150  std::string path;
151  GetRequestMethodAndPath(request, &method, &path);
152
153  *auth_token = AssembleCredentials(method, path,
154                                    *username,
155                                    *password,
156                                    cnonce, nonce_count_);
157  return OK;
158}
159
160HttpAuthHandlerDigest::HttpAuthHandlerDigest(
161    int nonce_count, const NonceGenerator* nonce_generator)
162    : stale_(false),
163      algorithm_(ALGORITHM_UNSPECIFIED),
164      qop_(QOP_UNSPECIFIED),
165      nonce_count_(nonce_count),
166      nonce_generator_(nonce_generator) {
167  DCHECK(nonce_generator_);
168}
169
170HttpAuthHandlerDigest::~HttpAuthHandlerDigest() {
171}
172
173// The digest challenge header looks like:
174//   WWW-Authenticate: Digest
175//     [realm="<realm-value>"]
176//     nonce="<nonce-value>"
177//     [domain="<list-of-URIs>"]
178//     [opaque="<opaque-token-value>"]
179//     [stale="<true-or-false>"]
180//     [algorithm="<digest-algorithm>"]
181//     [qop="<list-of-qop-values>"]
182//     [<extension-directive>]
183//
184// Note that according to RFC 2617 (section 1.2) the realm is required.
185// However we allow it to be omitted, in which case it will default to the
186// empty string.
187//
188// This allowance is for better compatibility with webservers that fail to
189// send the realm (See http://crbug.com/20984 for an instance where a
190// webserver was not sending the realm with a BASIC challenge).
191bool HttpAuthHandlerDigest::ParseChallenge(
192    HttpAuth::ChallengeTokenizer* challenge) {
193  auth_scheme_ = HttpAuth::AUTH_SCHEME_DIGEST;
194  score_ = 2;
195  properties_ = ENCRYPTS_IDENTITY;
196
197  // Initialize to defaults.
198  stale_ = false;
199  algorithm_ = ALGORITHM_UNSPECIFIED;
200  qop_ = QOP_UNSPECIFIED;
201  realm_ = nonce_ = domain_ = opaque_ = std::string();
202
203  // FAIL -- Couldn't match auth-scheme.
204  if (!LowerCaseEqualsASCII(challenge->scheme(), "digest"))
205    return false;
206
207  HttpUtil::NameValuePairsIterator parameters = challenge->param_pairs();
208
209  // Loop through all the properties.
210  while (parameters.GetNext()) {
211    // FAIL -- couldn't parse a property.
212    if (!ParseChallengeProperty(parameters.name(),
213                                parameters.value()))
214      return false;
215  }
216
217  // Check if tokenizer failed.
218  if (!parameters.valid())
219    return false;
220
221  // Check that a minimum set of properties were provided.
222  if (nonce_.empty())
223    return false;
224
225  return true;
226}
227
228bool HttpAuthHandlerDigest::ParseChallengeProperty(const std::string& name,
229                                                   const std::string& value) {
230  if (LowerCaseEqualsASCII(name, "realm")) {
231    realm_ = value;
232  } else if (LowerCaseEqualsASCII(name, "nonce")) {
233    nonce_ = value;
234  } else if (LowerCaseEqualsASCII(name, "domain")) {
235    domain_ = value;
236  } else if (LowerCaseEqualsASCII(name, "opaque")) {
237    opaque_ = value;
238  } else if (LowerCaseEqualsASCII(name, "stale")) {
239    // Parse the stale boolean.
240    stale_ = LowerCaseEqualsASCII(value, "true");
241  } else if (LowerCaseEqualsASCII(name, "algorithm")) {
242    // Parse the algorithm.
243    if (LowerCaseEqualsASCII(value, "md5")) {
244      algorithm_ = ALGORITHM_MD5;
245    } else if (LowerCaseEqualsASCII(value, "md5-sess")) {
246      algorithm_ = ALGORITHM_MD5_SESS;
247    } else {
248      DVLOG(1) << "Unknown value of algorithm";
249      return false;  // FAIL -- unsupported value of algorithm.
250    }
251  } else if (LowerCaseEqualsASCII(name, "qop")) {
252    // Parse the comma separated list of qops.
253    // auth is the only supported qop, and all other values are ignored.
254    HttpUtil::ValuesIterator qop_values(value.begin(), value.end(), ',');
255    qop_ = QOP_UNSPECIFIED;
256    while (qop_values.GetNext()) {
257      if (LowerCaseEqualsASCII(qop_values.value(), "auth")) {
258        qop_ = QOP_AUTH;
259        break;
260      }
261    }
262  } else {
263    DVLOG(1) << "Skipping unrecognized digest property";
264    // TODO(eroman): perhaps we should fail instead of silently skipping?
265  }
266  return true;
267}
268
269// static
270std::string HttpAuthHandlerDigest::QopToString(QualityOfProtection qop) {
271  switch (qop) {
272    case QOP_UNSPECIFIED:
273      return "";
274    case QOP_AUTH:
275      return "auth";
276    default:
277      NOTREACHED();
278      return "";
279  }
280}
281
282// static
283std::string HttpAuthHandlerDigest::AlgorithmToString(
284    DigestAlgorithm algorithm) {
285  switch (algorithm) {
286    case ALGORITHM_UNSPECIFIED:
287      return "";
288    case ALGORITHM_MD5:
289      return "MD5";
290    case ALGORITHM_MD5_SESS:
291      return "MD5-sess";
292    default:
293      NOTREACHED();
294      return "";
295  }
296}
297
298void HttpAuthHandlerDigest::GetRequestMethodAndPath(
299    const HttpRequestInfo* request,
300    std::string* method,
301    std::string* path) const {
302  DCHECK(request);
303
304  const GURL& url = request->url;
305
306  if (target_ == HttpAuth::AUTH_PROXY && url.SchemeIs("https")) {
307    *method = "CONNECT";
308    *path = GetHostAndPort(url);
309  } else {
310    *method = request->method;
311    *path = HttpUtil::PathForRequest(url);
312  }
313}
314
315std::string HttpAuthHandlerDigest::AssembleResponseDigest(
316    const std::string& method,
317    const std::string& path,
318    const string16& username,
319    const string16& password,
320    const std::string& cnonce,
321    const std::string& nc) const {
322  // ha1 = MD5(A1)
323  // TODO(eroman): is this the right encoding?
324  std::string ha1 = MD5String(UTF16ToUTF8(username) + ":" + realm_ + ":" +
325                              UTF16ToUTF8(password));
326  if (algorithm_ == HttpAuthHandlerDigest::ALGORITHM_MD5_SESS)
327    ha1 = MD5String(ha1 + ":" + nonce_ + ":" + cnonce);
328
329  // ha2 = MD5(A2)
330  // TODO(eroman): need to add MD5(req-entity-body) for qop=auth-int.
331  std::string ha2 = MD5String(method + ":" + path);
332
333  std::string nc_part;
334  if (qop_ != HttpAuthHandlerDigest::QOP_UNSPECIFIED) {
335    nc_part = nc + ":" + cnonce + ":" + QopToString(qop_) + ":";
336  }
337
338  return MD5String(ha1 + ":" + nonce_ + ":" + nc_part + ha2);
339}
340
341std::string HttpAuthHandlerDigest::AssembleCredentials(
342    const std::string& method,
343    const std::string& path,
344    const string16& username,
345    const string16& password,
346    const std::string& cnonce,
347    int nonce_count) const {
348  // the nonce-count is an 8 digit hex string.
349  std::string nc = base::StringPrintf("%08x", nonce_count);
350
351  // TODO(eroman): is this the right encoding?
352  std::string authorization = (std::string("Digest username=") +
353                               HttpUtil::Quote(UTF16ToUTF8(username)));
354  authorization += ", realm=" + HttpUtil::Quote(realm_);
355  authorization += ", nonce=" + HttpUtil::Quote(nonce_);
356  authorization += ", uri=" + HttpUtil::Quote(path);
357
358  if (algorithm_ != ALGORITHM_UNSPECIFIED) {
359    authorization += ", algorithm=" + AlgorithmToString(algorithm_);
360  }
361  std::string response = AssembleResponseDigest(method, path, username,
362                                                password, cnonce, nc);
363  // No need to call HttpUtil::Quote() as the response digest cannot contain
364  // any characters needing to be escaped.
365  authorization += ", response=\"" + response + "\"";
366
367  if (!opaque_.empty()) {
368    authorization += ", opaque=" + HttpUtil::Quote(opaque_);
369  }
370  if (qop_ != QOP_UNSPECIFIED) {
371    // TODO(eroman): Supposedly IIS server requires quotes surrounding qop.
372    authorization += ", qop=" + QopToString(qop_);
373    authorization += ", nc=" + nc;
374    authorization += ", cnonce=" + HttpUtil::Quote(cnonce);
375  }
376
377  return authorization;
378}
379
380}  // namespace net
381