Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
feat(signing): create the local signing identity so Steam keeps controller access across updates
raymondchinsa0c99d762fa2
diff --git a/app/Sources/NotProtonApp/Model/LocalSigning.swift b/app/Sources/NotProtonApp/Model/LocalSigning.swiftnew file mode 100644index 0000000..46acea4--- /dev/null+++ b/app/Sources/NotProtonApp/Model/LocalSigning.swift@@ -0,0 +1,124 @@+import Foundation++// Creates the self-signed code signing identity that SteamInstaller signs Steam with, so+// Steam's designated requirement (and with it the Input Monitoring approval macOS keys to+// it) stays the same across Bridgeplay updates. Without it Steam is signed ad hoc, the+// requirement is the cdhash, and every update makes macOS forget the controller approval.+//+// Design, checked on macOS 27 with a throwaway keychain:+// - The key and certificate come from /usr/bin/openssl (LibreSSL 3.3.6 accepts -addext)+// and go in through `security import -T /usr/bin/codesign`. The key's access list then+// names codesign, so signing never shows a keychain prompt. A key made with+// SecKeyCreateRandomKey inside this app would instead belong to this app's own+// signature, which changes with every ad hoc Bridgeplay build, and codesign would ask.+// - Nothing calls `security set-key-partition-list`: it needs the keychain password, and+// the import above already leaves codesign able to use the key without asking.+// - The certificate is NOT marked trusted (`security add-trusted-cert`). codesign signs+// with an untrusted identity just as well; the designated requirement is then+// `certificate leaf = H"<sha1>"`, which is what the owner's existing identity produces.+// Trusting it would cost a password prompt and could change that requirement's form+// (leaf to root), which would make macOS drop the approval once more.+// - The name stays "NotProton Local Signing": existing installs look it up by that name.+enum LocalSigning {++ static let name = SteamInstaller.localSigningIdentity+ static let step = String(localized: "Trust Bridgeplay on this Mac")++ typealias Runner = @Sendable (String, [String]) throws -> CommandResult++ static let realRunner: Runner = { try Shell.run($0, $1) }++ static var loginKeychain: URL {+ SupportPaths.home.appending(path: "Library/Keychains/login.keychain-db")+ }++ enum Outcome: Equatable, Sendable {+ case alreadyPresent(hash: String)+ case created(hash: String)+ }++ // `security find-identity -p codesigning` without -v, so an untrusted identity, which+ // is what this creates, still counts. Each line reads ` 1) <SHA-1> "<name>" (...)`.+ static func identityHash(in output: String, named wanted: String = name) -> String? {+ for line in output.split(separator: "\n") where line.contains("\"\(wanted)\"") {+ let fields = line.split(separator: " ")+ if let hash = fields.first(where: { $0.count == 40 && $0.allSatisfy(\.isHexDigit) }) {+ return String(hash)+ }+ }+ return nil+ }++ // Looks in the given keychains, or in the user's search list when none are given.+ static func existingHash(in keychains: [URL] = [], run: Runner = realRunner) -> String? {+ let arguments = ["find-identity", "-p", "codesigning"] + keychains.map { $0.path(percentEncoded: false) }+ guard let result = try? run("/usr/bin/security", arguments), result.succeeded else { return nil }+ return identityHash(in: result.stdout)+ }++ struct Command: Equatable, Sendable {+ let executable: String+ let arguments: [String]+ }++ // The commands that make the identity, in order. The key only ever exists in `work`,+ // which ensure() creates private to this user and removes afterwards.+ static func creationCommands(work: URL, keychain: URL, transportPassword: String) -> [Command] {+ let key = work.appending(path: "key.pem").path(percentEncoded: false)+ let cert = work.appending(path: "cert.pem").path(percentEncoded: false)+ let bundle = work.appending(path: "identity.p12").path(percentEncoded: false)+ return [+ Command(executable: "/usr/bin/openssl", arguments: [+ "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-sha256", "-days", "7300",+ "-subj", "/CN=\(name)",+ "-addext", "extendedKeyUsage=critical,codeSigning",+ "-addext", "keyUsage=critical,digitalSignature",+ "-addext", "basicConstraints=critical,CA:false",+ "-keyout", key, "-out", cert,+ ]),+ // security import refuses a PKCS#12 with an empty password, so the bundle gets a+ // random one that lives only as long as the file.+ Command(executable: "/usr/bin/openssl", arguments: [+ "pkcs12", "-export", "-inkey", key, "-in", cert, "-name", name,+ "-out", bundle, "-passout", "pass:\(transportPassword)",+ ]),+ Command(executable: "/usr/bin/security", arguments: [+ "import", bundle, "-k", keychain.path(percentEncoded: false), "-f", "pkcs12",+ "-P", transportPassword, "-T", "/usr/bin/codesign",+ ]),+ ]+ }++ // Creates the identity unless one with this name is already there. Never asks for a+ // password, except macOS's own prompt to unlock a locked login keychain.+ static func ensure(+ keychain: URL = loginKeychain,+ lookIn: [URL] = [],+ run: Runner = realRunner,+ temporaryRoot: URL = FileManager.default.temporaryDirectory+ ) throws -> Outcome {+ if let hash = existingHash(in: lookIn, run: run) {+ return .alreadyPresent(hash: hash)+ }+ let files = FileManager.default+ let work = temporaryRoot.appending(path: "bridgeplay-signing-\(UUID().uuidString)", directoryHint: .isDirectory)+ try files.createDirectory(at: work, withIntermediateDirectories: true,+ attributes: [.posixPermissions: 0o700])+ defer { try? files.removeItem(at: work) }++ let password = UUID().uuidString+ for command in creationCommands(work: work, keychain: keychain, transportPassword: password) {+ let result = try run(command.executable, command.arguments)+ guard result.succeeded else {+ let tool = (command.executable as NSString).lastPathComponent+ AppLog.note("signing: \(tool) \(command.arguments.first ?? "") failed: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")+ throw StepFailure(step: step, detail: String(localized: "macOS did not add the certificate to your keychain."))+ }+ }+ guard let hash = existingHash(in: lookIn, run: run) else {+ throw StepFailure(step: step, detail: String(localized: "The certificate was added, but macOS does not offer it for signing."))+ }+ AppLog.note("signing: created \(name) \(hash)")+ return .created(hash: hash)+ }+}diff --git a/app/Sources/NotProtonApp/Model/SteamInstaller.swift b/app/Sources/NotProtonApp/Model/SteamInstaller.swiftindex c681b9d..13f2383 100644--- a/app/Sources/NotProtonApp/Model/SteamInstaller.swift+++ b/app/Sources/NotProtonApp/Model/SteamInstaller.swift@@ -39,6 +39,8 @@ struct InstallOutcome: Sendable {let signatureDatabases: Intlet backedUpPlist: Boollet bridgeStaged: Int+ // Input access services macOS refused to reset after Steam's signature changed.+ var failedInputResets: [String] = []}enum SteamInstaller {@@ -76,7 +78,7 @@ enum SteamInstaller {},stopClient: ClientStopper = stopTheClient,register: BundleRegistrar = { SteamBundle.register($0) },- resetInputAccess: () -> Void = resetInputAccess,+ resetInputAccess: () -> [String] = resetInputAccess,report: @escaping @Sendable (InstallPhase) -> Void = { _ in }) throws -> InstallOutcome {report(.checkingPayload)@@ -160,6 +162,7 @@ enum SteamInstaller {try removeStaleFonts(in: fonts, keeping: payload.fonts)var backedUp = false+ var failedInputResets: [String] = []if patching {report(.settingInsert)backedUp = try backUpPlist(plist, into: backups)@@ -182,7 +185,7 @@ enum SteamInstaller {// cdhash, which every new dylib changes; signed with the local identity it is the// certificate, so the approval survives updates and is only cleared on a change.if designatedRequirement(of: app) != priorRequirement {- resetInputAccess()+ failedInputResets = resetInputAccess()}}@@ -210,7 +213,8 @@ enum SteamInstaller {build: build,signatureDatabases: payload.signatures.count,backedUpPlist: backedUp,- bridgeStaged: bridgeResult.staged.count+ bridgeStaged: bridgeResult.staged.count,+ failedInputResets: failedInputResets)}@@ -378,16 +382,9 @@ enum SteamInstaller {// Input Monitoring approval, the same across Bridgeplay updates.static let localSigningIdentity = "NotProton Local Signing"+ // LocalSigning creates it from the Setup Assistant or the Status page.static func signingIdentity() -> String {- guard let result = try? Shell.run("/usr/bin/security", ["find-identity", "-p", "codesigning"]),- result.succeeded else { return "-" }- for line in result.stdout.split(separator: "\n") where line.contains("\"\(localSigningIdentity)\"") {- let fields = line.split(separator: " ")- if let hash = fields.first(where: { $0.count == 40 && $0.allSatisfy(\.isHexDigit) }) {- return String(hash)- }- }- return "-"+ LocalSigning.existingHash() ?? "-"}static func sign(_ url: URL, identity: String, step: String = step) throws {@@ -446,10 +443,13 @@ enum SteamInstaller {// or Steam Input will silently not work.static let inputAccessServices = ["Accessibility", "PostEvent", "ListenEvent"]- static func resetInputAccess() {- for service in failedInputAccessResets() {+ // Returns what macOS refused to reset, so the Status page can say so.+ static func resetInputAccess() -> [String] {+ let failed = failedInputAccessResets()+ for service in failed {AppLog.note("install: could not reset \(service) for Steam")}+ return failed}static func failedInputAccessResets() -> [String] {diff --git a/app/Tests/NotProtonAppTests/LocalSigningTests.swift b/app/Tests/NotProtonAppTests/LocalSigningTests.swiftnew file mode 100644index 0000000..52d990b--- /dev/null+++ b/app/Tests/NotProtonAppTests/LocalSigningTests.swift@@ -0,0 +1,142 @@+import Foundation+import Testing++@testable import NotProtonApp++@Suite("Local signing identity")+struct LocalSigningTests {++ // What `security find-identity -p codesigning` printed on a Mac carrying the identity,+ // untrusted, next to another one.+ private static let listing = """++ Policy: Code Signing+ Matching identities+ 1) 1111111111111111111111111111111111111111 "Apple Development: [email protected] (ABCDE12345)"+ 2) E9B6B93497770DB40F9E30E511810EC68B9D4D93 "NotProton Local Signing" (CSSMERR_TP_NOT_TRUSTED)+ 2 identities found++ Valid identities only+ 1) 1111111111111111111111111111111111111111 "Apple Development: [email protected] (ABCDE12345)"+ 1 valid identities found+ """++ // Records every command and answers find-identity from a script of listings.+ private final class FakeSecurity: @unchecked Sendable {+ private let lock = NSLock()+ private var listings: [String]+ private(set) var commands: [[String]] = []+ var failing: String?++ init(listings: [String]) { self.listings = listings }++ var runner: LocalSigning.Runner {+ { executable, arguments in+ self.lock.lock(); defer { self.lock.unlock() }+ self.commands.append([executable] + arguments)+ if arguments.first == "find-identity" {+ let next = self.listings.count > 1 ? self.listings.removeFirst() : (self.listings.first ?? "")+ return CommandResult(status: 0, stdout: next, stderr: "")+ }+ if let failing = self.failing, arguments.first == failing {+ return CommandResult(status: 1, stdout: "", stderr: "refused")+ }+ return CommandResult(status: 0, stdout: "", stderr: "")+ }+ }++ var created: [[String]] { commands.filter { $0[1] != "find-identity" } }+ }++ @Test("The identity is found by name even when macOS does not trust it")+ func findsUntrustedIdentity() {+ #expect(LocalSigning.identityHash(in: Self.listing) == "E9B6B93497770DB40F9E30E511810EC68B9D4D93")+ #expect(LocalSigning.identityHash(in: Self.listing, named: "Someone Else") == nil)+ #expect(LocalSigning.identityHash(in: "\n 0 valid identities found\n") == nil)+ }++ @Test("The installer keeps signing with the same name")+ func keepsTheExistingName() {+ #expect(LocalSigning.name == "NotProton Local Signing")+ #expect(SteamInstaller.localSigningIdentity == LocalSigning.name)+ }++ @Test("An existing identity is kept and nothing is created")+ func idempotent() throws {+ let fake = FakeSecurity(listings: [Self.listing])+ let outcome = try LocalSigning.ensure(run: fake.runner)+ #expect(outcome == .alreadyPresent(hash: "E9B6B93497770DB40F9E30E511810EC68B9D4D93"))+ #expect(fake.created.isEmpty)+ #expect(fake.commands == [["/usr/bin/security", "find-identity", "-p", "codesigning"]])+ }++ @Test("A missing identity is made with openssl and imported for codesign only")+ func createsWhenMissing() throws {+ let temporary = FileManager.default.temporaryDirectory.appending(path: "signing-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ let keychain = URL(filePath: "/tmp/test.keychain-db")+ let fake = FakeSecurity(listings: [" 0 identities found\n", Self.listing])++ let outcome = try LocalSigning.ensure(keychain: keychain, run: fake.runner, temporaryRoot: temporary)++ #expect(outcome == .created(hash: "E9B6B93497770DB40F9E30E511810EC68B9D4D93"))+ let created = fake.created+ #expect(created.map { $0[0] } == ["/usr/bin/openssl", "/usr/bin/openssl", "/usr/bin/security"])+ let request = created[0]+ #expect(request.contains("/CN=NotProton Local Signing"))+ #expect(request.contains("extendedKeyUsage=critical,codeSigning"))+ let importing = created[2]+ #expect(importing[1] == "import")+ #expect(importing.contains(keychain.path(percentEncoded: false)))+ #expect(importing.firstIndex(of: "-T").map { importing[$0 + 1] } == "/usr/bin/codesign")+ // Neither asks for a password: no trust settings change, no partition list.+ #expect(!fake.commands.joined().contains("add-trusted-cert"))+ #expect(!fake.commands.joined().contains("set-key-partition-list"))+ // The private key never outlives the call.+ #expect(try FileManager.default.contentsOfDirectory(atPath: temporary.path(percentEncoded: false)).isEmpty)+ }++ @Test("The PKCS#12 password matches between export and import")+ func transportPasswordMatches() {+ let commands = LocalSigning.creationCommands(work: URL(filePath: "/w"), keychain: URL(filePath: "/k"), transportPassword: "secret")+ #expect(commands[1].arguments.contains("pass:secret"))+ #expect(commands[2].arguments.firstIndex(of: "-P").map { commands[2].arguments[$0 + 1] } == "secret")+ }++ @Test("A refused import is reported and leaves no key behind")+ func refusedImport() throws {+ let temporary = FileManager.default.temporaryDirectory.appending(path: "signing-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ let fake = FakeSecurity(listings: [""])+ fake.failing = "import"++ #expect(throws: StepFailure.self) { try LocalSigning.ensure(run: fake.runner, temporaryRoot: temporary) }+ #expect(try FileManager.default.contentsOfDirectory(atPath: temporary.path(percentEncoded: false)).isEmpty)+ }++ // Uses the real tools against a throwaway keychain file (not added to the search list)+ // and signs a copy of /bin/echo with the result: proves the identity is usable by+ // codesign without a prompt. Off by default because a prompt would hang the run.+ @Test("A real identity in a throwaway keychain signs without a prompt",+ .enabled(if: ProcessInfo.processInfo.environment["NOTPROTON_KEYCHAIN_TEST"] != nil))+ func realKeychain() throws {+ let work = FileManager.default.temporaryDirectory.appending(path: "signing-real-\(UUID().uuidString)", directoryHint: .isDirectory)+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: work) }+ let keychain = work.appending(path: "test.keychain-db")+ let path = keychain.path(percentEncoded: false)+ try Shell.check("/usr/bin/security", ["create-keychain", "-p", "test", path])+ defer { _ = try? Shell.run("/usr/bin/security", ["delete-keychain", path]) }+ try Shell.check("/usr/bin/security", ["unlock-keychain", "-p", "test", path])++ let first = try LocalSigning.ensure(keychain: keychain, lookIn: [keychain])+ guard case .created(let hash) = first else { Issue.record("expected a new identity, got \(first)"); return }+ #expect(try LocalSigning.ensure(keychain: keychain, lookIn: [keychain]) == .alreadyPresent(hash: hash))++ let binary = work.appending(path: "echo")+ try FileManager.default.copyItem(at: URL(filePath: "/bin/echo"), to: binary)+ try Shell.check("/usr/bin/codesign", ["-f", "-s", hash, "--keychain", path, binary.path(percentEncoded: false)])+ let requirement = try Shell.run("/usr/bin/codesign", ["-d", "-r-", binary.path(percentEncoded: false)])+ #expect((requirement.stdout + requirement.stderr).lowercased().contains("h\"\(hash.lowercased())\""))+ }+}diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swiftindex 59755e8..1543fd5 100644--- a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift@@ -131,7 +131,7 @@ struct SteamInstallerTests {patchRunner: { _, _, _ in },stopClient: { _, onStopping in if stopped { onStopping() }; return stopped },register: { calls.register($0) },- resetInputAccess: { calls.resetInputAccess() }+ resetInputAccess: { calls.resetInputAccess(); return [] })if recordBuild {try SteamInstaller.finish(outcome, deployedVersion: fixture.deployedVersion, isCurrent: { _ in true })