Ver Fonte

Match Digest algorithm and qop values case-insensitively

The Digest client compared the algorithm and qop values of a challenge
case-sensitively, so algorithm=sha-256 was answered with an MD5 hash and
qop="AUTH" without qop. A challenge whose algorithm it doesn't implement
(SHA-512-256, the -sess variants, or a value that isn't a token) was
answered with an MD5 hash under the server's algorithm name, and only the
first Digest challenge was ever looked at.

- Match algorithm and qop options case-insensitively. qop is split into
  tokens instead of searched as a substring, and sent as auth/auth-int.
- Collect params per Digest challenge and use the first one the client
  can answer (RFC 7616 Sections 3.3 and 3.7): realm and nonce present and
  an algorithm it implements. If there is none, the 401 is returned
  without a retry.
- digest_hash() is the single list of supported algorithms, used by both
  parse_www_authenticate() and make_digest_authentication_header(). The
  algorithm is sent back as the server wrote it (RFC 7616 Section 3.4).
  parse_www_authenticate() moves into the SSL block, next to the hash
  functions and its callers.
yhirose há 2 dias atrás
pai
commit
c5faf03dfe
2 ficheiros alterados com 211 adições e 185 exclusões
  1. 112 91
      httplib.h
  2. 99 94
      test/test.cc

+ 112 - 91
httplib.h

@@ -11224,76 +11224,6 @@ inline std::string escape_quoted_pairs(const std::string &s) {
   return out;
   return out;
 }
 }
 
 
-// RFC 9110 Section 11.6.1 defines a challenge list as
-//   WWW-Authenticate = #challenge
-//   challenge        = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
-//   auth-param       = token BWS "=" BWS ( token / quoted-string )
-// so a server may offer several schemes, each with its own comma-separated
-// auth-param list, in either order and either as separate field lines or
-// packed into one. Splitting on every comma would break apart a challenge's
-// own param list; splitting only on the first space would miss a Digest
-// challenge that isn't first. Split on commas that aren't inside a
-// quoted-string instead (split_unquoted), then track which scheme each
-// resulting segment belongs to: a segment whose text before "=" contains
-// whitespace (or that has no "=" at all) starts a new challenge named by its
-// leading token.
-inline bool parse_www_authenticate(const Response &res,
-                                   std::map<std::string, std::string> &auth,
-                                   bool is_proxy) {
-  auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
-  auto combined = get_combined_header_value(res.headers, auth_key);
-  if (combined.empty()) { return false; }
-
-  auto found_digest = false;
-  auto in_digest_challenge = false;
-  split_unquoted(
-      combined.data(), combined.data() + combined.size(), ',',
-      [&](const char *b, const char *e) {
-        std::string segment(b, e);
-        auto eq_pos = segment.find('=');
-        // BWS is allowed on both sides of "=", so the text naming the key (or,
-        // for the first segment of a challenge, "<scheme> <key>") must be
-        // trimmed before its boundaries are inspected.
-        auto key_part = trim_copy(
-            eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
-        auto space_pos = key_part.find_last_of(" \t");
-        if (space_pos != std::string::npos || eq_pos == std::string::npos) {
-          // "<scheme>[ <key>]" starts a new challenge.
-          auto scheme_end =
-              space_pos == std::string::npos ? key_part.size() : space_pos;
-          // RFC 7616 Section 3.7: a server may offer more than one Digest
-          // challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
-          // from one challenge is never paired with another's algorithm.
-          in_digest_challenge =
-              !found_digest &&
-              case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
-          if (in_digest_challenge) { found_digest = true; }
-          if (space_pos == std::string::npos) {
-            // Bare scheme (or a token68), no auth-param on this segment.
-            return;
-          }
-          key_part = key_part.substr(space_pos + 1);
-        }
-
-        if (!in_digest_challenge) { return; }
-
-        auto val = trim_copy(segment.substr(eq_pos + 1));
-        auto unquoted = trim_double_quotes_copy(val);
-        if (unquoted.size() != val.size()) {
-          unquoted = unescape_quoted_pairs(unquoted);
-        }
-        // auth-param names are case-insensitive (RFC 9110 Section 11.2)
-        auth[case_ignore::to_lower(key_part)] = std::move(unquoted);
-      });
-
-  // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
-  // make_digest_authentication_header() dereferences both unconditionally, so
-  // a challenge missing either can't produce a usable Authorization header.
-  // Treat it the same as no Digest challenge at all.
-  return found_digest && auth.find("realm") != auth.end() &&
-         auth.find("nonce") != auth.end();
-}
-
 class ContentProviderAdapter {
 class ContentProviderAdapter {
 public:
 public:
   explicit ContentProviderAdapter(
   explicit ContentProviderAdapter(
@@ -11762,6 +11692,99 @@ inline bool process_client_socket_ssl(
   return callback(strm);
   return callback(strm);
 }
 }
 
 
+using DigestHash = std::string (*)(const std::string &);
+
+// The Digest algorithms the client implements, matched case-insensitively;
+// nullptr for any other.
+inline DigestHash digest_hash(const std::string &algorithm) {
+  if (case_ignore::equal(algorithm, "MD5")) { return detail::MD5; }
+  if (case_ignore::equal(algorithm, "SHA-256")) { return detail::SHA_256; }
+  if (case_ignore::equal(algorithm, "SHA-512")) { return detail::SHA_512; }
+  return nullptr;
+}
+
+// RFC 9110 Section 11.6.1 defines a challenge list as
+//   WWW-Authenticate = #challenge
+//   challenge        = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
+//   auth-param       = token BWS "=" BWS ( token / quoted-string )
+// so a server may offer several schemes, each with its own comma-separated
+// auth-param list, in either order and either as separate field lines or
+// packed into one. Splitting on every comma would break apart a challenge's
+// own param list; splitting only on the first space would miss a Digest
+// challenge that isn't first. Split on commas that aren't inside a
+// quoted-string instead (split_unquoted), then track which scheme each
+// resulting segment belongs to: a segment whose text before "=" contains
+// whitespace (or that has no "=" at all) starts a new challenge named by its
+// leading token.
+inline bool parse_www_authenticate(const Response &res,
+                                   std::map<std::string, std::string> &auth,
+                                   bool is_proxy) {
+  auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
+  auto combined = get_combined_header_value(res.headers, auth_key);
+  if (combined.empty()) { return false; }
+
+  // RFC 7616 Section 3.7: a server may offer more than one Digest challenge
+  // (e.g. SHA-256 and MD5), and the client uses the first one it supports.
+  // A challenge whose algorithm the client doesn't implement is ignored
+  // (Section 3.3), and one without realm and nonce can't be answered. Params
+  // are collected per challenge, so a nonce from one is never paired with
+  // another's algorithm.
+  auto found = false;
+  auto in_digest_challenge = false;
+  std::map<std::string, std::string> challenge;
+  auto take_challenge_if_answerable = [&] {
+    if (!found && in_digest_challenge &&
+        challenge.find("realm") != challenge.end() &&
+        challenge.find("nonce") != challenge.end()) {
+      auto it = challenge.find("algorithm");
+      if (it == challenge.end() || digest_hash(it->second)) {
+        auth = std::move(challenge);
+        found = true;
+      }
+    }
+    challenge.clear();
+  };
+
+  split_unquoted(
+      combined.data(), combined.data() + combined.size(), ',',
+      [&](const char *b, const char *e) {
+        std::string segment(b, e);
+        auto eq_pos = segment.find('=');
+        // BWS is allowed on both sides of "=", so the text naming the key (or,
+        // for the first segment of a challenge, "<scheme> <key>") must be
+        // trimmed before its boundaries are inspected.
+        auto key_part = trim_copy(
+            eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
+        auto space_pos = key_part.find_last_of(" \t");
+        if (space_pos != std::string::npos || eq_pos == std::string::npos) {
+          // "<scheme>[ <key>]" starts a new challenge.
+          take_challenge_if_answerable();
+          auto scheme_end =
+              space_pos == std::string::npos ? key_part.size() : space_pos;
+          in_digest_challenge =
+              case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
+          if (space_pos == std::string::npos) {
+            // Bare scheme (or a token68), no auth-param on this segment.
+            return;
+          }
+          key_part = key_part.substr(space_pos + 1);
+        }
+
+        if (!in_digest_challenge) { return; }
+
+        auto val = trim_copy(segment.substr(eq_pos + 1));
+        auto unquoted = trim_double_quotes_copy(val);
+        if (unquoted.size() != val.size()) {
+          unquoted = unescape_quoted_pairs(unquoted);
+        }
+        // auth-param names are case-insensitive (RFC 9110 Section 11.2)
+        challenge[case_ignore::to_lower(key_part)] = std::move(unquoted);
+      });
+  take_challenge_if_answerable();
+
+  return found;
+}
+
 // `uri` is req's request-target in origin form, as curl sends it, also when
 // `uri` is req's request-target in origin form, as curl sends it, also when
 // the request line carries the absolute form for a proxy.
 // the request line carries the absolute form for a proxy.
 inline std::pair<std::string, std::string> make_digest_authentication_header(
 inline std::pair<std::string, std::string> make_digest_authentication_header(
@@ -11776,33 +11799,31 @@ inline std::pair<std::string, std::string> make_digest_authentication_header(
     nc = ss.str();
     nc = ss.str();
   }
   }
 
 
+  // auth-int is preferred over auth; other qop options are ignored.
   std::string qop;
   std::string qop;
-  if (auth.find("qop") != auth.end()) {
-    qop = auth.at("qop");
-    if (qop.find("auth-int") != std::string::npos) {
-      qop = "auth-int";
-    } else if (qop.find("auth") != std::string::npos) {
-      qop = "auth";
-    } else {
-      qop.clear();
-    }
+  auto qop_it = auth.find("qop");
+  if (qop_it != auth.end()) {
+    const auto &options = qop_it->second;
+    split(options.data(), options.data() + options.size(), ',',
+          [&](const char *b, const char *e) {
+            std::string option(b, e);
+            if (case_ignore::equal(option, "auth-int")) {
+              qop = "auth-int";
+            } else if (qop.empty() && case_ignore::equal(option, "auth")) {
+              qop = "auth";
+            }
+          });
   }
   }
 
 
-  std::string algo = "MD5";
-  if (auth.find("algorithm") != auth.end()) {
-    // algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
-    // not a token would otherwise be emitted verbatim and could carry commas
-    // or quotes that inject further auth-params into the header below.
-    const auto &a = auth.at("algorithm");
-    if (fields::is_token(a)) { algo = a; }
-  }
+  // Sent back as the server wrote it (RFC 7616 Section 3.4).
+  // parse_www_authenticate() accepts only one digest_hash() knows.
+  auto algo_it = auth.find("algorithm");
+  auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
+  auto H = digest_hash(algo);
+  assert(H);
 
 
   std::string response;
   std::string response;
   {
   {
-    auto H = algo == "SHA-256"   ? detail::SHA_256
-             : algo == "SHA-512" ? detail::SHA_512
-                                 : detail::MD5;
-
     auto A1 = username + ":" + auth.at("realm") + ":" + password;
     auto A1 = username + ":" + auth.at("realm") + ":" + password;
 
 
     auto A2 = req.method + ":" + uri;
     auto A2 = req.method + ":" + uri;

+ 99 - 94
test/test.cc

@@ -3963,17 +3963,13 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
   }
   }
 }
 }
 
 
-// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
-// comma-separated list of challenges, and each challenge may itself carry a
-// comma-separated auth-param list, so a server can legally offer Basic
-// before Digest, either as two field lines or packed into one. Runs one 401
-// -> Digest-retry round trip with the given field lines (get_combined_header_
-// value() joins them in receipt order) and checks that the retry carries a
-// well-formed Digest Authorization header naming expected_realm.
-static void
-run_digest_challenge_list_test(const std::vector<std::string> &challenges,
-                               const std::string &expected_realm) {
+// Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
+// field lines (get_combined_header_value() joins them in receipt order) and
+// returns the Authorization header of the retry.
+static std::string
+get_digest_retry_authorization(const std::vector<std::string> &challenges) {
   std::atomic<int> hits{0};
   std::atomic<int> hits{0};
+  std::string authorization;
 
 
   Server svr;
   Server svr;
   svr.Get("/x", [&](const Request &req, Response &res) {
   svr.Get("/x", [&](const Request &req, Response &res) {
@@ -3983,11 +3979,7 @@ run_digest_challenge_list_test(const std::vector<std::string> &challenges,
         res.set_header("WWW-Authenticate", challenge);
         res.set_header("WWW-Authenticate", challenge);
       }
       }
     } else {
     } else {
-      auto authorization = req.get_header_value("Authorization");
-      EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
-      EXPECT_NE(std::string::npos,
-                authorization.find("realm=\"" + expected_realm + "\""));
-      EXPECT_EQ(std::string::npos, authorization.find("Basic"));
+      authorization = req.get_header_value("Authorization");
       res.set_content("ok", "text/plain");
       res.set_content("ok", "text/plain");
     }
     }
   });
   });
@@ -4003,9 +3995,25 @@ run_digest_challenge_list_test(const std::vector<std::string> &challenges,
   Client cli(HOST, port);
   Client cli(HOST, port);
   cli.set_digest_auth("hello", "world");
   cli.set_digest_auth("hello", "world");
   auto res = cli.Get("/x");
   auto res = cli.Get("/x");
-  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
-
+  EXPECT_TRUE(res) << "Error: " << to_string(res.error());
   EXPECT_EQ(2, hits.load());
   EXPECT_EQ(2, hits.load());
+  return authorization;
+}
+
+// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
+// comma-separated list of challenges, and each challenge may itself carry a
+// comma-separated auth-param list, so a server can legally offer Basic
+// before Digest, either as two field lines or packed into one. Checks that
+// the retry carries a well-formed Digest Authorization header naming
+// expected_realm.
+static void
+run_digest_challenge_list_test(const std::vector<std::string> &challenges,
+                               const std::string &expected_realm) {
+  auto authorization = get_digest_retry_authorization(challenges);
+  EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
+  EXPECT_NE(std::string::npos,
+            authorization.find("realm=\"" + expected_realm + "\""));
+  EXPECT_EQ(std::string::npos, authorization.find("Basic"));
 }
 }
 
 
 static const char *kBasicChallenge = "Basic realm=\"decoy\"";
 static const char *kBasicChallenge = "Basic realm=\"decoy\"";
@@ -4036,36 +4044,9 @@ TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
 
 
 // RFC 9110 11.2: auth-param names are matched case-insensitively.
 // RFC 9110 11.2: auth-param names are matched case-insensitively.
 TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
 TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
-  std::atomic<int> hits{0};
-  std::string authorization;
-
-  Server svr;
-  svr.Get("/x", [&](const Request &req, Response &res) {
-    if (++hits == 1) {
-      res.status = StatusCode::Unauthorized_401;
-      res.set_header("WWW-Authenticate",
-                     "Digest Realm=\"testrealm\", QOP=\"auth\", "
-                     "Nonce=\"abc123\", Algorithm=SHA-256, OPAQUE=\"op\"");
-    } else {
-      authorization = req.get_header_value("Authorization");
-      res.set_content("ok", "text/plain");
-    }
-  });
-
-  auto port = svr.bind_to_any_port(HOST);
-  std::thread t([&]() { svr.listen_after_bind(); });
-  auto se = detail::scope_exit([&] {
-    svr.stop();
-    t.join();
-  });
-  svr.wait_until_ready();
-
-  Client cli(HOST, port);
-  cli.set_digest_auth("hello", "world");
-  auto res = cli.Get("/x");
-  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
-  EXPECT_EQ(2, hits.load());
-
+  auto authorization = get_digest_retry_authorization(
+      {"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
+       "Algorithm=SHA-256, OPAQUE=\"op\""});
   EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
   EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
   EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
   EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
   EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
   EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
@@ -4073,6 +4054,43 @@ TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
   EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
   EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
 }
 }
 
 
+// The algorithm is matched case-insensitively and sent back as the server
+// wrote it (RFC 7616 3.4).
+TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
+  auto authorization = get_digest_retry_authorization(
+      {"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
+  EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
+  const std::string prefix = "response=\"";
+  auto b = authorization.find(prefix);
+  ASSERT_NE(std::string::npos, b);
+  b += prefix.size();
+  EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
+}
+
+// qop options are matched case-insensitively as whole tokens.
+TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
+  auto authorization = get_digest_retry_authorization(
+      {"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
+  EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
+
+  authorization = get_digest_retry_authorization(
+      {"Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\""});
+  EXPECT_EQ(std::string::npos, authorization.find("qop="));
+}
+
+// RFC 7616 3.7: the client uses the first Digest challenge it can answer.
+TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
+  auto authorization = get_digest_retry_authorization(
+      {"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
+       "Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
+  EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
+  EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
+
+  authorization = get_digest_retry_authorization(
+      {"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
+  EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
+}
+
 // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
 // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
 // the params and leaves out the fragment.
 // the params and leaves out the fragment.
 TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
 TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
@@ -4107,13 +4125,16 @@ TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
   EXPECT_EQ(target, uri);
   EXPECT_EQ(target, uri);
 }
 }
 
 
-// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
-// make_digest_authentication_header() dereferences both unconditionally, so
-// a server sending a challenge missing either one must not be treated as
-// usable -- doing so used to crash the client with std::out_of_range.
-static void run_digest_challenge_missing_field_test(const char *challenge) {
+// A Digest challenge the client can't answer (realm or nonce missing, or an
+// algorithm it doesn't implement (RFC 7616 3.3)) must leave the 401 as it is,
+// without a retry.
+static void
+run_unanswerable_digest_challenge_test(const std::string &challenge) {
+  std::atomic<int> hits{0};
+
   Server svr;
   Server svr;
   svr.Get("/x", [&](const Request & /*req*/, Response &res) {
   svr.Get("/x", [&](const Request & /*req*/, Response &res) {
+    ++hits;
     res.status = StatusCode::Unauthorized_401;
     res.status = StatusCode::Unauthorized_401;
     res.set_header("WWW-Authenticate", challenge);
     res.set_header("WWW-Authenticate", challenge);
   });
   });
@@ -4131,65 +4152,49 @@ static void run_digest_challenge_missing_field_test(const char *challenge) {
   auto res = cli.Get("/x");
   auto res = cli.Get("/x");
   ASSERT_TRUE(res) << "Error: " << to_string(res.error());
   ASSERT_TRUE(res) << "Error: " << to_string(res.error());
   EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
   EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
+  EXPECT_EQ(1, hits.load());
 }
 }
 
 
 TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
 TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
-  run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
+  run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
 }
 }
 
 
 TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
 TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
-  run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
+  run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
 }
 }
 
 
 TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
 TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
-  run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
+  run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
 }
 }
 
 
-// A hostile server can put a '"' in realm/nonce/opaque, or a non-token
-// algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
-// when storing the values, so the header builder has to re-escape them (and
-// keep algorithm a bare token); otherwise the value breaks out of its
-// quoted-string and injects extra auth-params into the client's Authorization.
-TEST(DigestAuthTest, EscapesInjectedAuthParams) {
-  std::atomic<int> hits{0};
-  std::string authorization;
-
-  Server svr;
-  svr.Get("/x", [&](const Request &req, Response &res) {
-    if (++hits == 1) {
-      res.status = StatusCode::Unauthorized_401;
-      // On the wire the quotes embedded in the values are backslash-escaped.
-      res.set_header("WWW-Authenticate",
-                     "Digest realm=\"testrealm\", "
-                     "nonce=\"n\\\"; injected=\\\"x\", "
-                     "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
-    } else {
-      authorization = req.get_header_value("Authorization");
-      res.set_content("ok", "text/plain");
-    }
-  });
-
-  auto port = svr.bind_to_any_port(HOST);
-  std::thread t([&]() { svr.listen_after_bind(); });
-  auto se = detail::scope_exit([&] {
-    svr.stop();
-    t.join();
-  });
-  svr.wait_until_ready();
-
-  Client cli(HOST, port);
-  cli.set_digest_auth("hello", "world");
-  auto res = cli.Get("/x");
-  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
-  EXPECT_EQ(2, hits.load());
+// RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
+// ignored. The last value isn't a token and would otherwise inject auth-params
+// into the Authorization header.
+TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
+  for (auto algorithm :
+       {"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
+    SCOPED_TRACE(algorithm);
+    run_unanswerable_digest_challenge_test(
+        std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
+                    "algorithm=") +
+        algorithm);
+  }
+}
 
 
+// A hostile server can put a '"' in realm/nonce/opaque in its challenge.
+// parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
+// the header builder has to re-escape them; otherwise the value breaks out of
+// its quoted-string and injects extra auth-params into the Authorization.
+TEST(DigestAuthTest, EscapesInjectedAuthParams) {
+  // On the wire the quotes embedded in the value are backslash-escaped.
+  auto authorization = get_digest_retry_authorization(
+      {"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
+       "qop=\"auth\""});
   EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
   EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
   // The nonce (de-escaped to  n"; injected="x ) must be re-escaped so it stays
   // The nonce (de-escaped to  n"; injected="x ) must be re-escaped so it stays
   // inside its quoted-string rather than starting an "injected" auth-param.
   // inside its quoted-string rather than starting an "injected" auth-param.
   EXPECT_NE(std::string::npos,
   EXPECT_NE(std::string::npos,
             authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
             authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
-  // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
-  EXPECT_EQ(std::string::npos, authorization.find("injected2"));
 }
 }
 
 
 #endif
 #endif