From 087578eae2b630f91997df9ac2a99f0d0f2657d9 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Thu, 3 Dec 2026 19:01:02 +0200 Subject: [PATCH 1/2] Give every signing candidate a secure new second half of /ID A remote key or a timestamp authority receives only the digest of the signed bytes. For a document made from a known template with a few values filled in, that digest confirmed a guess at the values: the only bytes a guess could not reproduce were the second half of the trailer's /ID, drawn by FX_Random (a Mersenne Twister seeded from 32 bits), and an incremental save of an encrypted file kept the old second half, so its signed revision held nothing new at all. - CPDF_Creator::InitID draws every new half of /ID from EPDF_FillSecureRandom, for every save, and the save fails when the source fails. FX_Random no longer writes /ID. - CPDF_Creator::RequireNewChangingID(): the candidate saves (EPDFSig_SaveCandidateToOwnedBuffer and EPDFSig_SaveCandidate) always write a new second half, encrypted files included. RC4 and AES-128 derive the file key from the first half and AES-256 from neither, so the signed file opens with its password as before. Other incremental saves of an encrypted file keep the old second half, as upstream does. Tests (epdf_signature_embeddertest.cpp, *ChangingIdentifier): - two candidates with the same inputs and signing time get different second halves and digests, each unlike the base's, with the first half kept; a base without /ID gets a new one. Signature and document timestamp, buffer and writer save. - the two signed files differ only inside the /ID array. - the same on encrypted files (RC4 40 and 128 bits, AES-128, AES-256 R5 and R6): the result opens with its password, keeps its security handler and /M of the new revision decrypts. Without the change this test fails: both candidates had the base's second half and the same digest. - an ordinary incremental save of an encrypted file keeps its second half. --- core/fpdfapi/edit/cpdf_creator.cpp | 47 +-- core/fpdfapi/edit/cpdf_creator.h | 12 +- docs/embedpdf/fork-ledger.md | 25 +- fpdfsdk/epdf_signature.cpp | 5 + fpdfsdk/epdf_signature_embeddertest.cpp | 361 +++++++++++++++++++++++- public/epdf_signature.h | 10 +- testing/embedpdf_layer_mode_writers.txt | 4 + 7 files changed, 422 insertions(+), 42 deletions(-) diff --git a/core/fpdfapi/edit/cpdf_creator.cpp b/core/fpdfapi/edit/cpdf_creator.cpp index e10c219dbc..210884726c 100644 --- a/core/fpdfapi/edit/cpdf_creator.cpp +++ b/core/fpdfapi/edit/cpdf_creator.cpp @@ -39,9 +39,9 @@ #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" #include "core/fxcrt/containers/contains.h" +#include "core/fxcrt/epdf_secure_random.h" #include "core/fxcrt/fixed_size_data_vector.h" #include "core/fxcrt/fx_extension.h" -#include "core/fxcrt/fx_random.h" #include "core/fxcrt/fx_safe_types.h" #include "core/fxcrt/mask.h" #include "core/fxcrt/raw_span.h" @@ -227,6 +227,19 @@ class SaveObjectWorklist { std::deque pending_; }; +// EmbedPDF(save-security): a new half of /ID is 16 bytes from the secure +// random source. FX_Random follows from a 32-bit seed, so its bytes could be +// found again. +bool AppendNewIDHalf(CPDF_Array* id_array) { + std::array half; + if (!EPDF_FillSecureRandom(half)) { + return false; + } + id_array->AppendNew(pdfium::as_byte_span(half), + CPDF_String::DataType::kIsHex); + return true; +} + } // namespace CPDF_Creator::CPDF_Creator(CPDF_Document* doc, @@ -933,7 +946,11 @@ bool CPDF_Creator::Create(Mask flags, int32_t file_version) { decided_unchanged_ = false; skip_empty_revision_ = false; - InitID(); + // EmbedPDF(save-security): no save without a secure new identifier. + if (!InitID()) { + failure_reason_ = FailureReason::kOther; + return false; + } // EmbedPDF(save-traversal): pick the trailer, root, /Info and /Encrypt once, // before writing. if (!BuildTrailer()) { @@ -986,7 +1003,9 @@ bool CPDF_Creator::BuildTrailer() { return true; } -void CPDF_Creator::InitID() { +// EmbedPDF(save-security): every new half comes from AppendNewIDHalf(). With +// no old identifier, the second half repeats the new first half. +bool CPDF_Creator::InitID() { DCHECK(!id_array_); id_array_ = document_->New(); @@ -998,11 +1017,8 @@ void CPDF_Creator::InitID() { pOldIDArray ? pOldIDArray->GetObjectAt(0) : nullptr; if (pID1) { id_array_->Append(pID1->Clone()); - } else { - std::array file_id; - FX_Random::Fill(file_id); - id_array_->AppendNew(pdfium::as_byte_span(file_id), - CPDF_String::DataType::kIsHex); + } else if (!AppendNewIDHalf(id_array_.Get())) { + return false; } if (pOldIDArray) { @@ -1011,17 +1027,14 @@ void CPDF_Creator::InitID() { // drawing's) is written as given, both halves. if (!parser_ && pID2) { id_array_->Append(pID2->Clone()); - return; + return true; } - if (is_incremental_ && encrypt_dict_ && pID2) { + // EmbedPDF(signatures): never for a signing candidate. + if (is_incremental_ && encrypt_dict_ && pID2 && !require_new_changing_id_) { id_array_->Append(pID2->Clone()); - return; + return true; } - std::array file_id; - FX_Random::Fill(file_id); - id_array_->AppendNew(pdfium::as_byte_span(file_id), - CPDF_String::DataType::kIsHex); - return; + return AppendNewIDHalf(id_array_.Get()); } id_array_->Append(id_array_->GetObjectAt(0)->Clone()); @@ -1038,6 +1051,8 @@ void CPDF_Creator::InitID() { security_changed_ = true; } } + // EmbedPDF(save-security): every new half this save needed was drawn. + return true; } bool CPDF_Creator::Continue() { diff --git a/core/fpdfapi/edit/cpdf_creator.h b/core/fpdfapi/edit/cpdf_creator.h index ddefca81f1..d0269f63e3 100644 --- a/core/fpdfapi/edit/cpdf_creator.h +++ b/core/fpdfapi/edit/cpdf_creator.h @@ -98,6 +98,13 @@ class CPDF_Creator final : public CPDF_WriteContext { void SetEncryption(RetainPtr encrypt_dict, RetainPtr security_handler); + // EmbedPDF(signatures): for a signing candidate's save. The revision gets a + // new second half of /ID (the changing identifier) even where InitID() + // would keep the old one, in an incremental save of an encrypted file. The + // bytes a signature covers then always hold 16 secure random bytes, so its + // digest can't confirm a guess at the document. + void RequireNewChangingID() { require_new_changing_id_ = true; } + private: enum class Stage { kInvalid = -1, @@ -123,7 +130,8 @@ class CPDF_Creator final : public CPDF_WriteContext { // EmbedPDF(layer-save): picks what an incremental save writes; replaces // InitNewObjNumOffsets(). void PrepareIncrementalObjects(); - void InitID(); + // EmbedPDF(save-security): false when the secure random source fails. + bool InitID(); // EmbedPDF(save-traversal): picks the trailer, root, /Info and /Encrypt. bool BuildTrailer(); @@ -185,6 +193,8 @@ class CPDF_Creator final : public CPDF_WriteContext { // EmbedPDF(layer-save): the append-only mode, and why a save failed. bool is_incremental_append_only_ = false; FailureReason failure_reason_ = FailureReason::kNone; + // EmbedPDF(signatures): see RequireNewChangingID(). + bool require_new_changing_id_ = false; }; #endif // CORE_FPDFAPI_EDIT_CPDF_CREATOR_H_ diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index ec965b8ea5..1428232637 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -217,15 +217,17 @@ and the free list. Update sections (incremental saves) stay sparse. ### save-security **Rule.** Pending encryption settings belong to the document, not to a global. AES-256 encryption -and password probing are ours. The file key, the `/U` and `/O` salts and every AES IV come from -`EPDF_FillSecureRandom`, the operating system's secure random source, never from `FX_Random` or -`rand()`. When it fails, `EPDF_SetEncryption` or the save fails. +and password probing are ours. The file key, the `/U` and `/O` salts, every AES IV and every new +half of the trailer's `/ID` come from `EPDF_FillSecureRandom`, the operating system's secure random +source, never from `FX_Random` or `rand()`. When it fails, `EPDF_SetEncryption` or the save fails. **Why.** Saves on different threads must not share pending security state. `FX_Random` is a Mersenne Twister with a 32-bit seed (time, pid and a stack address outside Windows): the public -salts give the seed away, and with it a file key, without the password. +salts give the seed away, and with it a file key, without the password. A new `/ID` half is what +keeps a signed revision's digest from confirming a guess at the document (see `signatures`). **Where.** `CPDF_Document` pending security, `fpdf_save.cpp`, `cpdf_security_handler.cpp`, `cpdf_crypto_handler.cpp`, `CPDF_Encryptor` and its callers in `cpdf_string.cpp` and -`cpdf_stream.cpp`, `core/fxcrt/epdf_secure_random.{h,cpp}`. +`cpdf_stream.cpp`, `CPDF_Creator::InitID` (`AppendNewIDHalf`), +`core/fxcrt/epdf_secure_random.{h,cpp}`. **Guarded by.** Encrypted save embedder tests (`EncryptedSavesShareNoKeyOrSalts`), `epdf_secure_random_unittest.cpp`; the thread soak's encrypted save. **When upstream touches this.** The security handler and the save paths. New key, salt or IV bytes @@ -522,11 +524,16 @@ null. Keep `font_index_` declared after **When upstream touches this.** Annotation drawing. ### signatures -**Rule.** Revisions, signature reading and signing support, and the document security store. -**Why.** Digital signatures, and keeping them checkable for years. +**Rule.** Revisions, signature reading and signing support, and the document security store. A +signing candidate's save always writes a new second half of `/ID` (the changing identifier), from +the secure random source, also where other incremental saves of an encrypted file keep the old one. +**Why.** Digital signatures, and keeping them checkable for years. Only a digest leaves for a +remote key or a timestamp authority; without bytes no one can guess, it confirms a guess at a +document made from a known template. **Where.** `epdf_signature.cpp`, `epdf_revision_*`, `epdf_dss.cpp` (ours), hooks in the parser and -creator. -**Guarded by.** `epdf_signature_embeddertest.cpp`, `epdf_dss_embeddertest.cpp`. +creator (`CPDF_Creator::RequireNewChangingID`). +**Guarded by.** `epdf_signature_embeddertest.cpp` (`*ChangingIdentifier`), +`epdf_dss_embeddertest.cpp`. **When upstream touches this.** Parser revision handling and the creator. ### embed-metadata diff --git a/fpdfsdk/epdf_signature.cpp b/fpdfsdk/epdf_signature.cpp index 03dc811daf..8d248f05bc 100644 --- a/fpdfsdk/epdf_signature.cpp +++ b/fpdfsdk/epdf_signature.cpp @@ -2059,6 +2059,11 @@ bool SaveCandidateThrough(CPDF_Document* doc, // The creator buffers through its own archive and flushes on // destruction; the offsets are copied out before that. CPDF_Creator creator(doc, std::move(archive)); + // The revision always gets a new second half of /ID, encrypted files + // included: 16 secure random bytes inside what the signature covers, so + // the digest a key or a timestamp authority receives confirms no guess + // at the document. The save fails when the secure source does. + creator.RequireNewChangingID(); if (const CPDF_Document::PendingSecurity* pending = doc->GetPendingSecurity()) { if (pending->mode == CPDF_Document::PendingSecurityMode::kEncrypt) { diff --git a/fpdfsdk/epdf_signature_embeddertest.cpp b/fpdfsdk/epdf_signature_embeddertest.cpp index 094700593a..c5c9c109b9 100644 --- a/fpdfsdk/epdf_signature_embeddertest.cpp +++ b/fpdfsdk/epdf_signature_embeddertest.cpp @@ -27,6 +27,7 @@ #include "public/epdf_layer.h" #include "public/epdf_save.h" #include "public/fpdf_annot.h" +#include "public/fpdf_doc.h" #include "public/fpdf_edit.h" #include "public/fpdf_save.h" #include "public/fpdf_signature.h" @@ -676,18 +677,13 @@ struct Sealed { std::string digest_hex; }; -// save -> seal -> write for an already prepared /V |value|. -bool SealPrepared(FPDF_DOCUMENT doc, uint32_t value, int digest_algorithm, Sealed* out) { - unsigned long long size = 0; - unsigned long long obj_offset = 0; - unsigned long long obj_len = 0; - void* buffer = EPDFSig_SaveCandidateToOwnedBuffer(doc, value, &size, &obj_offset, &obj_len); - if (!buffer) { - ADD_FAILURE() << "EPDFSig_SaveCandidateToOwnedBuffer failed for value " << value; - return false; - } - out->bytes.assign(static_cast(buffer), static_cast(buffer) + size); - EPDF_FreeBuffer(buffer); +// seal -> write for candidate bytes already saved into |out->bytes|, whose +// /V object the save wrote at [obj_offset, obj_offset + obj_len). +bool SealSaved(unsigned long long obj_offset, + unsigned long long obj_len, + int digest_algorithm, + Sealed* out) { + const unsigned long long size = out->bytes.size(); unsigned char digest[64]; unsigned long len = sizeof(digest); if (!EPDFSig_Seal(out->bytes.data(), size, obj_offset, obj_len, digest_algorithm, out->range, @@ -707,6 +703,21 @@ bool SealPrepared(FPDF_DOCUMENT doc, uint32_t value, int digest_algorithm, Seale kFakeCms, sizeof(kFakeCms)); } +// save -> seal -> write for an already prepared /V |value|. +bool SealPrepared(FPDF_DOCUMENT doc, uint32_t value, int digest_algorithm, Sealed* out) { + unsigned long long size = 0; + unsigned long long obj_offset = 0; + unsigned long long obj_len = 0; + void* buffer = EPDFSig_SaveCandidateToOwnedBuffer(doc, value, &size, &obj_offset, &obj_len); + if (!buffer) { + ADD_FAILURE() << "EPDFSig_SaveCandidateToOwnedBuffer failed for value " << value; + return false; + } + out->bytes.assign(static_cast(buffer), static_cast(buffer) + size); + EPDF_FreeBuffer(buffer); + return SealSaved(obj_offset, obj_len, digest_algorithm, out); +} + // prepare -> save -> seal -> write, returning the signed bytes. bool SignField(FPDF_DOCUMENT doc, uint32_t field, const EPDF_SIG_PREPARE& opts, Sealed* out) { const uint32_t value = EPDFSig_Prepare(doc, field, &opts); @@ -2734,8 +2745,10 @@ TEST_F(EPDFSignatureEmbedderTest, FileCandidateSaveSealSpanAndFileDigestAgree) { EPDF_FreeBuffer(raw); // The writer save (this fixture collects FPDF_FILEWRITE output): the same - // size and object span. The bytes differ only in the fresh /ID each save - // draws, so the seal comparisons below run on ONE save. + // size and object span. The bytes differ only in the second half of /ID, + // which every candidate save draws anew from the secure random source + // (CandidateSavesWriteANewChangingIdentifier), so the seal comparisons + // below run on ONE save. ClearString(); unsigned long long fsize = 0; unsigned long long foff = 0; @@ -2799,6 +2812,326 @@ TEST_F(EPDFSignatureEmbedderTest, FileCandidateSaveSealSpanAndFileDigestAgree) { EXPECT_FALSE(EPDFSig_DigestFileRange(&access, bad, EPDF_DIGEST_SHA256, fdigest, &fdlen)); } +// --------------------------------------------------------------------------- +// The changing identifier. Every candidate save writes 16 bytes from the +// secure random source as the second half of /ID, encrypted files included. +// The bytes a signature covers then hold something no one can guess, so the +// digest a key or a timestamp authority receives confirms no guess at the +// document, even one made from a known template with a few values filled in. +// --------------------------------------------------------------------------- + +namespace { + +class CollectingFileWriter final : public FPDF_FILEWRITE { + public: + CollectingFileWriter() { + version = 1; + WriteBlock = WriteBlockImpl; + } + + const std::string& data() const { return data_; } + + private: + static int WriteBlockImpl(FPDF_FILEWRITE* self, + const void* data, + unsigned long size) { + static_cast(self)->data_.append( + static_cast(data), size); + return 1; + } + + std::string data_; +}; + +enum class CandidateSave { kBuffer, kWriter }; + +const char* SaveName(CandidateSave save) { + return save == CandidateSave::kBuffer ? "buffer save" : "writer save"; +} + +constexpr char kFixedSigningTime[] = "D:20261203120000Z"; + +// One half of the /ID that |doc|'s last trailer holds, as raw bytes; empty +// when it has none. +std::string FileIdentifier(FPDF_DOCUMENT doc, FPDF_FILEIDTYPE half) { + const unsigned long len = FPDF_GetFileIdentifier(doc, half, nullptr, 0); + if (len == 0) { + return std::string(); + } + std::vector buffer(len); + EXPECT_EQ(len, FPDF_GetFileIdentifier(doc, half, buffer.data(), len)); + return std::string(buffer.data(), len - 1); // without the terminating NUL +} + +// |base| (opened with |password|) signed on a new field, with the same +// inputs and signing time on every call: prepares |subfilter|, saves the +// candidate through |save|, seals it and writes the stand-in CMS. +bool SignWithFixedInputs(const std::string& base, + const char* password, + int subfilter, + CandidateSave save, + Sealed* out) { + embedpdf_test::ScopedTestDocument doc(embedpdf_test::LoadMemDocumentForTest( + base.data(), base.size(), password)); + if (!doc) { + ADD_FAILURE() << "the base did not open"; + return false; + } + ScopedFPDFPage page(FPDF_LoadPage(doc.get(), 0)); + if (!page) { + ADD_FAILURE() << "page 0 did not load"; + return false; + } + const uint32_t field = CreateSignatureField(doc.get(), page.get(), L"sig"); + page.reset(); + if (field == 0) { + return false; + } + EPDF_SIG_PREPARE opts = DefaultPrepare(); + opts.subfilter = subfilter; + opts.signing_time = kFixedSigningTime; + const uint32_t value = EPDFSig_Prepare(doc.get(), field, &opts); + if (value == 0) { + ADD_FAILURE() << "EPDFSig_Prepare refused"; + return false; + } + if (save == CandidateSave::kBuffer) { + return SealPrepared(doc.get(), value, opts.digest, out); + } + CollectingFileWriter writer; + unsigned long long size = 0; + unsigned long long obj_offset = 0; + unsigned long long obj_len = 0; + if (!EPDFSig_SaveCandidate(doc.get(), value, &writer, &size, &obj_offset, + &obj_len)) { + ADD_FAILURE() << "EPDFSig_SaveCandidate failed"; + return false; + } + out->bytes.assign(writer.data().begin(), writer.data().end()); + if (out->bytes.size() != size) { + ADD_FAILURE() << "the writer save reported " << size << " bytes, wrote " + << out->bytes.size(); + return false; + } + return SealSaved(obj_offset, obj_len, opts.digest, out); +} + +// What a signed result holds: its /ID halves, its security handler's +// revision (-1 when it isn't encrypted) and, read back through the +// signature model, the last signature's digest and /M. +struct SignedResult { + std::string permanent; + std::string changing; + int security_revision = -1; + std::string digest_hex; + std::wstring signing_time; +}; + +// Reopens |sealed| with |password| (it must open) and reads the signature +// that was added last. +SignedResult ReadSignedResult(const Sealed& sealed, + const char* password, + int kind) { + SignedResult result; + const std::string bytes = BytesOf(sealed); + embedpdf_test::ScopedTestDocument doc(embedpdf_test::LoadMemDocumentForTest( + bytes.data(), bytes.size(), password)); + if (!doc) { + ADD_FAILURE() << "the signed result does not open with its password"; + return result; + } + result.permanent = FileIdentifier(doc.get(), FILEIDTYPE_PERMANENT); + result.changing = FileIdentifier(doc.get(), FILEIDTYPE_CHANGING); + result.security_revision = FPDF_GetSecurityHandlerRevision(doc.get()); + EPDF_SIGNATURE_MODEL model = EPDFSig_LoadModel(doc.get()); + if (!model) { + ADD_FAILURE() << "no signature model"; + return result; + } + const int last = EPDFSig_Count(model) - 1; + EXPECT_TRUE(EPDFSig_IsSigned(model, last)); + EXPECT_EQ(kind, EPDFSig_GetKind(model, last)); + EXPECT_EQ(EPDF_SIG_COVERAGE_WHOLE_REVISION, EPDFSig_GetCoverage(model, last)); + unsigned long long range[4]; + if (EPDFSig_GetByteRange(model, last, range)) { + result.digest_hex = HexDigest(doc.get(), range, EPDF_DIGEST_SHA256); + } + result.signing_time = + ReadModelText(EPDFSig_GetString, model, last, EPDF_SIG_STRING_M); + EPDFSig_CloseModel(model); + return result; +} + +// Signs |base| twice with the same inputs, through |save|, and checks what +// the rule promises: each signed revision has a new second half of /ID, 16 +// bytes, unlike the other's and the base's, so the two digests differ. The +// first half stays the base's; a base without /ID gets a new one whose +// second half repeats the first. An encrypted base stays encrypted the same +// way. +void ExpectNewChangingIdentifiers(const std::string& base, + const char* password, + int subfilter, + CandidateSave save) { + std::string base_permanent; + std::string base_changing; + int base_security_revision = -1; + { + embedpdf_test::ScopedTestDocument doc(embedpdf_test::LoadMemDocumentForTest( + base.data(), base.size(), password)); + ASSERT_TRUE(doc); + base_permanent = FileIdentifier(doc.get(), FILEIDTYPE_PERMANENT); + base_changing = FileIdentifier(doc.get(), FILEIDTYPE_CHANGING); + base_security_revision = FPDF_GetSecurityHandlerRevision(doc.get()); + } + const int kind = subfilter == EPDF_SIG_SUBFILTER_ETSI_RFC3161 + ? EPDF_SIG_KIND_DOC_TIMESTAMP + : EPDF_SIG_KIND_SIGNATURE; + + Sealed first_sealed; + Sealed second_sealed; + ASSERT_TRUE( + SignWithFixedInputs(base, password, subfilter, save, &first_sealed)); + ASSERT_TRUE( + SignWithFixedInputs(base, password, subfilter, save, &second_sealed)); + EXPECT_EQ(base, BytesOf(first_sealed).substr(0, base.size())); + const SignedResult first = ReadSignedResult(first_sealed, password, kind); + const SignedResult second = ReadSignedResult(second_sealed, password, kind); + + for (const SignedResult* result : {&first, &second}) { + EXPECT_EQ(16u, result->changing.size()); + if (base_permanent.empty()) { + EXPECT_EQ(16u, result->permanent.size()); + EXPECT_EQ(result->permanent, result->changing); + } else { + EXPECT_EQ(base_permanent, result->permanent); + EXPECT_NE(base_changing, result->changing); + } + EXPECT_EQ(base_security_revision, result->security_revision); + // /M, written in the new revision, decrypts with the reopened key. + EXPECT_EQ(L"D:20261203120000Z", result->signing_time); + } + EXPECT_NE(first.changing, second.changing); + EXPECT_EQ(first_sealed.digest_hex, first.digest_hex); + EXPECT_EQ(second_sealed.digest_hex, second.digest_hex); + EXPECT_NE(first.digest_hex, second.digest_hex); +} + +// A classic-xref document of three objects whose trailer holds |id|. +std::string RawPdfWithId(const std::string& id) { + std::string bytes = MakeRawPdf(BasicObjects()).bytes; + const size_t trailer_end = bytes.rfind(">>\nstartxref"); + EXPECT_NE(std::string::npos, trailer_end); + bytes.insert(trailer_end, id); + return bytes; +} + +constexpr char kKnownId[] = + " /ID[<00112233445566778899AABBCCDDEEFF>" + "]"; + +} // namespace + +TEST_F(EPDFSignatureEmbedderTest, CandidateSavesWriteANewChangingIdentifier) { + const std::string with_id = RawPdfWithId(kKnownId); + const std::string without_id = MakeRawPdf(BasicObjects()).bytes; + for (int subfilter : {EPDF_SIG_SUBFILTER_ETSI_CADES_DETACHED, + EPDF_SIG_SUBFILTER_ETSI_RFC3161}) { + for (CandidateSave save : + {CandidateSave::kBuffer, CandidateSave::kWriter}) { + for (const std::string* base : {&with_id, &without_id}) { + SCOPED_TRACE(testing::Message() + << "subfilter " << subfilter << ", " << SaveName(save) + << ", " << (base == &with_id ? "with" : "without") + << " /ID"); + ExpectNewChangingIdentifiers(*base, nullptr, subfilter, save); + } + } + } +} + +// Everything else in the two signed files is the same: the /ID is all that +// tells their digests apart. +TEST_F(EPDFSignatureEmbedderTest, + CandidateSavesDifferOnlyInTheChangingIdentifier) { + const std::string base = RawPdfWithId(kKnownId); + for (CandidateSave save : {CandidateSave::kBuffer, CandidateSave::kWriter}) { + SCOPED_TRACE(SaveName(save)); + Sealed first; + Sealed second; + ASSERT_TRUE(SignWithFixedInputs( + base, nullptr, EPDF_SIG_SUBFILTER_ETSI_CADES_DETACHED, save, &first)); + ASSERT_TRUE(SignWithFixedInputs( + base, nullptr, EPDF_SIG_SUBFILTER_ETSI_CADES_DETACHED, save, &second)); + const std::string a = BytesOf(first); + const std::string b = BytesOf(second); + ASSERT_EQ(a.size(), b.size()); + const size_t id_start = a.rfind("/ID"); + ASSERT_NE(std::string::npos, id_start); + ASSERT_GT(id_start, base.size()); + const size_t id_end = a.find(']', id_start); + ASSERT_NE(std::string::npos, id_end); + EXPECT_EQ(id_start, b.rfind("/ID")); + EXPECT_EQ(a.substr(0, id_start), b.substr(0, id_start)); + EXPECT_EQ(a.substr(id_end), b.substr(id_end)); + EXPECT_NE(a.substr(id_start, id_end - id_start), + b.substr(id_start, id_end - id_start)); + } +} + +// An encrypted file is no exception: its incremental saves keep the old +// second half, a signing candidate's does not. RC4 and AES-128 derive the +// file key from the first half, AES-256 from neither, so the signed result +// still opens with its password. +TEST_F(EPDFSignatureEmbedderTest, + EncryptedCandidateSavesWriteANewChangingIdentifier) { + const std::pair fixtures[] = { + {"encrypted_hello_world_r2.pdf", "\xc3\xa2ge"}, // RC4, 40 bits + {"encrypted_hello_world_r3.pdf", "\xc3\xa2ge"}, // RC4, 128 bits + {"encrypted.pdf", "1234"}, // AES-128 + {"encrypted_hello_world_r5.pdf", "\xc3\xa2ge"}, // AES-256 + {"encrypted_hello_world_r6.pdf", "\xc3\xa2ge"}, // AES-256 + }; + for (const auto& [filename, password] : fixtures) { + const std::string path = PathService::GetTestFilePath(filename); + const std::vector contents = GetFileContents(path.c_str()); + ASSERT_FALSE(contents.empty()) << filename; + const std::string base(contents.begin(), contents.end()); + for (int subfilter : {EPDF_SIG_SUBFILTER_ETSI_CADES_DETACHED, + EPDF_SIG_SUBFILTER_ETSI_RFC3161}) { + for (CandidateSave save : + {CandidateSave::kBuffer, CandidateSave::kWriter}) { + SCOPED_TRACE(testing::Message() << filename << ", subfilter " + << subfilter << ", " << SaveName(save)); + ExpectNewChangingIdentifiers(base, password, subfilter, save); + } + } + } +} + +// Only a candidate's save asks for a new second half: an ordinary +// incremental save of an encrypted file keeps the old one, as upstream does. +TEST_F(EPDFSignatureEmbedderTest, + EncryptedIncrementalSaveKeepsItsChangingIdentifier) { + ASSERT_TRUE( + OpenDocumentWithPassword("encrypted_hello_world_r3.pdf", "\xc3\xa2ge")); + const std::string permanent = + FileIdentifier(document(), FILEIDTYPE_PERMANENT); + const std::string changing = FileIdentifier(document(), FILEIDTYPE_CHANGING); + ASSERT_EQ(16u, changing.size()); + ScopedFPDFPage page(FPDF_LoadPage(document(), 0)); + ASSERT_TRUE(page); + ASSERT_NE(0u, CreateSignatureField(document(), page.get(), L"sig")); + page.reset(); + ASSERT_TRUE(FPDF_SaveAsCopy(document(), this, FPDF_INCREMENTAL)); + const std::string saved = GetString(); + embedpdf_test::ScopedTestDocument reopened( + embedpdf_test::LoadMemDocumentForTest(saved.data(), saved.size(), + "\xc3\xa2ge")); + ASSERT_TRUE(reopened); + EXPECT_EQ(permanent, FileIdentifier(reopened.get(), FILEIDTYPE_PERMANENT)); + EXPECT_EQ(changing, FileIdentifier(reopened.get(), FILEIDTYPE_CHANGING)); +} + // --------------------------------------------------------------------------- // Reading an object an update did not write. // --------------------------------------------------------------------------- diff --git a/public/epdf_signature.h b/public/epdf_signature.h index fde8b4f90a..f36e71613a 100644 --- a/public/epdf_signature.h +++ b/public/epdf_signature.h @@ -674,8 +674,14 @@ EPDFSig_SetFieldLock(FPDF_DOCUMENT document, // Incremental save of the candidate into an owned buffer (release with // EPDF_FreeBuffer()), reporting where the serializer wrote object // |sig_objnum| (the /V dictionary from EPDFSig_Prepare) so the placeholders -// can be located inside that span, never by searching the file. Returns -// NULL when the save fails or the object was not written. +// can be located inside that span, never by searching the file. The +// revision's trailer gets a new second half of /ID (the changing +// identifier), encrypted files included: 16 bytes from the operating +// system's secure random source, inside the bytes the signature covers. Two +// saves of the same candidate therefore have different digests, and a +// digest confirms no guess at the document's content. Returns NULL when the +// save fails (the secure source failing included) or the object was not +// written. FPDF_EXPORT void* FPDF_CALLCONV EPDFSig_SaveCandidateToOwnedBuffer(FPDF_DOCUMENT candidate, uint32_t sig_objnum, diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 8b0831fdc6..2d07219a1e 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -363,8 +363,12 @@ EPDFSaveEmbedderTest.IncrementalSavePrunesUnlinkedNewAnnotation 2 EPDFSaveEmbedderTest.SaveAsCopyKeepsLinkedNewAnnotation 2 EPDFSaveEmbedderTest.SaveAsCopyPrunesUnlinkedNewAnnotation 2 EPDFSaveEmbedderTest.SavePreservesConsistentObjectGenerations 1 +EPDFSignatureEmbedderTest.CandidateSavesDifferOnlyInTheChangingIdentifier 8 +EPDFSignatureEmbedderTest.CandidateSavesWriteANewChangingIdentifier 8 EPDFSignatureEmbedderTest.CertifyThenRefuseSecondCertification 9 EPDFSignatureEmbedderTest.CreateSignatureFieldAndLock 6 +EPDFSignatureEmbedderTest.EncryptedCandidateSavesWriteANewChangingIdentifier 8 +EPDFSignatureEmbedderTest.EncryptedIncrementalSaveKeepsItsChangingIdentifier 7 EPDFSignatureEmbedderTest.PermissionOneAllowsOnlyTimestamps 9 EPDFSignatureEmbedderTest.PlacingADrawingAgainLeavesTheSignedRevisionAlone 17 EPDFSignatureEmbedderTest.ProbeContactInfoCannotBecomePlaceholder 3 From 5c160db19fd5be9ec094abde34aaf936ced1bf9b Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Thu, 3 Dec 2026 19:55:16 +0200 Subject: [PATCH 2/2] Fail a save instead of aborting when WebAssembly has no Web Crypto EPDF_FillSecureRandom promises false when the random source fails, but in WebAssembly it called getentropy(), which Emscripten implements with crypto.getRandomValues and which aborts the module when the host has none. The abort skips the save's cleanup and reaches the caller as a RuntimeError. Since the previous commit every save draws from this source, not only encrypted ones. The WebAssembly branch now calls the host's crypto.getRandomValues through its own EM_JS bridge, which returns 0 when there is none or it throws, so the save fails like any other failed save. Every browser (pages on http and workers included), Node 19+ and the edge runtimes have it. Chunks are now 64 KiB on every platform, getRandomValues' limit; the large-buffer unit test grows past one chunk. --- core/fxcrt/epdf_secure_random.cpp | 36 ++++++++++++++++------ core/fxcrt/epdf_secure_random.h | 2 +- core/fxcrt/epdf_secure_random_unittest.cpp | 8 ++--- docs/embedpdf/fork-ledger.md | 8 +++-- 4 files changed, 38 insertions(+), 16 deletions(-) diff --git a/core/fxcrt/epdf_secure_random.cpp b/core/fxcrt/epdf_secure_random.cpp index 74264ebd36..4b1e0bd61f 100644 --- a/core/fxcrt/epdf_secure_random.cpp +++ b/core/fxcrt/epdf_secure_random.cpp @@ -16,7 +16,7 @@ #elif BUILDFLAG(IS_APPLE) #include #elif BUILDFLAG(IS_ASMJS) -#include +#include #elif BUILDFLAG(IS_LINUX) #include #include @@ -24,14 +24,34 @@ #error "EPDF_FillSecureRandom has no secure random source for this platform." #endif +#if BUILDFLAG(IS_ASMJS) +// The host's crypto.getRandomValues, which every browser (pages on http and +// workers included), Node 19+ and the edge runtimes have. Returns 0 when the +// host has none or it throws. Emscripten's getentropy() aborts the module +// there, and an abort skips the caller's cleanup. +// clang-format off: the body is JavaScript, and `>>>` is not C++. +EM_JS(int, EPDF_FillFromHostCrypto, (uint8_t* data, size_t size), { + var hostCrypto = globalThis.crypto; + if (!hostCrypto || typeof hostCrypto.getRandomValues != 'function') { + return 0; + } + // The heap reaches 4 GB: addresses past 2 GB arrive negative. + data >>>= 0; + size >>>= 0; + try { + hostCrypto.getRandomValues(HEAPU8.subarray(data, data + size)); + } catch (e) { + return 0; + } + return 1; +}); +// clang-format on +#endif + namespace { -#if BUILDFLAG(IS_ASMJS) -// getentropy() takes at most 256 bytes per call. -constexpr size_t kMaxChunkSize = 256; -#else +// crypto.getRandomValues takes at most 65536 bytes per call. constexpr size_t kMaxChunkSize = 64 * 1024; -#endif bool FillChunk(pdfium::span chunk) { #if BUILDFLAG(IS_WIN) @@ -42,9 +62,7 @@ bool FillChunk(pdfium::span chunk) { arc4random_buf(chunk.data(), chunk.size()); return true; #elif BUILDFLAG(IS_ASMJS) - // Emscripten implements getentropy() with crypto.getRandomValues (or Node's - // crypto.randomFillSync), and aborts when neither exists. - return getentropy(chunk.data(), chunk.size()) == 0; + return EPDF_FillFromHostCrypto(chunk.data(), chunk.size()) == 1; #elif BUILDFLAG(IS_LINUX) while (!chunk.empty()) { const ssize_t read = getrandom(chunk.data(), chunk.size(), 0); diff --git a/core/fxcrt/epdf_secure_random.h b/core/fxcrt/epdf_secure_random.h index f8b9344dd8..af2a96adc9 100644 --- a/core/fxcrt/epdf_secure_random.h +++ b/core/fxcrt/epdf_secure_random.h @@ -10,7 +10,7 @@ // Fills `buffer` with bytes from the operating system's cryptographically // secure random source: BCryptGenRandom on Windows, arc4random_buf on Apple, -// getrandom on Linux, and getentropy (crypto.getRandomValues) in WebAssembly. +// getrandom on Linux, and the host's crypto.getRandomValues in WebAssembly. // // Use it for anything an attacker must not guess: encryption keys, salts and // IVs. FX_Random is a Mersenne Twister with a 32-bit seed and is not. diff --git a/core/fxcrt/epdf_secure_random_unittest.cpp b/core/fxcrt/epdf_secure_random_unittest.cpp index ab2658fc99..9c669e0c67 100644 --- a/core/fxcrt/epdf_secure_random_unittest.cpp +++ b/core/fxcrt/epdf_secure_random_unittest.cpp @@ -34,11 +34,11 @@ TEST(EPDFSecureRandomTest, TwoCallsDiffer) { EXPECT_NE(first, second); } -// The sources take a limited number of bytes per call (getentropy: 256), so a -// large buffer is filled in chunks. No 32-byte window may stay zero: one that -// did would be a chunk the loop skipped. +// The sources take a limited number of bytes per call (crypto.getRandomValues: +// 64 KiB), so a large buffer is filled in chunks. No 32-byte window may stay +// zero: one that did would be a chunk the loop skipped. TEST(EPDFSecureRandomTest, FillsALargeBufferToTheEnd) { - std::vector buffer(4096 + 32, 0); + std::vector buffer(64 * 1024 + 32, 0); ASSERT_TRUE(EPDF_FillSecureRandom(buffer)); const pdfium::span bytes(buffer); for (size_t offset = 0; offset < bytes.size(); offset += 32) { diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index 1428232637..3b7b06e7ee 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -220,16 +220,20 @@ and the free list. Update sections (incremental saves) stay sparse. and password probing are ours. The file key, the `/U` and `/O` salts, every AES IV and every new half of the trailer's `/ID` come from `EPDF_FillSecureRandom`, the operating system's secure random source, never from `FX_Random` or `rand()`. When it fails, `EPDF_SetEncryption` or the save fails. +In WebAssembly the source is the host's `crypto.getRandomValues`, reached through our own bridge +that reports failure where Emscripten's `getentropy` aborts the module. **Why.** Saves on different threads must not share pending security state. `FX_Random` is a Mersenne Twister with a 32-bit seed (time, pid and a stack address outside Windows): the public salts give the seed away, and with it a file key, without the password. A new `/ID` half is what -keeps a signed revision's digest from confirming a guess at the document (see `signatures`). +keeps a signed revision's digest from confirming a guess at the document (see `signatures`). An +abort skips the save's cleanup and ends in an exception instead of a failed save. **Where.** `CPDF_Document` pending security, `fpdf_save.cpp`, `cpdf_security_handler.cpp`, `cpdf_crypto_handler.cpp`, `CPDF_Encryptor` and its callers in `cpdf_string.cpp` and `cpdf_stream.cpp`, `CPDF_Creator::InitID` (`AppendNewIDHalf`), `core/fxcrt/epdf_secure_random.{h,cpp}`. **Guarded by.** Encrypted save embedder tests (`EncryptedSavesShareNoKeyOrSalts`), -`epdf_secure_random_unittest.cpp`; the thread soak's encrypted save. +`epdf_secure_random_unittest.cpp`; the thread soak's encrypted save. No fork suite runs +WebAssembly, so nothing here covers the bridge. **When upstream touches this.** The security handler and the save paths. New key, salt or IV bytes use `EPDF_FillSecureRandom` and fail when it fails. Two upstream draws still use `FX_Random`, and neither is secret: the `/Perms` filler bytes (encrypted under the file key) and the R≥5 branch of