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/zenutil/process/subprocessmanager.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/zenutil/process/subprocessmanager.cpp')
| -rw-r--r-- | src/zenutil/process/subprocessmanager.cpp | 64 |
1 files changed, 47 insertions, 17 deletions
diff --git a/src/zenutil/process/subprocessmanager.cpp b/src/zenutil/process/subprocessmanager.cpp index d0b912a0d..acb518808 100644 --- a/src/zenutil/process/subprocessmanager.cpp +++ b/src/zenutil/process/subprocessmanager.cpp @@ -236,7 +236,7 @@ ManagedProcess::GetTag() const // SubprocessManager::Impl // ============================================================================ -struct SubprocessManager::Impl +struct SubprocessManager::Impl : public std::enable_shared_from_this<Impl> { asio::io_context& m_IoContext; SubprocessManagerConfig m_Config; @@ -308,7 +308,10 @@ SubprocessManager::Impl::Impl(asio::io_context& IoContext, SubprocessManagerConf if (m_Config.MetricsSampleIntervalMs > 0) { m_MetricsTimer = std::make_unique<asio::steady_timer>(IoContext); - EnqueueMetricsTimer(); + // Don't start the timer here: EnqueueMetricsTimer captures + // weak_from_this(), which requires the enclosing shared_ptr to + // already own this. The caller (SubprocessManager ctor) invokes + // EnqueueMetricsTimer() after the shared_ptr is established. } } @@ -381,8 +384,17 @@ SubprocessManager::Impl::SetupExitWatcher(ManagedProcess* Proc, ProcessExitCallb { int Pid = Proc->Pid(); - Proc->m_Impl->m_ExitWatcher.Watch(Proc->m_Impl->m_Handle, [this, Pid, Callback = std::move(OnExit)](int ExitCode) { - ManagedProcess* Found = FindProcess(Pid); + // Capture a weak_ptr so the handler safely no-ops if the manager is + // destroyed (or the process has been Remove()'d) before the exit + // completion is dispatched on the io_context. + Proc->m_Impl->m_ExitWatcher.Watch(Proc->m_Impl->m_Handle, [Self = weak_from_this(), Pid, Callback = std::move(OnExit)](int ExitCode) { + auto Locked = Self.lock(); + if (!Locked) + { + return; + } + + ManagedProcess* Found = Locked->FindProcess(Pid); if (Found) { @@ -399,17 +411,22 @@ SubprocessManager::Impl::SetupStdoutReader(ManagedProcess* Proc, StdoutPipeHandl Proc->m_Impl->m_StdoutReader = std::make_unique<AsyncPipeReader>(m_IoContext); Proc->m_Impl->m_StdoutReader->Start( std::move(Pipe), - [this, Pid](std::string_view Data) { - ManagedProcess* Found = FindProcess(Pid); + [Self = weak_from_this(), Pid](std::string_view Data) { + auto Locked = Self.lock(); + if (!Locked) + { + return; + } + ManagedProcess* Found = Locked->FindProcess(Pid); if (Found) { if (Found->m_Impl->m_StdoutCallback) { Found->m_Impl->m_StdoutCallback(*Found, Data); } - else if (m_DefaultStdoutCallback) + else if (Locked->m_DefaultStdoutCallback) { - m_DefaultStdoutCallback(*Found, Data); + Locked->m_DefaultStdoutCallback(*Found, Data); } else { @@ -427,17 +444,22 @@ SubprocessManager::Impl::SetupStderrReader(ManagedProcess* Proc, StdoutPipeHandl Proc->m_Impl->m_StderrReader = std::make_unique<AsyncPipeReader>(m_IoContext); Proc->m_Impl->m_StderrReader->Start( std::move(Pipe), - [this, Pid](std::string_view Data) { - ManagedProcess* Found = FindProcess(Pid); + [Self = weak_from_this(), Pid](std::string_view Data) { + auto Locked = Self.lock(); + if (!Locked) + { + return; + } + ManagedProcess* Found = Locked->FindProcess(Pid); if (Found) { if (Found->m_Impl->m_StderrCallback) { Found->m_Impl->m_StderrCallback(*Found, Data); } - else if (m_DefaultStderrCallback) + else if (Locked->m_DefaultStderrCallback) { - m_DefaultStderrCallback(*Found, Data); + Locked->m_DefaultStderrCallback(*Found, Data); } else { @@ -557,14 +579,19 @@ SubprocessManager::Impl::EnqueueMetricsTimer() } m_MetricsTimer->expires_after(std::chrono::milliseconds(m_Config.MetricsSampleIntervalMs)); - m_MetricsTimer->async_wait([this](const asio::error_code& Ec) { - if (Ec || !m_Running.load()) + m_MetricsTimer->async_wait([Self = weak_from_this()](const asio::error_code& Ec) { + auto Locked = Self.lock(); + if (!Locked) + { + return; + } + if (Ec || !Locked->m_Running.load()) { return; } - SampleBatch(); - EnqueueMetricsTimer(); + Locked->SampleBatch(); + Locked->EnqueueMetricsTimer(); }); } @@ -711,8 +738,11 @@ SubprocessManager::Impl::EnumerateGroups(std::function<void(const ProcessGroup&) // ============================================================================ SubprocessManager::SubprocessManager(asio::io_context& IoContext, SubprocessManagerConfig Config) -: m_Impl(std::make_unique<Impl>(IoContext, Config)) +: m_Impl(std::make_shared<Impl>(IoContext, Config)) { + // Start the metrics timer now that the shared_ptr owns the Impl - only + // then does weak_from_this() produce a valid weak_ptr for the handler. + m_Impl->EnqueueMetricsTimer(); } SubprocessManager::~SubprocessManager() = default; |