Skip to content

Support encryption for END_DATE and START_DATE attributes in private keys#665

Open
antoinelochet wants to merge 1 commit into
softhsm:mainfrom
antoinelochet:fix_issue_655
Open

Support encryption for END_DATE and START_DATE attributes in private keys#665
antoinelochet wants to merge 1 commit into
softhsm:mainfrom
antoinelochet:fix_issue_655

Conversation

@antoinelochet
Copy link
Copy Markdown
Contributor

@antoinelochet antoinelochet commented Jan 11, 2022

Addresses the issue in #655

Summary by CodeRabbit

  • Bug Fixes

    • Start/end date attributes are now stored reliably and respect privacy (encrypted when marked private) and are correctly handled during object creation.
  • Tests

    • Added RSA public/private key tests validating behavior when start/end date attributes are provided.
  • Chores

    • Improved debug/error logging for template processing and data decryption; updated CI checkout/tooling versions.

Review Change Stack

@jschlyter jschlyter changed the title Fix issue 655 - Support encryption for END_DATE and START_DATE attributes in private keys Support encryption for END_DATE and START_DATE attributes in private keys Nov 29, 2024
@jschlyter jschlyter marked this pull request as draft November 29, 2024 16:26
@jschlyter
Copy link
Copy Markdown
Contributor

Please rebase on develop and mark as ready when ready.

@antoinelochet antoinelochet marked this pull request as ready for review November 29, 2024 19:00
@antoinelochet antoinelochet requested a review from a team as a code owner November 29, 2024 19:00
@antoinelochet
Copy link
Copy Markdown
Contributor Author

Hello @jschlyter
Done :)

@antoinelochet
Copy link
Copy Markdown
Contributor Author

As requested by @jschlyter, this PR has been rebased to the latest develop

@antoinelochet
Copy link
Copy Markdown
Contributor Author

This could be closed without merging when #805 is merged

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

📝 Walkthrough

Walkthrough

Encrypts CKA_START_DATE/CKA_END_DATE for private objects, writes back OSAttribute on creation when present, adds per-attribute debug/error logs in template handling and decryption, introduces RSA creation tests with date attributes, and updates CI checkout/tool versions.

Changes

Private Date Attribute Encryption and Logging

Layer / File(s) Summary
Date attribute encryption and OSAttribute writeback
src/lib/P11Attributes.cpp
P11AttrStartDate::updateAttr and P11AttrEndDate::updateAttr build plaintext from pValue, encrypt via token->encrypt when isPrivate, validate stored size against ulValueLen, store the encrypted/plaintext value, and on OBJECT_OP_CREATE write CKA_START_DATE/CKA_END_DATE via an OSAttribute only if that attribute exists.
Debug and error logging for object operations and decryption
src/lib/P11Objects.cpp, src/lib/data_mgr/SecureDataManager.cpp
Added DEBUG_MSG entries in loadTemplate, saveTemplate, and decrypt to log attribute type/pointer, IV, ciphertext, AES block size, and plaintext. Enhanced error paths emit ERROR_MSG with context (attribute type/index or decryption failure) before aborting or returning failure.
RSA key tests with date attributes
src/lib/test/ObjectTests.h, src/lib/test/ObjectTests.cpp
Added testDefaultRSAPubAttributesWithDates and testDefaultRSAPrivAttributesWithDates to create RSA keys with CKA_START_DATE/CKA_END_DATE in creation templates and assert that stored objects reflect the provided CK_DATE values.
CI workflow action updates
.github/workflows/ci.yml
Bumped actions/checkout to @v6 across jobs and pinned ilammy/msvc-dev-cmd on Windows to @v1.13.0.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • Issue #804: Addresses storing start/end date attributes in clear for private objects by encrypting private date attributes and performing create-time OSAttribute writeback.

Poem

🐰 Soft paws tap on cryptic dates,
I wrap them snug behind locked gates,
Logs whisper IVs and plaintext threads,
Tests hop in to check the beds,
Secure burrows guard time's estates.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Support encryption for END_DATE and START_DATE attributes in private keys' accurately describes the main changes in the pull request, which add encryption support for these date attributes when marked as private.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/data_mgr/SecureDataManager.cpp (1)

400-453: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove raw ciphertext/IV/plaintext dumping from decrypt debug logs

  • %s with ByteString::const_byte_str() is unsafe: const_byte_str() returns raw bytes without NUL termination (sentinel is uninitialized for the empty case), while softHSMLog uses vsnprintf which treats %s as a C-string; this can cause out-of-bounds reads (UB) and also leaks encrypted/IV/plaintext material to DEBUG logs (enabled by default).
  • Replace those %s buffer dumps with length-only (or hex) logging.
🛠️ Suggested patch
- DEBUG_MSG("encrypted %s", encrypted.const_byte_str());
+ DEBUG_MSG("decrypt input length=%lu", (unsigned long)encrypted.size());

- DEBUG_MSG("AES block size %d", aes->getBlockSize());
+ DEBUG_MSG("AES block size=%lu", (unsigned long)aes->getBlockSize());

- DEBUG_MSG("IV %s", IV.const_byte_str());
+ DEBUG_MSG("IV length=%lu", (unsigned long)IV.size());

- DEBUG_MSG("plaintext %s", plaintext.const_byte_str());
+ DEBUG_MSG("decrypt output length=%lu", (unsigned long)plaintext.size());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/data_mgr/SecureDataManager.cpp` around lines 400 - 453, The debug
logs in SecureDataManager.cpp leak raw ciphertext/IV/plaintext and misuse %s
with ByteString::const_byte_str(), causing potential UB and sensitive-data
exposure; update the DEBUG_MSG calls that reference encrypted.const_byte_str(),
IV.const_byte_str(), and plaintext.const_byte_str() (and any similar uses around
the decrypt flow in the decrypt routine using
aes/decryptInit/decryptUpdate/decryptFinal) to avoid printing raw bytes — log
only lengths or hex-encoded safe representations (or remove the logs), and
ensure you do not pass non-NUL-terminated buffers to %s (use a length-based
formatter or omit const_byte_str()).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/P11Objects.cpp`:
- Around line 172-173: Logging in loadTemplate and saveTemplate uses wrong
printf specifiers: change the pTemplate[i].pValue specifier from (%x) to (%p)
and pass it as (void*)pTemplate[i].pValue, and change the CK_ULONG index
specifier from @ %d to @ %lu or cast the index to (unsigned long) when using
%lu; update the ERROR_MSG calls in loadTemplate and saveTemplate to use these
corrected format specifiers and casts to match types.

In `@src/lib/test/ObjectTests.cpp`:
- Line 1818: The calls to checkCommonKeyAttributes pass pointer-size lengths for
CK_DATE fields; replace sizeof(&startDate) and sizeof(&endDate) with the actual
CK_DATE byte sizes by using sizeof(startDate) and sizeof(endDate) in the calls
(references: checkCommonKeyAttributes, startDate, endDate) so the
ulStartDateLen/ulEndDateLen reflect the CK_DATE struct size rather than the
pointer size.

---

Outside diff comments:
In `@src/lib/data_mgr/SecureDataManager.cpp`:
- Around line 400-453: The debug logs in SecureDataManager.cpp leak raw
ciphertext/IV/plaintext and misuse %s with ByteString::const_byte_str(), causing
potential UB and sensitive-data exposure; update the DEBUG_MSG calls that
reference encrypted.const_byte_str(), IV.const_byte_str(), and
plaintext.const_byte_str() (and any similar uses around the decrypt flow in the
decrypt routine using aes/decryptInit/decryptUpdate/decryptFinal) to avoid
printing raw bytes — log only lengths or hex-encoded safe representations (or
remove the logs), and ensure you do not pass non-NUL-terminated buffers to %s
(use a length-based formatter or omit const_byte_str()).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bfb22f6a-0f22-4ada-bc61-fa038f08c28b

📥 Commits

Reviewing files that changed from the base of the PR and between 679f33d and 8b69f59.

📒 Files selected for processing (5)
  • src/lib/P11Attributes.cpp
  • src/lib/P11Objects.cpp
  • src/lib/data_mgr/SecureDataManager.cpp
  • src/lib/test/ObjectTests.cpp
  • src/lib/test/ObjectTests.h

Comment thread src/lib/P11Objects.cpp Outdated
Comment thread src/lib/test/ObjectTests.cpp Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/data_mgr/SecureDataManager.cpp (1)

400-452: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove sensitive decrypt-path logging that prints raw ByteString bytes as %s

  • DEBUG_MSG(... "%s", <ByteString>::const_byte_str()) treats raw, non-null-terminated bytes as a C-string (can truncate on NULs and may read past the buffer); these statements log encrypted, IV, and plaintext directly in SecureDataManager::decrypt.
🛠️ Minimal fix
 bool SecureDataManager::decrypt(const ByteString& encrypted, ByteString& plaintext)
 {
-	DEBUG_MSG("encrypted %s", encrypted.const_byte_str());
 	// Check the object logged in state
 	if ((!userLoggedIn && !soLoggedIn) || (maskedKey.size() != 32))
 	{
 		return false;
@@
-	DEBUG_MSG("AES block size %d", aes->getBlockSize());
 	ByteString IV = encrypted.substr(0, aes->getBlockSize());
@@
-	DEBUG_MSG("IV %s", IV.const_byte_str());
-
 	ByteString finalBlock;
@@
 	plaintext += finalBlock;
-
-	DEBUG_MSG("plaintext %s", plaintext.const_byte_str());
 
 	return true;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/data_mgr/SecureDataManager.cpp` around lines 400 - 452, In
SecureDataManager::decrypt, remove or replace unsafe DEBUG_MSG(...) calls that
pass ByteString::const_byte_str() (currently logging variables encrypted, IV,
and plaintext) because they treat raw bytes as C-strings and leak sensitive
plaintext; instead log non-sensitive metadata (e.g., encrypted.size(),
IV.size(), plaintext.size()) or a safe encoded representation (e.g., a
hex/BASE64 of a limited prefix) using ByteString’s safe conversion helper rather
than const_byte_str(); update the DEBUG_MSG invocations so they reference
encrypted, IV, and plaintext only via safe methods and avoid printing raw
decrypted data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/ci.yml:
- Line 14: Update all usages of the actions/checkout step (e.g., the occurrence
using "actions/checkout@v6") to pin to a commit SHA instead of a tag (leave the
tag as a trailing comment for human readability, e.g., "# v6") and add the input
"persist-credentials: false" to each checkout step (unless later steps
explicitly require git credentials); ensure you change every checkout occurrence
reported (the ones using actions/checkout) so they consistently use SHA pinning
and persistent credentials are disabled.
- Line 14: The workflow uses actions/checkout@v6 (and other actions like
ilammy/msvc-dev-cmd@v1.13.0 and johnwason/vcpkg-action@v8); ensure those
versions/tags exist and then harden each checkout step by adding with:
persist-credentials: false to the actions/checkout@v6 invocations so credentials
are not left in the workspace when not needed, and if your security policy
requires immutable pins, replace tags like actions/checkout@v6 with their
corresponding commit SHAs to fully pin the action.

---

Outside diff comments:
In `@src/lib/data_mgr/SecureDataManager.cpp`:
- Around line 400-452: In SecureDataManager::decrypt, remove or replace unsafe
DEBUG_MSG(...) calls that pass ByteString::const_byte_str() (currently logging
variables encrypted, IV, and plaintext) because they treat raw bytes as
C-strings and leak sensitive plaintext; instead log non-sensitive metadata
(e.g., encrypted.size(), IV.size(), plaintext.size()) or a safe encoded
representation (e.g., a hex/BASE64 of a limited prefix) using ByteString’s safe
conversion helper rather than const_byte_str(); update the DEBUG_MSG invocations
so they reference encrypted, IV, and plaintext only via safe methods and avoid
printing raw decrypted data.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3190ae94-c06c-4b15-ba15-ccd1b9625be4

📥 Commits

Reviewing files that changed from the base of the PR and between 8b69f59 and fc8bd90.

📒 Files selected for processing (6)
  • .github/workflows/ci.yml
  • src/lib/P11Attributes.cpp
  • src/lib/P11Objects.cpp
  • src/lib/data_mgr/SecureDataManager.cpp
  • src/lib/test/ObjectTests.cpp
  • src/lib/test/ObjectTests.h

Comment thread .github/workflows/ci.yml
@antoinelochet antoinelochet force-pushed the fix_issue_655 branch 2 times, most recently from af80b1c to c7b9e02 Compare May 26, 2026 11:34
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/data_mgr/SecureDataManager.cpp (1)

400-452: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove raw ciphertext/IV/plaintext logging from SecureDataManager::decrypt

softHSMLog formats with vsnprintf, so the existing DEBUG_MSG("%s", <ByteString>.const_byte_str()) uses %s on non-NUL-terminated binary buffers (via ByteString::const_byte_str()), which is unsafe; it also leaks sensitive encrypted/IV/plaintext material from SecureDataManager::decrypt (lines ~400-452). Replace these logs with non-sensitive metadata only (e.g., lengths / success flag), or use safe hex/encoded representations that don’t treat raw bytes as C strings.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/data_mgr/SecureDataManager.cpp` around lines 400 - 452,
SecureDataManager::decrypt currently logs raw binary buffers (encrypted, IV,
plaintext) using DEBUG_MSG("%s", ByteString::const_byte_str()), which is unsafe
and leaks secrets; remove these raw %s logs and instead log only non-sensitive
metadata or safe encodings: replace DEBUG_MSG/ERROR_MSG calls that print
encrypted, IV or plaintext with statements that log lengths/status (e.g.,
encrypted.size(), IV.size(), plaintext.size()) or use a safe hex/base64 helper
(not using %s on const_byte_str()) to produce NUL-safe representations; ensure
references to symbols encrypted, IV, plaintext, DEBUG_MSG, ERROR_MSG, and
ByteString::const_byte_str() are updated accordingly and do not print raw binary
data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/lib/data_mgr/SecureDataManager.cpp`:
- Around line 400-452: SecureDataManager::decrypt currently logs raw binary
buffers (encrypted, IV, plaintext) using DEBUG_MSG("%s",
ByteString::const_byte_str()), which is unsafe and leaks secrets; remove these
raw %s logs and instead log only non-sensitive metadata or safe encodings:
replace DEBUG_MSG/ERROR_MSG calls that print encrypted, IV or plaintext with
statements that log lengths/status (e.g., encrypted.size(), IV.size(),
plaintext.size()) or use a safe hex/base64 helper (not using %s on
const_byte_str()) to produce NUL-safe representations; ensure references to
symbols encrypted, IV, plaintext, DEBUG_MSG, ERROR_MSG, and
ByteString::const_byte_str() are updated accordingly and do not print raw binary
data.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2508535b-9eaa-4ab0-a3d5-afd619bb00fc

📥 Commits

Reviewing files that changed from the base of the PR and between fc8bd90 and af80b1c.

📒 Files selected for processing (6)
  • .github/workflows/ci.yml
  • src/lib/P11Attributes.cpp
  • src/lib/P11Objects.cpp
  • src/lib/data_mgr/SecureDataManager.cpp
  • src/lib/test/ObjectTests.cpp
  • src/lib/test/ObjectTests.h
✅ Files skipped from review due to trivial changes (1)
  • src/lib/P11Objects.cpp

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/data_mgr/SecureDataManager.cpp (1)

400-452: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not log decrypted plaintext or crypto material in decrypt().

Lines 400/438/452 expose encrypted payloads, IV, and plaintext in logs; this can leak sensitive key material.

🔧 Suggested fix
-	DEBUG_MSG("encrypted %s", encrypted.hex_str().c_str());
@@
-	DEBUG_MSG("AES block size %d", aes->getBlockSize());
@@
-	DEBUG_MSG("IV %s", IV.hex_str().c_str());
@@
-	DEBUG_MSG("plaintext %s", plaintext.hex_str().c_str());
+	// Avoid logging sensitive cryptographic material
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/data_mgr/SecureDataManager.cpp` around lines 400 - 452, The decrypt()
implementation currently logs sensitive crypto material (encrypted, IV,
plaintext and unmasked key) via DEBUG_MSG/ERROR_MSG; remove or redact those log
calls and ensure unmaskedKey is never logged or persisted. Specifically, in
SecureDataManager::decrypt (references: variables encrypted, IV, plaintext,
unmaskedKey, AESKey theKey and calls unmask()/remask()) delete or replace
DEBUG_MSG("encrypted ..."), DEBUG_MSG("IV ..."), and DEBUG_MSG("plaintext ...")
with non-sensitive, high-level messages (e.g. "decrypt started" / "decrypt
completed" or nothing), and ensure errors reported by ERROR_MSG do not include
IV/plaintext/unmaskedKey contents; keep unmask()/remask() usage but never log
their results.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/lib/data_mgr/SecureDataManager.cpp`:
- Around line 400-452: The decrypt() implementation currently logs sensitive
crypto material (encrypted, IV, plaintext and unmasked key) via
DEBUG_MSG/ERROR_MSG; remove or redact those log calls and ensure unmaskedKey is
never logged or persisted. Specifically, in SecureDataManager::decrypt
(references: variables encrypted, IV, plaintext, unmaskedKey, AESKey theKey and
calls unmask()/remask()) delete or replace DEBUG_MSG("encrypted ..."),
DEBUG_MSG("IV ..."), and DEBUG_MSG("plaintext ...") with non-sensitive,
high-level messages (e.g. "decrypt started" / "decrypt completed" or nothing),
and ensure errors reported by ERROR_MSG do not include IV/plaintext/unmaskedKey
contents; keep unmask()/remask() usage but never log their results.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 423ae12f-7b2e-46fc-90e0-2eff4001ef19

📥 Commits

Reviewing files that changed from the base of the PR and between af80b1c and 5250f19.

📒 Files selected for processing (6)
  • .github/workflows/ci.yml
  • src/lib/P11Attributes.cpp
  • src/lib/P11Objects.cpp
  • src/lib/data_mgr/SecureDataManager.cpp
  • src/lib/test/ObjectTests.cpp
  • src/lib/test/ObjectTests.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Attributes START_DATE and END_DATE are not ciphered in a private key

2 participants