Reputation: 2624
My (non-sandboxed) app has an embedded XPC helper which runs as root.
I would like to reference the (real) user's home directory from inside my helper, but these usual suspects simply return /var/root
:
FileManager.default.homeDirectoryForCurrentUser
NSHomeDirectory()
I can't simply pass Users/bob
to my helper for security reasons — if an exploit managed to call my helper method with any URL it wished, and my helper did things based on that as root, I fear bad things could be achieved.
Upvotes: 0
Views: 224
Reputation: 883
As vadian commented there are fundamental conceptual issues with what you're asking. What you probably actually want to do is be sure the process communicating with your helper tool is in fact trusted.
To do that you need to use SecCodeCreateWithXPCMessage
and then use the resulting SecCode
instance to validate the caller. For an example of how to do that, take a look at the acceptMessage
function in the SecureXPC framework.
EDIT: Turns out there is a way to do this that does work from a Command Line Tool such as one installed with SMJobBless
. This answer is adapted from Apple's Technical Q&A QA1133.
If you for whatever reason want to ignore the above, there's an approach you can take which may produce unexpected results if multiple users have active consoles. From Apple's documentation for SCDynamicStoreCopyConsoleUser
: "Note that this function only provides information about the primary console. It does not provide any details about console sessions that have fast user switched out or about other consoles."
import SystemConfiguration
extension FileManager {
var homeDirectoryForConsoleUser: URL? {
var homeDirectory: URL?
if let consoleUser = SCDynamicStoreCopyConsoleUser(nil, nil, nil) as String?,
consoleUser != "loginwindow" {
homeDirectory = URL(fileURLWithPath: "/Users/\(consoleUser)")
}
return homeDirectory
}
}
And then you can make use of this anywhere in your helper tool:
if let homeDirectory = FileManager.default.homeDirectoryForConsoleUser {
// Do something useful here
}
Upvotes: 1