Skip to content

Conversation

@ruiliio
Copy link
Contributor

@ruiliio ruiliio commented Jun 16, 2025

This CKM_RSA_AES_KEY_WRAP implementation enables the wrapping and unwrapping of target asymmetric keys of any length and type using an RSA key. A corresponding test case is included to validate the functionality.

Summary by CodeRabbit

  • New Features
    • Added support for the RSA AES key wrap mechanism, enabling enhanced key wrapping and unwrapping operations.
  • Bug Fixes
    • Improved correctness of key attribute settings during RSA key generation.
  • Tests
    • Expanded test coverage to include RSA AES key wrap for various key types and attribute combinations.
    • Enabled additional tests to verify the new key wrapping mechanism.

@ruiliio ruiliio requested a review from a team as a code owner June 16, 2025 21:01
@coderabbitai
Copy link

coderabbitai bot commented Jun 16, 2025

Walkthrough

Support for the CKM_RSA_AES_KEY_WRAP mechanism was added across the SoftHSM codebase. This includes mechanism registration, parameter checking, key wrapping and unwrapping logic, and corresponding tests. New structures and enums for this mechanism were introduced, and tests were expanded to verify correct behavior for various key types and attributes.

Changes

File(s) Change Summary
SoftHSM core implementation
src/lib/SoftHSM.cpp, src/lib/SoftHSM.h
Added support for CKM_RSA_AES_KEY_WRAP in mechanism info, parameter validation, wrap/unwrap logic; new private methods added for wrapping and unwrapping with RSA-AES key wrap.
Asymmetric algorithm updates
src/lib/crypto/AsymmetricAlgorithm.cpp, src/lib/crypto/AsymmetricAlgorithm.h
Added RSA_AES_KEY_WRAP as a supported asymmetric wrapping mechanism in enum and updated isWrappingMech logic.
PKCS#11 compatibility layer
src/lib/pkcs11/pkcs11.h
Introduced ck_rsa_aes_key_wrap_params struct and typedefs for mechanism parameters, with compatibility macros.
Unit tests for asymmetric wrap/unwrap
src/lib/test/AsymWrapUnwrapTests.cpp, src/lib/test/AsymWrapUnwrapTests.h
Enabled test suite registration; added rsaWrapUnwrapPvt method for private key wrap/unwrap testing; expanded test coverage to include CKM_RSA_AES_KEY_WRAP across key types and token/session attributes.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant HSM as SoftHSM

    App->>HSM: C_WrapKey(mech=CKM_RSA_AES_KEY_WRAP, wrappingKey, key)
    HSM->>HSM: Validate mechanism params
    HSM->>HSM: Generate temporary AES key
    HSM->>HSM: Wrap target key with AES key (CKM_AES_KEY_WRAP_PAD)
    HSM->>HSM: Wrap AES key with RSA key (CKM_RSA_PKCS_OAEP)
    HSM->>App: Return concatenated wrapped blobs

    App->>HSM: C_UnwrapKey(mech=CKM_RSA_AES_KEY_WRAP, unwrappingKey, wrappedBlob)
    HSM->>HSM: Validate mechanism params
    HSM->>HSM: Split wrappedBlob into wrapped AES key and wrapped target key
    HSM->>HSM: Unwrap AES key with RSA key (CKM_RSA_PKCS_OAEP)
    HSM->>HSM: Unwrap target key with AES key (CKM_AES_KEY_WRAP_PAD)
    HSM->>App: Return handle to unwrapped key
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren of cryptic delight,
New keys now wrap up snug and tight.
With RSA and AES, hand in paw,
They twirl and unwrap without a flaw.
Tests hop along, mechanisms grow—
The code is secure, as rabbits know!
🐇🔑✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b9f2ee and a4e858d.

📒 Files selected for processing (2)
  • src/lib/SoftHSM.cpp (11 hunks)
  • src/lib/SoftHSM.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/SoftHSM.h
👮 Files not reviewed due to content moderation or server errors (1)
  • src/lib/SoftHSM.cpp
✨ 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

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: 3

🧹 Nitpick comments (6)
src/lib/SoftHSM.h (1)

490-493: Consistency note – duplicate parameter-check helpers

MechParamCheckRSAAESKEYWRAP is declared right after MechParamCheckRSAPKCSOAEP.
Given both perform OAEP-parameter validation, consider refactoring into a single helper that accepts the mechanism type to avoid code duplication in SoftHSM.cpp.

src/lib/test/AsymWrapUnwrapTests.h (1)

50-53: Unit-test helper visibility

rsaWrapUnwrapPvt is declared protected, yet it appears to be used only inside this test class. Making it private tightens the interface and prevents accidental re-use in derived tests.

src/lib/test/AsymWrapUnwrapTests.cpp (2)

74-80: Remove the commented out variable declaration.

The additions of CKA_CLASS, CKA_KEY_TYPE, CKA_ENCRYPT, and CKA_VERIFY attributes are correct and follow PKCS#11 standards. However, the commented out bFalse variable should be removed to keep the code clean.

 CK_BYTE pubExp[] = {0x01, 0x00, 0x01};
 CK_BYTE subject[] = { 0x12, 0x34 }; // dummy
 CK_BYTE id[] = { 123 } ; // dummy
-// CK_BBOOL bFalse = CK_FALSE;
 CK_BBOOL bTrue = CK_TRUE;

120-123: Consider C++ compatibility for the designated initializer syntax.

The C99 designated initializer syntax used here may not be compatible with older C++ standards (pre-C++20). For better portability, consider using traditional initialization.

 CK_RSA_AES_KEY_WRAP_PARAMS rsa_aes_params = {
-    .aes_key_bits = 256,
-    .oaep_params = &oaepParams
+    256,          // aes_key_bits
+    &oaepParams   // oaep_params
 };
src/lib/SoftHSM.cpp (2)

7326-7328: Sensitive material not wiped

emphKeyValue (encrypted form of the temporary AES key) remains in memory after use.
For consistency with emphkeydata wipe it as well:

-	emphkeydata.wipe();
-	/* missing */ 
-	emphKeyValue.wipe();
+	emphkeydata.wipe();
+	emphKeyValue.wipe();

[security]


13122-13131: Over-restrictive parameter validation

Spec restricts OAEP defaults to SHA-1 by default, but permitting SHA-256/384 is common practice and already supported elsewhere in SoftHSM. Consider relaxing the checks to accept other permitted digests & MGF combos, or surface CKR_MECHANISM_PARAM_INVALID only when the digest is unsupported by the underlying crypto backend.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 557b2fd and 19127cc.

📒 Files selected for processing (7)
  • src/lib/SoftHSM.cpp (9 hunks)
  • src/lib/SoftHSM.h (1 hunks)
  • src/lib/crypto/AsymmetricAlgorithm.cpp (1 hunks)
  • src/lib/crypto/AsymmetricAlgorithm.h (1 hunks)
  • src/lib/pkcs11/pkcs11.h (3 hunks)
  • src/lib/test/AsymWrapUnwrapTests.cpp (6 hunks)
  • src/lib/test/AsymWrapUnwrapTests.h (1 hunks)
🔇 Additional comments (8)
src/lib/crypto/AsymmetricAlgorithm.h (1)

64-72: ```shell
#!/bin/bash

Locate the enum definition to confirm ordering

grep -R -n "enum class Type" src/lib/crypto/AsymmetricAlgorithm.h || true

Find all references to AsymMech::Type to see how it's used

grep -R -n "AsymMech::Type" . || true

Identify switch statements on the Type enum

grep -R -n "switch.*Type" . || true

Check for casts of the enum to integer

grep -R -n "static_cast<.*Type" . || true

Look for to_string or serialization helpers for the enum

grep -R -n -E "to_string.*Type|from_string.*Type" . || true

Search for stream operators involving the enum

grep -R -n "operator<<.*Type" . || true


</details>
<details>
<summary>src/lib/crypto/AsymmetricAlgorithm.cpp (1)</summary>

`146-153`: **Good: `isWrappingMech` extended correctly**

`RSA_AES_KEY_WRAP` is now recognised as a wrapping mechanism, keeping the wrapper gate in sync with the new feature.  
Nothing further needed here.

</details>
<details>
<summary>src/lib/pkcs11/pkcs11.h (1)</summary>

`982-986`: **Struct definition looks OK – please cross-check macro collision**

The field names rely on earlier compatibility macros (`aes_key_bits`, `oaep_params`). Ensure no unintended macro substitution occurs when `CRYPTOKI_GNU` is **not** defined, otherwise the member names will differ between compatibility and GNU modes.  
If necessary, wrap the struct definition with `#undef` / `#define` to make the intent explicit.

</details>
<details>
<summary>src/lib/test/AsymWrapUnwrapTests.cpp (5)</summary>

`47-47`: **LGTM! Test suite is now activated.**

Uncommenting the test suite registration enables these important wrap/unwrap tests.

---

`96-105`: **LGTM! Private key attributes are properly configured.**

The additions of `CKA_CLASS`, `CKA_KEY_TYPE`, `CKA_DECRYPT`, `CKA_SIGN`, and `CKA_EXTRACTABLE` attributes are correct and necessary for RSA private key operations and wrapping functionality.

---

`115-190`: **LGTM! Comprehensive test implementation for CKM_RSA_AES_KEY_WRAP.**

The test function properly validates the new RSA AES key wrap mechanism by:
- Testing buffer size estimation
- Verifying proper error handling for insufficient buffers
- Wrapping and unwrapping RSA private keys
- Validating the unwrapped key works correctly through sign/verify operations

---

`231-235`: **LGTM! Proper delegation for asymmetric key wrapping.**

The early return and delegation to `rsaWrapUnwrapPvt` is correct since `CKM_RSA_AES_KEY_WRAP` handles asymmetric key wrapping, unlike the other mechanisms that wrap symmetric keys.

---

`313-343`: **LGTM! Comprehensive test coverage for all key combinations.**

The test now properly validates `CKM_RSA_AES_KEY_WRAP` alongside existing mechanisms for all combinations of:
- Session vs Token keys
- Public vs Private visibility
This ensures the new mechanism works correctly in all deployment scenarios.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@jschlyter jschlyter requested a review from bjosv July 26, 2025 08:04
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.

LGTM, just some comments

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.

4 participants