Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Serve no older Peel from the helper, and judge the folder it holds
Țugui Dragoș2930be761207
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex fde36971..ad0d3b5d 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -158,7 +158,8 @@ The helper (`com.tuguidragos.Peel.Helper`) is registered with `SMAppService` whemacOS asks the user to approve it once. It talks to the app over XPC.- It answers administrators only, asked when a connection opens and again with each message, and it accepts- only a copy of Peel signed by the same team, checked when a connection opens and for every message after it.+ only a copy of Peel signed by the same team and no older a build than itself, checked when a connection opens+ and for every message after it.A released helper refuses a build that can be debugged, and launchd starts the helper only as the team's ownbuild of it (`SpawnConstraint` in its launchd property list).- It does three things: moves items to the Trash, puts them back, and starts, stops, enables, or disables anotherdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1ac8bcd0..2d0246a7 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -218,11 +218,12 @@ disk that somebody may have replaced.- It answers administrators only, asked when a connection opens and again with each message. The account is theconnection's and says nothing about which process sent a message (`xpc_connection_create(3)`), so no rule mayrest on it for that.-- It accepts only a copy of Peel signed by the same team, checked when a connection opens and for every message- after it (`setCodeSigningRequirement` on each accepted connection), and a released helper refuses a build that- can be debugged.-- It never uses a path again after checking it. It holds the folder open and works through that descriptor, so- a folder swapped after the check leads nowhere.+- It accepts only a copy of Peel signed by the same team and no older a build than itself, checked when a+ connection opens and for every message after it (`setCodeSigningRequirement` on each accepted connection), and+ a released helper refuses a build that can be debugged.+- It never uses a path again after checking it. It opens the folder, checks the item there as the kernel names+ the folder (`F_GETPATH`), works only through that descriptor, and moves the item only while its identity is the+ one it checked, so a folder or an item swapped after the check leads nowhere.- A new operation needs `PrivilegedPathPolicyTests`, and any change to the helper a protocol version bump,which asks every user to install the helper again. That cost is deliberate.diff --git a/Packages/PeelCore/Sources/PeelPrivileged/CodeSigning.swift b/Packages/PeelCore/Sources/PeelPrivileged/CodeSigning.swiftindex 7f1b3fbb..3e6a77ba 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/CodeSigning.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/CodeSigning.swift@@ -45,14 +45,25 @@ public enum CodeSigning {/// Development build carries `get-task-allow`, so any process of the same user can control it, and/// accepting one would let that process move files as root through the helper. A Debug build also/// accepts the Apple Development certificate, since both sides are then Debug builds.- public static func requirement(identifier: String, teamIdentifier: String) -> String {- requirement(identifier: identifier, teamIdentifier: teamIdentifier, allowingDevelopmentBuilds: isADebugBuild)+ public static func requirement(identifier: String, teamIdentifier: String, minimumBuild: String? = nil) -> String {+ requirement(+ identifier: identifier,+ teamIdentifier: teamIdentifier,+ allowingDevelopmentBuilds: isADebugBuild,+ minimumBuild: minimumBuild+ )}/// Builds either requirement, so a test in a Debug build can check the one a shipped Peel uses.- static func requirement(identifier: String, teamIdentifier: String, allowingDevelopmentBuilds: Bool) -> String {+ static func requirement(+ identifier: String,+ teamIdentifier: String,+ allowingDevelopmentBuilds: Bool,+ minimumBuild: String? = nil+ ) -> String {let base = "identifier \"\(identifier)\" and anchor apple generic"+ " and certificate leaf[subject.OU] = \"\(teamIdentifier)\""+ + (minimumBuild.map { " and info[CFBundleVersion] >= \"\($0)\"" } ?? "")guard !allowingDevelopmentBuilds else {return base + " and (certificate leaf[\(developerIDLeaf)] or certificate leaf[\(developmentLeaf)])"}@@ -62,6 +73,24 @@ public enum CodeSigning {+ " and ! entitlement[\"com.apple.security.get-task-allow\"] exists"}+ /// The build in the running process's signed Info.plist, or nil when its signature binds none.+ public static let currentBuild: String? = {+ var code: SecCode?+ guard SecCodeCopySelf([], &code) == errSecSuccess, let code else { return nil }+ var staticCode: SecStaticCode?+ guard SecCodeCopyStaticCode(code, [], &staticCode) == errSecSuccess, let staticCode else { return nil }+ return build(of: staticCode)+ }()++ /// `CFBundleVersion` in the Info.plist the signature of `code` binds, which a requirement's `info[...]` reads.+ static func build(of code: SecStaticCode) -> String? {+ var information: CFDictionary?+ guard SecCodeCopySigningInformation(code, [], &information) == errSecSuccess,+ let plist = (information as? [String: Any])?[kSecCodeInfoPList as String] as? [String: Any]+ else { return nil }+ return plist["CFBundleVersion"] as? String+ }+static let isADebugBuild: Bool = {#if DEBUGtruediff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swiftindex 135976d9..a959bee2 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift@@ -7,14 +7,15 @@ public enum HelperIdentity {public static let launchdPlistName = "com.tuguidragos.Peel.Helper.plist"/// Raise it whenever the helper changes, so Peel asks for the helper to be installed again rather than work with/// an older one. The helper refuses requests that carry any other version.- public static let protocolVersion = 11+ public static let protocolVersion = 12}/// The complete set of privileged operations. The helper validates every argument itself.////// Each call carries the protocol version of the app making it. Any administrator can write to/// `/Applications`, so an older copy of Peel, signed by the same team but with older checks, can be put-/// there. The helper answers only the version it was installed with, so that copy gets nothing from it.+/// there. The helper answers only the version it was installed with, and only a build no older than its own, so+/// that copy gets nothing from it.@objc public protocol PeelHelperProtocol {func protocolVersion(withReply reply: @escaping @Sendable (Int) -> Void)diff --git a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swiftindex 560c1ea3..c8065351 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift@@ -128,6 +128,11 @@ public struct PrivilegedPathPolicy: Sendable {let parent = "/" + components.dropLast().joined(separator: "/")guard let resolvedParent = Self.realPath(parent) else { return .failure(.unresolvableParent) }+ return judge(name, in: resolvedParent, locations: locations)+ }++ /// The checks on `name` in a folder named with no link left in its path, as `realpath` or the kernel names it.+ private func judge(_ name: String, in resolvedParent: String, locations: [String]) -> Result<Resolved, Rejection> {let resolved = (resolvedParent == "/" ? "" : resolvedParent) + "/" + nameguard!ProtectedData.refuses(resolved, home: homeDirectory),@@ -163,35 +168,32 @@ public struct PrivilegedPathPolicy: Sendable {return nil}- /// Checks `path` and opens it through a descriptor on its parent. `refusal(of:)` answers about a name,- /// which can stop being true as soon as it returns. This holds the parent directory itself, and the move- /// that follows goes through the same descriptor, so nothing swapped in afterwards is ever reached.+ /// Checks `path`, opens its folder, and checks the item again there, as the kernel names that folder. The move+ /// goes through the same descriptor and moves only the item whose identity was read here.public func open(_ path: String) -> Result<OpenItem, Rejection> {- switch resolve(path, in: locations) {- case .failure(let rejection):- return .failure(rejection)- case .success(let item):- let parent: DirectoryHandle- switch DirectoryHandle.at(canonical: item.parent) {- case .success(let opened): parent = opened- case .failure(let error): return .failure(Rejection(openingFolderFailedWith: error))- }+ open(path, beforeOpening: {})+ }++ func open(_ path: String, beforeOpening: () -> Void) -> Result<OpenItem, Rejection> {+ openFolder(of: path, beforeOpening: beforeOpening).flatMap { name, parent invar info = stat()- guard item.name.withCString({ fstatat(parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {+ guard name.withCString({ fstatat(parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {return .failure(.missing)}- guard info.st_flags & Self.protectedFlags == 0 else { return .failure(.protectedByFlags) }- if links.contains(item.parent) {- guard info.st_mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }- // Followed this time: nothing there, or a chain that loops, is a link that leads nowhere.- var target = stat()- let leads = item.name.withCString { fstatat(parent.descriptor, $0, &target, 0) } == 0- let error = errno- guard !leads, error == ENOENT || error == ENOTDIR || error == ELOOP else {- return .failure(.leadsSomewhere)+ return judged(name, in: parent).flatMap { item in+ guard info.st_flags & Self.protectedFlags == 0 else { return .failure(.protectedByFlags) }+ if links.contains(item.parent) {+ guard info.st_mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }+ // Followed this time: nothing there, or a chain that loops, is a link that leads nowhere.+ var target = stat()+ let leads = item.name.withCString { fstatat(parent.descriptor, $0, &target, 0) } == 0+ let error = errno+ guard !leads, error == ENOENT || error == ENOTDIR || error == ELOOP else {+ return .failure(.leadsSomewhere)+ }}+ return .success(OpenItem(path: item.path, name: item.name, parent: parent, status: info))}- return .success(OpenItem(path: item.path, name: item.name, parent: parent, status: info))}}@@ -199,31 +201,45 @@ public struct PrivilegedPathPolicy: Sendable {/// item owned by root that nobody else can write to, which is how anything the helper took from there/// looks. Anything else could have been rewritten while it sat in the user's Trash.public func openDestination(_ path: String, for trashed: OpenItem) -> Result<OpenItem, Rejection> {- switch resolve(path, in: locations) {- case .failure(let rejection):- return .failure(rejection)- case .success(let item):- if links.contains(item.parent) {- guard let mode = trashed.mode, mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }- }- if !restorable.contains(where: { PathComponents.isPath(item.path, inside: $0) }) {- guard trashed.owner == trustedOwner, let mode = trashed.mode, mode & 0o022 == 0 else {- return .failure(.loadsCode)+ openFolder(of: path, beforeOpening: {}).flatMap { name, parent in+ judged(name, in: parent).flatMap { item in+ if links.contains(item.parent) {+ guard let mode = trashed.mode, mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }+ }+ if !restorable.contains(where: { PathComponents.isPath(item.path, inside: $0) }) {+ guard trashed.owner == trustedOwner, let mode = trashed.mode, mode & 0o022 == 0 else {+ return .failure(.loadsCode)+ }}+ var info = stat()+ guard item.name.withCString({ fstatat(parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) != 0 else {+ return .failure(.alreadyExists)+ }+ return .success(OpenItem(path: item.path, name: item.name, parent: parent))}- let parent: DirectoryHandle- switch DirectoryHandle.at(canonical: item.parent) {- case .success(let opened): parent = opened+ }+ }++ /// Checks `path` by name, so nothing is opened for a path refused anyway, then opens its folder.+ private func openFolder(+ of path: String,+ beforeOpening: () -> Void+ ) -> Result<(name: String, parent: DirectoryHandle), Rejection> {+ resolve(path, in: locations).flatMap { named in+ beforeOpening()+ switch DirectoryHandle.at(canonical: named.parent) {+ case .success(let parent): return .success((named.name, parent))case .failure(let error): return .failure(Rejection(openingFolderFailedWith: error))}- var info = stat()- guard item.name.withCString({ fstatat(parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) != 0 else {- return .failure(.alreadyExists)- }- return .success(OpenItem(path: item.path, name: item.name, parent: parent))}}+ /// Checks `name` again in the folder `parent` holds, as the kernel names it now.+ private func judged(_ name: String, in parent: DirectoryHandle) -> Result<Resolved, Rejection> {+ guard let folder = parent.currentPath else { return .failure(.unresolvableParent) }+ return judge(name, in: folder, locations: locations)+ }+/// Opens the user's own Trash. A link in place of `.Trash` is refused, and the folder must belong to/// `user`, so the Trash cannot be used to drop a root-owned file somewhere else.public func openTrash(ownedBy user: uid_t) -> DirectoryHandle? {diff --git a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swiftindex 29fad99c..596eba85 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift@@ -48,13 +48,19 @@ public enum TrashMover {/// A file system that cannot refuse to replace by itself answers `ENOTSUP` (rename(2)), as exFAT does for a free/// name. There the name is first taken with an empty placeholder of the item's kind, which only a free name- /// allows, and a plain rename then replaces the placeholder.+ /// allows, and a plain rename then replaces the placeholder. Only the item that was opened moves, never another+ /// renamed into its place.static func rename(_ item: OpenItem,to name: String,in directory: DirectoryHandle,exclusively: ExclusiveRename) -> Result<Void, POSIXError> {+ var info = stat()+ guard item.name.withCString({ fstatat(item.parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {+ return .failure(.last)+ }+ guard let identity = item.identity, ItemIdentity(info) == identity else { return .failure(POSIXError(.ENOENT)) }switch exclusively(item, name, directory) {case .failure(let error) where error.code == .ENOTSUP:return renameOntoPlaceholder(item, to: name, in: directory)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swiftindex e42e6d92..8879f667 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift@@ -51,6 +51,33 @@ struct AttackHelperPolicyTests {#expect(!policy(directory).open(directory.url.appending(path: "home/Library/Caches/com.example.app").path(percentEncoded: false)).isFailure)}+ @Test func whatTheHelperJudgesIsTheFolderItOpens() throws {+ let directory = try TemporaryDirectory()+ let vendor = try directory.directory("home/Library/Caches/Vendor/item")+ try directory.file("home/Library/Caches/Other/item/Family.photoslibrary/database/Photos.sqlite")+ let caches = vendor.deletingLastPathComponent().deletingLastPathComponent()++ let result = policy(directory).open(vendor.path(percentEncoded: false)) {+ try? FileManager.default.moveItem(at: caches.appending(path: "Vendor"), to: caches.appending(path: "Aside"))+ try? FileManager.default.moveItem(at: caches.appending(path: "Other"), to: caches.appending(path: "Vendor"))+ }++ #expect(result.isFailure, "ATTACK SUCCEEDED: root would move a photo library from a folder swapped in after the check")+ }++ @Test func anItemSwappedForAnotherAfterItWasOpenedStays() throws {+ let directory = try TemporaryDirectory()+ let judged = try directory.file("home/Library/Caches/org.example.app/cache.db").deletingLastPathComponent()+ let other = try directory.file("home/Library/Caches/org.example.kept/keep.db").deletingLastPathComponent()+ let item = try policy(directory).open(judged.path(percentEncoded: false)).get()+ try FileManager.default.moveItem(at: judged, to: judged.deletingLastPathComponent().appending(path: "Aside"))+ try FileManager.default.moveItem(at: other, to: judged)+ let trash = try DirectoryHandle.at(try directory.directory("Trash").path(percentEncoded: false)).get()++ #expect(TrashMover.move(item, into: trash).isFailure, "ATTACK SUCCEEDED: another item at the checked name moved")+ #expect(FileManager.default.fileExists(atPath: judged.appending(path: "keep.db").path(percentEncoded: false)))+ }+/// A `String` reads a slash followed by a combining mark as one character, so a path split on `"/"` keeps/// that slash inside a name, and the kernel still walks through it. Here `Caches/dir` is a link into the/// keychains, and the name after it begins with a combining mark.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperPolicyTests.swiftindex 5fb9ab24..d759b3a4 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperPolicyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperPolicyTests.swift@@ -35,6 +35,39 @@ struct HelperPolicyTests {}}+ @Test func theHelperServesNoCopyOfPeelOlderThanItself() {+ for allowing in [false, true] {+ let text = CodeSigning.requirement(+ identifier: "com.tuguidragos.Peel",+ teamIdentifier: "6R6J264YA2",+ allowingDevelopmentBuilds: allowing,+ minimumBuild: "261006"+ )+ #expect(text.contains("info[CFBundleVersion] >= \"261006\""), "an older Peel is served")+ var requirement: SecRequirement?+ #expect(SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess)+ }+ }++ @Test func aBuildFloorRefusesOlderCode() throws {+ let calculator = URL(filePath: "/System/Applications/Calculator.app")+ var code: SecStaticCode?+ #expect(SecStaticCodeCreateWithPath(calculator as CFURL, [], &code) == errSecSuccess)+ let signed = try #require(code)+ let build = try #require(CodeSigning.build(of: signed))+ #expect(build == Bundle(url: calculator)?.infoDictionary?["CFBundleVersion"] as? String)++ let satisfies = { (text: String) -> Bool in+ var requirement: SecRequirement?+ guard SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess else {+ return false+ }+ return SecStaticCodeCheckValidity(signed, [], requirement) == errSecSuccess+ }+ #expect(satisfies("info[CFBundleVersion] >= \"\(build)\""))+ #expect(!satisfies("info[CFBundleVersion] >= \"\(build)9\""), "a floor above the build let the code through")+ }+/// The team in `SpawnConstraint` has to be the one every target of the project signs with.@Test func launchdStartsOnlyTheTeamsOwnHelper() throws {let repository = StringCatalogTests.repositorydiff --git a/PeelHelper/main.swift b/PeelHelper/main.swiftindex bd979353..390804e0 100644--- a/PeelHelper/main.swift+++ b/PeelHelper/main.swift@@ -1,12 +1,17 @@import Foundationimport PeelPrivileged-// Clients must be signed by the helper's own team, so a helper with no team (unsigned or ad hoc) does not run.-guard let teamIdentifier = CodeSigning.currentTeamIdentifier() else {+// Clients must be signed by the helper's own team and be no older a build than the helper, so an older copy of Peel+// is never served. A helper with no team (unsigned or ad hoc) or no signed build does not run.+guard let teamIdentifier = CodeSigning.currentTeamIdentifier(), let build = CodeSigning.currentBuild else {exit(EXIT_FAILURE)}-let requirement = CodeSigning.requirement(identifier: HelperIdentity.appIdentifier, teamIdentifier: teamIdentifier)+let requirement = CodeSigning.requirement(+ identifier: HelperIdentity.appIdentifier,+ teamIdentifier: teamIdentifier,+ minimumBuild: build+)let listener = NSXPCListener(machServiceName: HelperIdentity.machServiceName)listener.setConnectionCodeSigningRequirement(requirement)let lifetime = HelperLifetime()diff --git a/SAFETY.md b/SAFETY.mdindex ef96645f..3aa40a2c 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -380,10 +380,10 @@ Peel is removed, it also moves its own ledger to the Trash. It is deliberately sand it fails closed.- It answers administrators only, and only a copy of Peel signed by the same team with its Developer ID,- built so it can't be debugged, that speaks the helper's own version. All of it is checked when the app- connects and again with each request, so an account that stops being an administrator is refused from then- on, and a message from any other program closes the connection. macOS starts the helper only as the- developer's own build of it, so other code put in its place never runs as root.+ built so it can't be debugged, no older a build than the helper itself, that speaks the helper's own version.+ All of it is checked when the app connects and again with each request, so an account that stops being an+ administrator is refused from then on, and a message from any other program closes the connection. macOS starts+ the helper only as the developer's own build of it, so other code put in its place never runs as root.- It refuses the list above on its own, without asking the app, and asks it both ways: a folder that holdssomething on the list is refused like the thing itself.- It serves a fixed list of folders and refuses everything else: `/Applications`, for apps only; eight folders@@ -404,8 +404,9 @@ and it fails closed.`share/fish/vendor_completions.d`, `etc/bash_completion.d`, and `share/pwsh/completions`), it takes only a link,never a file, and only one that leads nowhere. Peel sends an app's links there after the app itself, so they goonce the app is gone, and a link that still leads to something stays.-- It never reuses a path after checking it. It holds the parent directory open and works through that- descriptor, so a folder swapped after the check leads nowhere.+- It never reuses a path after checking it. It opens the parent directory, checks the item there as the system+ names that directory, works only through that descriptor, and moves the item only while it is still the one it+ checked, so a folder or an item swapped after the check leads nowhere.- "Put Back" is asked for by a record any process running as you can rewrite, so the helper believes none ofit. It keeps its own ledger, in a folder that is root's alone, of what it moved and from where: the item isrecognized by what it is (not by its name or place in the Trash), and it goes back only to the exact place