Skip to content

Conversation

@antoinelochet
Copy link
Contributor

@antoinelochet antoinelochet commented Oct 27, 2023

Allow attributes update when CKA_MODIFIABLE is false and the operation is UNWRAP.
Here is my proposed fix for #707

Summary by CodeRabbit

  • New Features

    • Allow certain attribute updates during object unwrapping.
    • Added tests covering AES key wrap/unwrap when resulting keys are non-modifiable.
  • Bug Fixes

    • Fix attribute-update checks so unwrap flows can modify allowed attributes (including unwrap operation).
    • Improved validation for wrap/unwrap flows with non-modifiable keys.

@jschlyter jschlyter linked an issue Nov 29, 2024 that may be closed by this pull request
@jschlyter jschlyter changed the title Fixed issue #707 Allow OBJECT_OP_UNWRAP to modify attributes Allow OBJECT_OP_UNWRAP to modify attributes Nov 29, 2024
@jschlyter jschlyter added the bug Some isn't right label Nov 29, 2024
@jschlyter
Copy link
Contributor

Please rebase on develop and mark as ready when ready.

@jschlyter jschlyter marked this pull request as draft November 29, 2024 16:27
@antoinelochet antoinelochet marked this pull request as ready for review November 29, 2024 19:04
@antoinelochet antoinelochet requested a review from a team as a code owner November 29, 2024 19:04
@antoinelochet
Copy link
Contributor Author

Hello @jschlyter
Done :)

@jschlyter
Copy link
Contributor

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link

coderabbitai bot commented Jan 29, 2025

Warning

Rate limit exceeded

@antoinelochet has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 45 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ccc1964 and 26ec19a.

📒 Files selected for processing (3)
  • src/lib/P11Attributes.cpp (1 hunks)
  • src/lib/test/SymmetricAlgorithmTests.cpp (2 hunks)
  • src/lib/test/SymmetricAlgorithmTests.h (1 hunks)

Walkthrough

P11Attribute::update now treats OBJECT_OP_UNWRAP like OBJECT_OP_GENERATE and OBJECT_OP_CREATE for attribute modification checks. New tests added: SymmetricAlgorithmTests gains aesWrapUnwrapNonModifiableGeneric and calls it for CKM_AES_KEY_WRAP and CKM_AES_CBC_PAD to verify unwrap into a non-modifiable key and buffer behavior.

Changes

Cohort / File(s) Change Summary
Attribute update logic
src/lib/P11Attributes.cpp
Two guard checks in P11Attribute::update were extended to exclude OBJECT_OP_UNWRAP from the modifiability and trusted/certificate restrictions, allowing attribute changes during unwrap. No public API/signature changes.
AES wrap/unwrap tests
src/lib/test/SymmetricAlgorithmTests.cpp, src/lib/test/SymmetricAlgorithmTests.h
Added aesWrapUnwrapNonModifiableGeneric(CK_MECHANISM_TYPE, CK_SESSION_HANDLE, CK_OBJECT_HANDLE) declaration and implementation; extended testAesWrapUnwrap() to invoke it for CKM_AES_KEY_WRAP and CKM_AES_CBC_PAD. Tests validate wrap length, buffer-too-small behavior, unwrap into a non-modifiable key, and cleanup.

Sequence Diagram(s)

sequenceDiagram
    participant Test as AES Test
    participant PKCS11 as PKCS#11 Layer
    participant Attr as P11Attribute::update

    Test->>PKCS11: Unwrap(wrappedKey, mechanism, unwrapAttrs)
    PKCS11->>Attr: update(unwrapAttrs, OBJECT_OP_UNWRAP)
    Note right of Attr: treat OBJECT_OP_UNWRAP like\nOBJECT_OP_GENERATE / OBJECT_OP_CREATE\nfor modifiability/trusted checks
    Alt attributes accepted
        Attr-->>PKCS11: accept attributes
        PKCS11-->>Test: return new key handle (unwrap succeeds)
    Else modification denied
        Attr-->>PKCS11: reject modification
        PKCS11-->>Test: unwrap error (e.g., CKR_ATTRIBUTE_READ_ONLY)
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

"A Rabbit's Note on Unwraps"

I nibbled bits of code at night,
Let UNWRAP join the modifiable light.
Wrapped seeds loosen, keys take flight,
Tests hop in to prove it's right. 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jschlyter jschlyter requested a review from bjosv January 29, 2025 05:38
Copy link
Contributor

@bjosv bjosv left a comment

Choose a reason for hiding this comment

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

I would be nice with a test in SymmetricAlgorithmTests.cpp similar to its testNonModifiableDesKeyGeneration.

Copy link

@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: 1

🔭 Outside diff range comments (1)
src/lib/test/SymmetricAlgorithmTests.h (1)

44-58: Add the new test to the test suite.

The new method aesWrapUnwrapNonModifiableGeneric is not included in the test suite. Consider adding it to ensure the new functionality is tested.

Apply this diff to add the test:

 CPPUNIT_TEST_SUITE(SymmetricAlgorithmTests);
 CPPUNIT_TEST(testAesEncryptDecrypt);
 CPPUNIT_TEST(testDesEncryptDecrypt);
#ifdef HAVE_AES_KEY_WRAP
 CPPUNIT_TEST(testAesWrapUnwrap);
+CPPUNIT_TEST(testAesWrapUnwrapNonModifiable);
#endif
 CPPUNIT_TEST(testNullTemplate);

You'll also need to add the corresponding public test method. Let me know if you'd like me to help with that implementation.

🧹 Nitpick comments (2)
src/lib/test/SymmetricAlgorithmTests.cpp (2)

1189-1190: Add documentation for the test method.

Please add comments explaining that this test verifies unwrapping behavior when CKA_MODIFIABLE is set to false.

+// Test that unwrapping works correctly when CKA_MODIFIABLE is set to false.
+// This verifies the fix for issue #707 which allows OBJECT_OP_UNWRAP to modify attributes
+// even when CKA_MODIFIABLE is false.
 void SymmetricAlgorithmTests::aesWrapUnwrapNonModifiableGeneric(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey)

1189-1288: Consider refactoring to reduce code duplication.

This method shares a lot of code with aesWrapUnwrapGeneric. Consider extracting the common functionality into helper methods to improve maintainability.

For example:

  1. Extract key generation and wrapping into a helper method
  2. Extract unwrapping and verification into another helper method
  3. Pass CKA_MODIFIABLE value as a parameter
+// Helper method for key generation and wrapping
+void wrapKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_TYPE mechanismType, 
+             CK_OBJECT_HANDLE hKey, CK_BBOOL bExtractable,
+             CK_BYTE_PTR& wrappedPtr, CK_ULONG& wrappedLen) {
+    // Common key generation and wrapping code
+}
+
+// Helper method for unwrapping and verification  
+void unwrapAndVerifyKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_TYPE mechanismType,
+                       CK_OBJECT_HANDLE hKey, CK_BBOOL bModifiable,
+                       CK_BYTE_PTR wrappedPtr, CK_ULONG wrappedLen) {
+    // Common unwrapping and verification code
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14749ef and 9e67f7e.

📒 Files selected for processing (3)
  • src/lib/P11Attributes.cpp (1 hunks)
  • src/lib/test/SymmetricAlgorithmTests.cpp (1 hunks)
  • src/lib/test/SymmetricAlgorithmTests.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/P11Attributes.cpp
🔇 Additional comments (1)
src/lib/test/SymmetricAlgorithmTests.h (1)

91-91: LGTM! Method signature follows existing patterns.

The new method aesWrapUnwrapNonModifiableGeneric follows the established pattern of similar methods in the class, maintaining consistency in the codebase.

@antoinelochet
Copy link
Contributor Author

antoinelochet commented Feb 6, 2025

I would be nice with a test in SymmetricAlgorithmTests.cpp similar to its testNonModifiableDesKeyGeneration.

I have added a aesWrapUnwrapNonModifiableGeneric test where the unwrap template sets CKA_UNMODIFIABLE to false.

@antoinelochet
Copy link
Contributor Author

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

Copy link

@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: 1

♻️ Duplicate comments (1)
src/lib/test/SymmetricAlgorithmTests.cpp (1)

1747-1748: Good integration: the new non-modifiable unwrap test is now exercised

These calls address the earlier request to invoke aesWrapUnwrapNonModifiableGeneric from the test suite. Consider also covering the PAD variant when available:

Additional suggestion (outside this hunk, under HAVE_AES_KEY_WRAP_PAD):

#ifdef HAVE_AES_KEY_WRAP_PAD
  aesWrapUnwrapNonModifiableGeneric(CKM_AES_KEY_WRAP_PAD, hSession, hKey);
#endif
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c98eb5 and 9887274.

📒 Files selected for processing (3)
  • src/lib/P11Attributes.cpp (1 hunks)
  • src/lib/test/SymmetricAlgorithmTests.cpp (2 hunks)
  • src/lib/test/SymmetricAlgorithmTests.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/test/SymmetricAlgorithmTests.h
  • src/lib/P11Attributes.cpp
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/lib/test/SymmetricAlgorithmTests.cpp (1)
src/lib/SoftHSM.cpp (2)
  • C_WrapKey (4792-5063)
  • C_UnwrapKey (5066-5361)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: macOS (botan)
  • GitHub Check: Linux (openssl)
  • GitHub Check: Windows (x64, openssl)
  • GitHub Check: Linux (botan)
  • GitHub Check: Windows (x64, botan)
  • GitHub Check: Windows (x86, openssl)

Copy link

@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: 0

♻️ Duplicate comments (2)
src/lib/test/SymmetricAlgorithmTests.cpp (2)

1189-1301: Good coverage of unwrap with CKA_MODIFIABLE=FALSE and solid cleanup

  • Asserts CKR_KEY_UNEXTRACTABLE first, then wraps after making the key extractable.
  • Validates wrap length including mechanism-dependent overhead.
  • Unwraps with CKA_MODIFIABLE=CK_FALSE, verifies via C_GetAttributeValue, and destroys both hSecret and hNew to avoid leaks.

Addresses earlier feedback to verify CKA_MODIFIABLE and clean up objects.


1759-1760: Integration looks good; consider adding KEY_WRAP_PAD variant too

The new helper is now invoked for CKM_AES_KEY_WRAP and CKM_AES_CBC_PAD — this addresses earlier integration feedback.

Optionally, mirror coverage for CKM_AES_KEY_WRAP_PAD inside the existing HAVE_AES_KEY_WRAP_PAD block, similar to aesWrapUnwrapGeneric/aesWrapUnwrapRsa.

Add inside the HAVE_AES_KEY_WRAP_PAD block:

// Also validate non-modifiable unwrap path for RFC5649
aesWrapUnwrapNonModifiableGeneric(CKM_AES_KEY_WRAP_PAD, hSession, hKey);
🧹 Nitpick comments (1)
src/lib/test/SymmetricAlgorithmTests.cpp (1)

1284-1293: Nit: read CKA_MODIFIABLE into a dedicated local variable for clarity

Use a separate buffer instead of reusing &bFalse as the output buffer. It makes the intent explicit and avoids confusion with the input template value.

-    CK_ATTRIBUTE modifiableAttribs[] = {
-        { CKA_MODIFIABLE, &bFalse, sizeof(bFalse) }
-    };
-
-    rv = CRYPTOKI_F_PTR( C_GetAttributeValue(hSession, hNew, modifiableAttribs, sizeof(modifiableAttribs)/sizeof(CK_ATTRIBUTE)) );
-    CPPUNIT_ASSERT(rv == CKR_OK);
-
-    CPPUNIT_ASSERT(modifiableAttribs[0].ulValueLen == sizeof(bFalse));
-    CPPUNIT_ASSERT(*(CK_BBOOL*)modifiableAttribs[0].pValue == bFalse);
+    CK_BBOOL modifiableReadback = CK_TRUE; // sentinel to ensure we read back from token
+    CK_ATTRIBUTE getAttrs[] = {
+        { CKA_MODIFIABLE, &modifiableReadback, sizeof(modifiableReadback) }
+    };
+
+    rv = CRYPTOKI_F_PTR( C_GetAttributeValue(hSession, hNew, getAttrs, 1) );
+    CPPUNIT_ASSERT(rv == CKR_OK);
+
+    CPPUNIT_ASSERT(getAttrs[0].ulValueLen == sizeof(modifiableReadback));
+    CPPUNIT_ASSERT(modifiableReadback == CK_FALSE);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9887274 and ee7749e.

📒 Files selected for processing (3)
  • src/lib/P11Attributes.cpp (1 hunks)
  • src/lib/test/SymmetricAlgorithmTests.cpp (2 hunks)
  • src/lib/test/SymmetricAlgorithmTests.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/lib/P11Attributes.cpp
  • src/lib/test/SymmetricAlgorithmTests.h

…ify attributes when CKA_MODIFIABLE is true
Copy link
Contributor

@bukka bukka left a comment

Choose a reason for hiding this comment

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

The logic makes sense to me. It looks really just like an omission as unwrap is the same as create in this context. The test also looks fine.

@jschlyter please can you approve the workflow so CI runs (it's rebased so it should get properly tested)

@jschlyter jschlyter merged commit 0f972d8 into softhsm:develop Dec 9, 2025
8 of 9 checks passed
@antoinelochet antoinelochet deleted the fix_issue_707 branch December 14, 2025 07:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Some isn't right

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CKA_MODIFIABLE must be true to Unwrap AES Key

4 participants