Compare commits

..
6 Commits
Author SHA1 Message Date
yhirose 22a57ffeba Release v0.69.0 2026-11-29 10:32:58 -05:00
yhirose 30d5f21b43 Require Mbed TLS built with MBEDTLS_THREADING_C
SSLServer runs TLS handshakes on several pool threads, and SSLClients
may be used from several threads. Mbed TLS is thread-safe only when it
is built with MBEDTLS_THREADING_C, which its default configuration
leaves off. Without it, concurrent handshakes race on the PSA key store
and the shared CTR-DRBG and corrupt memory.

Stop the build with an #error when the option is missing, and document
the requirement in the README. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED
to build anyway when Mbed TLS is only ever used from one thread.
Distribution packages (Debian, Ubuntu, Homebrew) already enable the
option, so builds against them are unaffected.
2026-11-29 10:14:56 -05:00
yhirose c76e1b6a98 Accept several spaces after the auth scheme
RFC 9110 allows 1*SP between the auth scheme and what follows it in both
challenges and credentials. parse_www_authenticate() took the scheme up
to the last whitespace before "=", so "Digest  realm=..." was not
recognized as Digest and the 401 was returned without a retry, and
get_bearer_token_auth() returned the token of "Bearer  abc" with a
leading space.

The scheme is now the text up to the first whitespace, with the key
after it trimmed, and get_bearer_token_auth() skips the extra spaces.
2026-11-28 20:47:13 -05:00
yhirose e22f398cf2 Prefer Digest qop=auth and skip challenges without a usable qop
When a server offered both qop=auth and qop=auth-int, the client chose
auth-int, which hashes req.body. That is empty when a content provider
streams the body, so the response was wrong and the request failed. A
challenge whose qop offered neither option (e.g. only auth-conf) was
answered without qop, although RFC 7616 makes qop mandatory and has the
client use the first challenge it supports.

select_digest_qop() now picks auth over auth-int, as curl does, and
parse_www_authenticate() treats a challenge whose qop offers neither as
unanswerable, so a later challenge is used or the 401 is returned. A
challenge without qop is still answered in the RFC 2069 form.
2026-11-28 20:38:11 -05:00
yhirose c5faf03dfe 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.
2026-11-28 20:30:40 -05:00
Leng Niu 58cd21449c Match Digest challenge parameter names case-insensitively (#2702) 2026-11-28 19:07:39 -05:00
4 changed files with 275 additions and 163 deletions

No files matched your search

+3
View File
@@ -70,6 +70,9 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x, 3.x, and 4.x supported (auto-detected); 4.x renames `libmbedcrypto` to `libtfpsacrypto` | | Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x, 3.x, and 4.x supported (auto-detected); 4.x renames `libmbedcrypto` to `libtfpsacrypto` |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` | | wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
> [!NOTE]
> **Mbed TLS threading:** Mbed TLS must be built with `MBEDTLS_THREADING_C`, because `SSLServer` handles connections on several threads and Mbed TLS is not thread-safe without it. Its default configuration leaves this option off, while distribution packages such as Debian, Ubuntu and Homebrew turn it on. Building against Mbed TLS without it stops with an `#error`. If Mbed TLS is only ever used from one thread, define `CPPHTTPLIB_MBEDTLS_SINGLE_THREADED` to build anyway.
> [!NOTE] > [!NOTE]
> **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable. > **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
> >
+1 -1
View File
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
[site] [site]
title = "cpp-httplib" title = "cpp-httplib"
version = "0.68.0" version = "0.69.0"
hostname = "https://yhirose.github.io" hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib" base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved." footer_message = "© 2026 Yuji Hirose. All rights reserved."
+139 -97
View File
@@ -8,8 +8,8 @@
#ifndef CPPHTTPLIB_HTTPLIB_H #ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H #define CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_VERSION "0.68.0" #define CPPHTTPLIB_VERSION "0.69.0"
#define CPPHTTPLIB_VERSION_NUM "0x004400" #define CPPHTTPLIB_VERSION_NUM "0x004500"
#ifdef _WIN32 #ifdef _WIN32
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00 #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
@@ -565,6 +565,13 @@ using socket_t = int;
#define CPPHTTPLIB_MBEDTLS_V3 #define CPPHTTPLIB_MBEDTLS_V3
#endif #endif
// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently.
#if !defined(MBEDTLS_THREADING_C) && \
!defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED)
#error \
"Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread."
#endif
#endif // CPPHTTPLIB_MBEDTLS_SUPPORT #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
#ifdef CPPHTTPLIB_WOLFSSL_SUPPORT #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
@@ -11224,75 +11231,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[std::move(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(
@@ -11761,6 +11699,121 @@ 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;
}
// Picks auth over auth-int from the qop options a server offers, as curl does:
// auth-int hashes req.body, which is empty when a content provider streams the
// body. Empty when it offers neither.
inline std::string select_digest_qop(const std::string &options) {
std::string qop;
split(options.data(), options.data() + options.size(), ',',
[&](const char *b, const char *e) {
std::string option(b, e);
if (case_ignore::equal(option, "auth")) {
qop = "auth";
} else if (qop.empty() && case_ignore::equal(option, "auth-int")) {
qop = "auth-int";
}
});
return qop;
}
// 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), as is one whose qop offers neither auth nor auth-int, 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 answerable = [](const std::map<std::string, std::string> &c) {
if (c.find("realm") == c.end() || c.find("nonce") == c.end()) {
return false;
}
auto algo_it = c.find("algorithm");
if (algo_it != c.end() && !digest_hash(algo_it->second)) { return false; }
auto qop_it = c.find("qop");
return qop_it == c.end() || !select_digest_qop(qop_it->second).empty();
};
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 && answerable(challenge)) {
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_first_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 = trim_copy(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(
@@ -11775,33 +11828,21 @@ inline std::pair<std::string, std::string> make_digest_authentication_header(
nc = ss.str(); nc = ss.str();
} }
std::string qop; // Without qop, the RFC 2069 form is used.
if (auth.find("qop") != auth.end()) { auto qop_it = auth.find("qop");
qop = auth.at("qop"); auto qop =
if (qop.find("auth-int") != std::string::npos) { qop_it == auth.end() ? std::string() : select_digest_qop(qop_it->second);
qop = "auth-int"; assert(qop_it == auth.end() || !qop.empty());
} else if (qop.find("auth") != std::string::npos) {
qop = "auth";
} else {
qop.clear();
}
}
std::string algo = "MD5"; // Sent back as the server wrote it (RFC 7616 Section 3.4).
if (auth.find("algorithm") != auth.end()) { // parse_www_authenticate() accepts only one digest_hash() knows.
// algorithm is an unquoted token (RFC 7616 §3.4). A server value that is auto algo_it = auth.find("algorithm");
// not a token would otherwise be emitted verbatim and could carry commas auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
// or quotes that inject further auth-params into the header below. auto H = digest_hash(algo);
const auto &a = auth.at("algorithm"); assert(H);
if (fields::is_token(a)) { algo = a; }
}
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;
@@ -12296,15 +12337,16 @@ inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
} }
inline std::string get_bearer_token_auth(const Request &req) { inline std::string get_bearer_token_auth(const Request &req) {
// The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter // The auth scheme is case-insensitive (RFC 9110 11.1) and followed by 1*SP,
// than the prefix carries no token. // and a value shorter than the prefix carries no token.
constexpr const char bearer_prefix[] = "Bearer "; constexpr const char bearer_prefix[] = "Bearer ";
constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix); constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
auto value = req.get_header_value("Authorization"); auto value = req.get_header_value("Authorization");
if (value.size() >= bearer_prefix_len && if (value.size() >= bearer_prefix_len &&
detail::case_ignore::equal(value.substr(0, bearer_prefix_len), detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
bearer_prefix)) { bearer_prefix)) {
return value.substr(bearer_prefix_len); auto pos = value.find_first_not_of(' ', bearer_prefix_len);
if (pos != std::string::npos) { return value.substr(pos); }
} }
return ""; return "";
} }
+132 -65
View File
@@ -2340,7 +2340,8 @@ TEST(BearerTokenAuthTest, SchemeValidation) {
{"x", ""}, {"x", ""},
{"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""}, {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
{"Bearer abc123", "abc123"}, {"Bearer abc123", "abc123"},
{"bearer abc123", "abc123"}, // scheme match is case-insensitive {"bearer abc123", "abc123"}, // scheme match is case-insensitive
{"Bearer abc123", "abc123"}, // 1*SP after the scheme
}; };
for (const auto &c : cases) { for (const auto &c : cases) {
@@ -3963,17 +3964,13 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
} }
} }
// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a // Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
// comma-separated list of challenges, and each challenge may itself carry a // field lines (get_combined_header_value() joins them in receipt order) and
// comma-separated auth-param list, so a server can legally offer Basic // returns the Authorization header of the retry.
// before Digest, either as two field lines or packed into one. Runs one 401 static std::string
// -> Digest-retry round trip with the given field lines (get_combined_header_ get_digest_retry_authorization(const std::vector<std::string> &challenges) {
// 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) {
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 +3980,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"); 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"));
res.set_content("ok", "text/plain"); res.set_content("ok", "text/plain");
} }
}); });
@@ -4003,9 +3996,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\"";
@@ -4034,6 +4043,70 @@ TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
"test,realm"); "test,realm");
} }
// RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
auto authorization =
get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
}
// RFC 9110 11.2: auth-param names are matched case-insensitively.
TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
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("nonce=\"abc123\""));
EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
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.
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,"));
}
// auth-int hashes req.body, which is empty when a content provider streams the
// body, so it is chosen only when the server offers no auth.
TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
}
// 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) {
@@ -4068,13 +4141,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. // A Digest challenge the client can't answer (realm or nonce missing, or no
// make_digest_authentication_header() dereferences both unconditionally, so // algorithm or qop option it implements) must leave the 401 as it is, without
// a server sending a challenge missing either one must not be treated as // a retry.
// usable -- doing so used to crash the client with std::out_of_range. static void
static void run_digest_challenge_missing_field_test(const char *challenge) { 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);
}); });
@@ -4092,65 +4168,56 @@ 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 // RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
// algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs // ignored. The last value isn't a token and would otherwise inject auth-params
// when storing the values, so the header builder has to re-escape them (and // into the Authorization header.
// keep algorithm a bare token); otherwise the value breaks out of its TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
// quoted-string and injects extra auth-params into the client's Authorization. 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);
}
}
// RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
// challenge that offers no other can't be answered.
TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
run_unanswerable_digest_challenge_test(
"Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
}
// 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) { TEST(DigestAuthTest, EscapesInjectedAuthParams) {
std::atomic<int> hits{0}; // On the wire the quotes embedded in the value are backslash-escaped.
std::string authorization; auto authorization = get_digest_retry_authorization(
{"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
Server svr; "qop=\"auth\""});
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());
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