Compare commits

...
3 Commits
Author SHA1 Message Date
Si Beaumont c2cbadd726 Merge commit from fork 2026-10-20 10:55:16 +02:00
deadcaf3 deb49b961e Bound the cost of RSA prime factor recovery (#484)
### Motivation:

`extractPrimeFactors` squares `t` times per attempt, where `t` is the
number of trailing zero bits of `e * d - 1`. Nothing bounds `e`, `d` or
`n`, so the caller picks the cost. A 2.5 KB `d` takes about 45 s before
throwing.

### Modifications:

- Reject `e >= n`, `d >= n`, and moduli over 8192 bits before factoring
- Throw once `g^(e * d - 1) != 1`, since then the numbers cannot form a
key
- Add tests for oversized and inconsistent numbers
- Keep the #482 attempt-limit test reaching the limit now that `e >= n`
is rejected

### Result:

These inputs now throw immediately. No public API change.

Valid keys aren't affected: they always have `e < n` and `d < n`, and
BoringSSL already rejects moduli over 8192 bits.

The oversized-number test fails on `main` and passes with this change.
The RSA tests pass on macOS.

Fixes #483
2026-10-20 09:38:39 +01:00
deadcaf3 0f6f68df04 Bound prime factor recovery in RSA _createFromNumbers (#482)
### Motivation:

`_createFromNumbers(n:e:d:)` can hang forever on some inputs. `e = 1, d
= 1` is enough to trigger it

`extractPrimeFactors` is meant to stop after 100 tries, but the
`continue` for a trivial base (`y` is `1` or `n - 1`) skipped the
counter. If every base is trivial, the loop never ends

### Modifications:

- Use `for _ in 0..<100` so every try counts
- Throw early when `e * d == 1`
- Add tests for both failing inputs

### Result:

These inputs now throw instead of hanging. No public API change.

The new tests hang on `main` and pass with this change. The full suite
passes on macOS and Linux.

Valid keys arent affected. Each try works at least half the time, so 100
failed tries wont happen in practice.

Fixes a hang in `_createFromNumbers(n:e:d:)`.

Fixes #481
2026-10-16 13:53:27 +00:00
5 changed files with 122 additions and 7 deletions

No files matched your search

@@ -35,6 +35,9 @@ extension P384 {
static var ciphersuite: Ciphersuite { Ciphersuite(H2G.self) }
/// The maximum length, in bytes, of an input, imposed by the two-byte length prefix in the RFC 9497 framing.
static let maximumInputByteCount = 0xFFFF
/// A P-384 public key used to blind inputs and finalize blinded elements.
public struct PublicKey {
fileprivate typealias BackingPublicKey = P384.Signing.PublicKey
@@ -367,6 +370,9 @@ extension P384._VOPRF {
@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, macCatalyst 16.0, visionOS 2.0, *)
extension P384._VOPRF.PublicKey {
internal func blind<D: DataProtocol>(_ input: D, with fixedBlind: P384._VOPRF.H2G.G.Scalar) throws -> P384._VOPRF.BlindedInput {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let input = Data(input)
let (blind, blindedElement) = Self.client.blindMessage(input, blind: fixedBlind)
return P384._VOPRF.BlindedInput(
@@ -436,6 +442,9 @@ extension P384._VOPRF.PrivateKey {
///
/// - Seealso: [RFC 9497: VOPRF Protocol - Evaluate]( https://cfrg.github.io/draft-irtf-cfrg-voprf/draft-irtf-cfrg-voprf.html#section-3.3.2-7).
public func evaluate<D: DataProtocol>(_ input: D) throws -> Data {
guard input.count <= P384._VOPRF.maximumInputByteCount else {
throw CryptoKitError.incorrectParameterSize
}
let inputElement = P384._VOPRF.H2G.hashToGroup(
Data(input),
domainSeparationString: Self.hashToGroupDST
+27 -7
View File
@@ -834,21 +834,37 @@ extension _RSA {
d: ArbitraryPrecisionInteger
) throws -> (p: ArbitraryPrecisionInteger, q: ArbitraryPrecisionInteger) {
// This is based on the proof of fact 1 in https://www.ams.org/notices/199902/boneh.pdf
let k = (d * e) - 1
let t = k.trailingZeroBitCount
let r = k >> t
guard k.isEven else {
// Valid keys have e < n, and BoringSSL rejects d >= n and moduli over its maximum. Larger
// values let the caller pick the cost of the exponentiations and squaring loop below.
guard n.byteCount <= _RSA.maximumModulusBitCount / 8, e < n, d < n else {
throw CryptoKitError.incorrectParameterSize
}
let k = (d * e) - 1
// k == 0 (that is, e * d == 1) gives r == 0 below, for which every base is trivial.
guard k > 0, k.isEven else {
throw CryptoKitError.incorrectParameterSize
}
let t = k.trailingZeroBitCount
let r = k >> t
var y: ArbitraryPrecisionInteger = 0
var i = 1
let context = try FiniteFieldArithmeticContext(fieldSize: n)
while i <= 100 {
// Every attempt must count towards the limit, including those where g^r is trivially
// 1 or n - 1. Inputs for which that holds for every base would otherwise never return.
for _ in 0..<100 {
let g = try ArbitraryPrecisionInteger.random(inclusiveMin: 2, exclusiveMax: n)
// The check at the end of this attempt only holds for bases coprime to n.
guard try ArbitraryPrecisionInteger.gcd(g, n) == 1 else {
continue
}
y = try context.pow(g, r)
guard y != 1, y != n - 1 else {
@@ -877,7 +893,11 @@ extension _RSA {
return (p, q)
}
i &+= 1
// Here x is g^k unless the loop stopped at n - 1. For a valid key g^k == 1 for every
// base coprime to n, so any other value means the numbers do not form a key.
guard x == n - 1 else {
throw CryptoKitError.incorrectParameterSize
}
}
throw CryptoKitError.incorrectParameterSize
@@ -1131,3 +1131,8 @@ enum BlindSigningHelpers {
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, macCatalyst 13, visionOS 1.0, *)
extension _RSA {
static let maximumModulusBitCount = Int(OPENSSL_RSA_MAX_MODULUS_BITS)
}
@@ -96,4 +96,21 @@ final class VOPRFPublicAPITests: XCTestCase {
XCTAssertThrowsError(try P384._VOPRF.BlindedElement(oprfRepresentation: uncompressed))
}
func testInputLongerThanRFC9497LimitThrows() throws {
let privateKey = P384._VOPRF.PrivateKey()
let publicKey = privateKey.publicKey
// RFC 9497 caps inputs at 2^16 - 1 bytes, the most the two-byte length prefix in the framing can encode.
let maximumInput = Data(repeating: 0x41, count: 0xFFFF)
let blindedInput = try publicKey.blind(maximumInput)
let blindEvaluation = try privateKey.evaluate(blindedInput.blindedElement)
XCTAssertNoThrow(try publicKey.finalize(blindedInput, using: blindEvaluation))
XCTAssertNoThrow(try privateKey.evaluate(maximumInput))
// Oversized inputs are rejected where they enter, so finalize can never be given one.
let oversizedInput = Data(repeating: 0x41, count: 0x1_0000)
XCTAssertThrowsError(try publicKey.blind(oversizedInput))
XCTAssertThrowsError(try privateKey.evaluate(oversizedInput))
}
}
@@ -1062,6 +1062,70 @@ final class TestRSASigning: XCTestCase {
}
}
func testConstructKeyFromRSANumbersWithDegenerateExponentsThrows() throws {
// e * d == 1 makes g^(e * d - 1) == 1 for every base, so prime recovery can never
// make progress. This must throw rather than retry forever.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
XCTAssertThrowsError(
try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.Encryption.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: [1] as [UInt8])
)
XCTAssertThrowsError(
try _RSA.BlindSigning.PrivateKey<SHA384>._createFromNumbers(
n: n, e: [1] as [UInt8], d: [1] as [UInt8], parameters: .RSABSSA_SHA384_PSS_Randomized
)
)
}
func testExtractPrimeFactorsGivesUpWhenEveryBaseIsTrivial() throws {
// n = 7 is prime and e * d - 1 == 24 == 2^3 * 3, so g^3 is 1 or n - 1 for every base g
// (the only cubic residues mod 7). The attempt limit must still apply.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 7, e: 5, d: 5))
// e * d == 1 gives an exponent of 0, so g^0 == 1 for every base.
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 1, d: 1))
}
func testExtractPrimeFactorsRejectsOversizedNumbers() throws {
// d == 2753 is valid for n == 3233, e == 17. Adding lambda(n) == 780 keeps the numbers
// consistent, so only the range check rejects d >= n.
XCTAssertNoThrow(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17, d: 2753 + 780))
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: 3233, e: 17 + 780 * 5, d: 2753))
// e * d - 1 == 2^9992, so without the range check the squaring loop runs 9991 times
// per attempt.
var n = [UInt8](repeating: 0xA7, count: 256)
n[255] = 0x01
var d = [UInt8](repeating: 0, count: 1250)
d[0] = 0x01
d[1249] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: n, e: [1] as [UInt8], d: d))
// A modulus over 8192 bits with d < n would otherwise make each attempt arbitrarily slow.
var bigN = [UInt8](repeating: 0xA7, count: 1025)
bigN[1024] = 0x01
var bigD = [UInt8](repeating: 0, count: 1025)
bigD[1] = 0x01
bigD[1024] = 0x01
XCTAssertThrowsError(try _RSA.Signing.PrivateKey._createFromNumbers(n: bigN, e: [1] as [UInt8], d: bigD))
}
func testExtractPrimeFactorsRejectsInconsistentNumbers() throws {
for testVector in RFC9474TestVector.allValues {
let n = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.n))
let e = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.e))
let d = try ArbitraryPrecisionInteger(bytes: Data(hexString: testVector.d))
// Using d = d + 2 means d is still even but no longer a multiple of lambda(n).
XCTAssertThrowsError(try _RSA.extractPrimeFactors(n: n, e: e, d: d + 2))
}
}
func testGetKeyPrimitives() throws {
for testVector in RFC9474TestVector.allValues {
let n = try Data(hexString: testVector.n)