From bb4ba815dab96d4edc1e0b86d7b9acf9ff973a84 Mon Sep 17 00:00:00 2001 From: Raphael Date: Wed, 1 Apr 2026 10:08:47 +0100 Subject: [PATCH] Merge commit from fork * Reproduce memory-safty issue in HPKE decapsulation * Validate ciphertext len before calling decapsulate --- .../Crypto/KEM/BoringSSL/XWing_boring.swift | 6 +++- Tests/CryptoTests/KEM/XWingTests.swift | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift b/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift index c9315c77..8944de77 100644 --- a/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift +++ b/Sources/Crypto/KEM/BoringSSL/XWing_boring.swift @@ -236,7 +236,11 @@ extension OpenSSLXWingPrivateKeyImpl { } func decapsulate(_ encapsulated: Data) throws -> SymmetricKey { - try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in + guard encapsulated.count == Int(XWING_CIPHERTEXT_BYTES) else { + throw CryptoKitError.incorrectParameterSize + } + + return try SymmetricKey(unsafeUninitializedCapacity: Int(XWING_SHARED_SECRET_BYTES)) { sharedSecretBytes, count in try encapsulated.withUnsafeBytes { encapsulatedSecretBytes in let rc = CCryptoBoringSSL_XWING_decap( sharedSecretBytes.baseAddress, diff --git a/Tests/CryptoTests/KEM/XWingTests.swift b/Tests/CryptoTests/KEM/XWingTests.swift index 22e5e19b..e55c8c39 100644 --- a/Tests/CryptoTests/KEM/XWingTests.swift +++ b/Tests/CryptoTests/KEM/XWingTests.swift @@ -84,6 +84,39 @@ final class XWingTests: XCTestCase { let importedKey = try XWingMLKEM768X25519.PrivateKey.init(integrityCheckedRepresentation: exportedFormat) XCTAssertEqual(importedKey.seedRepresentation, privateKey.seedRepresentation) } + + func testDecapsulateInputValidation() throws { + let ciphersuite = HPKE.Ciphersuite.XWingMLKEM768X25519_SHA256_AES_GCM_256 + let skR = try XWingMLKEM768X25519.PrivateKey.generate() + + // Dummy key with the correct size fails with an error from the underlying implementation. + let corretlySizedKey = Data(repeating: 0x00, count: 1120) + XCTAssertThrowsError( + try HPKE.Recipient( + privateKey: skR, + ciphersuite: ciphersuite, + info: Data(), + encapsulatedKey: corretlySizedKey + ), + error: CryptoKitError.underlyingCoreCryptoError(error: 0) + ) + + // Keys with the wrong size fail input validation. + let keySizesToTest = [0, 1, 1119, 1221, 2000] + for keySize in keySizesToTest { + let wronglySizedKey = Data(repeating: 0x00, count: keySize) + XCTAssertThrowsError( + try HPKE.Recipient( + privateKey: skR, + ciphersuite: ciphersuite, + info: Data(), + encapsulatedKey: wronglySizedKey + ), + error: CryptoKitError.incorrectParameterSize, + "Unexpectedly returned from malformed decapsulation path for keySize \(keySize)" + ) + } + } } // Struct to parse KAT file