Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 31 additions & 16 deletions core/fpdfapi/edit/cpdf_creator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -227,6 +227,19 @@ class SaveObjectWorklist {
std::deque<uint32_t> 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<uint8_t, 16> half;
if (!EPDF_FillSecureRandom(half)) {
return false;
}
id_array->AppendNew<CPDF_String>(pdfium::as_byte_span(half),
CPDF_String::DataType::kIsHex);
return true;
}

} // namespace

CPDF_Creator::CPDF_Creator(CPDF_Document* doc,
Expand Down Expand Up @@ -933,7 +946,11 @@ bool CPDF_Creator::Create(Mask<CreateFlags> 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()) {
Expand Down Expand Up @@ -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<CPDF_Array>();
Expand All @@ -998,11 +1017,8 @@ void CPDF_Creator::InitID() {
pOldIDArray ? pOldIDArray->GetObjectAt(0) : nullptr;
if (pID1) {
id_array_->Append(pID1->Clone());
} else {
std::array<uint32_t, 4> file_id;
FX_Random::Fill(file_id);
id_array_->AppendNew<CPDF_String>(pdfium::as_byte_span(file_id),
CPDF_String::DataType::kIsHex);
} else if (!AppendNewIDHalf(id_array_.Get())) {
return false;
}

if (pOldIDArray) {
Expand All @@ -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<uint32_t, 4> file_id;
FX_Random::Fill(file_id);
id_array_->AppendNew<CPDF_String>(pdfium::as_byte_span(file_id),
CPDF_String::DataType::kIsHex);
return;
return AppendNewIDHalf(id_array_.Get());
}

id_array_->Append(id_array_->GetObjectAt(0)->Clone());
Expand All @@ -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() {
Expand Down
12 changes: 11 additions & 1 deletion core/fpdfapi/edit/cpdf_creator.h
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ class CPDF_Creator final : public CPDF_WriteContext {
void SetEncryption(RetainPtr<CPDF_Dictionary> encrypt_dict,
RetainPtr<CPDF_SecurityHandler> 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,
Expand All @@ -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();

Expand Down Expand Up @@ -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_
36 changes: 27 additions & 9 deletions core/fxcrt/epdf_secure_random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,42 @@
#elif BUILDFLAG(IS_APPLE)
#include <stdlib.h>
#elif BUILDFLAG(IS_ASMJS)
#include <unistd.h>
#include <emscripten/em_js.h>
#elif BUILDFLAG(IS_LINUX)
#include <errno.h>
#include <sys/random.h>
#else
#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<uint8_t> chunk) {
#if BUILDFLAG(IS_WIN)
Expand All @@ -42,9 +62,7 @@ bool FillChunk(pdfium::span<uint8_t> 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);
Expand Down
2 changes: 1 addition & 1 deletion core/fxcrt/epdf_secure_random.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions core/fxcrt/epdf_secure_random_unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint8_t> buffer(4096 + 32, 0);
std::vector<uint8_t> buffer(64 * 1024 + 32, 0);
ASSERT_TRUE(EPDF_FillSecureRandom(buffer));
const pdfium::span<const uint8_t> bytes(buffer);
for (size_t offset = 0; offset < bytes.size(); offset += 32) {
Expand Down
31 changes: 21 additions & 10 deletions docs/embedpdf/fork-ledger.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,17 +217,23 @@ 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.
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.
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`). 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`, `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.
`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
Expand Down Expand Up @@ -522,11 +528,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
Expand Down
5 changes: 5 additions & 0 deletions fpdfsdk/epdf_signature.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading