0% found this document useful (0 votes)
8 views39 pages

HITSB

The document discusses the evolution of Apple's sandboxing technology, starting from its initial implementation in Mac OS 10.5 to its current state in iOS and MacOS. It highlights the significant improvements in security features, including mandatory sandboxing for third-party applications and the introduction of System Integrity Protection. The document also outlines the technical details of the Mandatory Access Control Framework and the various sandbox profiles used in both MacOS and iOS.

Uploaded by

mikuya233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views39 pages

HITSB

The document discusses the evolution of Apple's sandboxing technology, starting from its initial implementation in Mac OS 10.5 to its current state in iOS and MacOS. It highlights the significant improvements in security features, including mandatory sandboxing for third-party applications and the introduction of System Integrity Protection. The document also outlines the technical details of the Mandatory Access Control Framework and the various sandbox profiles used in both MacOS and iOS.

Uploaded by

mikuya233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Hack in the (sand)Box

(The Apple Sandbox - five years later)

Jonathan Levin
http://NewOSXBook.com/
http://technologeeks.com

(C) 2012, 2016 Technologeeks.com


Intro

The Apple Sandbox


• Introduced way back in Mac OS 10.5 as “Seatbelt”
– Very naive implementation originally, bypassed and opt-in

• Revamped in Mac OS 10.7 as “The App Sandbox”


– Stronger implementation, introducing containers
– Opt-in for Apple’s own binaries and apps
– Mandatory for Mac App Store apps (but not for DMG based)

• Far stronger still in iOS


– Mandatory for all third party applications
– Evolved beyond MacOS implementation

(C) 2012, 2016 Technologeeks.com


Intro

Sandbox versions
Version OS Version Notable Features
.. OS X 10.5/iOS 1-3 Initial version, white list approach
.. OS X 10.6/iOS 4
165 OS X 10.7/iOS 5 Basic containers
220 OS X 10.8/iOS 6 Sandbox exceptions
278-300 OS X 10.9/iOS 7 IOKit get property, vnode renaming
358 OS X 10.10/iOS 8 Rootless (introduction, non-enforcing), get-task,
AMFI integration (in OS X version), kexts (kind of)
460 OS X 10.11/iOS 9 Rootless enforcement, container manager
Host special ports, kexts, OSX NVRAM finally protected
Policy moved to __DATA.__const (iOS 9.2)
592 OS X 10.12/iOS 10 Container Manager enforcement (iOS)
User data items

(C) 2012, 2016 Technologeeks.com


Intro

So Why Are We Here?


• Last actual research conducted in 2011:
– Dionysus Balazakis seminal work - “The Apple Sandbox”

• Very little further research – partial, unpublished or both

• Sandbox has evolved by leaps and bounds


– Further evolves in iOS 10 and MacOS 12
– Provides “System Integrity Protection” as of MacOS 11 (not yet iOS)

• Provides first, strongest, and sometimes last line of defense


– Tons of exploitable bugs in services and kexts blocked by sandbox
– Breaking out of the sandbox is toughest stage of jailbreaking.
– ... And eight of you here voted for this talk ☺

(C) 2012, 2016 Technologeeks.com


Intro

Plan
• Prerequisite: MACF
• MacOS (“App Sandboxing”)
• *OS (Containers)
• Reversing (MacOS, iOS implementations)
• Sandbox APIs

You’re welcome to follow along:


http://NewOSXBook.com/articles/hitsb.html

(C) 2012, 2016 Technologeeks.com


MACF

Prerequisite: MACF
• Mandatory Access Control Framework serves as substrate
– XNU’s implementation modeled after FreeBSD’s
– Compare - SELinux/SEAndroid

• Simple idea, powerful impact:


– Kernel extensions provide a “policy” and call mac_policy_register
– Policy contains “hooks” (callbacks)
– Depending on process label, callbacks get invoked
– Kernel extension gets to inspect operation arguments
– Return 0 to allow, non-zero to thwart operation
– All registered hooks must allow operation.

(C) 2012, 2016 Technologeeks.com


MACF

MACF Policy Hooks Policy module may perform


upcalls to user mode lackey
Only if all MACF modules
approve, syscall/mach_trap will
be executed
User Mode Daemon
User mode process

Process perfoms a system call


(or mach trap)

sysent/mach_trap_table MACF calls out to


interested policies
Corresponding function in
kernel is called from table

Policy Module
Syscall/trap #n
Function calls out to Mandatory
Access Control Framework Policy module inspects
operation, and allows or
denies

MACF Additional Policy


Module...
MACF checks if any policy modules
requested to hook the particular functionality
in their policy
MACF

MACF Policy Modules


• Serves as basis for virtually all of Apple’s OS Security
• Currently 5 known policy modules:
Kext Oses # Ops Purpose
Quarantine MacOS ~15-17 Gatekeeper. Sort of.
MCXALR MacOS 1 Managed Client Extensions (MDM/Parental Controls)
TMSafetyNet MacOS ~26 TimeMachine hooks on file access
AMFI All (OSX >=10.10) ~8-13 Enforce code signing, some entitlements & Mach ports
Sandbox All 130+ Confine, strangle and block Applications at every turn

• Labels can define which policy, if any, will take effect


– Process can be execed into label with mac_execve(#380)
– posix_spawnattrs can similarly enforce sandbox
– Sandbox has own spawnattrs (for specific container or profile)
(C) 2012, 2016 Technologeeks.com
Sandbox

Sandboxing
• Original sandbox approach – “seatbelt” – opt in:
– You’d have to ask to confined (like, want to go to jail!)
– Like its namesake, most people find it borderline troublesome.

• Contemporary sandbox approach is radically different:


– You are either containerized or you are not:
• Voluntary: because you are a responsible developer
• Semi-voluntary: Code signature or location (Apple controlled)
• Non-voluntary: Based on install location (*OS)

– If containerized, Sandbox intercepts all important operations


• Definition of important keeps increasing to include more..
• Operation assessed versus a profile, or entitlements

(C) 2012, 2016 Technologeeks.com


App Sandbox

MacOS : App Sandboxing


• Sandbox no longer requires sandbox_init – but signature
– This way Apple, not developer, can enforce sandboxing
– In iOS, /var/mobile/Containers/Bundle location auto-sandboxes

• In MacOS, com.apple.security.app-sandbox sandboxes

• com.apple.application-identifier for container


– Otherwise defaults to CFBundleIdentifier from App’s Info.plist

• com.apple.application-groups (~10.7.5, 10.8.3 and later)


– ~/Library/Group Containers/…

(C) 2012, 2016 Technologeeks.com


App Sandbox
1) Process loads libSystem.B

libSystem.B.initializer

libdispatch_init

2) libSystem Initializer calls libsecinit


4) Securityd decides whether or not
libsecinit_initializer process needs to be sandboxed
3) Libsecinit registers with securityd

libsecinit_initialize_once <key>SECINITD_REGISTRATION_MESSAGE_SHORT_NAME_KEY</key>
<string>TextEdit</string>
<key>SECINITD_REGISTRATION_MESSAGE_IS_SANDBOX_CANDIDATE_KEY</key>
<bool>true</bool>
_libsecinit_setup_secinitd_client <key>SECINITD_REGISTRATION_MESSAGE_ENTITLEMENTS_DICT_KEY</key>
<dict> ... Entitlement dictionary</dict> s
e
xpc_copy_entitlements_for_pid c
i
n
xpc_pipe_routine <key>SECINITD_REPLY_MESSAGE_CONTAINER_ID_KEY</key> i
<string>com.apple.TextEdit</string> t
<key>SECINITD_REPLY_MESSAGE_QTN_PROC_FLAGS_KEY</key>
<integer>10</integer>
d
_libsecinit_setup_app_sandbox <key>SECINITD_REPLY_MESSAGE_CONTAINER_ROOT_PATH_KEY</key>
<string>/Users/morpheus/Library/Containers/com.apple.TextEdit/Data“</string>
<key>SECINITD_REPLY_MESSAGE_SANDBOX_PROFILE_DATA_KEY</key <data>
0x00003a014c004d0.. Compiled sandbox profile...</data>
__sandbox_ms <key>SECINITD_REPLY_MESSAGE_VERSION_NUMBER_KEY</key>
<integer>1</integer>
<key>SECINITD_MESSAGE_TYPE_KEY</key>
5) If decision is affirmative, libsecinit <integer>2</key>
voluntarily imposes sandbox on process <key>SECINITD_REPLY_FAILURE_CODE</key>
<integer>0</key>
App Sandbox

MacOS : App Sandboxing


• Containers created at ~/Library/Containers/{CFBundleIdentifier}
• All Structured the same way:
– Container.plist: metadata (in bplist00 format)
• Identity (Unicode, Base64)
• Compiled profile (SandboxProfileData, base64)
• SandboxProfileDataValidationInfo (long dict...)
• Version (36 = MacOS 10, 38 = MacOS 11, 39 = MacOS 12)
– Data: Directory structure, mimicking user’s home directory:
• .CFUserTextEncoding
• Documents
• Library
• Music
• Desktop
• Downloads
• Movies
• Pictures (C) 2012, 2016 Technologeeks.com
App Sandbox

MacOS : App Sandboxing


• Data directories are often symbolic links(!)
– SandboxProfileDataValidationRedirectablePathsKey limits links

• Metadata also holds entitlements, and other parameters


– SandboxProfileDataValidationEntitlementsKey
– SandboxProfileDataValidationParametersKey

(C) 2012, 2016 Technologeeks.com


iOS Sandbox

iOS: Containers

• Also allows for shared containers


– Apps with same team-id can share data
(C) 2012, 2016 Technologeeks.com
iOS 10

iOS 10 Containers

(C) 2012, 2016 Technologeeks.com


iOS 10

iOS: Containers
• The sandboxd has been entirely removed in iOS as of 9.x
– Still used in MacOS, primarily for tracing

• New daemon – containermanagerd – takes over


– Part of MobileContainer private framework
– Communicates with user mode (installd, etc) over XPC port
– Communicates with kernel mode (kext) over Special Port #25
• MIG message 0x13392fd4 (322514900)
• Contains sb_packbuff payload of kernel requests

(C) 2012, 2016 Technologeeks.com


iOS Sandbox

AMFI
• Sandbox and AMFI make good bedfellows
• AMFI ensures signature, provides entitlement services
• Sandbox depends on AMFI (as of 358 in MacOS)
morpheus@Zephyr(~)$ kextstat
19 2 0xffffff7f8100f000 0xd000 0xd000 com.apple.driver.AppleMobileFileIntegrity (1.0.5) <7 6 5 4 3 2 1>
22 2 0xffffff7f8101c000 0x5000 0x5000 com.apple.kext.AppleMatch (1.0.0d1) <4 1>
23 1 0xffffff7f81021000 0x17000 0x17000 com.apple.security.sandbox (300.0) <22 19 7 6 5 4 3 2

• iOS Sandbox uses specific entitlements:


– seatbelt-profiles – assign a particular profile to binary
– com.apple.private.security.container-required - Sandboxes built-in apps

(C) 2012, 2016 Technologeeks.com


Reversing

Deconstructing Sandbox
• MacOS Sandbox.kext can serve as a good reference
– Largely same codebase, with some differences, but symbolicated

• Joker can auto-symbolicate plenty*:


– Stubs to kernel functions
– Entire MACF Policy (120+ functions!)

• Can get other functions (no names, yet) with jtool:


– grep BL.*0x | cut –dx –f2 then feedback to companion file
– About 150 additional functions revealed by this method

• Important functions (e.g. smalloc, sfree) yield rest.


– Hook_policy_syscall especially important (for mac_policy_syscall)

* - Joker 3 can now handle split kexts from XNU 3750+!


Reversing

Sandbox MACF Policy Hooks


• Most MACF Policy hooks call cred_sb_evaluate
– 1st argument (in R0/X0/RDI) is MACF’s
– 2nd argument (in R1/X1/ESI) encodes operation number

(C) 2012, 2016 Technologeeks.com


Reversing

Sandbox MACF Policy Hooks


• Operation numbers correspond to hard-coded names

– Can also be found in older libsandbox.1.dylib


• Removed (precompiled) into 570+

– Names can be found in kext’s __DATA__CONST.__const


• Not going away since they are needed for APIs

– There are more operations than there are MACF hooks


• Some are callable from user mode by apps (e.g. AppleEvents, TCC)

(C) 2012, 2016 Technologeeks.com


Reversing

Sandbox MACF Policy Hooks


• cred_sb_evaluate calls sb_evaluate
– 1st parameter is sandbox obtained from label_get_sandbox
– Operation as 2nd Parameter
– Buffer as 3rd Parameter

(C) 2012, 2016 Technologeeks.com


Reversing

Sandbox MACF Policy Hooks


• cred_sb_evaluate derives credentials, and calls eval *
– May or may not report sandbox violations (based on argument to check)

• Evaluation first attempted against platform_profile


• Can default to specific process-defined (container) profile

* - MacOS implementation slightly different (includes csr_check, etc). iOS also inlines eval_filter into eval
Profiles

Reversing Profiles
• Sandbox Profiles are written in tinyScheme (UGH!)
– In MacOS – plaintext, in /System/Library/Sandbox/Profiles
• Per framework profiles also exist for Apple’s frameworks
– in iOS – compiled & built-in!

• The gist:
– (version 1) (only version supported)
– (deny default) (least privilege)
– (allow ……) (selectively allow APIs)
– (deny ……) (selectively disallow APIs)

• Can apply and trace using sandbox-exec:


(version 1)
(trace "/tmp/appTrace.sb")

(C) 2012, 2016 Technologeeks.com


Profiles

Sandbox-exec
• Simple binary (300-500 lines of ASM)
morpheus@Zephyr (~)$ sandbox-exec
Usage: sandbox-exec [options] command [args]
Options:
-f profile-file Read profile from file.
-n profile-name Use pre-defined profile.
-p profile-string Specify profile on the command line.
-D key=value Define a profile parameter.
Exactly one of -f, -n, -p must be specified.

• MacOS 11 adds undocumented “-t” for tracing


– Tracing broken in iOS with the removal of sandboxd

• Closed source – but....


– Fully compatible clone at http://NewOSXBook.com/tools/sob.html
– Wil l also dump compiled profile in /tmp
– Provides first implementation of sandbox-exec for iOS!

(C) 2012, 2016 Technologeeks.com


Profiles

Built-in Profiles
• MacOS originally had 4 “built-in” profiles
– Weren’t so useful in the first place and largely deprecated
• iOS extends that to dozens of profiles
– Can be found in kext
– Can also be found in iOS’s libsandbox.1.dylib
• AGXCompilerService ... wifiFirmwareLoader

• Built-in profiles are precompiled


– Originally, maintained by sandboxd
– In iOS 9+, maintained inside kext (__TEXT.__const)

(C) 2012, 2016 Technologeeks.com


iOS Containers

Containerizing Applications (iOS)


mpo_cred_label_update_execve hook MACF calls sandbox, because it registered hook

amfi_copy_seatbelt_profile_names Get <seatbelt-profiles> entitlement, if any

PE_I_can_haz_debugger Allows debug_mode (if boot arg was set, non-issue)

get_signing_identifier Gets application-identifier (from entitlement)

get_container_required_entitlement Get com.apple.private.security.container-required ent

check sandbox spawnattrs Several validations on spawn attributes

Upcall to container manager


(C) 2012, 2016 Technologeeks.com
iOS Containers

Containerizing Applications (iOS)


Validate container name No null bytes, special cases for plugins, keyboard, etc..

builtin_sandbox_create Create a sandbox object, from a builtin (precompiled) profile

platform_set_container Create com.apple.sandbox.containe Sandbox Extension

Create executable extension Allow App to access and launch own executable

cred_set_sandbox Attach sandbox struct to kauth credentials

Revoke privileged ports Remove access to dangerous Mach Ports

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox APIs
• Sandbox usermode APIs provided by two libraries:
– /usr/lib/system/libsystem_sandbox.dylib
• Re-exported by LibSystem.B.dylib
• Mostly direct APIs to kext

– /usr/lib/libsandbox.1.dylib
• Profile compilation
• TinyScheme implementation statically linked in
• Plenty of Scheme strings/profile definitions in __TEXT.__const

• Containment (often) performed over mac_execve()


• KEXT APIs invoked over macf_syscall()

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox APIs
• mac_syscall (#381) used extensively:

– Allows ioctl(2) style multiplexing of syscalls provided by a kext

– Generic mechanism, used by all policy modules

– On kext end, hook_policy_syscall enables multiplexing

– Different offerings in MacOS and *OS

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox APIs
• Syscall implementations differ in between OSes, versions!
Op Sandbox function Purpose
0-1 _set_profile[_builtin] Set a profile (=label & containment) of a process

2 _check Check if operation is allowed in confines of sandbox

3 _note Attaches a note (memory buffer) to sandbox (offset 0x80)

4 _container_path_for_pid Retrieve container path for a given PID

5-7 _extension_issue/consume/release Issue, apply and remove a temporary exception

8-9 _extension_update_file[_with_new_type] Update/twiddle extension

10-11 _suspend/unsuspend Suspend/resume sandbox checks for PID*

13-15 _policy_syscall related... iOS, routed to container manager

16 _inspect Dump tons of great information on SB.

17 profile_dump Dumps compiled profile for a PID (MacOS, AppleInternal** )

19 _vtrace[|enable|disable|report] Trace operation to a buffer. Not on iOS

21 _rootless_allows_task_for_pid Does current policy allow task_for_pid call?

• Get a more accurate list with jtool’s switch detection (ARM64)


* - Don’t get excited. Process can only do it on itself, if entitled as a sandbox-manager *and* another exception entitlement..
** - csr_check(0x01) – can be tweaked via direct access to NVRAM
User-Mode APIs

Sandbox APIs
• sandbox_check especially useful:
– Widely used in tweaks to gauge sandbox restrictions
– Commonly used with SANDBOX_CHECK_NO_REPORT
• Performs check silently, without any user-mode output

• Really useful for probing container XPC/file restrictions


– Much more reliable than decompiling!
• Sandbox 570+ adds sandbox_check_bulk
(C) 2012, 2016 Technologeeks.com
User-Mode APIs

Demo: sbtool

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox APIs - undocumented


• sandbox_inspect_pid super useful, but undocumented:
– Available in *OS as of somewhere in 460 (iOS 9.something)
int sandbox_inspect_pid(int pid, /* in */
char **buf, /* out */
int *size); /* out */

– Implemented via __sandbox_ms (..., 0x10);


– Very valuable information on process, directly from kext

• Requires root privileges (or AppleInternal build)

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Demo: sbtool

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox Extensions
Extensions allow exceptions to a given profile

iOS apps get the “standard extensions”:


- com.apple.sandbox.executable
- com.apple.sandbox.container
- com.apple.sandbox.application-group

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox Extensions
Apple’s App provide even more extensions for themselves:

Extension
com.apple.security.exception.shared-preference.read-write
com.apple.sandbox.application-group
com.apple.tcc.kTCCServiceAddressBook
com.apple.sandbox.executable
com.apple.app-sandbox.read
com.apple.security.exception.mach-lookup.global-name
com.apple.security.exception.iokit-user-client-class
com.apple.security.exception.files
com.apple.sandbox.container

(C) 2012, 2016 Technologeeks.com


User-Mode APIs

Sandbox Extensions
• Before sandboxing, caller can set extensions (unless forbidden)

• Extensions are issued by sandbox kext as “tokens”


• Hmac_sha1 with secret value (not exposed to user space)

(C) 2012, 2016 Technologeeks.com


Summary

Take Aways
• If you’re even loosely interested in OSX/iOS:
– The sandbox is the first, possibly last line of security
– In iOS, provides the most important obstacle to jailbreaking
– In MacOS, containerizes AppStore Apps, and implements SIP

• http://NewOSXBook.com/articles/hitsb.html
– Source of sandbox_exec clone
– Sbtool – open source
– Ongoing documentation on profile reversing
– Fully symbolicated companion file for iOS 10 kext

(C) 2012, 2016 Technologeeks.com


Suggested Links
• http://NewOSXBook.com/ - MOXiI, 2nd Edition
– Volume III (Security & Insecurity) available for pre-order!

• http://NewOSXBook.com/forum - Open forum for MOXiI

• http://Technologeeks.com/OSXRE - Related Training

(C) 2012, 2016 Technologeeks.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy