Repository navigation
rgw: fix AES-256-GCM key/IV reuse on multipart part re-upload - #69336
Conversation
There was a problem hiding this comment.
PASS:
Manual Review of findings (no AI):
I have concerns about the multipart AEAD without salt support, it could allow for nonce reuse, which is what we're trying to avoid. The constant time comparison is less of a concern, but seems a simple switch to prevent side channel attacks. The rest seems to be testing related or best practice for future edits. I do not have serious concerns that block the merge though and think this ought to be merged. Thank you for your work here!
In the future for quantum safety, I am glad we're using AES-256-GCM and SHA-256. There's a theoretical risk with Grover's algorithm potentially halving key sizes (with well, very large almost linear constants), but it is still a very reasonable approach to have.
Summary generated by Claude Opus 4.8.
Summary: PR #69336 correctly fixes the AES-256-GCM key/IV reuse on multipart part re-upload by adding a fresh random per-part salt to the key derivation. The fix is cryptographically sound and the overall risk is Low — it should be merged. However, the scheme's safety rests entirely on each upload getting a unique key, and a few paths make that guarantee more fragile than it should be.
Recommendations (in priority order):
** Fail closed on multipart AEAD without salt support (highest priority). If a backend's supports_crypt_part_salts() is false or the part salt is empty, encryption silently falls back to a deterministic, salt-free key — reintroducing the exact nonce reuse this PR fixes. Refuse the upload instead of degrading silently.
** Use constant-time tag comparison. The ISA-L path verifies the GCM tag with memcmp (a timing oracle); switch to CRYPTO_memcmp to match the OpenSSL path.
** Add guards that enforce the key-uniqueness invariant. Assert a fresh salt was applied on new multipart writes, and assert stream_offset is chunk-aligned, so a future regression can't silently restore IV reuse.
** Harden the AEAD against truncation (defense-in-depth). Bind total length or a final-chunk flag into the AAD; today, boundary truncation is caught only by the separate manifest size check. Optionally add part_number to the AAD.
** Verify/fix the bundled CI workflow. The pull_request_target audit uses a possibly out-of-scope getOctokit; confirm the symbol or use github.getOctokit.
** Before merge, confirm against the full tree: the default return value of supports_crypt_part_salts(), and whether any ranged-read path can pass a non-chunk-aligned stream_offset.
Using promoting developed at IBM with the Power Team and Project Bob:
Security Code Review
Review Scope
- Source reviewed: #69336
- Review type: GitHub pull request
- Commit: a53af5e0e25 "rgw: fix AES-256-GCM key/IV reuse on multipart part re-upload"
- Files examined: 14 files across RGW (RADOS Gateway) cryptography implementation
- Files not examined: Test infrastructure files (only test logic reviewed)
- Assumptions or limitations: Review focused on the cryptographic changes; did not audit entire Ceph RGW codebase for other issues
Executive Summary
- Overall risk level: Low (This is a security FIX that addresses a Critical vulnerability)
- Short summary: The PR correctly fixes a critical AES-256-GCM key/IV reuse vulnerability in multipart uploads by introducing per-upload random salts. The implementation is cryptographically sound and includes proper backward compatibility.
- Most important observations:
- Correctly fixes Critical vulnerability: Prevents GCM nonce reuse by adding 16-byte random salt to part key derivation
- Proper backward compatibility: Empty salt reproduces old key derivation for existing encrypted data
- Well-tested: Includes unit test verifying key isolation between different salts
Findings
Finding 1: Part number validation added but upper bound may be too restrictive
- Severity: Informational
- Category: Input validation
- Location:
rgw_rest_s3.cc:2961-2964 - Evidence:
if (multipart_part_num < 1 || multipart_part_num > 10000) {
ldpp_dout(s, 10) << "part number out of range: " << multipart_part_num << dendl;
return -EINVAL;
}- Why this is a problem: S3 specification allows part numbers from 1 to 10,000, so this validation is correct. However, the code previously had no validation, so this is actually an improvement. This is informational only.
- Exploit scenario: None - this is a security improvement
- Recommended fix: None required - validation is correct per S3 spec
- Confidence: High
Finding 2: Random salt generation uses proper CSPRNG
- Severity: Informational (Positive finding)
- Category: Cryptography
- Location:
rgw_rest_s3.cc:3131 - Evidence:
s->cct->random()->get_bytes(part_salt.data(), part_salt.size());- Why this is good: Uses Ceph's cryptographic random number generator, not a weak PRNG
- Confidence: High
Finding 3: Salt size is cryptographically appropriate
- Severity: Informational (Positive finding)
- Category: Cryptography
- Location:
rgw_crypt.h:114 - Evidence:
static constexpr size_t AES_256_GCM_PART_SALT_SIZE = 16; // per-UploadPart entropy- Why this is good: 16 bytes (128 bits) provides sufficient entropy for HMAC-based key derivation
- Confidence: High
Finding 4: Backward compatibility properly implemented
- Severity: Informational (Positive finding)
- Category: Cryptography / Data integrity
- Location:
rgw_crypt.cc:862-865 - Evidence:
if (!part_salt.empty()) {
hmac.Update(reinterpret_cast<const uint8_t*>(part_salt.data()), part_salt.size());
}- Why this is good: Empty salt reproduces old key derivation, allowing existing encrypted multipart objects to decrypt correctly
- Confidence: High
Finding 5: HMAC-SHA256 used for key derivation
- Severity: Informational (Positive finding)
- Category: Cryptography
- Location:
rgw_crypt.cc:856-866 - Evidence:
ceph::crypto::HMACSHA256 hmac(this->key, AES_256_KEYSIZE);
hmac.Update(part_bytes, 4);
if (!part_salt.empty()) {
hmac.Update(reinterpret_cast<const uint8_t*>(part_salt.data()), part_salt.size());
}
hmac.Final(derived);- Why this is good: HMAC-SHA256 is the appropriate construction for key derivation. The formula
HMAC(ObjectKey, BE32(part_number) || salt)properly binds the derived key to both the part number and the upload instance - Confidence: High
Finding 6: Test coverage validates key isolation
- Severity: Informational (Positive finding)
- Category: Testing
- Location:
test_rgw_crypto.cc:1248-1284 - Evidence: New test
verify_AES_256_GCM_part_salt_key_isolationverifies that:- Same part number with different salts produces different ciphertext
- Correct salt decrypts successfully
- Wrong salt fails GCM authentication tag verification
- Why this is good: Comprehensive test coverage of the security fix
- Confidence: High
No Findings In These Areas
- OWASP Top 10 risks: No injection, authentication, authorization, or other OWASP issues found in the changed code
- Buffer overflow and memory safety: C++ code uses safe abstractions (bufferlist, std::string, std::vector)
- Denial of Service: Part number validation prevents excessive part numbers; salt size is fixed at 16 bytes
- Input validation: Part number validation added (1-10000 range check)
- Error handling: Proper error handling for HMAC failures and decode errors
- Privilege and access control: Not applicable to these cryptographic changes
Dependency and Configuration Notes
- No dependency changes in this PR
- New attribute
RGW_ATTR_CRYPT_PART_SALTadded to store per-part salt during upload - Attribute
RGW_ATTR_CRYPT_PART_NUMSnow stores(part_number, salt)pairs instead of just part numbers - Backward compatible: empty salt in pair reproduces old behavior
Questions or Missing Context
None - the implementation is complete and well-documented in the commit message and code comments.
Final Recommendation
This PR should be approved and merged. It correctly fixes a Critical security vulnerability (AES-256-GCM key/IV reuse) with a cryptographically sound solution:
- ✅ Proper fix: Adds 16-byte random salt per UploadPart, folded into HMAC-based part key derivation
- ✅ Backward compatible: Empty salt preserves old key derivation for existing encrypted data
- ✅ Well-tested: Includes unit test verifying key isolation
- ✅ Correct cryptography: Uses CSPRNG for salt generation and HMAC-SHA256 for key derivation
- ✅ No new vulnerabilities introduced: Code review found no security issues in the implementation
Priority: High - this fixes a vulnerability that could allow attackers to break GCM confidentiality and integrity guarantees when multipart uploads are re-uploaded.
Original Vulnerability Severity: Critical - GCM nonce reuse with the same key is a catastrophic failure that can leak plaintext and allow forgery attacks.
no fancy prompts with Claude Opus 4.8, just asked for a security review:
Source reviewed: GitHub PR ceph/ceph #69336 ("rgw: fix AES-256-GCM key/IV reuse on multipart part re-upload"), as provided in the uploaded unified diff review.txt (branch mheler:wip-rgw-sse-gcm-mpu-fix → ceph:main), supplemented by the PR metadata/commit message.
Review type: patch / diff (GitHub source).
Files examined: src/rgw/rgw_crypt.cc (new AES_256_GCM class, HMAC-based key derivation, IV/AAD construction, encrypt/decrypt, multipart GET re-derivation, rgw_s3_prepare_encrypt/rgw_s3_prepare_decrypt); src/rgw/rgw_crypt.h (GCM constants, BlockCrypt interface, is_aead_mode); the RGWUploadPartInfo struct and RGW_ATTR_CRYPT_* definitions; src/rgw/rgw_op.cc (UploadPart encrypt-filter setup); src/rgw/driver/rados/rgw_sal_rados.* (multipart complete() storing (part, salt) pairs; supports_crypt_part_salts()); and .github/workflows/releng-audit.yaml.
Files not examined in depth: the unrelated bundled changes in the same diff — src/tools/cephfs/DataScan.cc, ProgressTracker.cc, src/tools/rados/rados.cc, src/vstart.sh, CMakeLists.txt, win32_build.sh — and the unit-test body beyond confirming it exercises part-salt key isolation.
Assumptions or limitations: Line references are to the provided diff. The diff is a ~111k-line branch diff that bundles the entire SSE-GCM feature plus unrelated commits, not only the small re-upload fix the PR title describes; I scoped the security review to the crypto and the CI workflow. I assume Ceph's encode/decode for std::vector<std::pair<uint32_t,std::string>> performs standard length-checked decoding (it does, and the call site additionally wraps it in try/catch). Tests were not executed.
Executive Summary
Overall risk level: Low (this is a security-hardening change, and the central fix is implemented correctly).
Short summary: The change adds authenticated SSE (AES-256-GCM) and specifically fixes GCM (key, IV) reuse when a multipart part number is re-uploaded. The IV stays positional (part_number || chunk_index), so the fix removes nonce reuse by making the key unique per upload: a fresh 16-byte CSPRNG salt is folded into the part-key derivation PartKey = HMAC-SHA256(ObjectKey, BE32(part) || part_salt). The salt is persisted per part, recorded as (part, salt) pairs at multipart-complete, and read back at GET to re-derive the key. The wider GCM code uses sound primitives (CSPRNG salts, HMAC-SHA256 KDF with length-prefixed inputs and per-mode domain separation, per-chunk AEAD with a chunk-index AAD, key/salt zeroization, fail-closed validation).
Most important issues:
The per-part salt protection is conditional and falls back silently to the old deterministic derivation when the SAL driver lacks supports_crypt_part_salts() or a stored part salt is empty.
Because the IV remained positional, the fix's safety rests entirely on key uniqueness, yet there is no runtime guard asserting a fresh salt was actually applied on new AEAD multipart writes.
The bundled pull_request_target CI workflow calls a possibly out-of-scope getOctokit global in its new authorization helper.
Findings
Finding 1: Stated fix (multipart re-upload key/IV reuse) is implemented correctly
Severity: Informational (the pre-fix behavior it removes was a High-severity GCM nonce reuse).
Category: Cryptography / nonce-IV reuse (OWASP Cryptographic Failures).
Location: src/rgw/rgw_crypt.cc — derive_part_key (diff ~93217–93271), set_part_number (diff 93031–93042), derive_object_key (diff 93086–93204); src/rgw/rgw_op.cc UploadPart path (diff 98077–98092); rgw_sal_rados complete() (diff 90450–90492); GET re-derivation (diff 93854–94012).
Evidence: On an AEAD UploadPart, a 16-byte salt is drawn from s->cct->random()->get_bytes(...) and applied via set_part_number(part, salt), which resets the working key to the saved object base key (memcpy(this->key, this->base_key, ...)) before computing HMAC(ObjectKey, BE32(part) || salt). The salt is written to RGW_ATTR_CRYPT_PART_SALT, captured into RGWUploadPartInfo::crypt_salt, encoded as (num, salt) pairs into RGW_ATTR_CRYPT_PART_NUMS at complete, and read back at GET to call set_part_number(num, stored_salt).
Why this is a problem: It is the fix, not a defect. Re-uploading the same part number now produces the same positional IV but a different key, so the (key, nonce) pair is unique — eliminating the GCM nonce-reuse condition that otherwise leaks the XOR of plaintexts and enables authentication-subkey (H) recovery and forgery.
Exploit scenario: Pre-fix, an attacker with raw RADOS read access who captured a superseded re-uploaded part before garbage collection could recover plaintext relationships or forge ciphertext; the fix closes this.
Recommended fix: None for the mechanism. Object-identity binding is consistent: derive_object_key uses bucket.bucket_id and s->object->get_name() (the logical key) at both UploadPart and GET, and the object-level salt is generated once and read back for parts, so keys reconcile across PUT/complete/GET.
Safer example, if useful: N/A — the chosen construction (per-upload key randomization) is an appropriate remedy for a positional IV.
Confidence: High.
Finding 2: Silent fallback to deterministic part key when salt support or value is absent
Severity: Low (Medium if a non-RADOS SAL driver is used for AEAD multipart).
Category: Insecure design / cryptographic failure (defense-in-depth).
Location: src/rgw/rgw_op.cc UploadPart path, condition is_aead_mode(...) && upload->supports_crypt_part_salts() (diff 98082–98090); derive_part_key empty-salt branch (diff 93235–93237); capability default false (diff 98815) vs RADOS override true (diff 90505).
Evidence: The salt is generated and folded in only when both the mode is AEAD and the driver reports supports_crypt_part_salts(). derive_part_key treats an empty part_salt as "reproduce the old derivation," and no warning is logged when the salt path is skipped.
Why this is a problem: The production RADOS driver returns true, so current deployments are protected. But any SAL backend that does not override the capability (or any part whose stored salt is empty) silently reverts to the deterministic HMAC(ObjectKey, BE32(part)) part key — re-introducing exactly the (key, IV) reuse this PR fixes — with no operator-visible signal.
Exploit scenario: On a backend lacking salt support, an attacker with raw object-store read access who captures a superseded re-uploaded part could mount the original GCM nonce-reuse attack.
Recommended fix: Emit a warning-level log (or refuse AEAD multipart) when an AEAD multipart UploadPart proceeds without part-salt support, so the weaker path is never silent.
Safer example, if useful: if (is_aead && !upload->supports_crypt_part_salts()) { ldpp_dout(s, 0) << "AEAD multipart without part-salt support; refusing" << dendl; return -EINVAL; }
Confidence: Medium.
Finding 3: Nonce uniqueness depends solely on key uniqueness, with no guard that a fresh salt was applied
Severity: Low (defense-in-depth).
Category: Cryptography / insecure design.
Location: IV construction iv_cursor / init_iv_cursor (diff 93675–93699); encryption salt application (diff 98084–98089).
Evidence: The IV is part_number (32b) || chunk_index (64b) and does not depend on the salt; the salt enters only the key derivation. The encrypt path asserts salt_initialized (the object salt) but does not assert that a non-empty part salt was applied for a multipart-part write.
Why this is a problem: Because the IV stayed positional, all protection rests on the derived key differing between uploads. A future refactor that drops or empties the part salt would silently recreate nonce reuse with no test or runtime tripwire.
Exploit scenario: A regression that bypasses set_part_number(part, salt) on the new-write path would restore the original vulnerability without any obvious failure.
Recommended fix: On the new-write AEAD multipart path, track whether a non-empty part salt was applied and ceph_assert/error if it was not for part_number > 0 writes; keep empty-salt acceptance strictly on the decrypt/legacy path.
Safer example, if useful: a bool part_salt_applied_ flag set in set_part_number(...) when !part_salt.empty(), checked at the start of encrypt() for multipart writes.
Confidence: Medium.
Finding 4: Chunked AEAD does not bind total length or global part ordering in the tag
Severity: Informational.
Category: Cryptography / integrity scope.
Location: encrypt/decrypt per-chunk loops and encode_chunk_aad (diff 93286–93290, 93468–93665).
Evidence: Each 4 KB chunk is sealed independently with AAD = 8-byte chunk index, and the IV embeds the part number. Total object length and global part ordering live in the separate manifest / parts_len and RGW_ATTR_CRYPT_ORIGINAL_SIZE, not in any single tag.
Why this is a problem: Cross-chunk reordering (distinct AAD) and cross-part splicing (distinct key/IV) fail authentication — good. However, whole-chunk truncation at a chunk boundary is not detected by the AEAD layer itself; it relies on stored size/manifest metadata. Tampering with RGW_ATTR_CRYPT_PART_NUMS or salts yields decryption failure (a read denial), not plaintext disclosure.
Exploit scenario: Under the SSE threat model (attacker reads raw RADOS but cannot forge trusted metadata) this is not a confidentiality break; if the attacker can write attributes/data, the trust boundary is already crossed.
Recommended fix: Optional hardening — bind part count / total length into the first or last chunk's AAD, and document that object-length integrity depends on the manifest attributes.
Safer example, if useful: include part_count and total_plaintext_len in the AAD of the object's final chunk.
Confidence: Medium.
Finding 5: Bundled pull_request_target CI workflow may call an out-of-scope getOctokit
Severity: Low.
Category: Security misconfiguration / CI authorization (accompanied by positive supply-chain hardening).
Location: .github/workflows/releng-audit.yaml, new checkAuthorization() helper — const orgOctokit = getOctokit(process.env.ORG_TOKEN); (diff 30–53).
Evidence: The original inline code used github.getOctokit(...); the refactored helper calls a bare getOctokit(...). The call sits inside a try/catch that sets authorized = false on throw.
Why this is a problem: If getOctokit is not a global in the actions/github-script runtime, the org-team-membership fallback always throws, is caught, and authorization stays false. This fails closed (denies override), so it is not a privilege-escalation risk, but it can silently break legitimate release-manager overrides. (Positives in the same change: github-script, checkout, and setup-python are pinned to commit SHAs; concurrency is serialized with cancel-in-progress: false; the audit checks out the trusted base repo rather than PR head — all appropriate for pull_request_target.)
Exploit scenario: No privilege escalation; realistic impact is a functional regression. The note matters because pull_request_target workflows are a common source of real token-leak/RCE bugs, so the symbol scope is worth confirming.
Recommended fix: Use github.getOctokit(process.env.ORG_TOKEN) to match the pre-existing pattern, or confirm getOctokit is exposed in the pinned github-script version.
Safer example, if useful: const orgOctokit = github.getOctokit(process.env.ORG_TOKEN);
Confidence: Medium.
No Findings In These Areas
Reviewed in the GCM code with no issue found: insecure algorithms/modes (uses AES-256-GCM and HMAC-SHA256; no MD5/SHA-1/DES/RC4/ECB for security purposes); weak randomness (salts from cct->random()->get_bytes, a CSPRNG); KDF safety (length-prefixed HMAC inputs prevent ambiguous-concatenation attacks; per-mode domain separators bind the algorithm context); secret hygiene (key, base_key, salt zeroized in the destructor and error paths; key length validated before memcpy, avoiding OOB); AEAD handling (output buffer zeroized and not appended on tag-verification failure, so no unauthenticated plaintext is emitted); unsafe deserialization (the (part, salt) vector is decoded with Ceph's bounded decode() inside try/catch, with a size-consistency check against parts_len and explicit empty/size validation in get_gcm_salt); and integer/bounds handling (input-offset checks, the remainder <= GCM_TAG_SIZE guard preventing underflow, ceph_assert(size <= CHUNK_SIZE)). No SQL/command/template injection, SSRF, broken access control, IDOR, or path-traversal surface is introduced by these changes.
Dependency and Configuration Notes
The CI workflow now pins third-party actions to commit SHAs (positive supply-chain hardening). CMakeLists.txt adds WITH_SYSTEM_SPDK / WITH_SYSTEM_JERASURE find_package options (supply-chain neutral-to-positive, allowing system libraries). vstart.sh Ganesha changes are for the developer harness, not production. src/tools/cephfs/DataScan.cc now calls get_pool_objects(...) inside per-object loops — a potential O(n) RADOS-stat performance/resource concern, but in an offline admin/recovery CLI, not a request path; noted for awareness, out of security scope. rados.cc removes a stray debug cout (benign).
Questions or Missing Context
Do any non-RADOS SAL drivers (dbstore, posix, cloud/tiering) support AEAD multipart, and if so do they override supports_crypt_part_salts() to true or reject AEAD multipart? (Finding 2.)
Is getOctokit available as a top-level binding in the pinned actions/github-script@v9, or must it be github.getOctokit? (Finding 5.)
For SSE-KMS/RGW-AUTO GCM, is the object-level salt generated exactly once at multipart initiate and never regenerated on later part writes, so all parts share one ObjectKey? The UploadPart path reading the stored salt suggests yes; confirming closes the last key-consistency question.
Final Recommendation
The core change is cryptographically correct and merge-worthy: the multipart re-upload (key, IV) reuse is eliminated by per-upload key randomization, and the surrounding GCM implementation follows sound practices. Before merge, prioritize, in order: (1) make the weaker fallback non-silent — log a warning or refuse AEAD multipart when supports_crypt_part_salts() is false or a part salt is empty (Finding 2); (2) add a runtime/test guard that a fresh non-empty salt was applied for new AEAD multipart writes, so a future regression cannot silently restore nonce reuse (Finding 3); and (3) fix or verify the getOctokit reference in the audit workflow (Finding 5). Findings 4 and the DataScan performance note are lower priority and can be tracked separately. Because the fix's safety depends entirely on the derived key being unique per upload, treat the verification questions above as gating checks rather than optional.
Using promoting developed at IBM with the Power Team and Claude Opus 4.8:
This is a 111K-line diff across 1,081 files from the Ceph project — not a standalone AES-GCM implementation. There is AES-256-GCM content in here though. Let me locate the actual implementation code (not just docs) so I can review the real thing.Pinpointed critical cryptographic files for comprehensive security analysisPinpointed critical cryptographic files for comprehensive security analysisFound the actual implementation. The core AES-GCM work is in src/crypto/* and src/rgw/rgw_crypt.cc. Let me read those sections.Examined cryptographic implementations and located relevant code sectionsExamined cryptographic implementations and located relevant code sectionsLet me see the part I missed (the ISA-L batch stubs and the start of the OpenSSL encrypt).Examined cryptographic implementation details across substantial codebase sectionsExamined cryptographic implementation details across substantial codebase sectionsNow the most important file — rgw_crypt.cc, the RGW crypto handler. This is ~2,200 lines of diff; let me read it in chunks.Examined IV handling protocols and cryptographic vulnerability risksExamined IV handling protocols and cryptographic vulnerability risksThis is the core. The most critical thing for GCM is IV construction — let me read the encrypt/decrypt and IV generation logic.Scrutinized cryptographic implementation for IV reuse vulnerabilities and authentication gapsScrutinized cryptographic implementation for IV reuse vulnerabilities and authentication gapsLet me see the encrypt loop I skipped, plus the salt-size constant and how salt/part handling is wired in the header.Examined cryptographic implementation details and salt handling mechanismsExamined cryptographic implementation details and salt handling mechanismsNow the header and the set_part_number body I skipped, to nail down salt size and the multipart re-derivation path.Investigated salt mechanisms and IV-reuse vulnerabilities in cryptographic implementationInvestigated salt mechanisms and IV-reuse vulnerabilities in cryptographic implementationThe multipart part-salt flow is the crux of IV-uniqueness. Let me examine how part salts are generated and stored on multipart upload.Synthesized cryptographic vulnerabilities and defensive recommendationsSynthesized cryptographic vulnerabilities and defensive recommendationsI reviewed the file. Quick note first: this isn't a standalone AES-GCM file — it's a 111K-line, 1,081-file Ceph pull request. The actual AES-256-GCM work (a new server-side-encryption mode for the RADOS Gateway) lives in a handful of files, and that's what I reviewed:
src/crypto/crypto_accel.h + the OpenSSL/ISA-L/QAT accel backends
src/rgw/rgw_crypt.cc / .h (the AES_256_GCM BlockCrypt class — the core)
the multipart wiring in rgw_putobj_processor.cc and rgw_op / S3 REST layer
Here's the review.
The thing that matters most in a GCM review: nonce uniqueness
With GCM, a single (key, IV) reuse is catastrophic — it leaks the XOR of plaintexts and, worse, allows forging the authentication tag for that key. So the central question is: can this code ever encrypt two different plaintexts under the same key and IV?
The construction here is a deterministic-IV / derived-key scheme, which is a legitimate and good choice:
IV (96 bits) = part_number (32 bits) || chunk_index (64 bits), emitted by iv_cursor. Fully deterministic — no random component.
Key is derived per object: ObjectKey = HMAC-SHA256(user_key, salt ‖ domain ‖ bucket_id ‖ object) with a fresh random 32-byte salt per encryption, and for multipart PartKey = HMAC-SHA256(ObjectKey, BE32(part) ‖ part_salt) with a fresh random 16-byte salt per UploadPart.
Because the IV itself carries no randomness, the entire no-reuse guarantee rests on the key being unique per encryption. I traced the paths and the design is mostly sound:
Single PUT / overwrite → generate_salt() runs every time → new 32-byte salt → new key, even though the IV sequence restarts at (0,0). ✓
Re-uploading a multipart part → fresh 16-byte part_salt generated at rgw_putobj_processor/S3 layer (lines ~98084), folded into the part key. So the deterministic IV is safe because the key changed. ✓ This is the correct fix for the classic multipart-reupload nonce-reuse trap, and it's nicely commented.
So the core is right. But there are several places where that guarantee is more fragile than it should be:
High — multipart AEAD fails open when the backend lacks part-salt support
In the encrypt-filter wiring:
cppif (is_aead_mode(...) && upload->supports_crypt_part_salts()) {
// generate fresh part_salt, fold into key, store attr
}
filter->reset(new RGWPutObj_BlockEncrypt(...)); // runs regardless
If supports_crypt_part_salts() returns false, the whole salt block is skipped but encryption still proceeds using a part key derived from part_number alone (deterministic). At that point, re-uploading the same part number reproduces the same (key, IV) → nonce reuse. The rados driver overrides this to true, but the safe behavior is to fail closed: if AEAD multipart is requested and the backend can't supply per-part salts, refuse the upload rather than silently degrade to a deterministic part key. Right now the security of the scheme depends on an easily-missed capability flag.
Medium — nothing in the AEAD layer prevents truncation
Each 4 KB chunk is sealed independently; the AAD binds only the 8-byte chunk_index. Reordering and splicing are caught (index in AAD, index+part in IV, per-object/part keys). But dropping trailing chunks yields a shorter, fully valid plaintext — every remaining chunk still authenticates. There's no "final chunk" marker or total-length binding in the AEAD layer (cf. the STREAM construction, which folds a last-block flag into the nonce). In practice RGW's stored object size in the manifest probably catches a truncated object, so this is defense-in-depth rather than a clean break — but I'd bind either a final-chunk flag or the total length into the last chunk's AAD so the crypto layer is self-protecting and doesn't rely on a separate size check being present and trusted.
Medium — non-constant-time tag comparison in the ISA-L path
cppaes_gcm_dec_256(..., computed_tag, AES_GCM_TAGSIZE);
if (memcmp(computed_tag, tag, AES_GCM_TAGSIZE) != 0) { ... }
memcmp is not constant-time, so this is a tag-verification timing oracle. The OpenSSL path is fine (EVP_DecryptFinal_ex compares internally in constant time), which makes the inconsistency easy to overlook. Use CRYPTO_memcmp (or Ceph's constant-time equivalent). The same memcmp appears in the ISA-L key-schedule cache (get_cached_gcm_key) comparing raw key bytes — lower severity, but same fix is cheap.
Low / defense-in-depth
No chunk-alignment assert on stream_offset. init_iv_cursor does cursor.lo = stream_offset / CHUNK_SIZE. If any caller ever passes a non-CHUNK_SIZE-aligned offset, two distinct offsets collide to the same chunk_index → IV reuse under the same key. Add ceph_assert(stream_offset % CHUNK_SIZE == 0) so the invariant is enforced, not assumed.
memset(out, 0, size) on auth failure can be elided by the optimizer. It's clearing output (not key material) and callers ignore out on false, so impact is limited — but you already have ceph::crypto::zeroize_for_security; use it consistently so "clear on failure" actually means it.
Process-global fallback latch. static std::atomic failed_to_get_crypto_gcm inside get_gcm_accel() is function-local-static, i.e. shared across all AES_256_GCM instances. One accelerator-init failure permanently routes every object in the process to the EVP path. Probably intended, but it's surprising global state worth a comment or per-context scoping.
AAD omits part_number. Cross-part splicing is already blocked by per-part keys, but adding part_number to the AAD is nearly free and gives belt-and-suspenders binding.
Part salt is 16 bytes. Fine for this use (collision ~2⁻⁶⁴ after ~2³² re-uploads of the same part), but worth a one-line rationale next to the constant since it's the linchpin of multipart nonce safety.
What's done well (worth keeping)
The crypto hygiene here is above average and I'd call it out in the PR so it doesn't get lost:
Length-prefixed HMAC inputs in derive_object_key — prevents the canonicalization/concatenation ambiguity that bites a lot of homegrown KDFs (HMAC(k, "ab"‖"c") vs HMAC(k, "a"‖"bc")).
Domain separation ("SSE-C-GCM", etc.) folded into derivation.
Per-object key binds ciphertext to object identity (bucket_id + object), so a RADOS-level object move/rename produces the wrong key and fails closed.
12-byte IVs per NIST SP 800-38D, and static_asserts coupling the accel-layer and RGW constants so an IV/tag size drift becomes a compile error.
Key zeroization in the destructor via zeroize_for_security, and the ISA-L key cache zeroizes on thread exit.
The multipart per-part random salt is exactly the right mitigation for the reupload nonce trap — many implementations get this wrong.
Suggested priorities
Make AEAD multipart fail closed when supports_crypt_part_salts() is false. (Prevents the one realistic path to nonce reuse.)
Switch the ISA-L tag/key comparisons to constant-time.
Add the stream_offset alignment assert.
Decide on truncation: either document that it's intentionally delegated to the manifest size check, or bind length/final-flag into the last chunk's AAD.
A couple of things I couldn't fully resolve from the diff and would verify against the full tree: the base/default return value of supports_crypt_part_salts() (drives finding #1's real-world exposure), and whether any GET/decrypt path can pass a non-chunk-aligned stream_offset for ranged reads (drives the alignment assert from "defensive" to "necessary"). If you point me at rgw_op.cc's decrypt-filter range handling I can check the second one.
85a2557 to
9931acb
Compare
|
@mheler I was evaluating the QA run and I have a question. It looks like |
@ivancich unittest_rgw_crypto is a make check, which is ran as part of the ceph-pull-requests jenkins job. So it ran as part of this PR's make check result. |
|
pr testing completed and approved by @ivancich , More detail's : https://tracker.ceph.com/issues/77430 This pr approved by RGW |
|
jenkins test ceph windows test |
8a8345d to
9931acb
Compare
|
jenkins test ceph api test |
a2e1a4a to
8398e45
Compare
|
jenkins test api |
|
jenkins test make check |
|
jenkins test make check arm64 |
Re-uploading the same part number in a GCM multipart upload encrypted the new data under the same key and IV as the first upload, since the IV is part_number||chunk_index and the part key came from the part number alone. GCM requires a unique IV per key; reusing one to encrypt different data weakens its confidentiality and integrity guarantees. Generate a random 16-byte salt on each UploadPart and fold it into the part key, HMAC(ObjectKey, BE32(part) || salt), so every upload gets a fresh key. The salt rides RGWUploadPartInfo, and complete stores the selected part's salt in RGW_ATTR_CRYPT_PART_NUMS, which now holds (part, salt) pairs. GET reads it back to re-derive the key, and an empty salt reproduces the old derivation so unsalted parts still decrypt. Signed-off-by: Matthew N. Heler <[email protected]>
a8ed43b replaced ct_memeq with memcmp in the ISA-L GCM accelerator, making tag verification and the key-cache compare non-constant-time. Restore ct_memeq for both; the OpenSSL and EVP paths already compare in constant time. Signed-off-by: Matthew N. Heler <[email protected]>
8398e45 to
3a81a12
Compare
Part of the review for GCM #67246 brought up a concern around IV re-use for multipart uploads.
Although practical exposure is limited in that the superseded part ciphertext is overwritten at completion, so capturing both plaintexts under one
(key, IV)would require read access to the raw RADOS objects and catching the old part before garbage collection. However it still violates GCM's requirements and should be fixed, even though the impact is to single upload part.Fixes: https://tracker.ceph.com/issues/77588
Contribution Guidelines
To sign and title your commits, please refer to Submitting Patches to Ceph.
If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.
When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an
xbetween the brackets:[x]. Spaces and capitalization matter when checking off items this way.Checklist
Show available Jenkins commands
jenkins test classic perfJenkins Job | Jenkins Job Definitionjenkins test crimson perfJenkins Job | Jenkins Job Definitionjenkins test signedJenkins Job | Jenkins Job Definitionjenkins test make checkJenkins Job | Jenkins Job Definitionjenkins test make check arm64Jenkins Job | Jenkins Job Definitionjenkins test submodulesJenkins Job | Jenkins Job Definitionjenkins test dashboardJenkins Job | Jenkins Job Definitionjenkins test dashboard cephadmJenkins Job | Jenkins Job Definitionjenkins test apiJenkins Job | Jenkins Job Definitionjenkins test docsReadTheDocs | Github Workflow Definitionjenkins test ceph-volume allJenkins Jobs | Jenkins Jobs Definitionjenkins test windowsJenkins Job | Jenkins Job Definitionjenkins test rook e2eJenkins Job | Jenkins Job DefinitionYou must only issue one Jenkins command per-comment. Jenkins does not understand
comments with more than one command.