Skip to content

ML-KEM: Fix-up ASN.1 reading and writing logic #115066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 29, 2025

Conversation

vcsjones
Copy link
Member

This has a couple of improvements to how MLKem interacts with SubjectPublicKeyInfo and PrivateKeyInfo.

  • Thrown exceptions are improved, either by throwing the right exception or not including irrelevant inner exceptions.
  • The trailing data check will now account for improperly encoded ASN.1
  • Improved handling when derived types have an incorrectly implemented TryExportPkcs8PrivateKeyCore

Fixes #115063

This addresses a couple of validation deficiencies when loading ASN.1 content. This ensures invalid ASN.1 receives the proper exception and that SubjectPublicKeyInfo imports do not permit trailing data.

For PKCS#8 export, we more reliably clear buffers and handle incorrectly implemented exports when the amount written is negative.
@Copilot Copilot AI review requested due to automatic review settings April 25, 2025 22:10
@ghost ghost added the area-System.Security label Apr 25, 2025
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR improves the ASN.1 reading and writing logic for MLKem by enhancing exception handling, validating trailing data, and improving the handling of private key exports.

  • Improved exception types and messages for ASN.1 issues.
  • Added tests for non-ASN.1 inputs and trailing data.
  • Updated logic in MLKem key reader and private key export to validate key lengths and buffer handling.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
src/libraries/Common/tests/System/Security/Cryptography/MLKemTests.cs Added tests for non-ASN.1 inputs and trailing data.
src/libraries/Common/tests/System/Security/Cryptography/MLKemContractTests.cs Renamed and added tests for misbehaving bytes-written scenarios in private key export.
src/libraries/Common/src/System/Security/Cryptography/MLKem.cs Updated ASN.1 trailing data validation and key reader logic and revised buffer handling in the private key export callback.
Comments suppressed due to low confidence (1)

src/libraries/Common/src/System/Security/Cryptography/MLKem.cs:1823

  • In ExportPkcs8PrivateKeyCallback, the initial allocation uses CryptoPool but the fallback allocation uses ArrayPool.Shared. For consistency and to avoid potential pool misuse, allocate all buffers using the same pool.
buffer = ArrayPool<byte>.Shared.Rent(size);

Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-security, @bartonjs, @vcsjones
See info in area-owners.md if you want to be subscribed.

@vcsjones vcsjones added this to the 10.0.0 milestone Apr 27, 2025
@bartonjs
Copy link
Member

ICYMI:

  Discovering: Microsoft.Bcl.Cryptography.Tests (method display = ClassAndMethod, method display options = None)
  Discovered:  Microsoft.Bcl.Cryptography.Tests (found 360 of 481 test cases)
  Starting:    Microsoft.Bcl.Cryptography.Tests (parallel test collections = on [2 threads], stop on fail = off)
    System.Security.Cryptography.Tests.MLKemNotSupportedTests.ImportSubjectPublicKeyInfo_NotSupported [FAIL]
      Assert.Throws() Failure: Exception type was not an exact match
      Expected: typeof(System.PlatformNotSupportedException)
      Actual:   typeof(System.Security.Cryptography.CryptographicException)
      ---- System.Security.Cryptography.CryptographicException : ASN1 corrupted data.
      Stack Trace:
        /_/src/libraries/Common/tests/System/Security/Cryptography/MLKemNotSupportedTests.cs(35,0): at System.Security.Cryptography.Tests.MLKemNotSupportedTests.ImportSubjectPublicKeyInfo_NotSupported()
           at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnStack result)
           at System.RuntimeMethodHandle.InvokeMethod(ObjectHandleOnStack target, Void** arguments, ObjectHandleOnStack sig, BOOL isConstructor, ObjectHandleOnStack result)
        /_/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs(1159,0): at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
        /_/src/coreclr/System.Private.CoreLib/src/System/Reflection/MethodBaseInvoker.CoreCLR.cs(36,0): at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
        /_/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBaseInvoker.cs(57,0): at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
        ----- Inner Stack Trace -----
        /_/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs(1764,0): at System.Security.Cryptography.MLKem.ThrowIfTrailingData(ReadOnlySpan`1 data)
        /_/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs(1173,0): at System.Security.Cryptography.MLKem.ImportSubjectPublicKeyInfo(ReadOnlySpan`1 source)
        /_/src/libraries/Common/src/System/Security/Cryptography/MLKem.cs(1205,0): at System.Security.Cryptography.MLKem.ImportSubjectPublicKeyInfo(Byte[] source)
        /_/src/libraries/Common/tests/System/Security/Cryptography/MLKemNotSupportedTests.cs(36,0): at System.Security.Cryptography.Tests.MLKemNotSupportedTests.<>c.<ImportSubjectPublicKeyInfo_NotSupported>b__4_0()
    System.Security.Cryptography.Tests.AesGcmIsSupportedTests.CtorThrowsPNSEIfNotSupported [SKIP]
      Condition(s) not met: "RuntimeSaysIsNotSupported"
  Finished:    Microsoft.Bcl.Cryptography.Tests

@vcsjones
Copy link
Member Author

runtime-ci run is here: https://github.com/vcsjones/runtime-ci/actions/runs/14720877862/job/41314348123

Only commit since that green run was a merge commit.

@vcsjones vcsjones merged commit bf37cde into dotnet:main Apr 29, 2025
82 of 85 checks passed
@vcsjones vcsjones deleted the ml-kem-fix-asn-things branch April 29, 2025 09:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Wrong exception thrown by MLKem.ImportPkcs8PrivateKey for a too-small buffer
3 participants