aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/crypto.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/zencore/crypto.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/zencore/crypto.cpp')
-rw-r--r--src/zencore/crypto.cpp550
1 files changed, 550 insertions, 0 deletions
diff --git a/src/zencore/crypto.cpp b/src/zencore/crypto.cpp
index 9984f35ac..8a172de3a 100644
--- a/src/zencore/crypto.cpp
+++ b/src/zencore/crypto.cpp
@@ -432,6 +432,285 @@ namespace crypto {
return true;
}
+ //////////////////////////////////////////////////////////////////////////
+ //
+ // AES-256-GCM backends
+ //
+
+#if ZEN_USE_MBEDTLS
+
+ MemoryView GcmTransform(TransformMode Mode,
+ const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView In,
+ MutableMemoryView Out,
+ MutableMemoryView TagOut, // only used for Encrypt
+ MemoryView TagIn, // only used for Decrypt
+ std::optional<std::string>& Reason)
+ {
+ Reason = "AES-GCM is not implemented on the mbedTLS backend"sv;
+ (void)Mode;
+ (void)Key;
+ (void)Nonce;
+ (void)Aad;
+ (void)In;
+ (void)Out;
+ (void)TagOut;
+ (void)TagIn;
+ return MemoryView();
+ }
+
+#elif ZEN_USE_OPENSSL
+
+ MemoryView GcmTransform(TransformMode Mode,
+ const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView In,
+ MutableMemoryView Out,
+ MutableMemoryView TagOut,
+ MemoryView TagIn,
+ std::optional<std::string>& Reason)
+ {
+ EvpContext Ctx;
+
+ const EVP_CIPHER* Cipher = EVP_aes_256_gcm();
+ ZEN_ASSERT(Cipher != nullptr);
+
+ const bool Encrypting = (Mode == TransformMode::Encrypt);
+
+ if (EVP_CipherInit_ex(Ctx, Cipher, nullptr, nullptr, nullptr, Encrypting ? 1 : 0) != 1)
+ {
+ Reason = "EVP_CipherInit_ex (algo) failed"sv;
+ return {};
+ }
+
+ // Explicitly set IV length to 12; the default is 12 for GCM but pinning
+ // it prevents any surprise from an OpenSSL build that defaults
+ // differently.
+ if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_SET_IVLEN, (int)AesGcm::NonceSize, nullptr) != 1)
+ {
+ Reason = "EVP_CTRL_AEAD_SET_IVLEN failed"sv;
+ return {};
+ }
+
+ if (EVP_CipherInit_ex(Ctx,
+ nullptr,
+ nullptr,
+ reinterpret_cast<const unsigned char*>(Key.GetView().GetData()),
+ reinterpret_cast<const unsigned char*>(Nonce.GetData()),
+ Encrypting ? 1 : 0) != 1)
+ {
+ Reason = "EVP_CipherInit_ex (key+nonce) failed"sv;
+ return {};
+ }
+
+ // Feed AAD (if any) before the ciphertext/plaintext.
+ if (!Aad.IsEmpty())
+ {
+ int AadOutLen = 0;
+ if (EVP_CipherUpdate(Ctx,
+ nullptr,
+ &AadOutLen,
+ reinterpret_cast<const unsigned char*>(Aad.GetData()),
+ static_cast<int>(Aad.GetSize())) != 1)
+ {
+ Reason = "EVP_CipherUpdate (AAD) failed"sv;
+ return {};
+ }
+ }
+
+ // For decrypt, set the expected tag before calling Final so the tag
+ // check can fail cleanly.
+ if (!Encrypting)
+ {
+ if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_SET_TAG, (int)TagIn.GetSize(), (void*)TagIn.GetData()) != 1)
+ {
+ Reason = "EVP_CTRL_AEAD_SET_TAG failed"sv;
+ return {};
+ }
+ }
+
+ int BodyLen = 0;
+ if (EVP_CipherUpdate(Ctx,
+ reinterpret_cast<unsigned char*>(Out.GetData()),
+ &BodyLen,
+ reinterpret_cast<const unsigned char*>(In.GetData()),
+ static_cast<int>(In.GetSize())) != 1)
+ {
+ Reason = "EVP_CipherUpdate (body) failed"sv;
+ return {};
+ }
+
+ int FinalLen = 0;
+ if (EVP_CipherFinal_ex(Ctx, reinterpret_cast<unsigned char*>(Out.GetData()) + BodyLen, &FinalLen) != 1)
+ {
+ // For decrypt, this is the authentication-tag mismatch path.
+ Reason = Encrypting ? std::string("EVP_CipherFinal_ex (encrypt) failed") : std::string("AES-GCM authentication tag mismatch");
+ return {};
+ }
+
+ if (Encrypting)
+ {
+ if (EVP_CIPHER_CTX_ctrl(Ctx, EVP_CTRL_AEAD_GET_TAG, (int)TagOut.GetSize(), TagOut.GetData()) != 1)
+ {
+ Reason = "EVP_CTRL_AEAD_GET_TAG failed"sv;
+ return {};
+ }
+ }
+
+ return Out.Left(static_cast<size_t>(BodyLen + FinalLen));
+ }
+
+#else // ZEN_USE_BCRYPT
+
+ MemoryView GcmTransform(TransformMode Mode,
+ const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView In,
+ MutableMemoryView Out,
+ MutableMemoryView TagOut,
+ MemoryView TagIn,
+ std::optional<std::string>& Reason)
+ {
+ BCRYPT_ALG_HANDLE hAlg = nullptr;
+ NTSTATUS Status = STATUS_UNSUCCESSFUL;
+
+ if (!NT_SUCCESS(Status = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM, nullptr, 0)))
+ {
+ Reason = fmt::format("BCryptOpenAlgorithmProvider failed, 0x{:08x}"sv, Status);
+ return {};
+ }
+ auto CloseAlg = MakeGuard([hAlg] { BCryptCloseAlgorithmProvider(hAlg, 0); });
+
+ if (!NT_SUCCESS(Status =
+ BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0)))
+ {
+ Reason = fmt::format("BCryptSetProperty(CHAIN_MODE_GCM) failed, 0x{:08x}"sv, Status);
+ return {};
+ }
+
+ BCRYPT_KEY_HANDLE hKey = nullptr;
+ if (!NT_SUCCESS(Status = BCryptGenerateSymmetricKey(hAlg,
+ &hKey,
+ nullptr,
+ 0,
+ (PUCHAR)Key.GetView().GetData(),
+ (ULONG)Key.GetView().GetSize(),
+ 0)))
+ {
+ Reason = fmt::format("BCryptGenerateSymmetricKey failed, 0x{:08x}"sv, Status);
+ return {};
+ }
+ auto CloseKey = MakeGuard([hKey] { BCryptDestroyKey(hKey); });
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO AuthInfo;
+ BCRYPT_INIT_AUTH_MODE_INFO(AuthInfo);
+ AuthInfo.pbNonce = (PUCHAR)Nonce.GetData();
+ AuthInfo.cbNonce = (ULONG)Nonce.GetSize();
+ AuthInfo.pbAuthData = Aad.IsEmpty() ? nullptr : (PUCHAR)Aad.GetData();
+ AuthInfo.cbAuthData = (ULONG)Aad.GetSize();
+
+ ULONG ResultLen = 0;
+
+ if (Mode == TransformMode::Encrypt)
+ {
+ AuthInfo.pbTag = (PUCHAR)TagOut.GetData();
+ AuthInfo.cbTag = (ULONG)TagOut.GetSize();
+
+ Status = BCryptEncrypt(hKey,
+ (PUCHAR)In.GetData(),
+ (ULONG)In.GetSize(),
+ &AuthInfo,
+ nullptr,
+ 0,
+ (PUCHAR)Out.GetData(),
+ (ULONG)Out.GetSize(),
+ &ResultLen,
+ /*flags=*/0);
+
+ if (!NT_SUCCESS(Status))
+ {
+ Reason = fmt::format("BCryptEncrypt (GCM) failed, 0x{:08x}"sv, Status);
+ return {};
+ }
+ }
+ else
+ {
+ AuthInfo.pbTag = (PUCHAR)TagIn.GetData();
+ AuthInfo.cbTag = (ULONG)TagIn.GetSize();
+
+ Status = BCryptDecrypt(hKey,
+ (PUCHAR)In.GetData(),
+ (ULONG)In.GetSize(),
+ &AuthInfo,
+ nullptr,
+ 0,
+ (PUCHAR)Out.GetData(),
+ (ULONG)Out.GetSize(),
+ &ResultLen,
+ /*flags=*/0);
+
+ if (!NT_SUCCESS(Status))
+ {
+ // STATUS_AUTH_TAG_MISMATCH (0xC000A002) is the tag-failure path.
+ Reason = fmt::format("BCryptDecrypt (GCM) failed, 0x{:08x}"sv, Status);
+ return {};
+ }
+ }
+
+ return Out.Left(ResultLen);
+ }
+
+#endif // backend selection
+
+ MemoryView Gcm(TransformMode Mode,
+ const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView In,
+ MutableMemoryView Out,
+ MutableMemoryView TagOut,
+ MemoryView TagIn,
+ std::optional<std::string>& Reason)
+ {
+ if (!Key.IsValid())
+ {
+ Reason = "invalid key"sv;
+ return {};
+ }
+ if (Nonce.GetSize() != AesGcm::NonceSize)
+ {
+ Reason = fmt::format("AES-GCM nonce must be exactly {} bytes"sv, AesGcm::NonceSize);
+ return {};
+ }
+ if (Out.GetSize() < In.GetSize())
+ {
+ Reason = "AES-GCM output buffer is too small"sv;
+ return {};
+ }
+ if (Mode == TransformMode::Encrypt)
+ {
+ if (TagOut.GetSize() != AesGcm::TagSize)
+ {
+ Reason = fmt::format("AES-GCM tag output must be exactly {} bytes"sv, AesGcm::TagSize);
+ return {};
+ }
+ }
+ else
+ {
+ if (TagIn.GetSize() != AesGcm::TagSize)
+ {
+ Reason = fmt::format("AES-GCM tag input must be exactly {} bytes"sv, AesGcm::TagSize);
+ return {};
+ }
+ }
+
+ return GcmTransform(Mode, Key, Nonce, Aad, In, Out, TagOut, TagIn, Reason);
+ }
+
} // namespace crypto
bool
@@ -741,6 +1020,78 @@ Aes::Decrypt(const AesKey256Bit& Key, const AesIV128Bit& IV, MemoryView In, Muta
return crypto::Transform(crypto::TransformMode::Decrypt, Key.GetView(), IV.GetView(), In, Out, Reason);
}
+MemoryView
+AesGcm::Encrypt(const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView Plaintext,
+ MutableMemoryView Out,
+ MutableMemoryView OutTag,
+ std::optional<std::string>& Reason)
+{
+ return crypto::Gcm(crypto::TransformMode::Encrypt, Key, Nonce, Aad, Plaintext, Out, OutTag, /*TagIn*/ {}, Reason);
+}
+
+MemoryView
+AesGcm::Decrypt(const AesKey256Bit& Key,
+ MemoryView Nonce,
+ MemoryView Aad,
+ MemoryView Ciphertext,
+ MemoryView Tag,
+ MutableMemoryView Out,
+ std::optional<std::string>& Reason)
+{
+ return crypto::Gcm(crypto::TransformMode::Decrypt, Key, Nonce, Aad, Ciphertext, Out, /*TagOut*/ {}, Tag, Reason);
+}
+
+//////////////////////////////////////////////////////////////////////////
+//
+// CryptoRandom
+//
+
+bool
+CryptoRandom::Fill(MutableMemoryView Buffer, std::optional<std::string>* Reason)
+{
+ if (Buffer.GetSize() == 0)
+ {
+ return true;
+ }
+
+ auto SetReason = [&](std::string Msg) {
+ if (Reason)
+ {
+ *Reason = std::move(Msg);
+ }
+ };
+
+#if ZEN_USE_BCRYPT
+ // BCRYPT_USE_SYSTEM_PREFERRED_RNG draws from the OS CSPRNG without
+ // requiring the caller to manage an algorithm handle.
+ const NTSTATUS Status = BCryptGenRandom(nullptr, (PUCHAR)Buffer.GetData(), (ULONG)Buffer.GetSize(), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
+ if (!NT_SUCCESS(Status))
+ {
+ SetReason(fmt::format("BCryptGenRandom failed, 0x{:08x}", static_cast<uint32_t>(Status)));
+ return false;
+ }
+ return true;
+#elif ZEN_USE_OPENSSL
+ // RAND_bytes returns 1 on success, 0 on failure, -1 if not supported.
+ const int Rc = RAND_bytes(reinterpret_cast<unsigned char*>(Buffer.GetData()), static_cast<int>(Buffer.GetSize()));
+ if (Rc != 1)
+ {
+ SetReason(fmt::format("RAND_bytes failed (rc={})", Rc));
+ return false;
+ }
+ return true;
+#else
+ // mbedTLS: no CSPRNG wired up here yet. Callers on this backend must
+ // provide their own random source until a proper wiring is added.
+ SetReason("CryptoRandom::Fill is not implemented on the mbedTLS backend");
+ (void)Buffer;
+ return false;
+#endif
+}
+
#if ZEN_WITH_TESTS
void
@@ -801,6 +1152,205 @@ TEST_CASE("crypto.aes")
}
}
+TEST_CASE("crypto.aesgcm")
+{
+ const AesKey256Bit Key = AesKey256Bit::FromString("abcdefghijklmnopqrstuvxyz0123456"sv);
+ const uint8_t NonceBytes[AesGcm::NonceSize] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
+ const MemoryView Nonce = MakeMemoryView(NonceBytes);
+
+ SUBCASE("round trip without AAD")
+ {
+ std::string_view Plain = "The quick brown fox jumps over the lazy dog"sv;
+
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ Nonce,
+ /*Aad*/ {},
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ REQUIRE(!Reason.has_value());
+ CHECK_EQ(CipherView.GetSize(), Plain.size());
+
+ std::vector<uint8_t> Decoded(Plain.size());
+ MemoryView DecodedView =
+ AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
+ REQUIRE(!Reason.has_value());
+ CHECK_EQ(DecodedView.GetSize(), Plain.size());
+
+ std::string_view DecodedText(reinterpret_cast<const char*>(DecodedView.GetData()), DecodedView.GetSize());
+ CHECK_EQ(DecodedText, Plain);
+ }
+
+ SUBCASE("round trip with AAD")
+ {
+ std::string_view Plain = "payload"sv;
+ std::string_view Aad = "header bits that are authenticated but not encrypted"sv;
+
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ Nonce,
+ MakeMemoryView(Aad),
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ REQUIRE(!Reason.has_value());
+
+ std::vector<uint8_t> Decoded(Plain.size());
+ MemoryView DecodedView =
+ AesGcm::Decrypt(Key, Nonce, MakeMemoryView(Aad), CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
+ REQUIRE(!Reason.has_value());
+ CHECK_EQ(DecodedView.GetSize(), Plain.size());
+ }
+
+ SUBCASE("tampered ciphertext fails authentication")
+ {
+ std::string_view Plain = "important"sv;
+
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ Nonce,
+ /*Aad*/ {},
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ REQUIRE(!Reason.has_value());
+
+ // Flip a bit in the ciphertext.
+ Cipher[0] ^= 0x01;
+
+ std::vector<uint8_t> Decoded(Plain.size());
+ MemoryView DecodedView =
+ AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
+ CHECK(Reason.has_value());
+ CHECK(DecodedView.IsEmpty());
+ }
+
+ SUBCASE("tampered tag fails authentication")
+ {
+ std::string_view Plain = "important"sv;
+
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ Nonce,
+ /*Aad*/ {},
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ REQUIRE(!Reason.has_value());
+
+ Tag[0] ^= 0x80;
+
+ std::vector<uint8_t> Decoded(Plain.size());
+ MemoryView DecodedView =
+ AesGcm::Decrypt(Key, Nonce, /*Aad*/ {}, CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
+ CHECK(Reason.has_value());
+ CHECK(DecodedView.IsEmpty());
+ }
+
+ SUBCASE("AAD mismatch fails authentication")
+ {
+ std::string_view Plain = "payload"sv;
+ std::string_view AadOk = "expected header"sv;
+ std::string_view AadNo = "different header"sv;
+
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ Nonce,
+ MakeMemoryView(AadOk),
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ REQUIRE(!Reason.has_value());
+
+ std::vector<uint8_t> Decoded(Plain.size());
+ MemoryView DecodedView =
+ AesGcm::Decrypt(Key, Nonce, MakeMemoryView(AadNo), CipherView, MakeMemoryView(Tag), MakeMutableMemoryView(Decoded), Reason);
+ CHECK(Reason.has_value());
+ CHECK(DecodedView.IsEmpty());
+ }
+
+ SUBCASE("wrong nonce size is rejected")
+ {
+ std::string_view Plain = "x"sv;
+
+ const uint8_t TooShort[8] = {0};
+ std::vector<uint8_t> Cipher(Plain.size());
+ std::vector<uint8_t> Tag(AesGcm::TagSize);
+ std::optional<std::string> Reason;
+
+ MemoryView CipherView = AesGcm::Encrypt(Key,
+ MakeMemoryView(TooShort),
+ /*Aad*/ {},
+ MakeMemoryView(Plain),
+ MakeMutableMemoryView(Cipher),
+ MakeMutableMemoryView(Tag),
+ Reason);
+ CHECK(Reason.has_value());
+ CHECK(CipherView.IsEmpty());
+ }
+}
+
+TEST_CASE("crypto.random")
+{
+ SUBCASE("fills buffer with non-zero bytes")
+ {
+ uint8_t Buffer[32] = {};
+ MutableMemoryView View = MakeMutableMemoryView(Buffer);
+ const bool Ok = CryptoRandom::Fill(View);
+ REQUIRE(Ok);
+
+ // Probability of 32 all-zero bytes from a CSPRNG is 2^-256 โ€” we
+ // accept it as "effectively never".
+ bool AnyNonZero = false;
+ for (uint8_t B : Buffer)
+ {
+ if (B != 0)
+ {
+ AnyNonZero = true;
+ break;
+ }
+ }
+ CHECK(AnyNonZero);
+ }
+
+ SUBCASE("two calls produce different output")
+ {
+ uint8_t A[32] = {};
+ uint8_t B[32] = {};
+ CHECK(CryptoRandom::Fill(MakeMutableMemoryView(A)));
+ CHECK(CryptoRandom::Fill(MakeMutableMemoryView(B)));
+ CHECK(memcmp(A, B, 32) != 0);
+ }
+
+ SUBCASE("zero-size buffer is a no-op success")
+ {
+ uint8_t Dummy = 0xAB;
+ CHECK(CryptoRandom::Fill(MutableMemoryView(&Dummy, size_t{0})));
+ CHECK_EQ(Dummy, 0xAB);
+ }
+}
+
TEST_CASE("crypto.securerandom")
{
std::array<uint8_t, 64> A{};