General:
DevForums tag: App Sandbox
App Sandbox documentation
App Sandbox Design Guide documentation — This is no longer available from Apple. There’s still some info in there that isn’t covered by the current docs but, with the latest updates, it’s pretty minimal (r. 110052019). Still, if you’re curious, you can consult an old copy [1].
App Sandbox Temporary Exception Entitlements archived documentation — To better understand the role of temporary exception entitlements, see this post.
Embedding a Command-Line Tool in a Sandboxed App documentation
Discovering and diagnosing App Sandbox violations (replaces the Viewing Sandbox Violation Reports DevForums post)
Resolving App Sandbox Inheritance Problems DevForums post
The Case for Sandboxing a Directly Distributed App DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] For example, this one archived by the Wayback Machine.
App Sandbox
RSS for tagApp Sandbox is a macOS access control technology designed to contain damage to the system and user data if an app becomes compromised.
Posts under App Sandbox tag
123 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I'm trying to launch a command line app from my objective C application (sandboxed) using NSTask and I keep getting "launch path not accessible"
Here is the path:
[task setLaunchPath:@"/usr/local/bin/codeview"];
I have set the appropriate attributes for codeview and it is working perfectly when I use it from the command line and /usr/local/bin IS in the $PATH
I know I have NSTask configured correctly because this WILL work:
[task setLaunchPath:@"/usr/bin/hexdump"];
With the exception being that I'm using a command already in /usr/bin. But I can't copy codeview into /usr/bin due to SIPS.
I've tried moving codeview to various other non-SIPS protected locations all to no avail. Must all NSTask commands come from /usr/bin? Where might I put codeview so that it can be launched.
Today I'm going to use an older computer and disable SIPS to put my command in /usr/bin and see if that works. If it does. I will do it on my main machine.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Entitlements
Objective-C
Command Line Tools
App Sandbox
I am using macOS virtualization farmework and able to create nad and run VMS. I need to resize the disk images using hdiutil in app sandbox environment. Is that possible? i tried disabling sandbox and it worked ok. But with sandbox i get the error message device is not configured. If this cant be done in sandbox what could be the alternative way to to achive this in sandboxed app.
thanks
Hello,
I'm seeking some clarification regarding the use of accessibility and input monitoring APIs in sandboxed apps that are distributed through the App Store.
I understand that accessibility permissions are generally restricted for App Store apps. However, I've seen several recently released apps request these permissions directly upon first launch. I'm aware that apps submitted prior to 2012 may have legacy access to certain APIs, but the ones I'm referring to appear to be recent - within the past year.
While it's possible these apps were approved despite the restrictions, I want to make sure I'm not overlooking something. I also came across a recent discussion on this topic, and one post in particular stood out: Link
I’d really appreciate some clarification on what's officially allowed. Specifically:
Are accessibility permissions ever allowed? If so, under what circumstances?
Is input monitoring permitted for apps on the App Store? (The referenced post says yes, but since it's from 2022, I just want to confirm)
The linked post suggests that event generation might be allowed on the App Store, though the author hadn’t explored that privilege in detail and recommended opening a DTS tech support incident. I’ve done that and have a support case open - would it be possible to take a closer look at this?
For context, my app (currently distributed outside the App Store) uses CGEventPost and CGEventCreateMouseEvent to modify mouse behavior.
Thank you
Hello,
I'm seeking some clarification regarding the use of accessibility and input monitoring APIs in sandboxed apps that are distributed through the App Store.
I understand that accessibility permissions are generally restricted for App Store apps. However, I've seen several recently released apps request these permissions directly upon first launch. I'm aware that apps submitted prior to 2012 may have legacy access to certain APIs, but the ones I'm referring to appear to be recent - within the past year.
While it's possible these apps were approved despite the restrictions, I want to make sure I'm not overlooking something. I also came across a recent discussion on this topic, and one post in particular stood out: Link
I’d really appreciate some clarification on what's officially allowed. Specifically:
Are accessibility permissions ever allowed? If so, under what circumstances?
Is input monitoring permitted for apps on the App Store? (The referenced post says yes, but since it's from 2022, I just want to confirm)
The linked post suggests that event generation might be allowed on the App Store, though the author hadn’t explored that privilege in detail and recommended opening a DTS tech support incident. I’ve done that and have a support case open - would it be possible to take a closer look at this?
For context, my app (currently distributed outside the App Store) uses CGEventPost and CGEventCreateMouseEvent to modify mouse behavior.
Thank you
We’re receiving increasing user reports that our macOS app is unexpectedly terminated in the background—without crash reports or user action.
Our app is a sandboxed status-bar app (UIElement, NSStatusItem) running continuously, syncing data via CloudKit and Core Data. It has no main window unless opened via the status bar.
Observed patterns:
Happens more frequent on macOS 15 (Sonoma), though earlier versions are affected too.
Often occurs when disk space is limited (~10% free), but occasionally happens with ample free space.
System logs consistently show: CacheDeleteAppContainerCaches requesting termination assertion for <our bundle ID>
No crash reports are generated, indicating macOS silently terminates our app, likely related to RunningBoard or CacheDelete purging caches during disk pressure. Since our app is meant to run persistently, these silent terminations significantly disrupt user experience.
We’re seeking guidance on:
Can we prevent or reduce these terminations for persistently running status bar apps?
Are there recommended APIs or configurations (e.g., NSProcessInfo assertions, entitlements, LaunchAgents) to resist termination or receive notifications under low disk conditions?
What are Apple’s best practices for ensuring sandboxed apps reliably run during disk pressure?
We understand macOS terminates apps to reclaim space but would appreciate recommendations to improve resilience within platform guidelines.
Thank you!
Topic:
App & System Services
SubTopic:
Core OS
Tags:
App Sandbox
Core Services
Background Tasks
Files and Storage
Hello all,
I'm the developer of REHex, a hex editor which I have been distributing as an app bundle outside of the app store for a few years.
REHex allows assigning various bits of metadata (comments, data types, etc) which get stored as filename.rehex-meta alongside the original filename, this works fine when the app is just a standalone bundle, however, when distributed via the app store, sandboxing seems to be mandatory, and there doesn't appear to be any obvious way to get permission to read/write such files.
As fallbacks, I've considered adding support for storing the metadata as an extended attribute instead (which breaks compatibility, and won't translate when the file is on a FAT/etc filesystem or network share), or popping up the save/load dialog a second time for the user to select a .rehex-meta file, adding it to the list of whitelisted files for the application (keeps compatibility, but UX is clunky).
Are there any ways I can work around this, or perhaps other methods I should consider for storing the metadata in an Apple-tolerant manner?
Thanks
I have an app with two file types with the following extensions:
gop (an exported type),
sgf (an imported type).
The Save command fails after the following sequence of events:
I open a gop file, say the file "A.gop".
I save this file as an sgf file, say "A.sgf".
This Save As works perfectly and the document name in the document’s title bar has changed to "A.sgf".
I change something in the document and then try to Save this change.
This should just resave the document to "A.sgf", but "A.sgf" remains untouched. Instead I get a system alert with the message
The document “A.sgf” could not be saved. A file with the name “A.gop” already exists. To save the file, either provide a different name, or move aside or delete the existing file, and try again.
In the Xcode console I get the following diagnostic:
NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 2 [NSFileCoordinator itemAtURL:willMoveToURL:] could not get a sandbox extension. oldURL: file:///Users/francois/Desktop/A.sgf, newURL: file:///Users/francois/Desktop/A.gop
The problem seems to relate to the sandbox. But I am at a loss to find a solution. (After closing the alert, I check that A.sgf did not register the change.)
If I open an sgf file, say "B.sgf", save it as "B.gop", make a change in the document and then try to save this change (into "B.gop"), I hit the same problem, with "gop" and "sgf" interchanged.
If, instead of saving "A.gop" as "A.sgf", I save it as "B.sgf", make a change in the document and then try to save this change into "B.sgf", I get the following system alert:
The document “B.sgf” could not be saved. You don’t have permission. To view or change permissions, select the item in the Finder and choose File > Get Info.
And in the Xcode console I get the following diagnostic:
NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 2 [NSFileCoordinator itemAtURL:willMoveToURL:] could not get a sandbox extension. oldURL: file:///Users/francois/Desktop/B.sgf, newURL: file:///Users/francois/Desktop/B.gop
Again the sandbox ! (After closing the alert, I check that B.sgf did not register the change.)
It’s clear my code is missing something, but what?
I have my both app and fskit sandboxed
<key>com.apple.security.app-sandbox</key>
<true/>
Which means that I can read files only in app container.
First, is sandboxing required for fskit modules?
Second, there are docs which implies that it's possible to explicitly allow fskit module to access external files, by passing their paths to mount params.
https://developer.apple.com/documentation/fskit/fstaskoptions/url(foroption:)
and also
options: Options to apply to the activation. These can include security-scoped file paths. There are no defined options currently.
I've tried this, but haven't success.
My Info.plist is
<key>FSActivateOptionSyntax</key>
<dict>
<key>shortOptions</key>
<string>g:m:</string>
<key>pathOptions</key>
<dict>
<key>m</key>
<string>file</string>
<key>g</key>
<string>directory</string>
</dict>
</dict>
I'm mounting with
mount -F -t MyFS -o -m=./build.sh,-g=./ /dev/disk5 /tmp/TestVol
Getting them via
options.url(forOption: "m"),
options.url(forOption: "g")
Both nulls.
I also see that options are presented in options.taskOptions
But they are not expanded to absolute pathes or urls, which makes me think that pathOptions declaration is incorrect.
Docs says
This dictionary uses the command option name as a key, and each entry has a value indicating what kind of entry to create.
What entry kind means in this context?
Can you send example of correct pathOptions?
Security scoped bookmarks that were created before updating to macOS 14.7.5 cannot be resolved anymore after updating to macOS 14.7.5.
Reproduction:
Sandboxed app on macOS version 14.7.4
Create and store a security scoped bookmark to a user selected folder:
let url: URL = <user selected url from NSOpenPanel>
let data = try url.bookmarkData(options: [.withSecurityScope], includingResourceValuesForKeys: nil, relativeTo: nil)
<persistently store data>
Update to macOS 14.7.5
Resolve the previously stored bookmark:
let data: Data = <restore data from persistent storage>
var stale: Bool = true
let url = try URL(resolvingBookmarkData: data, options: [.withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &stale)
Expected:
The bookmark is resolved correctly and the resulting url can be used to access the folder/file in the sandboxed app after starting access.
Observed:
URL(resolvingBookmarkData:) throws an error:
Error Domain=NSCocoaErrorDomain Code=259 "The file couldn’t be opened because it isn’t in the correct format."
New security scoped bookmarks created on macOS 14.5.7 can be resolved without issue.
The same appears to happen with macOS 13.7.5.
Entitlements:
com.apple.security.app-sandbox
com.apple.security.files.bookmarks.app-scope
com.apple.security.files.user-selected.read-write
This is very disruptive, as it appears that Sandboxed apps cannot access any previously stored bookmarks anymore.
Particularly after the recent ScopedBookmarkAgent issues in 14.7.1 and 15.0, which were resolved in 14.7.3/15.1 respectively: https://developer.apple.com/forums/thread/764435
I have a sandboxed Mac app which I can grant access to a folder using an NSOpenPanel. Once it’s been granted access it can enumerate the contents of the folder just fine. If I rename the folder while the app is open and then make the app enumerate the folder’s contents again, though, it seems to have lost access.
What’s the recommended way to have an app’s sandbox “track” files as they’re moved around the filesystem? (NSDocument handles this for you, from what I can tell.) I’ve managed to hack something together with a combination of Dispatch sources and security-scoped bookmarks, but it feels like there must be an easier solution …
Hi guys,
I'm developing a FinderSync Extension that extends Finder contextual menu with a couple of items doing some trivial file operations.
I'm using Xcode 16.2 on macOS Sequoia 15.3.2
I could run the containing app in debug, and in System Preferences -> File Providers the flag is enabled for my app finder extension.
Anyway, the contextual menu does not show in Finder, probably because the finder extension crashes immediately.
Some output:
pluginkit -m | grep "com\.[^a]"
+ com.mycompany.MyApp.MyAppFinderExtension(1.1.14)
codesign -dvvv --entitlements - /Users/me/Library/Developer/Xcode/DerivedData/MyApp-dmzhnwmosboixodalsrrbwvwvmqm/Build/Products/Debug/MyApp.app/Contents/PlugIns/MyApp\ Finder\ Extension.appex
Executable=/Users/me/Library/Developer/Xcode/DerivedData/MyApp-dmzhnwmosboixodalsrrbwvwvmqm/Build/Products/Debug/MyApp.app/Contents/PlugIns/MyApp Finder Extension.appex/Contents/MacOS/MyApp Finder Extension
Identifier=com.mycompany.MyApp.MyAppFinderExtension
Format=bundle with Mach-O thin (arm64)
CodeDirectory v=20400 size=659 flags=0x2(adhoc) hashes=9+7 location=embedded
Hash type=sha256 size=32
CandidateCDHash sha256=b59538ef9e3b6e8cf462a3e260e3bf26d050deb5
CandidateCDHashFull sha256=b59538ef9e3b6e8cf462a3e260e3bf26d050deb5e21fb27d4fa0a4fe5f3e78b7
Hash choices=sha256
CMSDigest=b59538ef9e3b6e8cf462a3e260e3bf26d050deb5e21fb27d4fa0a4fe5f3e78b7
CMSDigestType=2
CDHash=b59538ef9e3b6e8cf462a3e260e3bf26d050deb5
Signature=adhoc
Info.plist entries=23
TeamIdentifier=not set
Sealed Resources version=2 rules=13 files=9
Internal requirements count=0 size=12
[Dict]
[Key] com.apple.security.app-sandbox
[Value]
[Bool] true
[Key] com.apple.security.application-groups
[Value]
[Array]
[String]
[Key] com.apple.security.assets.movies.read-write
[Value]
[Bool] true
[Key] com.apple.security.assets.music.read-write
[Value]
[Bool] true
[Key] com.apple.security.assets.pictures.read-write
[Value]
[Bool] true
[Key] com.apple.security.files.documents.read-write
[Value]
[Bool] true
[Key] com.apple.security.files.downloads.read-write
[Value]
[Bool] true
[Key] com.apple.security.files.user-selected.read-write
[Value]
[Bool] true
[Key] com.apple.security.get-task-allow
[Value]
[Bool] true
[Key] com.apple.security.personal-information.location
[Value]
[Bool] true
The log is showing something very strange:
log show --predicate 'eventMessage contains "com.mycompany.MyApp" and messageType = error' --last 1h
Filtering the log data using "composedMessage CONTAINS "com.mycompany.MyApp" AND logType == 16"
Skipping info and debug messages, pass --info and/or --debug to include.
Timestamp Thread Type Activity PID TTL
2025-03-25 10:20:48.428127+0100 0x221af Error 0x53dbe 159 0 tccd: [com.apple.TCC:access] Request message contains a target_token to accessing_process (TCCDProcess: identifier=com.mycompany.MyApp, pid=4140, auid=501, euid=501, binary_path=/Users/me/Library/Developer/Xcode/DerivedData/MyApp-dmzhnwmosboixodalsrrbwvwvmqm/Build/Products/Debug/MyApp.app/Contents/MacOS/MyApp) but TCCDProcess: identifier=com.apple.audio.coreaudiod, pid=184, auid=202, euid=202, binary_path=/usr/sbin/coreaudiod is not a TCC manager for service: kTCCServiceScreenCapture.
2025-03-25 10:20:53.166554+0100 0x22139 Error 0x67ff4 163 0 runningboardd: (RunningBoard) [com.apple.runningboard:general] RBSStateCapture remove item called for untracked item 163-158-7088 (target:[app<application.com.mycompany.MyApp.36628067.36635236.92E24CD3-97A8-4340-A46E-4493456283C7(501)>:4140])
2025-03-25 10:20:53.166575+0100 0x22139 Error 0x67ff4 163 0 runningboardd: (RunningBoard) [com.apple.runningboard:general] RBSStateCapture remove item called for untracked item 163-158-7087 (target:[app<application.com.mycompany.MyApp.36628067.36635236.92E24CD3-97A8-4340-A46E-4493456283C7(501)>:4140])
2025-03-25 10:20:53.166582+0100 0x22139 Error 0x67ff4 163 0 runningboardd: (RunningBoard) [com.apple.runningboard:general] RBSStateCapture remove item called for untracked item 163-158-7091 (target:[app<application.com.mycompany.MyApp.36628067.36635236.92E24CD3-97A8-4340-A46E-4493456283C7(501)>:4140])
2025-03-25 10:20:53.166593+0100 0x22139 Error 0x67ff4 163 0 runningboardd: (RunningBoard) [com.apple.runningboard:general] RBSStateCapture remove item called for untracked item 163-132-7084 (target:[xpcservice<com.apple.finder.FinderSync.IsExtensionEnabled([app<application.com.mycompany.MyApp.36628067.36635236.92E24CD3-97A8-4340-A46E-4493456283C7(501)>:4140])(501)>{vt hash: 0}:4144:4144])
--------------------------------------------------------------------------------------------------------------------
Log - Default: 0, Info: 0, Debug: 0, Error: 13, Fault: 0
Activity - Create: 0, Transition: 0, Actions: 0
Especially the first line: MyApp is not accessing coreaudiod - neither trying to get a ScreenCapture, so ... WTF???
How is it possibile?
Why is the system blocking MyApp FinderExtension, or preventing it to run?
Thank you in advance
_Alex
Topic:
App & System Services
SubTopic:
General
Tags:
Finder Sync
Entitlements
Signing Certificates
App Sandbox
Why are we doing this nonsense?
We want to be able to run builds in a sandbox such that they can only see the paths they are intended to depend on, to improve reproducibility.
With builds with a very large number of dependencies, there's a very large number of paths added to the sandbox, and it breaks things inside libsandbox.
Either it hits some sandbox length limit (sandbox-exec: pattern serialization length 66460 exceeds maximum (65535), Nix issue #4119, worked around: Nix PR 12570), or it hits an assert (this report; also Nix issue #2311).
The other options for sandboxing on macOS are not viable; we acknowledge sandbox-exec and sandbox_init_with_parameters are deprecated; App Sandbox is inapplicable because we aren't an app.
Our use case is closer to a browser, and all the browsers use libsandbox internally.
We could possibly use SystemExtension or a particularly diabolical use of Virtualization.framework, but the former API requires notarization which is close to a no-go for our use case as open source software: it is nearly impossible to develop the software on one's own computer, and it would require us to ship a binary blob (and have the build processes to produce one in infrastructure completely dissimilar to what we use today); it also requires a bunch of engineering time.
Today, we can pretend that code signing/notarization doesn't exist and that we are writing an old-school Unix daemon, because we are one.
The latter is absolutely diabolical and hard to implement.
See this saga about the bug we are facing: Nix issue #4119, Nix issue #2311, etc.
What is going wrong
I can't attach the file fail.sb as it is too large (you can view the failing test case at Lix's gerrit, CL 2870) and run this:
$ sandbox-exec -D _GLOBAL_TMP_DIR=/tmp -f fail.sb /bin/sh
Assertion failed: (diff <= INSTR_JUMP_NE_MAX_LENGTH), function push_jne_instr, file serialize.c, line 240.
zsh: abort sandbox-exec -D _GLOBAL_TMP_DIR=/tmp -f fail.sb /bin/sh
Or a stacktrace:
stacktrace.txt
Credits
Full credits to Jade Lovelace (Lix) for writing the above text and filing a bug.
This is submitted under FB16964888
Hi all,
I'm developing a sandboxed Mac OS app that generates and compiles AppleScript files to automate tasks in Pages (and other iWork apps). The app creates an AppleScript file and writes it to the NSApplicationScriptsDirectory (i.e., ~/Library/Application Scripts/com.example.app), then compiles and executes it via NSUserAppleScriptTask.
On Mac OS Ventura, however, I get the following error in the console when trying to write the file:
[PagesModifier] Error creating or compiling the script: You are not allowed to save the file "PagesModifier_...applescript" in the folder "com.example.app"
Here are my current entitlements:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.application-groups</key>
<array/>
<key>com.apple.security.automation.apple-events</key>
<array>
<string>com.apple.iWork.Pages</string>
<string>com.apple.iWork.Numbers</string>
<string>com.apple.iWork.Keynote</string>
</array>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.scripting-targets</key>
<dict>
<key>com.apple.iWork.Keynote</key>
<array>
<string>com.apple.iWork.Keynote</string>
</array>
<key>com.apple.iWork.Numbers</key>
<array>
<string>com.apple.iWork.Numbers</string>
</array>
<key>com.apple.iWork.Pages</key>
<array>
<string>com.apple.iWork.Pages</string>
</array>
</dict>
<key>com.apple.security.temporary-exception.apple-events</key>
<array>
<string>com.apple.iWork.Pages</string>
<string>com.apple.iWork.Numbers</string>
<string>com.apple.iWork.Keynote</string>
</array>
<key>com.apple.security.temporary-exception.files.home-relative-path.read-write</key>
<array>
<string>Library/Application Scripts/com.example.app</string>
</array>
</dict>
</plist>
I suspect the issue might be due to sandbox restrictions on dynamically creating or modifying the Application Scripts directory on Ventura. Has anyone experienced something similar or have any suggestions on how to work around this?
Thanks in advance for your help!
Topic:
App & System Services
SubTopic:
Automation & Scripting
Tags:
Entitlements
Scripting
AppleScript
App Sandbox
I’ve explained this point many times on the forums, so I figured I’d write it up properly once and for all.
If you have questions or comments, start a new thread in Privacy & Security > General and add the App Sandbox tag. That way I’ll be sure to see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
The Case for Sandboxing a Directly Distributed App
Many folks consider the App Sandbox to be a binary choice:
“My app ships in the Mac App Store, so I must sandbox it.”
“I directly distribute my app, so I’ll ignore the App Sandbox.”
However, those are not your only options. In many cases it makes sense to sandbox a directly distributed app. Sandboxing your app has at least three benefits:
It enables app container protection. See Trusted Execution Resources for a link to more info on that.
If your app includes any app extensions, it simplifies your development experience because your app and its extensions run in a similar environment.
It improves your app’s security (although the actual benefits vary based on the specifics of your app).
Sandboxing some apps can be tricky because of the additional security limits applied by the sandbox. However, in a directly distributed app you have access to two techniques that are not available to Mac App Store apps:
Temporary exception entitlements
Non-sandboxed XPC services
Temporary exception entitlements
Use temporary exception entitlements to selectively disable specific sandbox security limits.
Imagine, for example, that you’re creating a simple document-based app that’s generally compatible with the sandbox. However, that app needs to send an Apple event to Music to create a playlist. That Apple event is blocked by the sandbox. You don’t need to disable the entire App Sandbox just to get around this security limit. Instead, use the com.apple.security.temporary-exception.apple-events entitlement to open a small hole in the sandbox.
There are temporary exception entitlements to disable most sandbox security limits. For more information about them, follow the link in App Sandbox Resources.
IMPORTANT Don’t be alarmed by the temporary in temporary exception entitlements. That word makes sense when you view this from the Mac App Store perspective. Back in the early days of the Mac App Store, some apps were allowed to use temporary exception entitlements because of limitations in the App Sandbox. Once App Sandbox was sufficiently enhanced, these temporary exception entitlements were no longer allowed in the Mac App Store. However, there’s nothing temporary about the implementation of these entitlements. They work today and are expected to continue working in the future. Using them in a directly distributed app is not a problem.
Non-sandboxed XPC services
Not all sandbox security limits have a corresponding temporary exception entitlement. For example, the sandbox prevents you from sending a Unix signal to other processes, and there’s no temporary exception entitlement to allow that.
If you run into such a limit, move that code to a non-sandboxed XPC service, then have the main app request that the XPC service perform the operation on its behalf.
An XPC service can be useful even when there is a temporary exception entitlement to disable a specific sandbox security limit. Continuing the Apple event example from above, if you put the code that sends the Apple event into an XPC service, you only need to apply the temporary exception entitlement to that service, not to your app as a whole.
Conclusion
If you directly distribute your app, consider enabling the App Sandbox. It has some important benefits, and it might be more feasible than you think.
Hello, our app is non-sandboxed app, but we do want to support widget extension and safari extension. Those extensions require sandboxing. Is it possible to do this without sandboxing our app? Thank you!
Hi. I'm trying to learn macOS app development. i'm trying to run unix commands:
func execute(_ command: String) throws -> String {
let process = Process()
let pipe = Pipe()
process.executableURL = URL(fileURLWithPath: "/bin/bash")
process.arguments = ["-c", command]
process.standardOutput = pipe
// process.standardError
try process.run()
process.waitUntilExit()
guard let data = try pipe.fileHandleForReading.readToEnd() else {
throw CommandError.readError
}
guard let output = String(data: data, encoding: .utf8) else {
throw CommandError.invalidData
}
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw CommandError.commandFailed(output)
}
return output
}
when try to run "pgrep" in sandbox mode ON, i get:
sysmon request failed with error: sysmond service not found error. if i turn it off it works. i don't know what to do. anyone can help me out?
The application search for the occurences of a string into files and folders.
Everything work fine until I enable sanbox. Then opendir(path_to_folder) report "Operation not permitted".
By example dp = opendir("/Users/alain/Desktop"); set dp to NULL for my own Desktop.
The application need only read access. How can I get this access ?
I’m attempting to make an app that uses Disk Arbitration to intercept a disk mount (by creating and returning a dissenter in the appropriate callback) and then mount the disk with certain options (specifically, read-only, nobrowse, or both, depending on user options). For example:
DADiskMountWithArguments(disk, nil, DADiskMountOptions(kDADiskMountOptionDefault), nil, nil, kReadOnly)
…where kReadOnly is a pointer to an array only containing a “rdonly” CFString.
While DADiskMountWithArguments seems to be usable in a sandboxed app for disk images, it doesn’t work when the disk is an external disk (e.g. connected via USB). I see lines like this in Console.app when this happens:
Sandbox denied authorizing right 'system.volume.external.mount' by client '/path/to/exe' [17934] (engine 580)
I’ve identified two workarounds that allow this to work in a sandbox, but both have their own problems:
If a LaunchDaemon (even a sandboxed one, which is required for registration with SMAppService.daemon from the sandboxed app) does the call to DADiskMountWithArguments, it will succeed. But App Store policies don’t allow escalation to root.
If I use the undocumented entitlement com.apple.security.temporary-exception.sbpl with a value of (allow authorization-right-obtain (right-name "system.volume.external.mount")), the mount works without escalation to root. But I understand that App Review is likely to reject the use of this entitlement, and that this entitlement isn't supported to begin with.
Specifically, these are the behaviors I see on macOS Sequoia 15.3.1 and Xcode 16.2.
Since I would like to try to publish this app on the App Store, neither of these seem like acceptable solutions.
I don’t see why this should be restricted if the sandboxed app is not declaring a special path (i.e. the path in DADiskMountWithArguments is set to nil) and still does not have access to the mounted filesystem - am I missing something/is there a way to accomplish this?
Topic:
App & System Services
SubTopic:
Core OS
Tags:
Entitlements
macOS
App Sandbox
Disk Arbitration
I am currently developing a No-Sandbox application.
What I want to achieve is to use AuthorizationCopyRights in a No-Sandbox application to elevate to root, then register SMAppService.daemon after elevation, and finally call the registered daemon from within the No-Sandbox application.
Implementation Details
Here is the Plist that I am registering with SMAppService:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.agent</string>
<key>BundleProgram</key>
<string>/usr/local/bin/test</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/test</string>
<string>login</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Code that successfully performs privilege escalation (a helper tool popup appears)
private func registerSMAppServiceDaemon() -> Bool {
let service = SMAppService.daemon(plistName: "com.example.plist")
do {
try service.register()
print("Successfully registered \(service)")
return true
} catch {
print("Unable to register \(error)")
return false
}
}
private func levelUpRoot() -> Bool {
var authRef: AuthorizationRef?
let status = AuthorizationCreate(nil, nil, [], &authRef)
if status != errAuthorizationSuccess {
return false
}
let rightName = kSMRightBlessPrivilegedHelper
return rightName.withCString { cStringName -> Bool in
var authItem = AuthorizationItem(
name: cStringName,
valueLength: 0,
value: nil,
flags: 0
)
return withUnsafeMutablePointer(to: &authItem) { authItemPointer -> Bool in
var authRights = AuthorizationRights(count: 1, items: authItemPointer)
let authFlags: AuthorizationFlags = [.interactionAllowed, .preAuthorize, .extendRights]
let status = AuthorizationCopyRights(authRef!, &authRights, nil, authFlags, nil)
if status == errAuthorizationSuccess {
if !registerSMAppServiceDaemon() {
return false
}
return true
}
return false
}
}
}
Error Details
Unable to register Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted}
The likely cause of this error is that /usr/local/bin/test is being bundled.
However, based on my understanding, since this is a non-sandboxed application, the binary should be accessible as long as it is run as root.
Trying
post as mentioned in the response, placing the test binary under Contents/Resources/ allows SMAppService to successfully register it. However, executing the binary results in a different error.
Here is the plist at that time.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.example.agent</string>
<key>BundleProgram</key>
<string>Contents/Resources/test</string>
<key>ProgramArguments</key>
<array>
<string>Contents/Resources/test</string>
<string>login</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Here is the function at that time.
private func executeBin() {
let bundle = Bundle.main
if let binaryPath = bundle.path(forResource: "test", ofType: nil) {
print(binaryPath)
let task = Process()
task.executableURL = URL(fileURLWithPath: binaryPath)
task.arguments = ["login"]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
do {
try task.run()
let outputData = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: outputData, encoding: .utf8) {
print("Binary output: \(output)")
}
task.waitUntilExit()
if task.terminationStatus == 0 {
print("Binary executed successfully")
} else {
print("Binary execution failed with status: \(task.terminationStatus)")
}
} catch {
print("Error executing binary: \(error)")
}
} else {
print("Binary not found in the app bundle")
}
}
Executed After Error
Binary output:
Binary execution failed with status: 5
Are there any other ways to execute a specific binary as root when using AuthorizationCopyRights?
For example, by preparing a Helper Tool?
Hello, I'm buiding a macos app where I bundled a command line tool (Python) with my app. I put the tool in ****.app/Contents/MacOS folder, but it seems like the tool can not execute/read/ access. I don't know if a sandbox app can access/create a folder inside ****.app/Contents folder???
If not where can I put the tool that can access from my macos app?
Any idea would be appreciated!