Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,9 @@ down, the response directs the user to start it instead of asking for an IP or p
session. Agent, broker, AskPass, and trusted setup use role-specific signing identifiers. Setup
sessions additionally bind the begin/commit pair to the same caller and expire within five minutes.
- **Service lifecycle:** register the per-user broker through `SMAppService`; show registration state
and a direct System Settings remediation path.
and a direct System Settings remediation path. Before initializing runtime services, the broker
replaces its own process image with an explicit minimal environment. Removing variables only after
startup does not remove them from the operating system's initial process metadata.
- **Files:** application-support directories are `0700`; vault/config/known-host files are `0600`;
temporary request directories are removed after execution.

Expand Down
1 change: 1 addition & 0 deletions Sources/SAFABroker/BrokerService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,7 @@ public final class BrokerService: @unchecked Sendable {

public enum BrokerRuntime {
public static func main() async -> Never {
BrokerProcessEnvironment.reexecIfNeeded()
BrokerProcessEnvironment.apply()
let teamIdentifier: String
do {
Expand Down
97 changes: 97 additions & 0 deletions Sources/SAFABroker/Runtime/BrokerProcessEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import Darwin
import Foundation

enum BrokerProcessEnvironment {
static let cleanReexecMarker = "SAFA_BROKER_CLEAN_REEXEC_PID"

private static let fixedPath = "/usr/bin:/bin:/usr/sbin:/sbin"

static func sanitized(
Expand All @@ -26,6 +28,59 @@ enum BrokerProcessEnvironment {
return result
}

static func reexecEnvironment(
inherited: [String: String],
homeDirectory: String,
username: String,
temporaryDirectory: String,
processIdentifier: Int32
) -> [String: String] {
var environment = sanitized(
inherited: inherited,
homeDirectory: homeDirectory,
username: username,
temporaryDirectory: temporaryDirectory
)
environment[cleanReexecMarker] = String(processIdentifier)
return environment
}

static func requiresCleanReexec(
inherited: [String: String],
processIdentifier: Int32
) -> Bool {
inherited[cleanReexecMarker] != String(processIdentifier)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate the full environment before skipping re-exec

When a fork/exec launcher sets SAFA_BROKER_CLEAN_REEXEC_PID to the child's getpid() while also supplying sensitive variables such as API_TOKEN or DYLD_INSERT_LIBRARIES, this predicate returns false and skips the clean re-exec. BrokerRuntime then calls only apply(), which mutates the live environment but leaves the unsanitized initial environment visible through process inspection—the leak this change is intended to prevent. A PID is not proof that this image created the marker because the launching child knows its own PID; skip re-exec only when the inherited environment exactly matches the generated clean environment, including the marker.

AGENTS.md reference: AGENTS.md:L3-L4

Useful? React with 👍 / 👎.

}

static func reexecIfNeeded() {
let inherited = ProcessInfo.processInfo.environment
let processIdentifier = getpid()
guard
requiresCleanReexec(
inherited: inherited,
processIdentifier: processIdentifier
)
else {
return
}
guard let executablePath = Bundle.main.executableURL?.path else {
Foundation.exit(45)
}

let environment = reexecEnvironment(
inherited: inherited,
homeDirectory: FileManager.default.homeDirectoryForCurrentUser.path,
username: NSUserName(),
temporaryDirectory: NSTemporaryDirectory(),
processIdentifier: processIdentifier
)
replaceProcessImage(
executablePath: executablePath,
arguments: CommandLine.arguments,
environment: environment
)
}

static func apply() {
let inherited = ProcessInfo.processInfo.environment
let environment = sanitized(
Expand All @@ -41,4 +96,46 @@ enum BrokerProcessEnvironment {
setenv(key, value, 1)
}
}

private static func replaceProcessImage(
executablePath: String,
arguments: [String],
environment: [String: String]
) -> Never {
let effectiveArguments = arguments.isEmpty ? [executablePath] : arguments
var argumentPointers = effectiveArguments.map { strdup($0) }
var environmentPointers =
environment
.sorted { $0.key < $1.key }
.map { strdup("\($0.key)=\($0.value)") }

guard
argumentPointers.allSatisfy({ $0 != nil }),
environmentPointers.allSatisfy({ $0 != nil })
else {
argumentPointers.forEach { free($0) }
environmentPointers.forEach { free($0) }
Foundation.exit(45)
}

argumentPointers.append(nil)
environmentPointers.append(nil)
defer {
argumentPointers.forEach { free($0) }
environmentPointers.forEach { free($0) }
}

executablePath.withCString { path in
argumentPointers.withUnsafeMutableBufferPointer { argumentsBuffer in
environmentPointers.withUnsafeMutableBufferPointer { environmentBuffer in
_ = Darwin.execve(
path,
argumentsBuffer.baseAddress,
environmentBuffer.baseAddress
)
}
}
}
Foundation.exit(45)
}
}
42 changes: 42 additions & 0 deletions Tests/Security/BrokerProcessEnvironmentTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,46 @@ struct BrokerProcessEnvironmentTests {

#expect(environment["SSH_AUTH_SOCK"] == nil)
}

@Test("broker re-exec replaces the inherited process image environment")
func reexecEnvironmentIsMinimal() {
let environment = BrokerProcessEnvironment.reexecEnvironment(
inherited: [
"API_TOKEN": "must-not-survive",
"PATH": "/tmp/untrusted-bin",
"SSH_AUTH_SOCK": "/private/tmp/agent.sock",
],
homeDirectory: "/Users/example",
username: "example",
temporaryDirectory: "/private/tmp/",
processIdentifier: 4242
)

#expect(environment["API_TOKEN"] == nil)
#expect(environment["PATH"] == "/usr/bin:/bin:/usr/sbin:/sbin")
#expect(environment["SSH_AUTH_SOCK"] == "/private/tmp/agent.sock")
#expect(environment[BrokerProcessEnvironment.cleanReexecMarker] == "4242")
}

@Test("clean marker prevents a broker re-exec loop")
func cleanMarkerPreventsLoop() {
#expect(
BrokerProcessEnvironment.requiresCleanReexec(
inherited: [BrokerProcessEnvironment.cleanReexecMarker: "4242"],
processIdentifier: 4242
) == false
)
#expect(
BrokerProcessEnvironment.requiresCleanReexec(
inherited: [BrokerProcessEnvironment.cleanReexecMarker: "1"],
processIdentifier: 4242
)
)
#expect(
BrokerProcessEnvironment.requiresCleanReexec(
inherited: [:],
processIdentifier: 4242
)
)
}
}