aboutsummaryrefslogtreecommitdiff
path: root/src/zenhttp/zipfs.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/zenhttp/zipfs.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/zenhttp/zipfs.cpp')
-rw-r--r--src/zenhttp/zipfs.cpp111
1 files changed, 79 insertions, 32 deletions
diff --git a/src/zenhttp/zipfs.cpp b/src/zenhttp/zipfs.cpp
index c0ffa2052..3bd09091a 100644
--- a/src/zenhttp/zipfs.cpp
+++ b/src/zenhttp/zipfs.cpp
@@ -100,57 +100,105 @@ namespace {
//////////////////////////////////////////////////////////////////////////
ZipFs::ZipFs(IoBuffer&& Buffer)
{
- MemoryView View = Buffer.GetView();
-
- uint8_t* Cursor = (uint8_t*)(View.GetData()) + View.GetSize();
- if (View.GetSize() < sizeof(EocdRecord))
+ // Treat the input buffer as attacker-controlled. Every offset, size, and
+ // trailer length is validated against View.GetSize() before it is used to
+ // form a pointer. All additions are performed in uint64_t to prevent 32-bit
+ // wrap.
+ const MemoryView View = Buffer.GetView();
+ const uint8_t* Base = static_cast<const uint8_t*>(View.GetData());
+ const size_t Size = View.GetSize();
+
+ if (Size < sizeof(EocdRecord))
{
return;
}
- const auto* EocdCursor = (EocdRecord*)(Cursor - sizeof(EocdRecord));
+ const size_t EocdOffset = Size - sizeof(EocdRecord);
+ const EocdRecord* Eocd = reinterpret_cast<const EocdRecord*>(Base + EocdOffset);
- // It is more correct to search backwards for EocdRecord::Magic as the
- // comment can be of a variable length. But here we're not going to support
- // zip files with comments.
- if (EocdCursor->Signature != EocdRecord::Magic)
+ // We only support a zip whose EOCD sits at the very end of the buffer โ€” no
+ // trailing comment, no Zip64.
+ if (Eocd->Signature != EocdRecord::Magic)
+ {
+ return;
+ }
+ if (Eocd->ThisDiskIndex == 0xffff)
{
return;
}
- // Zip64 isn't supported either
- if (EocdCursor->ThisDiskIndex == 0xffff)
+ const uint32_t CdOffsetRel = Eocd->CdOffset;
+ const uint32_t CdSize = Eocd->CdSize;
+ const uint16_t CdRecordCount = Eocd->CdRecordCount;
+
+ // Central directory must fit strictly before the EOCD. Derive the archive
+ // origin from the EOCD's declared layout so any pre-zip padding in the
+ // buffer is accounted for; LFH offsets are relative to this origin.
+ if (uint64_t(CdOffsetRel) + uint64_t(CdSize) > EocdOffset)
{
return;
}
- Cursor = (uint8_t*)EocdCursor - uint32_t(EocdCursor->CdOffset) - uint32_t(EocdCursor->CdSize);
+ const uint8_t* ArchiveStart = Base + (EocdOffset - CdOffsetRel - CdSize);
+ const uint8_t* CdCursor = ArchiveStart + CdOffsetRel;
+ const uint8_t* CdEnd = CdCursor + CdSize;
- const auto* CdCursor = (CentralDirectoryRecord*)(Cursor + EocdCursor->CdOffset);
- for (int i = 0, n = EocdCursor->CdRecordCount; i < n; ++i)
+ for (uint32_t Record = 0; Record < CdRecordCount; ++Record)
{
- const CentralDirectoryRecord& Cd = *CdCursor;
+ if (size_t(CdEnd - CdCursor) < sizeof(CentralDirectoryRecord))
+ {
+ return;
+ }
+ const CentralDirectoryRecord& Cd = *reinterpret_cast<const CentralDirectoryRecord*>(CdCursor);
+ if (Cd.Signature != CentralDirectoryRecord::Magic)
+ {
+ return;
+ }
+
+ const uint16_t NameLen = Cd.FileNameLength;
+ const uint16_t ExtraLen = Cd.ExtraFieldLength;
+ const uint16_t CommentLen = Cd.CommentLength;
+ const uint32_t Trailer = uint32_t(NameLen) + uint32_t(ExtraLen) + uint32_t(CommentLen);
+ if (size_t(CdEnd - CdCursor) - sizeof(CentralDirectoryRecord) < Trailer)
+ {
+ return;
+ }
+
+ const uint16_t Compression = Cd.CompressionMethod;
+ const uint32_t Compressed = Cd.CompressedSize;
+ const uint32_t Original = Cd.OriginalSize;
+ const uint32_t LfhOffset = Cd.Offset;
- bool Acceptable = true;
- Acceptable &= (Cd.OriginalSize > 0); // has some content
- Acceptable &= (Cd.CompressionMethod == 0 || Cd.CompressionMethod == 8); // stored or deflate
- if (Acceptable)
+ const bool AcceptableCompression = (Compression == 0) || (Compression == 8);
+ const bool HasContent = Original > 0;
+ if (AcceptableCompression && HasContent)
{
- const uint8_t* Lfh = Cursor + Cd.Offset;
- if (uintptr_t(Lfh - Cursor) < View.GetSize())
+ // LFH header must fit inside the [ArchiveStart, CdOffsetRel) region
+ // (i.e. the pre-CD body). The LFH's own name + extra + compressed
+ // payload must also fit in that region.
+ const uint64_t LfhEndRel = uint64_t(LfhOffset) + sizeof(LocalFileHeader);
+ if (LfhEndRel <= CdOffsetRel)
{
- std::string_view FileName(Cd.FileName, Cd.FileNameLength);
- FileItem Item;
- Item.View = MemoryView{Lfh, size_t(0)};
- Item.CompressionMethod = Cd.CompressionMethod;
- Item.CompressedSize = Cd.CompressedSize;
- Item.UncompressedSize = Cd.OriginalSize;
- m_Files.insert(std::make_pair(FileName, std::move(Item)));
+ const LocalFileHeader* Lfh = reinterpret_cast<const LocalFileHeader*>(ArchiveStart + LfhOffset);
+ const uint64_t DataStartRel =
+ LfhEndRel + uint64_t(uint16_t(Lfh->FileNameLength)) + uint64_t(uint16_t(Lfh->ExtraFieldLength));
+ const uint64_t DataEndRel = DataStartRel + uint64_t(Compressed);
+ if (DataEndRel <= CdOffsetRel)
+ {
+ const uint8_t* FileData = ArchiveStart + DataStartRel;
+ std::string_view FileName(Cd.FileName, NameLen);
+
+ FileItem Item;
+ Item.View = MemoryView{FileData, size_t(0)};
+ Item.CompressionMethod = Compression;
+ Item.CompressedSize = Compressed;
+ Item.UncompressedSize = Original;
+ m_Files.insert({FileName, std::move(Item)});
+ }
}
}
- uint32_t ExtraBytes = Cd.FileNameLength + Cd.ExtraFieldLength + Cd.CommentLength;
- CdCursor = (CentralDirectoryRecord*)(Cd.FileName + ExtraBytes);
+ CdCursor += sizeof(CentralDirectoryRecord) + Trailer;
}
m_Buffer = std::move(Buffer);
@@ -184,8 +232,7 @@ ZipFs::GetFile(const std::string_view& FileName) const
return IoBuffer(IoBuffer::Wrap, Item.View.GetData(), Item.View.GetSize());
}
- const auto* Lfh = (LocalFileHeader*)(Item.View.GetData());
- const uint8_t* FileData = (const uint8_t*)(Lfh->FileName + Lfh->FileNameLength + Lfh->ExtraFieldLength);
+ const uint8_t* FileData = static_cast<const uint8_t*>(Item.View.GetData());
if (Item.CompressionMethod == 0)
{