TimedCertificateReloader prevents non-self-signed certificates from b… (#274)

…eing loaded

Fix certificate check and make sure all code paths throw an error.

### Motivation:

TimedCertificateReloader currently has an invalid check that
accidecanlly enforces self-signed certificates. Additionally some code
paths of `reload()` did not throw an error which made it hard for the
call site to judge if the reloader was initialized successfully or not.
Further, the missing errors also meant that the `run()` method would
never be able to log these.

### Modifications:

* Updated the certificate check to validate the the public key of the
private key matches the cert's public key (instead of checking the
signature).
* Added three new error cases.

### Result:

* A caller can now be sure that their certificate and private key pair
are valid after calling `reload()` the first time.
* Errors in future reloads will be surfaced using the provided logger
and do not go unnoticed.
* You can actually use the reloader with normal certificates.
This commit is contained in:
Franz Busch authored and GitHub committed 2025-05-30 12:31:14 +00:00
1 parent 24cb15c9bc
commit 145db1962f
2 files changed
+207 -79

No files matched your search

@@ -210,6 +210,9 @@ public struct TimedCertificateReloader: CertificateReloader {
private enum _Backing: Hashable, CustomStringConvertible {
case certificatePathNotFound(String)
case privateKeyPathNotFound(String)
case certificateLoadingError(reason: String)
case privateKeyLoadingError(reason: String)
case publicKeyMismatch
var description: String {
switch self {
@@ -217,6 +220,16 @@ public struct TimedCertificateReloader: CertificateReloader {
return "Certificate path not found: \(path)"
case .privateKeyPathNotFound(let path):
return "Private key path not found: \(path)"
case let .certificateLoadingError(reason):
return "Failed to load certificate: \(reason)"
case let .privateKeyLoadingError(reason):
return "Failed to load private key: \(reason)"
case .publicKeyMismatch:
return
"""
The public key derived from the private key does not match the public key in the certificate. \n
This may occur if the certificate and key were reloaded inconsistently or during an update in progress.
"""
}
}
}
@@ -241,6 +254,25 @@ public struct TimedCertificateReloader: CertificateReloader {
Self(.privateKeyPathNotFound(path))
}
/// Failed to load the certificate.
/// - Parameter reason: A description of the error occurred.
/// - Returns: A ``TimedCertificateReloader/Error``.
public static func certificateLoadingError(reason: String) -> Self {
Self(.certificateLoadingError(reason: reason))
}
/// Failed to load the private key.
/// - Parameter reason: A description of the error occurred.
/// - Returns: A ``TimedCertificateReloader/Error``.
public static func privateKeyLoadingError(reason: String) -> Self {
Self(.privateKeyLoadingError(reason: reason))
}
/// The private key does not match the provided certificate.
public static var publicKeyMismatch: Self {
Self(.publicKeyMismatch)
}
public var description: String {
self._backing.description
}
@@ -350,13 +382,19 @@ public struct TimedCertificateReloader: CertificateReloader {
public func reload() throws {
let certificateBytes = try self.loadCertificate()
let keyBytes = try self.loadPrivateKey()
if let certificates = try self.parseCertificates(from: certificateBytes),
let key = try self.parsePrivateKey(from: keyBytes),
let firstCertificate = certificates.first,
key.publicKey.isValidSignature(firstCertificate.signature, for: firstCertificate)
{
try self.attemptToUpdatePair(certificates: certificates, key: key)
let certificates = try self.parseCertificates(from: certificateBytes)
let key = try self.parsePrivateKey(from: keyBytes)
guard let firstCertificate = certificates.first else {
throw Error.certificateLoadingError(reason: "The provided file does not contain any certificates.")
}
guard key.publicKey == firstCertificate.publicKey else {
throw Error.publicKeyMismatch
}
try self.attemptToUpdatePair(certificates: certificates, key: key)
}
private func loadCertificate() throws -> [UInt8] {
@@ -389,28 +427,34 @@ public struct TimedCertificateReloader: CertificateReloader {
return keyBytes
}
private func parseCertificates(from certificateBytes: [UInt8]) throws -> [Certificate]? {
let certificates: [Certificate]?
private func parseCertificates(from certificateBytes: [UInt8]) throws -> [Certificate] {
let certificates: [Certificate]
switch self.certificateSource.format._backing {
case .der:
certificates = [try Certificate(derEncoded: certificateBytes)]
case .pem:
certificates = try String(bytes: certificateBytes, encoding: .utf8)
.flatMap { try PEMDocument.parseMultiple(pemString: $0).map { try Certificate(pemDocument: $0) } }
guard let pemString = String(bytes: certificateBytes, encoding: .utf8) else {
throw Error.certificateLoadingError(reason: "Certificate data is not valid UTF-8.")
}
certificates = try PEMDocument.parseMultiple(pemString: pemString)
.map { try Certificate(pemDocument: $0) }
}
return certificates
}
private func parsePrivateKey(from keyBytes: [UInt8]) throws -> Certificate.PrivateKey? {
let key: Certificate.PrivateKey?
private func parsePrivateKey(from keyBytes: [UInt8]) throws -> Certificate.PrivateKey {
let key: Certificate.PrivateKey
switch self.privateKeySource.format._backing {
case .der:
key = try Certificate.PrivateKey(derBytes: keyBytes)
case .pem:
key = try String(bytes: keyBytes, encoding: .utf8)
.flatMap { try Certificate.PrivateKey(pemEncoded: $0) }
guard let pemString = String(bytes: keyBytes, encoding: .utf8) else {
throw Error.privateKeyLoadingError(reason: "Private Key data is not valid UTF-8.")
}
key = try Certificate.PrivateKey(pemEncoded: pemString)
}
return key
}
@@ -61,6 +61,24 @@ final class TimedCertificateReloaderTests: XCTestCase {
}
}
func testNonSelfSignedCert() async throws {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCertNotSelfSigned.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
),
validateSources: true
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNotNil(override.certificateChain)
XCTAssertNotNil(override.privateKey)
}
}
func testKeyPathDoesNotExist() async throws {
try await runTimedCertificateReloaderTest(
certificate: .init(
@@ -102,19 +120,23 @@ final class TimedCertificateReloaderTests: XCTestCase {
}
func testCertificateIsInUnexpectedFormat_FromMemory() async throws {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .pem
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
)
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNil(override.certificateChain)
XCTAssertNil(override.privateKey)
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .pem
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .certificateLoadingError(reason: "Certificate data is not valid UTF-8."))
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
@@ -131,72 +153,111 @@ final class TimedCertificateReloaderTests: XCTestCase {
func testCertificateIsInUnexpectedFormat_FromFile() async throws {
let certBytes = try Self.sampleCert.serializeAsPEM().derBytes
let file = try self.createTempFile(contents: Data(certBytes))
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .file(path: file.path),
format: .pem
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
)
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNil(override.certificateChain)
XCTAssertNil(override.privateKey)
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .file(path: file.path),
format: .pem
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .certificateLoadingError(reason: "Certificate data is not valid UTF-8."))
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
func testKeyIsInUnexpectedFormat_FromMemory() async throws {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .pem
)
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNil(override.certificateChain)
XCTAssertNil(override.privateKey)
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .pem
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .privateKeyLoadingError(reason: "Private Key data is not valid UTF-8."))
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
func testKeyIsInUnexpectedFormat_FromFile() async throws {
let keyBytes = Self.samplePrivateKey1.derRepresentation
let file = try self.createTempFile(contents: keyBytes)
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .file(path: file.path),
format: .pem
)
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNil(override.certificateChain)
XCTAssertNil(override.privateKey)
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .file(path: file.path),
format: .pem
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .privateKeyLoadingError(reason: "Private Key data is not valid UTF-8."))
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
func testCertificateAndKeyDoNotMatch() async throws {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .memory(provider: { Array(P384.Signing.PrivateKey().derRepresentation) }),
format: .der
)
) { reloader in
let override = reloader.sslContextConfigurationOverride
XCTAssertNil(override.certificateChain)
XCTAssertNil(override.privateKey)
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { try Self.sampleCert.serializeAsPEM().derBytes }),
format: .der
),
privateKey: .init(
location: .memory(provider: { Array(P384.Signing.PrivateKey().derRepresentation) }),
format: .der
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .publicKeyMismatch)
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
func testEmptyCertificateChain() async throws {
do {
try await runTimedCertificateReloaderTest(
certificate: .init(
location: .memory(provider: { [] }),
format: .pem
),
privateKey: .init(
location: .memory(provider: { Array(Self.samplePrivateKey1.derRepresentation) }),
format: .der
)
) { reloader in
XCTFail("Certificate reloader loaded correctly.")
}
} catch let error as TimedCertificateReloader.Error {
XCTAssert(error == .certificateLoadingError(reason: "The provided file does not contain any certificates."))
} catch {
XCTFail("Encountered unexpected error \(error)")
}
}
@@ -563,6 +624,11 @@ final class TimedCertificateReloaderTests: XCTestCase {
OrganizationName("Apple")
CommonName("Swift Certificate Test")
}
static let issuerCertName = try! DistinguishedName {
CountryName("US")
OrganizationName("Apple")
CommonName("Swift Certificate Test Issuer")
}
static let sampleCert: Certificate = {
try! Certificate(
version: .v3,
@@ -581,6 +647,24 @@ final class TimedCertificateReloaderTests: XCTestCase {
issuerPrivateKey: .init(samplePrivateKey1)
)
}()
static let sampleCertNotSelfSigned: Certificate = {
try! Certificate(
version: .v3,
serialNumber: .init(),
publicKey: .init(samplePrivateKey1.publicKey),
notValidBefore: startDate.advanced(by: -60 * 60 * 24 * 360),
notValidAfter: startDate.advanced(by: 60 * 60 * 24 * 360),
issuer: issuerCertName,
subject: sampleCertName,
signatureAlgorithm: .ecdsaWithSHA384,
extensions: Certificate.Extensions {
Critical(
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
},
issuerPrivateKey: .init(samplePrivateKey2)
)
}()
static let sampleCertChain: [Certificate] = {
[
try! Certificate(