From 8d6849435ff000a83882cabb3c9dac06e1fff2ed Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 20 Nov 2026 16:23:44 +0000 Subject: [PATCH] Correctly require no padding bits in bit strings for signatures (#329) Motivation We have a check that requires that the bit strings for Ed25519 signatures don't have any padding bits. That check is good, but the same check should have been applied to all the signatures, and it wasn't. There is no particular security risk with this: while it allows moderate signature malleability (as we accept multiple signatures that have different bits as equally valid), there is no way we can conceive of to launch an attack based on this malleability: the signature itself needs to remain valid. The only note is that the representation differs. Modifications Centralise the check and apply it to all the code paths. Make sure the OCSP code doesn't lose track of whether there was any padding. Add tests for the OCSP verifier and the signature code directly. Result No more signature malleability. --- Sources/X509/OCSP/OCSPPolicy.swift | 6 +- Sources/X509/Signature.swift | 25 ++- Tests/X509Tests/OCSPPolicyVerifierTests.swift | 78 +++++++ Tests/X509Tests/SignatureTests.swift | 205 ++++++++++++++++++ 4 files changed, 303 insertions(+), 11 deletions(-) diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 240e145..a5a1d6d 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -542,7 +542,7 @@ extension OCSPVerifierPolicy.Storage { let signatureValidationResult = self.validateSignature( certificate: leafCertificate, tbsResponse: basicResponse.responseDataBytes, - signatureBytes: basicResponse.signature.bytes, + signatureBytes: basicResponse.signature, signatureAlgorithmIdentifier: basicResponse.signatureAlgorithm ) @@ -580,7 +580,7 @@ extension OCSPVerifierPolicy.Storage { private func validateSignature( certificate: Certificate, tbsResponse: ArraySlice, - signatureBytes: ArraySlice, + signatureBytes: ASN1BitString, signatureAlgorithmIdentifier: AlgorithmIdentifier ) -> PolicyEvaluationResult { let signatureAlgorithm = Certificate.SignatureAlgorithm(algorithmIdentifier: signatureAlgorithmIdentifier) @@ -588,7 +588,7 @@ extension OCSPVerifierPolicy.Storage { do { signature = try Certificate.Signature( signatureAlgorithm: signatureAlgorithm, - signatureBytes: .init(bytes: signatureBytes) + signatureBytes: signatureBytes ) } catch { return .failsToMeetPolicy(reason: "could not create signature for OCSP response \(error)") diff --git a/Sources/X509/Signature.swift b/Sources/X509/Signature.swift index 4d9b495..4e88768 100644 --- a/Sources/X509/Signature.swift +++ b/Sources/X509/Signature.swift @@ -50,23 +50,32 @@ extension Certificate { public init(signatureAlgorithm: SignatureAlgorithm, signatureBytes: ASN1BitString) throws { switch signatureAlgorithm { case .ecdsaWithSHA256, .ecdsaWithSHA384, .ecdsaWithSHA512: - let signature = try ECDSASignature(derEncoded: signatureBytes.bytes) + let signature = try ECDSASignature(derEncoded: Self.octetAlignedBytes(signatureBytes)) self.backing = .ecdsa(signature) case .sha1WithRSAEncryption, .sha256WithRSAEncryption, .sha384WithRSAEncryption, .sha512WithRSAEncryption: - let signature = _RSA.Signing.RSASignature(rawRepresentation: signatureBytes.bytes) + let signature = _RSA.Signing.RSASignature(rawRepresentation: try Self.octetAlignedBytes(signatureBytes)) self.backing = .rsa(signature) case .ed25519: - guard signatureBytes.paddingBits == 0 else { - throw CertificateError.invalidSignatureForCertificate( - reason: "No padding bits are allowed on Ed25519 signatures" - ) - } - let signature = Data(signatureBytes.bytes) + let signature = Data(try Self.octetAlignedBytes(signatureBytes)) self.backing = .ed25519(signature) default: throw CertificateError.unsupportedSignatureAlgorithm(reason: "\(signatureAlgorithm)") } } + + /// Returns the bytes of a signature BIT STRING, rejecting it if it has any padding bits. + /// + /// All signature algorithms we support produce octet-aligned signatures, so padding bits are + /// never valid. Accepting them would allow multiple distinct encodings of the same signature. + @inlinable + static func octetAlignedBytes(_ signatureBytes: ASN1BitString) throws -> ArraySlice { + guard signatureBytes.paddingBits == 0 else { + throw CertificateError.invalidSignatureForCertificate( + reason: "Signature BIT STRING must not contain padding bits, found \(signatureBytes.paddingBits)" + ) + } + return signatureBytes.bytes + } } } diff --git a/Tests/X509Tests/OCSPPolicyVerifierTests.swift b/Tests/X509Tests/OCSPPolicyVerifierTests.swift index d6a6038..a1ecdcf 100644 --- a/Tests/X509Tests/OCSPPolicyVerifierTests.swift +++ b/Tests/X509Tests/OCSPPolicyVerifierTests.swift @@ -596,6 +596,84 @@ final class OCSPVerifierPolicyTests: XCTestCase { ) } + func testResponderSignatureWithPaddingBits() async { + // An ordinary, unpadded signature is accepted... + await self.assertChain( + soft: .meetsPolicy, + hard: .meetsPolicy, + chain: Self.chainWithSingleCertWithOCSP, + requester: TestRequester.noThrow { [validationTime] request, uri -> OCSPResponse in + try Self.goodResponse(for: request, uri: uri, now: validationTime, padSignature: false) + } + ) + + // ...but an otherwise identical response, whose signature BIT STRING claims that the final bit is + // padding, is not. + await self.assertChain( + soft: .meetsPolicy, + hard: .failsToMeetPolicy, + chain: Self.chainWithSingleCertWithOCSP, + requester: TestRequester.noThrow { [validationTime] request, uri -> OCSPResponse in + try Self.goodResponse(for: request, uri: uri, now: validationTime, padSignature: true) + } + ) + } + + /// Builds a response asserting that the certificate in `request` is good, signed by the intermediate. + /// + /// If `padSignature` is true, the signature BIT STRING claims that the final bit of the signature is padding. + private static func goodResponse( + for request: OCSPRequest, + uri: String, + now: Date, + padSignature: Bool + ) throws -> OCSPResponse { + XCTAssertEqual(uri, Self.responderURI) + XCTAssertNil(request.signature) + let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) + XCTAssertEqual(request.tbsRequest.requestList.count, 1) + let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) + + let responseData = OCSPResponseData( + version: .v1, + responderID: .byName(Self.intermediate1Name), + producedAt: .init(now), + responses: [ + OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .good, + thisUpdate: .init(now - .days(1)), + nextUpdate: .init(now + .days(1)) + ) + ], + responseExtensions: try .init { + nonce + } + ) + + let digest = SHA384.hash(data: try DER.Serializer.serialized(element: responseData)) + + // ECDSA signatures are randomised, so keep signing until the final byte has its lowest bit clear. Only then + // can the signature be encoded as a BIT STRING with a padding bit. We do this regardless of `padSignature`, + // so that both cases use the same kind of signature. + var signatureBytes: [UInt8]? = nil + for _ in 0..<64 { + let candidate = Array(try Self.intermediatePrivateKey.signature(for: digest).derRepresentation) + if let finalByte = candidate.last, finalByte & 0x01 == 0 { + signatureBytes = candidate + break + } + } + + let response = try BasicOCSPResponse( + responseData: responseData, + signatureAlgorithm: .ecdsaWithSHA384, + signature: .init(bytes: try XCTUnwrap(signatureBytes)[...], paddingBits: padSignature ? 1 : 0), + certs: [] + ) + return .successful(response) + } + func testResponseDoesNotIncludeResponseForRequestedCert() async { let now = self.validationTime await self.assertChain( diff --git a/Tests/X509Tests/SignatureTests.swift b/Tests/X509Tests/SignatureTests.swift index 52b5f0a..e13c6bd 100644 --- a/Tests/X509Tests/SignatureTests.swift +++ b/Tests/X509Tests/SignatureTests.swift @@ -1444,4 +1444,209 @@ final class SignatureTests: XCTestCase { ) ) } + + // MARK: Signature BIT STRING padding + + /// Every supported signature algorithm, paired with a key that can produce it. + private static var allSupportedSigningCombinations: [(Certificate.PrivateKey, Certificate.SignatureAlgorithm)] { + [ + (.init(Self.p256Key), .ecdsaWithSHA256), + (.init(Self.p384Key), .ecdsaWithSHA384), + (.init(Self.p521Key), .ecdsaWithSHA512), + (.init(Self.rsaKey), .sha1WithRSAEncryption), + (.init(Self.rsaKey), .sha256WithRSAEncryption), + (.init(Self.rsaKey), .sha384WithRSAEncryption), + (.init(Self.rsaKey), .sha512WithRSAEncryption), + (.init(Self.ed25519Key), .ed25519), + ] + } + + /// Repeatedly calls `make` until it produces a value whose signature has a final byte with its lowest bit clear. + /// + /// Only such a signature can be re-encoded as a BIT STRING with a padding bit, as DER requires padding bits to be + /// zero. `make` is passed the attempt number so that it can vary its input: this ensures that deterministic + /// signature schemes (RSA PKCS#1 v1.5, Ed25519) also produce a fresh signature on each attempt. Each attempt has + /// roughly a 50% chance of success. + private static func withEvenFinalSignatureByte( + _ make: (Int) throws -> T, + signature: (T) -> Certificate.Signature + ) rethrows -> T? { + for attempt in 0..<64 { + let value = try make(attempt) + if let finalByte = signature(value).rawRepresentation.last, finalByte & 0x01 == 0 { + return value + } + } + return nil + } + + /// Returns `der` with the unused-bits octet of its trailing signature BIT STRING set to `paddingBits`. + /// + /// Certificates and CSRs both end with the signature BIT STRING, so its unused-bits octet sits immediately + /// before the final `signatureLength` bytes. + private static func settingSignaturePaddingBits( + _ paddingBits: UInt8, + in der: [UInt8], + signatureLength: Int, + file: StaticString = #filePath, + line: UInt = #line + ) -> [UInt8] { + var der = der + let paddingOctetIndex = der.endIndex - signatureLength - 1 + XCTAssertEqual(der[paddingOctetIndex], 0x00, "expected an unpadded signature", file: file, line: line) + der[paddingOctetIndex] = paddingBits + return der + } + + func testSignatureRejectsPaddingBits() throws { + let input = Array("Hello World".utf8) + + for (privateKey, signatureAlgorithm) in Self.allSupportedSigningCombinations { + var signatureBytes = try privateKey.sign(bytes: input, signatureAlgorithm: signatureAlgorithm) + .rawRepresentation + // Clear the low 7 bits of the final byte, so these bytes form a valid BIT STRING with any + // number of padding bits. This invalidates the signature, but parsing doesn't check that. + signatureBytes[signatureBytes.endIndex - 1] &= 0x80 + + XCTAssertNoThrow( + try Certificate.Signature( + signatureAlgorithm: signatureAlgorithm, + signatureBytes: ASN1BitString(bytes: signatureBytes[...], paddingBits: 0) + ), + "\(signatureAlgorithm) with no padding bits" + ) + + for paddingBits in 1..<8 { + XCTAssertThrowsError( + try Certificate.Signature( + signatureAlgorithm: signatureAlgorithm, + signatureBytes: ASN1BitString(bytes: signatureBytes[...], paddingBits: paddingBits) + ), + "\(signatureAlgorithm) with \(paddingBits) padding bits" + ) { error in + XCTAssertEqual( + (error as? CertificateError)?.code, + .invalidSignatureForCertificate, + "wrong error \(error)" + ) + } + } + } + } + + func testUnsupportedSignatureAlgorithmWithPaddingBitsIsReportedAsUnsupported() throws { + let unsupportedAlgorithm = Certificate.SignatureAlgorithm( + algorithmIdentifier: AlgorithmIdentifier(algorithm: [1, 2, 3, 4], parameters: nil) + ) + + XCTAssertThrowsError( + try Certificate.Signature( + signatureAlgorithm: unsupportedAlgorithm, + signatureBytes: ASN1BitString(bytes: [0x00], paddingBits: 1) + ) + ) { error in + XCTAssertEqual( + (error as? CertificateError)?.code, + .unsupportedSignatureAlgorithm, + "wrong error \(error)" + ) + } + } + + func testCertificateWithPaddedSignatureIsRejected() throws { + let name = try DistinguishedName { + CommonName("Signature padding test") + } + + for (privateKey, signatureAlgorithm) in Self.allSupportedSigningCombinations { + let certificate = try XCTUnwrap( + Self.withEvenFinalSignatureByte( + { _ in + // The serial number is random, so every attempt has a fresh signature. + try Certificate( + version: .v3, + serialNumber: .init(), + publicKey: privateKey.publicKey, + notValidBefore: Self.now, + notValidAfter: Self.oneYearFromNow, + issuer: name, + subject: name, + signatureAlgorithm: signatureAlgorithm, + extensions: Certificate.Extensions(), + issuerPrivateKey: privateKey + ) + }, + signature: \.signature + ), + "Unable to produce a suitable \(signatureAlgorithm) certificate" + ) + let der = try DER.Serializer.serialized(element: certificate) + + // The unmodified certificate parses and has a valid signature. + let parsed = try Certificate(derEncoded: der) + XCTAssertTrue( + privateKey.publicKey.isValidSignature(parsed.signature, for: parsed), + "\(signatureAlgorithm)" + ) + + // Marking the final (zero) bit of the signature as padding is still valid DER and leaves the signature + // bytes unchanged, but must be rejected. + let padded = Self.settingSignaturePaddingBits( + 1, + in: der, + signatureLength: certificate.signature.rawRepresentation.count + ) + XCTAssertThrowsError(try Certificate(derEncoded: padded), "\(signatureAlgorithm)") { error in + XCTAssertEqual( + (error as? CertificateError)?.code, + .invalidSignatureForCertificate, + "wrong error \(error)" + ) + } + } + } + + func testCSRWithPaddedSignatureIsRejected() throws { + for (privateKey, signatureAlgorithm) in Self.allSupportedSigningCombinations { + let csr = try XCTUnwrap( + Self.withEvenFinalSignatureByte( + { attempt in + try CertificateSigningRequest( + version: .v1, + subject: DistinguishedName { + CommonName("Signature padding test \(attempt)") + }, + privateKey: privateKey, + attributes: CertificateSigningRequest.Attributes(), + signatureAlgorithm: signatureAlgorithm + ) + }, + signature: \.signature + ), + "Unable to produce a suitable \(signatureAlgorithm) CSR" + ) + let der = try DER.Serializer.serialized(element: csr) + + // The unmodified CSR parses and has a valid signature. + let parsed = try CertificateSigningRequest(derEncoded: der) + XCTAssertTrue( + privateKey.publicKey.isValidSignature(parsed.signature, for: parsed), + "\(signatureAlgorithm)" + ) + + let padded = Self.settingSignaturePaddingBits( + 1, + in: der, + signatureLength: csr.signature.rawRepresentation.count + ) + XCTAssertThrowsError(try CertificateSigningRequest(derEncoded: padded), "\(signatureAlgorithm)") { + error in + XCTAssertEqual( + (error as? CertificateError)?.code, + .invalidSignatureForCertificate, + "wrong error \(error)" + ) + } + } + } }