Posts Tagged ‘sandbox’

Sandbox in Mac OS X Lion and Apple’s App Store Submissions

Monday, November 7th, 2011

Note: For more information about the information contained in this article, contact us for a professional consultation.

In our previous tech journal article, we touched on the history of sandboxing, from its evolution out of the POSIX model to the more granular controls provided by the ACL model and how they are both derived from a concept called Discretionary Access Controls. For this discussion, please check out out previous article “A brief introduction to Mac OS X SandBox Technology.”

New Sandboxing & Privilege Separation in Lion

This article will attempt to clarify and explain the changes in Lion and iOS sandboxing and the upcoming change in requirements for App Store submissions.  Apple has decreed that all applications submitted to the App Store MUST be sandboxed, originally the deadline was November 2011, but the deadline has recently been moved back to March 1, 2012.

iOS sandboxing has been in place for a while now.  iOS applications can only see their own data and documents, cannot alter your devices underlying settings, and generally appear to be isolated from other apps on your iOS device.  Apple has brought this methodology to Macs with 10.7 Lion.

Compared to previous Mac OS security models, Lion has made leaps and bounds in terms of sandbox security, with Apple finally promoting the technology for use by third party developers.  The 2 ways of Apple has increased security is through Sandboxing and Privilege Separation.  Sandboxing refers to the process whereby a developer specifies a list of expected operations an application will perform, while Privilege Separation refers to splitting an application or daemon into more granular pieces where each piece is only given rights to its particular task.  Every sandbox application must include a set of “entitlements,” or a list of resources the application needs to perform its tasks.  Lion has around 30 entitlements ranging from low-level operations (e.g. creating or listening to network connections), to higher level operations (e.g. printing or accessing the camera).

Application Sandboxing

App Sandboxing can help prevent flaws or oversights in programming from becoming security threats via privilege escalation.  By specifying a set of entitlements, a developer tells the OS which operations are allowed and expected.  This way if a user process tries to perform a task that is not entitled, the OS will not allow the task.  This makes executing arbitrary code from a problem like a buffer overflow much less likely.  Listing entitlements also lets the system know to create a container directory for the application itself and runs it inside a sandbox configured for that particular application. If a developer creates an internet browser application and didn’t grant the entitlements to the camera and microphone, a website with malicious code trying to access the camera would be thwarted by the OS.

The container directory is where your sandboxed application can read and write its private files and data, including preferences, autosave info and other information needed by the application itself.  The sandboxed application is prevented from accessing data and files from outside the sandbox with a few exceptions, like the systems Open and Save dialog boxes, which require user intervention to explicitly work outside the sandbox. Upon first launch, the OS creates a container directory in ~/Library/Containers with the application bundle identifier as the directory name (e.g. com.apple.TextEdit).

Sandboxing an application is not a replacement for good coding practices or testing.  Indeed, sandboxing actually will increase the requirements for testing as each entitlement will need to be verified and tested, but it will provide a valuable line of defense against unanticipated malware or other nefarious activity.

App Store Sandboxing

While not being privy to behind the scenes discussions at Apple, the benefits of requiring Application sandboxing for App Store submissions are fairly intuitive. By requiring sandboxing, Apple will simplify its audit process and can more easily provide security assurances for App Store purchases.  Ars Technica seems to confirm this as well.   By sandboxing all Apps, Apple will greatly reduce the potential for rogue code coming out of the App Store, thereby reducing their potential liability.

Adding Sandboxing to your applications in Xcode

To sandbox an application in Xcode, you will need a couple of things. One is a valid code signing certificate issued by a trusted third certification authority (think Verisign, Thawt or Digicert).  Self-signed certificates won’t work as your Certificate Authority (CA) credentials are not included in either the Mac OS or iOS.  The CA root certificate allows a chain of trust to be built to your code signing certificate. Apple has more info on their Root Certificate program here.

An entitlements .plist, named Info.plist.  You will add this file in your project in Xcode.  The Info.plist must have the following Keys:  CFBundleIndentifier, CFBundleName.  The identifier MUST be globally unique.  To help ensure this, please include your company’s name in the indentifier (e.g. com.318.OurLatestApp).  Apple recommends that the identifer be in reverse DNS notation as well.  Your Info.plist must include all the entitlements your application needs.

In Xcode, please add the following linker flags:

-sectcreate __TEXT __info_plist Info.plist_path

where Info.plist_path is the complete path of the Info.plist file in your project.

These flags should be added to the OTHER_LDFLAGS build variable in Xcode.  Please refer to the documentation for other development environments.

You will also need to go into the summary tab for your Xcode project and check

  • Enable Entitlements
  • Enable App Sandboxing

A comprehensive guide to code signing and entitlements is available from Apple here.

Wrapup

Apple’s new paradigm for security will provide additional protection from malicious code.  This new paradigm will necessitate some additional planning and testing.  It will allow Apple to better ensure that any App from the App Store will not harm your computing experience. Apple has a list of entitlements that must be used, but you must be a developer to access this content. In the writing of this article we have attempted to be cognizant of what is and is not under non-disclosure, so if you need access to that, then please grab a free account at the Apple Developer Connection.

A brief introduction to Mac OS X SandBox Technology

Thursday, April 17th, 2008

Note: For more information about the information contained in this article, contact us for a professional consultation.

In all versions of OS X previous to Leopard, access control restrictions were limited to a security model referred to as Discretionary Access Controls (DAC). The most visible form of DAC in OS X is in it’s implementation of the POSIX file-system security model, which establishes identity-based restrictions on an object in the form of a subject’s user or group membership. Similarly Access Control Lists are a form of discretionary control, though they are far more extensible and discrete then the POSIX model. In such models,  newly created objects or processes inherit their access rights based upon those of the creating subject, so that any spawned objects are not granted access rights beyond that of their creating subject. The key idea behind the DAC model is that the security of an object is left to the discretion of the object’s owner; an object’s owner has the ability to assign varying levels of access control to that object within the confines of the DAC implementation. The DAC model has for decades been a staple in the management of both object/process creation and access across all mainstream computer systems due to it’s user-centric nature. However there is a persistent caveat in these implementations;  in all mainstream implementations of such models, there exists a superuser which has the capabilities to completely bypass access restrictions placed on objects. In POSIX-based Operating Systems such as Unix, Linux, or OS X, this superuser exists in the form of the root user. The existence of such a loophole presents a bit of a paradox. On one hand, it introduces several obvious security ramifications by providing capabilities to completely bypass the DAC model all together; any processes which are invoked by the superuser inherit the “god mode” access controls, they have free reign over the entire system. At the same time, the existence of the superuser account becomes a vital tool for the practical administration of data objects and system resources. In a perfect world, this wouldn’t necessarily be a bad thing. Unfortunately that’s not the world we live in, and it is not uncommon to hear about processes being hijacked for ill-will. If the compromised process has been invoked by the superuser, then the entire system has been compromised, including all user data with it. 

With 10.5 Leopard, Apple has introduced a new low-level access control model into their OS, based upon the mandatory access control (MAC) model. Conceptually, the MAC system implements restrictions based upon actors, objects, and actions. In such a system, the actor typically assumes the form of a process, thread, or socket. The object can be any type of resource, such as a file, directory, socket, or even a TCP/UDP network port, among others. The action is simply the request of the actor to be applied to the respective object, and varies depending on the type of object involved in the request. Referring back to the file system model; the actor would be a word processor, the object would be a .txt flat file, and the action would be a call to either read to or write to that text file. When the actor requests access to the object, the MAC authorization system evaluates security policies and decides whether the request can proceed, or if it should be prohibited. In a pure MAC model, the object or process ownership is not generally a consideration; individual users do not have the ability to override defined policy. 

Leopard enforces the MAC model via a new framework, architected from TrustedBSD’s MAC framework. This framework introduces “sandbox” access control capabilities which allow a developer or user to apply access control policies to a process, restricting privileges to various specified system resources. The restrictions are generally enforced upon acquisition, so any active file descriptors would not be immediately affected by any policy changes, however, any new open() operations would be subject to the new restrictions. In a fashion similar to the DAC model, new processes and forks will inherit the access restrictions of their parent. In Leopard, these restriction policies can be pre-compiled into any given program, or they can be applied to any executable at runtime. 

While Leopard’s MAC framework is based off of TrustedBSD’s,  it’s implementation deploys only a subset of control points provided by the TrustedBSD implementation. Noticeably absent are the majority of the Security Policy Modules available for TrustedBSD and FreeBSD implementations, such as Biba, MLS, or NSA’s FLASK/TE (implemented in SEDarwin), though perhaps some day we’ll see some of these ported to Leopard’s MAC framework.  For now, Apple has offered their own Security Policy Module dubbed “Seatbelt”, which is implemented as a KEXT installed at /System/Library/Extensions/seatbelt.kext.  As of 10.5.2, the feature set of Seatbelt seems to be very much in flux. The only documented way to apply these controls in code is via the sandbox_init() function. Utilizing this function in code provides a way for an application programmer to voluntarily restrict access privileges in a running program. sandbox_init() is very limited at this point, providing only 5 pre-defined constants: 

• kSBXProfileNoInternet  – disables TCP/IP networking.
• kSBXProfileNoNetwork – disables all sockets-based networking
• kSBXProfileNoWrite – disables write access to all filesystem objects
• kSBXProfileNoWriteExceptTemporary – disables write access to filesystem objects except /var/tmp and `getconf DARWIN_USER_TEMP_DIR`
• kSBXProfilePureComputation – all OS services are restricted

An application can utilize one of these constants to restrict capabilities in spawned processes or threads, minimizing the potential damage that can occur in the event that the process is compromised. Figure 1 shows an example implementation of the kSBXProfileNoWrite profile in code:

Figure 1.

#include
#include
#include
#include

int main()
{
int sb, fh;
char **errbuf;
char rtxt[255];
char wtxt[255] = "Sandboxed you aren't\n\n";

// init our sandbox, if we don't return 0 then there's a problem
sb = sandbox_init(kSBXProfileNoWrite, SANDBOX_NAMED, errbuf);
if ( sb != 0 ) {
        printf("Sandbox failed\n");
return sb;
};

fh = open("test.txt", O_RDONLY);
if ( fh == -1 ) {
perror("Read failed");
} else {
read(fh, rtxt, 255);
close(fh);
printf("FileContents:\n %s\n", rtxt); 
};

fh = open("test.txt", O_RDWR | O_CREAT, 0000644);
if ( fh == -1 ) {
perror("Write Failed");
} else {
write(fh, wtxt, strlen(wtxt));
close(fh);
printf("Successfully wrote file!\n");
}

return 0;
}

Compiling and running this code returns the following results:
% ./sandBoxTest
FileContents:
 hello              

Write Failed: Operation not permitted

So, even though our POSIX permissions allows for read/write access to the file, the sandbox prevents it, regardless of user. Running the program even with root privileges yields the same results. 

Currently, the options provided by Apple are very all-or-nothing, particularly in the area of file system restrictions. In this way, Seatbelt acts more as a clumsy broadsword, lopping off functionality in large chunks at a time for the sake of security. In this form, Seatbelt has minimized use outside of very vertical applications or the increasingly rare applications that don’t utilize network communication in one way or another. Though these limitations will significantly limit widespread adoption, I believe it would be a mistake for a developer to shrug off Seatbelt as a whole.

Luckily, Seatbelt has an alternate application, though currently it is not officially supported. As I mentioned earlier, it is possible to apply sandbox restrictions to any pre-complied executable at runtime. This is done via the sandbox-exec binary, and uses predefined profiles housed at /usr/share/sandbox which provide for fine-grained control of resources. These profiles use a combination of allow/deny rules in combination with regular expressions to specify system resource access. There are numerous control points, such as network sockets, signals, sysctl variables, forking abilities, and process execution, most of which can be tuned with fairly decent precision by utilizing a combination of regex and static inclusion sets. Filesystem objects and processes are identified via POSIX paths; there currently is no target validation performed ether via checksums or digital signing.  

Figure 2 shows a sample sandbox profile that can be applied to restrict an application from making outbound communications and restricts file system writes to temporary directories and the user’s preferences folder. The ‘debug deny’ line tells seatbelt to log all policy violations. This proves to be very useful in determining filesystem and network activity by an untrusted program. It facilitates a quick-and-easy way to do basic forensic testing on any program acquired from an untrusted source. Figure 3 shows example log violations of a network-outbound violation, and of a file-write violation, respectively.

To apply a sandbox profile to a standard application bundle you must pass sandbox-exec the path of the mach-o binary file which is typically located in ‘Contents/MacOS/’, relative to the application’s bundle. You can specify a sandbox profile by name using the -n flag if the profile resides in /usr/share/sandbox, or you can specify a full path to a profile with the -f argument. Carbon applications may require the LaunchCFMApp wrapper to properly execute. See figure 4 for example syntax for both Cocoa and Carbon Applications.

Figure 2. Example sandbox profile

(version 1)
(debug deny)
(allow default)
(allow process*)
(deny network-outbound)

(allow file-read-data file-read-metadata
  (regex "^/.*"))
(deny file-write*
        (regex "^/.*"))
(allow file-write*
        (regex "^/Users/johndoe/Library/Preferences.*"))
(allow file-write* file-read-data file-read-metadata
  (regex "^(/private)?/tmp/"))

(import "bsd.sb")

Figure 3. Example log entries from TCP and filesystem write violations

3/4/08 12:15:10 AM kernel dig 79302 NET_OUTBOUND DENY l= unavailable r= 4.2.2.2/domain UDP 1 (seatbelt) 
3/4/08 12:43:05 AM kernel sh 79147 FS_WRITE_DATA SBF /Users/Shared/test.txt 13 (seatbelt) 

Figure 4. Using launchd to sandbox cocoa and carbon applications.  

Cocoa

% sandbox-exec -n localonly /Applications/TextEdit.app/Contents/MacOS/TextEdit

Carbon

% sandbox-exec -n localonly /System/Library/Frameworks/Carbon.framework/Versions/A/Support/LaunchCFMApp /Applications/Microsoft\ Office\ 2004/Microsoft\ Word

Unfortunately, the system seems to be far from finalized, and even some example profiles provided by Apple do not seem to be completely functional, or contain unimplemented control points. One example of this is seen when trying to implement IP-based network restrictions. Apple provides example entries for layer3 filtering in the included profiles, but they are commented-out and illicit a syntax error when ran. Additionally, Apple has a rather ominous warning in each of it’s provided profiles, stating that current profiles are deemed to be Apple System Private Interfaces, and may change at any time.

However, that’s no reason to completely ignore the technology. Given what has currently been implemented, and taking into consideration control points which are alluded to by Apple’s own imbedded comments, Seatbelt is showing significant promise to provide very fine-grained resource access capabilities. By utilizing these restrictions, applications and users can ensure that even in a worst-case scenario, possibilities for errant/hijacked process damage becomes mitigated and compartmentalized. There are many real-world situations where this type of access control model fits very well, particularly in complement to standard DAC systems: they can be used to mitigate privilege escalation opportunities for shell users, to confine behavior conformance of processes to defined resources (and there by protect against hacked processes), or as a forensic tool to determine software malfeasance. By providing these type of capabilities through the Seatbelt policy module, and by providing a path towards implementing more complex MAC policy modules, Leopard’s new MAC framework ushers in a new level of security and access control capabilities for OS X.