aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/storage/workspaces/httpworkspaces.cpp
diff options
context:
space:
mode:
authorStefan Boberg <[email protected]>2026-05-04 16:46:03 +0200
committerGitHub Enterprise <[email protected]>2026-05-04 16:46:03 +0200
commit10d2a61fe1c848f44033e8450ff3a5ffa7f4322a (patch)
treeaa66c6a068b50d2390bdae5f857c7151f15e5a86 /src/zenserver/storage/workspaces/httpworkspaces.cpp
parentTui picker fixes (#1027) (diff)
downloadarchived-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/zenserver/storage/workspaces/httpworkspaces.cpp')
-rw-r--r--src/zenserver/storage/workspaces/httpworkspaces.cpp62
1 files changed, 59 insertions, 3 deletions
diff --git a/src/zenserver/storage/workspaces/httpworkspaces.cpp b/src/zenserver/storage/workspaces/httpworkspaces.cpp
index 12e7bae73..ba3bc00dd 100644
--- a/src/zenserver/storage/workspaces/httpworkspaces.cpp
+++ b/src/zenserver/storage/workspaces/httpworkspaces.cpp
@@ -4,6 +4,7 @@
#include <zencore/basicfile.h>
#include <zencore/compactbinarybuilder.h>
+#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/trace.h>
@@ -29,6 +30,48 @@ namespace {
return {};
}
+ // Validate a workspace root_path supplied via HTTP. Rejects empty / non-absolute
+ // paths, Windows UNC (\\server\share) and device-namespace prefixes (\\?\, \\.\),
+ // and strings containing control characters. Canonicalises the result so any later
+ // joins and stored config anchor at a resolved, existing directory โ€” a follow-up
+ // symlink swap on disk can no longer redirect the workspace root.
+ std::optional<std::filesystem::path> ValidateWorkspaceRootPath(std::string_view RawInput)
+ {
+ if (RawInput.empty())
+ {
+ return std::nullopt;
+ }
+ for (char C : RawInput)
+ {
+ if (static_cast<unsigned char>(C) < 0x20 || C == 0x7F)
+ {
+ return std::nullopt;
+ }
+ }
+ if (RawInput.starts_with("\\\\") || RawInput.starts_with("//"))
+ {
+ return std::nullopt;
+ }
+
+ std::filesystem::path Requested(RawInput);
+ if (!Requested.is_absolute())
+ {
+ return std::nullopt;
+ }
+
+ std::error_code Ec;
+ std::filesystem::path Canonical = std::filesystem::canonical(Requested, Ec);
+ if (Ec)
+ {
+ return std::nullopt;
+ }
+ if (!std::filesystem::is_directory(Canonical, Ec) || Ec)
+ {
+ return std::nullopt;
+ }
+ return Canonical;
+ }
+
void WriteWorkspaceConfig(CbWriter& Writer, const Workspaces::WorkspaceConfiguration& Config)
{
Writer << "id" << Config.Id;
@@ -505,14 +548,17 @@ HttpWorkspacesService::WorkspaceRequest(HttpRouterRequest& Req)
{
case HttpVerb::kPut:
{
- std::filesystem::path WorkspacePath = GetPathParameter(ServerRequest, "root_path"sv);
- if (WorkspacePath.empty())
+ const std::string RawRootPath = HttpServerRequest::Decode(ServerRequest.GetQueryParams().GetValue("root_path"sv));
+ std::optional<std::filesystem::path> ValidatedRootPath = ValidateWorkspaceRootPath(RawRootPath);
+ if (!ValidatedRootPath)
{
m_WorkspacesStats.BadRequestCount++;
+ ZEN_WARN("workspace PUT rejected unsafe 'root_path' parameter '{}'", RawRootPath);
return ServerRequest.WriteResponse(HttpResponseCode::BadRequest,
HttpContentType::kText,
"Invalid 'root_path' parameter");
}
+ std::filesystem::path WorkspacePath = std::move(*ValidatedRootPath);
if (Req.GetCapture(1) == Oid::Zero.ToString())
{
@@ -1096,6 +1142,16 @@ HttpWorkspacesService::ShareRequest(HttpRouterRequest& Req, const Oid& Workspace
fmt::format("Workspace '{}' does not exist", WorkspaceId));
}
+ std::optional<std::filesystem::path> ResolvedSharePath = ResolveSafeRelativePath(Workspace.RootPath, SharePath.string());
+ if (!ResolvedSharePath)
+ {
+ m_WorkspacesStats.BadRequestCount++;
+ ZEN_WARN("share PUT in workspace '{}' rejected unsafe 'share_path' parameter '{}'", WorkspaceId, SharePath);
+ return ServerRequest.WriteResponse(HttpResponseCode::BadRequest,
+ HttpContentType::kText,
+ "Invalid 'share_path' parameter");
+ }
+
if (!Workspace.AllowShareCreationFromHttp)
{
if (!MayChangeConfiguration(ServerRequest))
@@ -1143,7 +1199,7 @@ HttpWorkspacesService::ShareRequest(HttpRouterRequest& Req, const Oid& Workspace
}
}
- if (!IsDir(Workspace.RootPath / NewConfig.SharePath))
+ if (!IsDir(*ResolvedSharePath))
{
return ServerRequest.WriteResponse(HttpResponseCode::NotFound,
HttpContentType::kText,