;;; Copyright (c) 2017 Apple Inc.  All Rights reserved.
;;;
;;; WARNING: The sandbox rules in this file currently constitute
;;; Apple System Private Interface and are subject to change at any time and
;;; without notice.
;;;

(version 1)
(import "system.sb")
(import "contacts.sb")

;;; Denials

;; Swap these in for debugging
; (allow (with report) default)
; (allow (with report) file-map-executable iokit-get-properties process-info* nvram*)
; (allow (with report) dynamic-code-generation)

(deny default)
(deny file-map-executable iokit-get-properties process-info* nvram*)
(deny dynamic-code-generation)

;;; Constants

(define home-directory-path  (param "HOME_DIR"))
(define temp-directory-path  (param "TEMP_DIR"))
(define cache-directory-path (param "CACHE_DIR"))

(define address-book-directory-path         "/Library/Application Support/AddressBook/")
(define applications-directory-path         "/Applications/")
(define education-configuration-path        "/Library/Apple Education Configuration/")
(define keychain-check-path                 "/private/var/run/systemkeychaincheck.done")
(define keychains-directory-path            "/Library/Keychains/")
(define library-caches-directory-path       "/Library/Caches/")
(define login-keychain-db-path              "/Library/Keychains/login.keychain-db")
(define private-temp-directory-path         "/private/tmp/")
(define private-var-folders-directory-path  "/private/var/folders/")
(define security-plist-path                 "/Library/Preferences/com.apple.security.plist")
(define studentd-data-directory-path        "/Library/studentd/")
(define system-applications-directory-path  "/System/Applications/")
(define system-keychain-path                "/Library/Keychains/System.keychain")

(define studentd-signing-id "com.apple.studentd")

;; Helpers

(define (temp-directory-subpath temp-relative-subpath)
  (subpath (string-append temp-directory-path temp-relative-subpath)))

(define (home-directory-subpath temp-relative-subpath)
  (subpath (string-append home-directory-path temp-relative-subpath)))

;;; Permissions

(contacts-client home-directory-path temp-directory-path)

(system-network)

(allow network-outbound
  (literal "/private/var/run/mDNSResponder")
  (control-name "com.apple.network.statistics")
  (control-name "com.apple.netsrc")
  (remote tcp "*:3283" "*:3284" "*:3285") ; These are the Classroom ports
  (remote ip "*:80" "*:443") ; studentd needs to connect to apple.com
  (remote ip "*:2000")) ; studentd needs to fetch user photos from internal test servers

(allow network-inbound
  (local ip "*:3284")) ; studentd hosts files on this port for Classroom AirDrop

(allow process-info-pidinfo (target self))
(allow process-info-dirtycontrol (target self))
(allow process-info-setcontrol (target self))

(allow distributed-notification-post)

(allow lsopen)

(allow file-read* file-write*
  ; Files received from teachers need to be moved to a hidden folder inside the Downloads
  ; folder so the AirDrop UI can see them. Once the user accepts the transfer, the files
  ; need to be moved from the hidden folder to the top level of the Downloads folder.
  (home-directory-subpath "/Downloads/")
  
  ; The Contacts framework requires readwrite access to the AddressBook, even though
  ; studentd only needs to read it (for the "me card"). See rdar://problem/54057889.
  (home-directory-subpath address-book-directory-path)
  
  ; Path to Apple Education Configuration to perform migration and remove that directory
  (home-directory-subpath education-configuration-path)
  
  ; App group library
  (extension "com.apple.sandbox.application-group"))

;; Sandbox Extensions
(allow file-read*
  (extension "com.apple.app-sandbox.read")) ; sharingd gives studentd sandbox extensions for files sent over Classroom AirDrop

(allow file-read*
  (home-directory-subpath keychains-directory-path)
  (home-directory-subpath library-caches-directory-path)
  (home-directory-subpath login-keychain-db-path)
  (home-directory-subpath studentd-data-directory-path)
  (literal "/Library/Application Support/CrashReporter/SubmitDiagInfo.domains")
  (literal "/Library/MessageTracer/SubmitDiagInfo.default.domains.searchtree")
  (literal "/Library/Preferences/SystemConfiguration/preferences.plist") ; Used to look up network interfaces and determine their IP addresses
  (literal "/private/var/db/ConfigurationProfiles/Settings/.profilesAreInstalled")
  (literal "/private/var/db/mds/messages/501/se_SecurityMessages")
  (literal "/private/var/db/mds/system/mdsDirectory.db")
  (literal "/private/var/db/mds/system/mdsObject.db")
  (literal system-keychain-path)
  (subpath applications-directory-path)
  (subpath private-temp-directory-path)
  (subpath private-var-folders-directory-path)
  (subpath system-applications-directory-path))

(allow file-read-metadata
  (home-directory-subpath security-plist-path)
  (literal "/private/var/db/.AppleSetupDone")
  (literal home-directory-path)
  (literal keychain-check-path)
  (literal security-plist-path))

(allow file-read-data
  (home-directory-subpath security-plist-path)
  (literal "/Library/Audio/Plug-Ins/HAL")
  (literal "/Library/Preferences/com.apple.mdmclient.plist")
  (literal "/Library/Preferences/com.apple.ViewBridge.plist")
  (literal "/usr/libexec/studentd")
  (literal security-plist-path)
  (temp-directory-subpath studentd-signing-id))

(allow file-write*
  (home-directory-subpath keychains-directory-path)
  (home-directory-subpath studentd-data-directory-path)
  (subpath private-temp-directory-path)
  (subpath private-var-folders-directory-path))

(allow file-write-data
  (temp-directory-subpath studentd-signing-id))

(allow ipc-posix-shm-read-data
    (ipc-posix-name-regex #"^/tmp/com.apple.csseed.[0-9]+$"))

(allow system-fsctl
  (fsctl-command (_IO "h" 47)) ; HFSIOC_SET_HOTFILE_STATE
)

(allow mach-lookup
  (global-name "com.apple.accountsd.accountmanager")
  (global-name "com.apple.AddressBook.abd")
  (global-name "com.apple.AddressBook.ContactsAccountsService")
  (global-name "com.apple.analyticsd")
  (global-name "com.apple.analyticsd.messagetracer")
  (global-name "com.apple.audio.audiohald")
  (global-name "com.apple.cookied")
  (global-name "com.apple.CoreDisplay.master")
  (global-name "com.apple.coremedia.endpoint.xpc")
  (global-name "com.apple.coremedia.routediscoverer.xpc")
  (global-name "com.apple.coremedia.routingcontext.xpc")
  (global-name "com.apple.coremedia.volumecontroller.xpc")
  (global-name "com.apple.coreservices.appleevents")
  (global-name "com.apple.CoreServices.coreservicesd")
  (global-name "com.apple.coreservices.launchservicesd")
  (global-name "com.apple.coreservices.quarantine-resolver")
  (global-name "com.apple.coreservices.sharedfilelistd.xpc")
  (global-name "com.apple.distributed_notifications@Uv3")
  (global-name "com.apple.dock.server")
  (global-name "com.apple.FileCoordination")
  (global-name "com.apple.iconservices")
  (global-name "com.apple.iconservices.store")
  (global-name "com.apple.identityservicesd.desktop.auth")
  (global-name "com.apple.identityservicesd.nsxpc")
  (global-name "com.apple.logind")
  (global-name "com.apple.lsd.mapdb")
  (global-name "com.apple.lsd.open")
  (global-name "com.apple.lsd.trustedsignatures")
  (global-name "com.apple.mdmclient.agent")
  (global-name "com.apple.mdmclient.daemon.unrestricted")
  (global-name "com.apple.mediaremoted.xpc")
  (global-name "com.apple.metadata.mds")
  (global-name "com.apple.metadata.mds.legacy")
  (global-name "com.apple.ocspd")
  (global-name "com.apple.pluginkit.pkd")
  (global-name "com.apple.PowerManagement.control")
  (global-name "com.apple.progressd")
  (global-name "com.apple.securityd.xpc")
  (global-name "com.apple.SecurityServer")
  (global-name "com.apple.sharing.classroom-transfer") ; studentd needs to talk to sharingd to show the AirDrop UI when receiving files from teachers
  (global-name "com.apple.system.opendirectoryd.api")
  (global-name "com.apple.SystemConfiguration.configd")
  (global-name "com.apple.SystemConfiguration.DNSConfiguration")
  (global-name "com.apple.tccd")
  (global-name "com.apple.tccd.system")
  (global-name "com.apple.UNCUserNotification")
  (global-name "com.apple.usernoted.daemon_client")
  (global-name "com.apple.usernotifications.usernotificationservice")
  (global-name "com.apple.usernotifications.listener")
  (global-name "com.apple.windowserver.active")
  (global-name "com.apple.wirelessproxd")
  (global-name "com.apple.dmd")
  (global-name "com.apple.cfnetwork.cfnetworkagent")
  (global-name "com.apple.containermanagerd"))

(allow iokit-open
  (iokit-user-client-class "AppleKeyStoreUserClient")
  (iokit-user-client-class "IOAudioControlUserClient")
  (iokit-user-client-class "IOAudioEngineUserClient"))

(allow iokit-get-properties
  (iokit-property "BSD Name")
  (iokit-property "device-colors")
  (iokit-property "DeviceEqID")
  (iokit-property "DeviceModemOverrides")
  (iokit-property "DevicePPPOverrides")
  (iokit-property "DisplayRouting")
  (iokit-property "HiddenConfiguration")
  (iokit-property "HiddenInterface")
  (iokit-property "HiddenPort")
  (iokit-property "idProduct")
  (iokit-property "idVendor")
  (iokit-property "Initializing")
  (iokit-property "InterfaceRole")
  (iokit-property "IOActivePacketFilters")
  (iokit-property "IOAudioControlChannelID")
  (iokit-property "IOAudioControlID")
  (iokit-property "IOAudioControlSubType")
  (iokit-property "IOAudioControlUsage")
  (iokit-property "IOAudioDeviceCanBeDefaults")
  (iokit-property "IOAudioEngineChannelNames")
  (iokit-property "IOAudioEngineClientDescription")
  (iokit-property "IOAudioEngineClockDomain")
  (iokit-property "IOAudioEngineClockIsStable")
  (iokit-property "IOAudioEngineCoreAudioPlugIn")
  (iokit-property "IOAudioEngineDescription")
  (iokit-property "IOAudioEngineDeviceDescription")
  (iokit-property "IOAudioEngineDisableClockBoundsCheck")
  (iokit-property "IOAudioEngineFlavor")
  (iokit-property "IOAudioEngineGlobalUniqueID")
  (iokit-property "IOAudioEngineGlobalUniqueIDLegacy")
  (iokit-property "IOAudioEngineInputSampleLatency")
  (iokit-property "IOAudioEngineInputSampleOffset")
  (iokit-property "IOAudioEngineNumActiveUserClients")
  (iokit-property "IOAudioEngineNumSampleFramesPerBuffer")
  (iokit-property "IOAudioEngineOutputSampleLatency")
  (iokit-property "IOAudioEngineSampleOffset")
  (iokit-property "IOAudioEngineState")
  (iokit-property "IOAudioSampleRate")
  (iokit-property "IOAudioStreamSampleFormatByteOrder")
  (iokit-property "IOBuiltin")
  (iokit-property "IOClassNameOverride")
  (iokit-property "IOConsoleUsers")
  (iokit-property "IOFeatures")
  (iokit-property "IOGeneralInterest")
  (iokit-property "IOInterfaceExtraFlags")
  (iokit-property "IOInterfaceFlags")
  (iokit-property "IOInterfaceNamePrefix")
  (iokit-property "IOInterfaceState")
  (iokit-property "IOInterfaceType")
  (iokit-property "IOInterfaceUnit")
  (iokit-property "IOLocation")
  (iokit-property "IOMACAddress")
  (iokit-property "IOMaxTransferUnit")
  (iokit-property "IOMediaAddressLength")
  (iokit-property "IOMediaHeaderLength")
  (iokit-property "IONetworkData")
  (iokit-property "IOPlatformSerialNumber")
  (iokit-property "IOPowerManagement")
  (iokit-property "IOPrimaryInterface")
  (iokit-property "IOProviderClass")
  (iokit-property "IORequiredPacketFilters")
  (iokit-property "IOSerialBSDClientType")
  (iokit-property "IOTTYBaseName")
  (iokit-property "IOTTYDevice")
  (iokit-property "kUSBProductString")
  (iokit-property "locationID")
  (iokit-property "ModemCCL")
  (iokit-property "name")
  (iokit-property "NetworkConfigurationOverrides")
  (iokit-property "New Interface Detected Action")
  (iokit-property "Product Name")
  (iokit-property "Protocol Characteristics")
  (iokit-property "SupportAudioAUUC")
  (iokit-property "SupportsIPhoneOS")
  (iokit-property "USBADC")
  (iokit-property "WWAN")
  (iokit-property "product-id"))

(allow user-preference*
  (preference-domain "com.apple.classroom")
  (preference-domain "com.apple.studentd"))

(allow user-preference-read
  (preference-domain "com.apple.AddressBook")
  (preference-domain "com.apple.airplay")
  (preference-domain "com.apple.avfoundation")
  (preference-domain "com.apple.avfoundation.frecents")
  (preference-domain "com.apple.coreaudio")
  (preference-domain "com.apple.coremedia")
  (preference-domain "com.apple.HIToolbox")
  (preference-domain "com.apple.ImageIO")
  (preference-domain "com.apple.LaunchServices")
  (preference-domain "com.apple.universalaccess")
  (preference-domain "kCFPreferencesAnyApplication"))

(allow user-preference-write
  (preference-domain "com.apple.airplay")
  (preference-domain "com.apple.avfoundation.frecents"))

(allow process-info-codesignature
  (target self)
  (target-signing-identifier "com.apple.classroom"))

(allow file-issue-extension
  (require-all
    (extension-class "com.apple.app-sandbox.read-write")))

(allow file-map-executable
  (subpath "/System/Library/Address Book Plug-Ins/")
  (subpath "/System/Library/CoreServices/")
  (subpath "/System/Library/Extensions/"))

(allow ipc-posix-shm
  (ipc-posix-name "com.apple.AppleDatabaseChanged"))

(allow appleevent-send)
