Skip to content

Added support for AES CBC Key Unwrap#871

Open
Hussainity wants to merge 3 commits intosofthsm:mainfrom
Hussainity:hm/cbc-unwrap
Open

Added support for AES CBC Key Unwrap#871
Hussainity wants to merge 3 commits intosofthsm:mainfrom
Hussainity:hm/cbc-unwrap

Conversation

@Hussainity
Copy link
Copy Markdown

@Hussainity Hussainity commented May 1, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Fixed AES-CBC block/IV initialization and handling during key wrap, ensuring correct IV length and no unintended unpadding for non-padding AES-CBC.
    • Updated mechanism reporting so AES-CBC is advertised as supporting both wrap and unwrap; added IV-length validation for AES-CBC unwrap.
  • Tests

    • Added tests for AES-CBC (non-padding) wrap/unwrap and adjusted wrap-length expectations.

@Hussainity Hussainity requested a review from a team as a code owner May 1, 2026 17:29
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 04ff1590-c921-4494-9846-26ca83620878

📥 Commits

Reviewing files that changed from the base of the PR and between 1e55512 and 0f2c65f.

📒 Files selected for processing (1)
  • src/lib/SoftHSM.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/SoftHSM.cpp

📝 Walkthrough

Walkthrough

Adds explicit CKM_AES_CBC wrap/unwrap handling: reports AES-CBC as both wrap and unwrap, initializes AES CBC blocksize for wrapping, implements IV-based CBC decryption without unpadding for unwrap, accepts CKM_AES_CBC in C_UnwrapKey, and extends tests to cover AES-CBC (non-padding) paths.

Changes

AES-CBC wrap/unwrap

Layer / File(s) Summary
Mechanism Info
src/lib/SoftHSM.cpp
C_GetMechanismInfo now reports CKM_AES_CBC flags including CKF_WRAP and CKF_UNWRAP.
Wrap initialization
src/lib/SoftHSM.cpp
WrapKeySym sets blocksize = 16 for CKM_AES_CBC so the IV buffer and copy use a 16-byte size.
Unwrap implementation
src/lib/SoftHSM.cpp
UnwrapKeySym adds a CKM_AES_CBC branch: extracts IV from mechanism params, performs decryptInit/decryptUpdate/decryptFinal, appends decrypted bytes to keydata, and explicitly skips unpadding for AES-CBC (non-pad).
API validation
src/lib/SoftHSM.cpp
C_UnwrapKey mechanism validation switch now accepts CKM_AES_CBC and enforces the same IV-length checks as CKM_AES_CBC_PAD.
Tests
src/lib/test/SymmetricAlgorithmTests.cpp
Adds CKM_AES_CBC cases to generic and non-modifiable AES wrap/unwrap tests; ensures 16-byte IV generation/parameter length for AES-CBC; adjusts expected wrap overhead (0 for CKM_AES_CBC, 16 for CKM_AES_CBC_PAD, 8 for AES key-wrap).

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant SoftHSM as SoftHSM (PKCS#11)
    participant Crypto as CryptoEngine
    participant Store as KeyStore

    Client->>SoftHSM: C_UnwrapKey(mech=CKM_AES_CBC, mechParams(IV), wrappedData)
    SoftHSM->>SoftHSM: validate mechanism & IV length
    SoftHSM->>Crypto: decryptInit(alg=AES-CBC, key, IV)
    SoftHSM->>Crypto: decryptUpdate(wrappedData)
    SoftHSM->>Crypto: decryptFinal()
    Crypto-->>SoftHSM: plaintext_keydata
    SoftHSM->>SoftHSM: assemble key object (no unpadding)
    SoftHSM->>Store: persist key / return handle
    Store-->>Client: return handle / CKR_OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • antoinelochet
  • jschlyter
  • bjosv

Poem

🐰
I hopped through code to set the IV right,
AES-CBC now wakes without a fight.
Bytes decrypt clean, no padding to shed,
Tests hum softly — all green ahead. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 accurately summarizes the main change: adding AES CBC key unwrap support, which is the primary focus of the changeset across both implementation and test files.
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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@Hussainity
Copy link
Copy Markdown
Author

Resolves the CBC Unwrap portion of this issue: #856

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/SoftHSM.cpp (1)

7596-7609: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add wrapped blob block-alignment checks during C_UnwrapKey mechanism validation.

IV length is validated, but ciphertext length is not. For CBC unwrap, reject non-block-aligned ulWrappedKeyLen early (CKR_WRAPPED_KEY_LEN_RANGE) instead of failing later as generic decrypt errors.

Proposed patch
 		case CKM_AES_CBC:
 	        case CKM_AES_CBC_PAD:
-			// TODO check block length
 			if (pMechanism->pParameter == NULL_PTR ||
                             pMechanism->ulParameterLen != 16)
 				return CKR_ARGUMENTS_BAD;
+			if (ulWrappedKeyLen == 0 || (ulWrappedKeyLen % 16) != 0)
+				return CKR_WRAPPED_KEY_LEN_RANGE;
 			break;
 
 	        case CKM_DES3_CBC_PAD:
-			// TODO check block length
 			if (pMechanism->pParameter == NULL_PTR ||
                             pMechanism->ulParameterLen != 8)
 				return CKR_ARGUMENTS_BAD;
+			if (ulWrappedKeyLen == 0 || (ulWrappedKeyLen % 8) != 0)
+				return CKR_WRAPPED_KEY_LEN_RANGE;
 			break;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/SoftHSM.cpp` around lines 7596 - 7609, In C_UnwrapKey mechanism
validation for CKM_AES_CBC, CKM_AES_CBC_PAD and CKM_DES3_CBC_PAD, add a
block-alignment check on ulWrappedKeyLen: ensure ulWrappedKeyLen is at least
pMechanism->ulParameterLen + blockSize and that (ulWrappedKeyLen -
pMechanism->ulParameterLen) % blockSize == 0 (use blockSize=16 for AES, 8 for
3DES); if not, return CKR_WRAPPED_KEY_LEN_RANGE instead of proceeding to
decryption. Locate these checks near the existing IV-length checks that
reference pMechanism->pParameter and pMechanism->ulParameterLen and enforce the
new condition before breaking out of the switch.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/lib/SoftHSM.cpp`:
- Around line 7596-7609: In C_UnwrapKey mechanism validation for CKM_AES_CBC,
CKM_AES_CBC_PAD and CKM_DES3_CBC_PAD, add a block-alignment check on
ulWrappedKeyLen: ensure ulWrappedKeyLen is at least pMechanism->ulParameterLen +
blockSize and that (ulWrappedKeyLen - pMechanism->ulParameterLen) % blockSize ==
0 (use blockSize=16 for AES, 8 for 3DES); if not, return
CKR_WRAPPED_KEY_LEN_RANGE instead of proceeding to decryption. Locate these
checks near the existing IV-length checks that reference pMechanism->pParameter
and pMechanism->ulParameterLen and enforce the new condition before breaking out
of the switch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 421f8fe1-10aa-4e04-a83a-9396b68ef9fd

📥 Commits

Reviewing files that changed from the base of the PR and between 6319797 and 842dad7.

📒 Files selected for processing (2)
  • src/lib/SoftHSM.cpp
  • src/lib/test/SymmetricAlgorithmTests.cpp

Comment thread src/lib/SoftHSM.cpp
algo = SymAlgo::AES;
break;

case CKM_DES3_CBC:
Copy link
Copy Markdown
Contributor

@antoinelochet antoinelochet May 2, 2026

Choose a reason for hiding this comment

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

There is PR #812 about CKM_DES3_CBC. I think it would be better to remove this change.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Addressed

@antoinelochet
Copy link
Copy Markdown
Contributor

Apart from my comment about CKM_DES3_CBC blocksize, this seems good !

@Leont
Copy link
Copy Markdown

Leont commented May 3, 2026

Looks sensible to me

Copy link
Copy Markdown
Member

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

I agree with @antoinelochet comment so please get rid of that bit and then it should be fine to merge.

@Hussainity Hussainity requested a review from bukka May 3, 2026 21:00
@Hussainity
Copy link
Copy Markdown
Author

Thanks all for the review!

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