diff options
| author | Stefan Boberg <[email protected]> | 2026-05-04 16:46:03 +0200 |
|---|---|---|
| committer | GitHub Enterprise <[email protected]> | 2026-05-04 16:46:03 +0200 |
| commit | 10d2a61fe1c848f44033e8450ff3a5ffa7f4322a (patch) | |
| tree | aa66c6a068b50d2390bdae5f857c7151f15e5a86 /src/zenhttp/auth/oidc.cpp | |
| parent | Tui picker fixes (#1027) (diff) | |
| download | archived-zen-10d2a61fe1c848f44033e8450ff3a5ffa7f4322a.tar.xz archived-zen-10d2a61fe1c848f44033e8450ff3a5ffa7f4322a.zip | |
zenhttp improvements (robustness / correctness) (#968)
A collection of security, correctness, and robustness fixes in `zenhttp` and `zencore` surfaced by security review. Most items are small, independent commits grouped here because they all tighten trust boundaries or fix UB along the same code paths.
## WebSocket protocol hardening (RFC 6455)
- **Enforce the client-side mask bit**. Server-side frame loops now reject unmasked frames with close code 1002 per §5.1. Prevents HTTP intermediary smuggling.
- **Validate control frames and RSV bits**. Fragmented control frames, oversized (>125 B) control payloads, and any non-zero RSV bit now fail the connection before allocation.
- **Lower per-frame payload cap** from 256 MB → 4 MB. Bounds per-connection accumulator memory.
- **Implement message fragmentation**. Continuation frames are coalesced and delivered as a single message; interleaved non-control frames close with 1002; assembled messages are capped at 4 MB (1009 on overflow). Previously partial fragments were delivered to handlers, bypassing payload validation.
- **Parse the 101 handshake response properly** in `HttpWsClient`. Status-line, `Upgrade`, `Connection`, and `Sec-WebSocket-Accept` are now matched exactly rather than via substring searches against the full body.
## Auth / OIDC hardening
- **Constant-time password compare** in `PasswordSecurity::IsAllowed` (closes a remote length/content timing oracle). Adds a shared `ConstantTimeEquals` helper.
- **Harden Basic-auth header parsing**: trim trailing LWS, reject control bytes and DEL in the credential.
- **OIDC discovery pinning**: require HTTPS (loopback exempt), verify `issuer` matches `BaseUrl`, require `token_endpoint` / `userinfo_endpoint` / `jwks_uri` to share origin with `BaseUrl`, reject empty `token_endpoint`.
- **Restrict `POST /auth/oidc/refreshtoken`** to local-machine requests. Previously unauthenticated in default deployments — remote callers could evict or replace cached tokens.
- **Stop logging OIDC provider response bodies** on refresh failure (IdPs echo `refresh_token` back in error bodies).
- **Drop the unused `IdentityToken` field** from `OidcClient` / `OpenIdToken` so nothing in the tree accidentally trusts an unverified JWT.
## Auth state encryption migration
- Add `AesGcm` AEAD primitive (BCrypt / OpenSSL backends, mbedTLS stubbed) and `CryptoRandom::Fill` CSPRNG helper in `zencore/crypto.h`.
- Migrate authstate file from AES-256-CBC with a fixed IV to AES-GCM with a fresh 12-byte random nonce per write and the 4-byte `ZEN1` magic bound as AAD. Legacy-CBC files are transparently read once and rewritten in the new format.
## Filesystem / IO robustness
- `IoBufferExtendedCore::Materialize` now checks `MAP_FAILED` on POSIX (was comparing to `nullptr`, which let the failure sentinel propagate into later reads and `munmap(MAP_FAILED, ...)`).
- `IoBufferBuilder::MakeFromFile / MakeFromTemporaryFile`: close the FD/HANDLE on exception via a dismissable `ScopeGuard`; actually check the `fstat()` return value (previously used an uninitialized `FileSize`).
- `ReadFromFileMaybe`: loop short reads, retry `EINTR`, chunk Windows `ReadFile` at `0xFFFFFFFF` bytes (fixes silent truncation of multi-GiB reads).
- `WipeDirectory`: compare `FindFirstFileW` handle against `INVALID_HANDLE_VALUE` rather than `nullptr`.
- `RemoveFileNative` (Linux/macOS): report non-`ENOENT` stat failures via the `std::error_code` out-param and stop reading `st_mode` after a failed stat.
## Buffer / compression correctness
- Avoid per-copy `IoBufferCore` heap allocations in `CompositeBuffer::CopyTo / ViewOrCopyRange` iterators; add fast path for `BufferHeader::Read` when the 64-byte header fits in the first plain-memory segment.
- `BufferHeader`: add `IsHeaderValid()` gate covering `BlockSizeExponent` range, `BlockCount * BlockSize` overflow, and `TotalRawSize` bounds before any arithmetic uses them. Defends against attacker-controlled headers that can pass the CRC and trigger OOB writes in `DecompressBlock`.
Diffstat (limited to 'src/zenhttp/auth/oidc.cpp')
| -rw-r--r-- | src/zenhttp/auth/oidc.cpp | 168 |
1 files changed, 162 insertions, 6 deletions
diff --git a/src/zenhttp/auth/oidc.cpp b/src/zenhttp/auth/oidc.cpp index 23bbc17e8..63c8d9030 100644 --- a/src/zenhttp/auth/oidc.cpp +++ b/src/zenhttp/auth/oidc.cpp @@ -32,6 +32,68 @@ namespace details { using namespace std::literals; +// Return the "scheme://host[:port]" prefix of an absolute URL, or empty on +// malformed input. RFC 8414 §3 requires every endpoint advertised by an +// OP to live under the issuer's origin, so exact-prefix comparison on this +// value is sufficient to pin an endpoint to the configured IdP. +static std::string_view +OriginOf(std::string_view Url) +{ + // scheme://... + auto SchemeEnd = Url.find("://"); + if (SchemeEnd == std::string_view::npos) + { + return {}; + } + // First path char (or query / fragment) after the authority. + const size_t AuthorityStart = SchemeEnd + 3; + size_t OriginEnd = Url.size(); + for (size_t I = AuthorityStart; I < Url.size(); ++I) + { + const char C = Url[I]; + if (C == '/' || C == '?' || C == '#') + { + OriginEnd = I; + break; + } + } + // Require at least one character in the authority. + if (OriginEnd == AuthorityStart) + { + return {}; + } + return Url.substr(0, OriginEnd); +} + +// True if the URL uses a scheme / host that we trust for discovery even +// without HTTPS — narrowly, only loopback for dev / test setups. +static bool +IsLoopbackHttp(std::string_view Url) +{ + constexpr std::string_view Prefixes[] = { + "http://localhost"sv, + "http://127.0.0.1"sv, + "http://[::1]"sv, + }; + for (std::string_view P : Prefixes) + { + if (Url.size() >= P.size() && Url.substr(0, P.size()) == P) + { + // Ensure the next char (if any) ends the authority cleanly. + if (Url.size() == P.size()) + { + return true; + } + const char Next = Url[P.size()]; + if (Next == ':' || Next == '/' || Next == '?' || Next == '#') + { + return true; + } + } + } + return false; +} + static std::string FormUrlEncode(std::string_view Input) { @@ -60,6 +122,19 @@ OidcClient::OidcClient(const OidcClient::Options& Options) OidcClient::InitResult OidcClient::Initialize() { + // The OIDC discovery document determines where we send refresh tokens, so + // the transport to the discovery endpoint has to be trustworthy. Require + // HTTPS on the configured BaseUrl. Loopback is permitted over plain HTTP + // for developer setups that run a local IdP mock — no meaningful attack + // surface on the loopback interface. + if (m_BaseUrl.size() < 8 || m_BaseUrl.substr(0, 8) != "https://"sv) + { + if (!IsLoopbackHttp(m_BaseUrl)) + { + return {.Reason = "BaseUrl must use https:// (or a http://localhost / 127.0.0.1 / [::1] loopback)"}; + } + } + HttpClient Http{m_BaseUrl}; HttpClient::Response Response = Http.Get("/.well-known/openid-configuration"sv); @@ -81,14 +156,86 @@ OidcClient::Initialize() return {.Reason = std::move(JsonError)}; } - m_Config = {.Issuer = Json["issuer"].string_value(), + // RFC 8414 §3: the discovery document's `issuer` value MUST identify the + // OP and MUST be the origin used to fetch the document. Without this + // check, an attacker who can intercept discovery (or a misconfigured + // intermediate) can swap the issuer identity without detection. Accept + // a trailing '/' divergence since OPs vary. + const std::string Issuer = Json["issuer"].string_value(); + { + std::string_view ExpectedBase = m_BaseUrl; + while (!ExpectedBase.empty() && ExpectedBase.back() == '/') + { + ExpectedBase.remove_suffix(1); + } + std::string_view ActualIssuer = Issuer; + while (!ActualIssuer.empty() && ActualIssuer.back() == '/') + { + ActualIssuer.remove_suffix(1); + } + if (ActualIssuer.empty() || ActualIssuer != ExpectedBase) + { + return {.Reason = fmt::format("discovery issuer mismatch (expected '{}')", ExpectedBase)}; + } + } + + // Pin every endpoint we actually use to the same origin as BaseUrl. This + // is the last defense against a tampered discovery document redirecting + // token submissions to an attacker-controlled host. We check the + // endpoints we may call later; endpoints this client never dispatches to + // are left alone so a discovery document with unrelated auxiliary URLs + // isn't rejected for no reason. + const std::string_view BaseOrigin = OriginOf(m_BaseUrl); + if (BaseOrigin.empty()) + { + return {.Reason = "BaseUrl is malformed"}; + } + + const std::string TokenEndpoint = Json["token_endpoint"].string_value(); + const std::string UserInfoEndpoint = Json["userinfo_endpoint"].string_value(); + const std::string JwksUri = Json["jwks_uri"].string_value(); + + auto CheckOrigin = [&](std::string_view Name, std::string_view Url) -> std::optional<std::string> { + if (Url.empty()) + { + return std::nullopt; + } + const std::string_view Origin = OriginOf(Url); + if (Origin != BaseOrigin) + { + return fmt::format("discovery endpoint '{}' is off-origin (expected origin '{}')", Name, BaseOrigin); + } + return std::nullopt; + }; + + if (auto Err = CheckOrigin("token_endpoint"sv, TokenEndpoint); Err.has_value()) + { + return {.Reason = std::move(*Err)}; + } + if (auto Err = CheckOrigin("userinfo_endpoint"sv, UserInfoEndpoint); Err.has_value()) + { + return {.Reason = std::move(*Err)}; + } + if (auto Err = CheckOrigin("jwks_uri"sv, JwksUri); Err.has_value()) + { + return {.Reason = std::move(*Err)}; + } + + // token_endpoint is required for the refresh flow we implement; fail early + // rather than at RefreshToken time if the OP omitted it. + if (TokenEndpoint.empty()) + { + return {.Reason = "discovery document is missing token_endpoint"}; + } + + m_Config = {.Issuer = Issuer, .AuthorizationEndpoint = Json["authorization_endpoint"].string_value(), - .TokenEndpoint = Json["token_endpoint"].string_value(), - .UserInfoEndpoint = Json["userinfo_endpoint"].string_value(), + .TokenEndpoint = TokenEndpoint, + .UserInfoEndpoint = UserInfoEndpoint, .RegistrationEndpoint = Json["registration_endpoint"].string_value(), .EndSessionEndpoint = Json["end_session_endpoint"].string_value(), .DeviceAuthorizationEndpoint = Json["device_authorization_endpoint"].string_value(), - .JwksUri = Json["jwks_uri"].string_value(), + .JwksUri = JwksUri, .SupportedResponseTypes = details::ToStringArray(Json["response_types_supported"]), .SupportedResponseModes = details::ToStringArray(Json["response_modes_supported"]), .SupportedGrantTypes = details::ToStringArray(Json["grant_types_supported"]), @@ -118,7 +265,12 @@ OidcClient::RefreshToken(std::string_view RefreshToken) if (Response.StatusCode != HttpResponseCode::OK) { - return {.Reason = fmt::format("{} ({})", ToString(Response.StatusCode), Response.AsText())}; + // Do NOT include Response.AsText() in the reason string. Some IdPs + // echo the submitted refresh_token (or a prefix of it) in their error + // body — plumbing that into the Reason string causes AuthMgrImpl's + // ZEN_WARN in the refresh paths to write the token into the log. + // Only the status code is safe to surface up to the log sites. + return {.Reason = fmt::format("{} (provider returned {} bytes)", ToString(Response.StatusCode), Response.AsText().size())}; } std::string JsonError; @@ -129,10 +281,14 @@ OidcClient::RefreshToken(std::string_view RefreshToken) return {.Reason = std::move(JsonError)}; } + // Note: id_token is intentionally not parsed. It is a JWT whose contents + // are meaningful only after signature / issuer / audience / expiry + // verification against the provider's JWKS, and nothing downstream + // currently consumes it. Leaving it unparsed avoids planting an + // unauthenticated identity claim in the OpenIdToken cache. return {.TokenType = Json["token_type"].string_value(), .AccessToken = Json["access_token"].string_value(), .RefreshToken = Json["refresh_token"].string_value(), - .IdentityToken = Json["id_token"].string_value(), .Scope = Json["scope"].string_value(), .ExpiresInSeconds = static_cast<int64_t>(Json["expires_in"].int_value()), .Ok = true}; |