Skip to main content

endpoint_sec/
event.rs

1//! Definitions of Endpoint Security events.
2
3use endpoint_sec_sys::{es_event_type_t, es_events_t};
4
5/// Helper macro to define the whole Event enum at once, avoiding endless repetitions of the CFGs
6macro_rules! define_event_enum {
7    (
8        $(#[$enum_meta: meta])*
9        pub enum $enum_name: ident from ($raw_ev: ident, $version: ident) {
10            $(
11                $(#[$b_v_doc: meta])*
12                $b_v_const: ident => $b_v_name: ident($b_v_inner: ident [$b_v_var: pat => $b_v_expected_resp_type: expr] {
13                    $($b_v_new_name: ident $(: $b_v_new_expr: expr)?,)+
14                }),
15            )*
16            $(
17                == #[$v_cfg: meta]
18                $(
19                    $(#[$v_doc: meta])*
20                    $v_const: ident => $v_name: ident($v_inner: ident [$v_var: pat => $v_expected_resp_type: expr] {
21                        $($v_new_name: ident $(: $v_new_expr: expr)?,)+
22                    }),
23                )+
24            )*
25        }
26    ) => {
27        $(#[$enum_meta])*
28        pub enum $enum_name<'a> {
29            $( $(#[$b_v_doc])* $b_v_name($b_v_inner<'a>), )*
30            $( $( #[$v_cfg] $(#[$v_doc])* $v_name($v_inner<'a>), )* )*
31        }
32
33        #[cfg(feature = "static_assertions")]
34        ::static_assertions::assert_impl_all!(Event<'_>: Send);
35
36        impl<'a> $enum_name<'a> {
37            /// Create an instance from raw parts.
38            ///
39            /// # Safety
40            ///
41            /// `event_type`, `raw_event` and `version` must be coming from the same [`crate::message::Message`].
42            #[inline(always)]
43            pub(crate) unsafe fn from_raw_parts(
44                event_type: es_event_type_t,
45                $raw_ev: &'a es_events_t,
46                $version: u32,
47            ) -> Option<Self> {
48                // Safety: Safe as we select the union field corresponding to that type and the
49                // caller must have respected the calling condition.
50                let v = unsafe {
51                    match event_type {
52                        $( es_event_type_t::$b_v_const => Self::$b_v_name($b_v_inner { $( $b_v_new_name $(: $b_v_new_expr)? ),* }), )*
53                        $( $( #[$v_cfg] es_event_type_t::$v_const => Self::$v_name($v_inner { $( $v_new_name $(: $v_new_expr)? ),* }), )* )*
54                        _ => return None,
55                    }
56                };
57                Some(v)
58            }
59
60            /// For `Auth` events, returns the type of response to use when allowing or denying.
61            pub fn expected_response_type(&self) -> Option<ExpectedResponseType> {
62                match self {
63                    $( Self::$b_v_name($b_v_var) => $b_v_expected_resp_type, )*
64                    $( $( #[$v_cfg] Self::$v_name($v_var) => $v_expected_resp_type, )* )*
65                }
66            }
67        }
68    };
69}
70
71define_event_enum!(
72    /// Information related to an event.
73    #[derive(Debug, PartialEq, Eq, Hash)]
74    pub enum Event from (raw_event, version) {
75        /// Authorization request for a process execution.
76        ES_EVENT_TYPE_AUTH_EXEC => AuthExec(EventExec [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.exec, version, }),
77        /// Authorization request for a file system object being opened.
78        ES_EVENT_TYPE_AUTH_OPEN => AuthOpen(EventOpen [e => Some(ExpectedResponseType::Flags { flags: e.fflag() as u32, }) ] { raw: &raw_event.open, }),
79        /// Authorization request for a kernel extension being loaded.
80        ES_EVENT_TYPE_AUTH_KEXTLOAD => AuthKextLoad(EventKextLoad [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.kextload, }),
81        /// Authorization request for a memory map of a file.
82        ES_EVENT_TYPE_AUTH_MMAP => AuthMmap(EventMmap [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.mmap, }),
83        /// Authorization request for a change of protection for pages.
84        ES_EVENT_TYPE_AUTH_MPROTECT => AuthMprotect(EventMprotect [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.mprotect, }),
85        /// Authorization request for a file system being mounted.
86        ES_EVENT_TYPE_AUTH_MOUNT => AuthMount(EventMount [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.mount, }),
87        /// Authorization request for a file system object being renamed.
88        ES_EVENT_TYPE_AUTH_RENAME => AuthRename(EventRename [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.rename, }),
89        /// Authorization request for a signal being sent to a process.
90        ES_EVENT_TYPE_AUTH_SIGNAL => AuthSignal(EventSignal [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.signal, version, }),
91        /// Authorization request for a file system object being unlinked.
92        ES_EVENT_TYPE_AUTH_UNLINK => AuthUnlink(EventUnlink [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.unlink, }),
93        /// Notify a process execution.
94        ES_EVENT_TYPE_NOTIFY_EXEC => NotifyExec(EventExec [_ => None ] { raw: &raw_event.exec, version, }),
95        /// Notify a file system object being open.
96        ES_EVENT_TYPE_NOTIFY_OPEN => NotifyOpen(EventOpen [_ => None ] { raw: &raw_event.open, }),
97        /// Notify a new process being forked.
98        ES_EVENT_TYPE_NOTIFY_FORK => NotifyFork(EventFork [_ => None ] { raw: &raw_event.fork, version, }),
99        /// Notify a new file system object being closed.
100        ES_EVENT_TYPE_NOTIFY_CLOSE => NotifyClose(EventClose [_ => None ] { raw: &raw_event.close, version, }),
101        /// Notify a file system object being created.
102        ES_EVENT_TYPE_NOTIFY_CREATE => NotifyCreate(EventCreate [_ => None ] { raw: &raw_event.create, version, }),
103        /// Notify data being atomically exchanged between two files.
104        ES_EVENT_TYPE_NOTIFY_EXCHANGEDATA => NotifyExchangeData(EventExchangeData [_ => None ] { raw: &raw_event.exchangedata, }),
105        /// Notify a process termination.
106        ES_EVENT_TYPE_NOTIFY_EXIT => NotifyExit(EventExit [_ => None ] { raw: &raw_event.exit, }),
107        /// Notify a process's task control port event.
108        ES_EVENT_TYPE_NOTIFY_GET_TASK => NotifyGetTask(EventGetTask [_ => None ] { raw: &raw_event.get_task, version, }),
109        /// Notify a kernel extension being loaded.
110        ES_EVENT_TYPE_NOTIFY_KEXTLOAD => NotifyKextLoad(EventKextLoad [_ => None ] { raw: &raw_event.kextload, }),
111        /// Notify a kernel extension being unloaded.
112        ES_EVENT_TYPE_NOTIFY_KEXTUNLOAD => NotifyKextUnload(EventKextUnload[_ => None ]{ raw: &raw_event.kextunload, }),
113        /// Notify a file system object being linked.
114        ES_EVENT_TYPE_NOTIFY_LINK => NotifyLink(EventLink[_ => None ]{ raw: &raw_event.link, }),
115        /// Notify a memory map of a file.
116        ES_EVENT_TYPE_NOTIFY_MMAP => NotifyMmap(EventMmap [_ => None ] { raw: &raw_event.mmap, }),
117        /// Notify a change of protection for pages.
118        ES_EVENT_TYPE_NOTIFY_MPROTECT => NotifyMprotect(EventMprotect [_ => None ] { raw: &raw_event.mprotect, }),
119        /// Notify a file system being mounted.
120        ES_EVENT_TYPE_NOTIFY_MOUNT => NotifyMount(EventMount [_ => None ] { raw: &raw_event.mount, }),
121        /// Notify a file system being unmounted.
122        ES_EVENT_TYPE_NOTIFY_UNMOUNT => NotifyUnmount(EventUnmount [_ => None ] { raw: &raw_event.unmount, }),
123        /// Notify a connection being opened to an I/O Kit IOService.
124        ES_EVENT_TYPE_NOTIFY_IOKIT_OPEN => NotifyIoKitOpen(EventIoKitOpen [_ => None ] { raw: &raw_event.iokit_open, }),
125        /// Notify a file system object being renamed.
126        ES_EVENT_TYPE_NOTIFY_RENAME => NotifyRename(EventRename [_ => None ] { raw: &raw_event.rename, }),
127        /// Notify when file system attributes are being modified.
128        ES_EVENT_TYPE_NOTIFY_SETATTRLIST => NotifySetAttrlist(EventSetAttrlist [_ => None ] { raw: &raw_event.setattrlist, }),
129        /// Notify when extended attribute are being set.
130        ES_EVENT_TYPE_NOTIFY_SETEXTATTR => NotifySetExtAttr(EventSetExtAttr[_ => None ]{ raw: &raw_event.setextattr, }),
131        /// Notify when a file system object flags are being modified.
132        ES_EVENT_TYPE_NOTIFY_SETFLAGS => NotifySetFlags(EventSetFlags [_ => None ] { raw: &raw_event.setflags, }),
133        /// Notify when a file system object mode is being modified.
134        ES_EVENT_TYPE_NOTIFY_SETMODE => NotifySetMode(EventSetMode [_ => None ] { raw: &raw_event.setmode, }),
135        /// Notify when a file system object owner is being modified.
136        ES_EVENT_TYPE_NOTIFY_SETOWNER => NotifySetOwner(EventSetOwner [_ => None ] { raw: &raw_event.setowner, }),
137        /// Notify a signal being sent to a process.
138        ES_EVENT_TYPE_NOTIFY_SIGNAL => NotifySignal(EventSignal [_ => None ] { raw: &raw_event.signal, version, }),
139        /// Notify a file system object being unlinked.
140        ES_EVENT_TYPE_NOTIFY_UNLINK => NotifyUnlink(EventUnlink [_ => None ] { raw: &raw_event.unlink, }),
141        /// Notify a write to a file.
142        ES_EVENT_TYPE_NOTIFY_WRITE => NotifyWrite(EventWrite [_ => None ] { raw: &raw_event.write, }),
143        /// Authorization request for a file being materialize via the FileProvider framework.
144        ES_EVENT_TYPE_AUTH_FILE_PROVIDER_MATERIALIZE => AuthFileProviderMaterialize( EventFileProviderMaterialize [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.file_provider_materialize, version, } ),
145        /// Notify a file being materialize via the FileProvider framework.
146        ES_EVENT_TYPE_NOTIFY_FILE_PROVIDER_MATERIALIZE => NotifyFileProviderMaterialize(EventFileProviderMaterialize [_ => None ] { raw: &raw_event.file_provider_materialize, version, }),
147        /// Authorization request for file contents being updated via the FileProvider framework.
148        ES_EVENT_TYPE_AUTH_FILE_PROVIDER_UPDATE => AuthFileProviderUpdate( EventFileProviderUpdate [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.file_provider_update, } ),
149        /// Notify a file contents being updated via the FileProvider framework.
150        ES_EVENT_TYPE_NOTIFY_FILE_PROVIDER_UPDATE => NotifyFileProviderUpdate( EventFileProviderUpdate [_ => None ] { raw: &raw_event.file_provider_update, } ),
151        /// Authorization request for a symbolic link being resolved.
152        ES_EVENT_TYPE_AUTH_READLINK => AuthReadLink(EventReadLink [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.readlink, }),
153        /// Notify a symbolic link being resolved.
154        ES_EVENT_TYPE_NOTIFY_READLINK => NotifyReadLink(EventReadLink [_ => None ] { raw: &raw_event.readlink, }),
155        /// Authorization request for a file being truncated.
156        ES_EVENT_TYPE_AUTH_TRUNCATE => AuthTruncate(EventTruncate [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.truncate, }),
157        /// Notify a file being truncated.
158        ES_EVENT_TYPE_NOTIFY_TRUNCATE => NotifyTruncate(EventTruncate [_ => None ] { raw: &raw_event.truncate, }),
159        /// Authorization request for a file system object being linked.
160        ES_EVENT_TYPE_AUTH_LINK => AuthLink(EventLink[_ => Some(ExpectedResponseType::Auth) ]{ raw: &raw_event.link, }),
161        /// Notify a file system object being lookup.
162        ES_EVENT_TYPE_NOTIFY_LOOKUP => NotifyLookup(EventLookup [_ => None ] { raw: &raw_event.lookup, }),
163        /// Authorization request for a file system object being created.
164        ES_EVENT_TYPE_AUTH_CREATE => AuthCreate(EventCreate [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.create, version, }),
165        /// Authorization request for file system attributes being modified.
166        ES_EVENT_TYPE_AUTH_SETATTRLIST => AuthSetAttrlist(EventSetAttrlist [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setattrlist, }),
167        /// Authorization request for an extended attribute being set.
168        ES_EVENT_TYPE_AUTH_SETEXTATTR => AuthSetExtAttr(EventSetExtAttr [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setextattr, }),
169        /// Authorization request for a file system object flags being modified.
170        ES_EVENT_TYPE_AUTH_SETFLAGS => AuthSetFlags(EventSetFlags [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setflags, }),
171        /// Authorization request for a file system object mode being modified.
172        ES_EVENT_TYPE_AUTH_SETMODE => AuthSetMode(EventSetMode [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setmode, }),
173        /// Authorization request for a file system object owner being modified.
174        ES_EVENT_TYPE_AUTH_SETOWNER => AuthSetOwner(EventSetOwner [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setowner, }),
175
176        == #[cfg(feature = "macos_10_15_1")]
177        /// Authorization request for when the current working directory of a process is being changed.
178        ES_EVENT_TYPE_AUTH_CHDIR => AuthChdir(EventChdir [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.chdir, }),
179        /// Notify when the current working directory change for a process.
180        ES_EVENT_TYPE_NOTIFY_CHDIR => NotifyChdir(EventChdir [_ => None ] { raw: &raw_event.chdir, }),
181        /// Authorization request for file system attributes being retrieved.
182        ES_EVENT_TYPE_AUTH_GETATTRLIST => AuthGetAttrlist(EventGetAttrlist [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.getattrlist, }),
183        /// Notify when file system attributes are being retrieved.
184        ES_EVENT_TYPE_NOTIFY_GETATTRLIST => NotifyGetAttrlist(EventGetAttrlist [_ => None ] { raw: &raw_event.getattrlist, }),
185        /// Notify when a file is being stat.
186        ES_EVENT_TYPE_NOTIFY_STAT => NotifyStat(EventStat [_ => None ] { raw: &raw_event.stat, }),
187        /// Notify when a file access test is performed.
188        ES_EVENT_TYPE_NOTIFY_ACCESS => NotifyAccess(EventAccess [_ => None ] { raw: &raw_event.access, }),
189        /// Authorization request for a chroot.
190        ES_EVENT_TYPE_AUTH_CHROOT => AuthChroot(EventChroot [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.chroot, }),
191        /// Notify when a chroot is performed.
192        ES_EVENT_TYPE_NOTIFY_CHROOT => NotifyChroot(EventChroot [_ => None ] { raw: &raw_event.chroot, }),
193        /// Authorization request for a file access and modification times change.
194        ES_EVENT_TYPE_AUTH_UTIMES => AuthUTimes(EventUTimes [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.utimes, }),
195        /// Notify when a file access and modification times changed.
196        ES_EVENT_TYPE_NOTIFY_UTIMES => NotifyUTimes(EventUTimes [_ => None ] { raw: &raw_event.utimes, }),
197        /// Authorization request for a file being cloned.
198        ES_EVENT_TYPE_AUTH_CLONE => AuthClone(EventClone [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.clone, }),
199        /// Notify for a file being cloned.
200        ES_EVENT_TYPE_NOTIFY_CLONE => NotifyClone(EventClone [_ => None ] { raw: &raw_event.clone, }),
201        /// Notify for a file control event.
202        ES_EVENT_TYPE_NOTIFY_FCNTL => NotifyFcntl(EventFcntl [_ => None ] { raw: &raw_event.fcntl, }),
203        /// Authorization request for extended attribute being retrieved.
204        ES_EVENT_TYPE_AUTH_GETEXTATTR => AuthGetExtAttr(EventGetExtAttr [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.getextattr, }),
205        /// Notify when extended attribute are being retrieved.
206        ES_EVENT_TYPE_NOTIFY_GETEXTATTR => NotifyGetExtAttr(EventGetExtAttr[_ => None ]{ raw: &raw_event.getextattr, }),
207        /// Authorization request for extended attributes being listed.
208        ES_EVENT_TYPE_AUTH_LISTEXTATTR => AuthListExtAttr(EventListExtAttr [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.listextattr, }),
209        /// Notify when extended attributes are being listed.
210        ES_EVENT_TYPE_NOTIFY_LISTEXTATTR => NotifyListExtAttr(EventListExtAttr [_ => None ] { raw: &raw_event.listextattr , }),
211        /// Authorization request for directory entries being read.
212        ES_EVENT_TYPE_AUTH_READDIR => AuthReadDir(EventReadDir [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.readdir, }),
213        /// Notify when directory entries are being read.
214        ES_EVENT_TYPE_NOTIFY_READDIR => NotifyReadDir(EventReadDir [_ => None ] { raw: &raw_event.readdir, }),
215        /// Authorization request for an extended attribute being deleted.
216        ES_EVENT_TYPE_AUTH_DELETEEXTATTR => AuthDeleteExtAttr(EventDeleteExtAttr [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.deleteextattr , }),
217        /// Notify when an extended attribute are being deleted.
218        ES_EVENT_TYPE_NOTIFY_DELETEEXTATTR => NotifyDeleteExtAttr( EventDeleteExtAttr [_ => None ] { raw: &raw_event.deleteextattr, } ),
219        /// Authorization request for a file system path being retrieved based on FSID.
220        ES_EVENT_TYPE_AUTH_FSGETPATH => AuthFsGetPath(EventFsGetPath [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.fsgetpath, }),
221        /// Notify when a file system path is retrieved based on FSID.
222        ES_EVENT_TYPE_NOTIFY_FSGETPATH => NotifyFsGetPath(EventFsGetPath [_ => None ] { raw: &raw_event.fsgetpath, }),
223        /// Notify when a file descriptor is being duplicated.
224        ES_EVENT_TYPE_NOTIFY_DUP => NotifyDup(EventDup [_ => None ] { raw: &raw_event.dup, }),
225        /// Authorization request for the system time being modified.
226        ES_EVENT_TYPE_AUTH_SETTIME => AuthSetTime(EventSetTime [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.settime, }),
227        /// Notify the system time being modified.
228        ES_EVENT_TYPE_NOTIFY_SETTIME => NotifySetTime(EventSetTime [_ => None ] { raw: &raw_event.settime, }),
229        /// Notify a UNIX-domain socket is about to be bound to a path.
230        ES_EVENT_TYPE_NOTIFY_UIPC_BIND => NotifyUipcBind(EventUipcBind [_ => None ] { raw: &raw_event.uipc_bind, }),
231        /// Authorization request to bind a UNIX-domain socket to a path.
232        ES_EVENT_TYPE_AUTH_UIPC_BIND => AuthUipcBind(EventUipcBind [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.uipc_bind, }),
233        /// Notify a UNIX-domain socket is about to be connected.
234        ES_EVENT_TYPE_NOTIFY_UIPC_CONNECT => NotifyUipcConnect(EventUipcConnect [_ => None ] { raw: &raw_event.uipc_connect , }),
235        /// Authorization request to connect a UNIX-domain socket.
236        ES_EVENT_TYPE_AUTH_UIPC_CONNECT => AuthUipcConnect(EventUipcConnect[_ => Some(ExpectedResponseType::Auth) ]{ raw: &raw_event.uipc_connect, }),
237        /// Authorization request for data being atomically exchanged between two files.
238        ES_EVENT_TYPE_AUTH_EXCHANGEDATA => AuthExchangeData(EventExchangeData [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.exchangedata , }),
239        /// Authorization request to set a file's ACL.
240        ES_EVENT_TYPE_AUTH_SETACL => AuthSetAcl(EventSetAcl [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.setacl, }),
241        /// Notify a file's ACL was set.
242        ES_EVENT_TYPE_NOTIFY_SETACL => NotifySetAcl(EventSetAcl [_ => None ] { raw: &raw_event.setacl, }),
243
244        == #[cfg(feature = "macos_10_15_4")]
245        /// Notify a pseudoterminal control device was granted.
246        ES_EVENT_TYPE_NOTIFY_PTY_GRANT => NotifyPtyGrant(EventPtyGrant [_ => None ] { raw: &raw_event.pty_grant, }),
247        /// Notify a pseudoterminal control device was closed.
248        ES_EVENT_TYPE_NOTIFY_PTY_CLOSE => NotifyPtyClose(EventPtyClose [_ => None ] { raw: &raw_event.pty_close, }),
249        /// Authorization request for retrieving process information.
250        ES_EVENT_TYPE_AUTH_PROC_CHECK => AuthProcCheck(EventProcCheck [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.proc_check, version, }),
251        /// Notify about retrieval of process information.
252        ES_EVENT_TYPE_NOTIFY_PROC_CHECK => NotifyProcCheck(EventProcCheck [_ => None ] { raw: &raw_event.proc_check, version, }),
253        /// Authorization request for a process's task control port event.
254        ES_EVENT_TYPE_AUTH_GET_TASK => AuthGetTask(EventGetTask [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.get_task, version, }),
255
256        == #[cfg(feature = "macos_11_0_0")]
257        /// Authorization request for an access control check being performed when searching a volume or mounted filesystem.
258        ES_EVENT_TYPE_AUTH_SEARCHFS => AuthSearchFs(EventSearchFs [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.searchfs, }),
259        /// Notify for an access control check performed when searching a volume or mounted filesystem.
260        ES_EVENT_TYPE_NOTIFY_SEARCHFS => NotifySearchFs(EventSearchFs [_ => None ] { raw: &raw_event.searchfs, }),
261        /// Authorization request for a file control.
262        ES_EVENT_TYPE_AUTH_FCNTL => AuthFcntl(EventFcntl [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.fcntl, }),
263        /// Authorization request for a connection being opened to an I/O Kit IOService.
264        ES_EVENT_TYPE_AUTH_IOKIT_OPEN => AuthIoKitOpen(EventIoKitOpen [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.iokit_open, }),
265        /// Authorization request for one of `pid_suspend()`, `pid_resume()` or `pid_shutdown_sockets()` to be called
266        ES_EVENT_TYPE_AUTH_PROC_SUSPEND_RESUME => AuthProcSuspendResume( EventProcSuspendResume [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.proc_suspend_resume, version, } ),
267        /// called on a process.
268        ES_EVENT_TYPE_NOTIFY_PROC_SUSPEND_RESUME => NotifyProcSuspendResume( EventProcSuspendResume [_ => None ] { raw: &raw_event.proc_suspend_resume, version, } ),
269        /// Notify for one of `pid_suspend()`, `pid_resume()` or `pid_shutdown_sockets()` is being
270        ES_EVENT_TYPE_NOTIFY_CS_INVALIDATED => NotifyCSInvalidated( EventCSInvalidated [_ => None ] { raw: &raw_event.cs_invalidated, } ),
271        /// called on a process.
272        ES_EVENT_TYPE_NOTIFY_GET_TASK_NAME => NotifyGetTaskName(EventGetTaskName [_ => None ] { raw: &raw_event.get_task_name, version, }),
273        /// Notify for a code signing status for a process being invalidated.
274        ES_EVENT_TYPE_NOTIFY_TRACE => NotifyTrace(EventTrace [_ => None ] { raw: &raw_event.trace, version, }),
275        /// Notify for the recuperation of a process's task name port.
276        ES_EVENT_TYPE_NOTIFY_REMOTE_THREAD_CREATE => NotifyRemoteThreadCreate( EventRemoteThreadCreate [_ => None ] { raw: &raw_event.remote_thread_create, version, } ),
277        /// Notify for an attempt to attach another process.
278        ES_EVENT_TYPE_AUTH_REMOUNT => AuthRemount(EventRemount [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.remount, }),
279        /// Notify a process has attempted to create a thread in another process.
280        ES_EVENT_TYPE_NOTIFY_REMOUNT => NotifyRemount(EventRemount [_ => None ] { raw: &raw_event.remount, }),
281
282        == #[cfg(feature = "macos_11_3_0")]
283        /// Authorization request for a file system being remounted.
284        ES_EVENT_TYPE_AUTH_GET_TASK_READ => AuthGetTaskRead(EventGetTaskRead [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.get_task_read, version, }),
285        /// Notify a file system being remounted.
286        ES_EVENT_TYPE_NOTIFY_GET_TASK_READ => NotifyGetTaskRead(EventGetTaskRead [_ => None ] { raw: &raw_event.get_task_read, version, }),
287        /// Authorization request for the recuperation of a process's task read port.
288        ES_EVENT_TYPE_NOTIFY_GET_TASK_INSPECT => NotifyGetTaskInspect(EventGetTaskInspect [_ => None ]{ raw: &raw_event.get_task_inspect, version, }),
289
290        == #[cfg(feature = "macos_12_0_0")]
291        /// Notify for the recuperation of a process's task read port.
292        ES_EVENT_TYPE_NOTIFY_SETUID => NotifySetuid(EventSetuid [_ => None ] { raw: &raw_event.setuid, }),
293        /// Notify for the recuperation of a process's task inspect port.
294        ES_EVENT_TYPE_NOTIFY_SETGID => NotifySetgid(EventSetgid [_ => None ] { raw: &raw_event.setgid, }),
295        /// Notify a process has called `setuid()`.
296        ES_EVENT_TYPE_NOTIFY_SETEUID => NotifySeteuid(EventSeteuid [_ => None ] { raw: &raw_event.seteuid, }),
297        /// Notify a process has called `setgid()`.
298        ES_EVENT_TYPE_NOTIFY_SETEGID => NotifySetegid(EventSetegid [_ => None ] { raw: &raw_event.setegid, }),
299        /// Notify a process has called `seteuid()`.
300        ES_EVENT_TYPE_NOTIFY_SETREUID => NotifySetreuid(EventSetreuid [_ => None ] { raw: &raw_event.setreuid, }),
301        /// Notify a process has called `setegid()`.
302        ES_EVENT_TYPE_NOTIFY_SETREGID => NotifySetregid(EventSetregid [_ => None ] { raw: &raw_event.setregid, }),
303        /// Notify a process has called `setreuid()`.
304        ES_EVENT_TYPE_AUTH_COPYFILE => AuthCopyFile(EventCopyFile [_ => Some(ExpectedResponseType::Auth) ] { raw: &raw_event.copyfile, }),
305        /// Notify a process has called `setregid()`.
306        ES_EVENT_TYPE_NOTIFY_COPYFILE => NotifyCopyFile(EventCopyFile [_ => None ] { raw: &raw_event.copyfile, }),
307
308        == #[cfg(feature = "macos_13_0_0")]
309        /// Notify an authentication was performed.
310        ES_EVENT_TYPE_NOTIFY_AUTHENTICATION => NotifyAuthentication(EventAuthentication [_ => None] { raw: raw_event.authentication.as_opt()?, version, }),
311        /// Notify that XProtect detected malware.
312        ES_EVENT_TYPE_NOTIFY_XP_MALWARE_DETECTED => NotifyXpMalwareDetected(EventXpMalwareDetected [_ => None] { raw: raw_event.xp_malware_detected.as_opt()?, }),
313        /// Notify that XProtect remediated malware.
314        ES_EVENT_TYPE_NOTIFY_XP_MALWARE_REMEDIATED => NotifyXpMalwareRemediated(EventXpMalwareRemediated [_ => None] { raw: raw_event.xp_malware_remediated.as_opt()?, }),
315        /// Notify that LoginWindow has logged in a user.
316        ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOGIN => NotifyLwSessionLogin(EventLwSessionLogin [_ => None] { raw: raw_event.lw_session_login.as_opt()?, }),
317        /// Notify that LoginWindow has logged out a user.
318        ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOGOUT => NotifyLwSessionLogout(EventLwSessionLogout [_ => None] { raw: raw_event.lw_session_logout.as_opt()?, }),
319        /// Notify that LoginWindow locked the screen of a session.
320        ES_EVENT_TYPE_NOTIFY_LW_SESSION_LOCK => NotifyLwSessionLock(EventLwSessionLock [_ => None] { raw: raw_event.lw_session_lock.as_opt()?, }),
321        /// Notify that LoginWindow unlocked the screen of a session.
322        ES_EVENT_TYPE_NOTIFY_LW_SESSION_UNLOCK => NotifyLwSessionUnlock(EventLwSessionUnlock [_ => None] { raw: raw_event.lw_session_unlock.as_opt()?, }),
323        /// that Screen Sharing has attached to a graphical session.
324        ES_EVENT_TYPE_NOTIFY_SCREENSHARING_ATTACH => NotifyScreensharingAttach(EventScreensharingAttach [_ => None] { raw: raw_event.screensharing_attach.as_opt()?, }),
325        /// Notify that Screen Sharing has detached from a graphical session.
326        ES_EVENT_TYPE_NOTIFY_SCREENSHARING_DETACH => NotifyScreensharingDetach(EventScreensharingDetach [_ => None] { raw: raw_event.screensharing_detach.as_opt()?, }),
327        /// Notify about an OpenSSH login event.
328        ES_EVENT_TYPE_NOTIFY_OPENSSH_LOGIN => NotifyOpensshLogin(EventOpensshLogin [_ => None] { raw: raw_event.openssh_login.as_opt()?, }),
329        /// Notify about an OpenSSH logout event.
330        ES_EVENT_TYPE_NOTIFY_OPENSSH_LOGOUT => NotifyOpensshLogout(EventOpensshLogout [_ => None] { raw: raw_event.openssh_logout.as_opt()?, }),
331        /// Notify about an authenticated login event from `/usr/bin/login`.
332        ES_EVENT_TYPE_NOTIFY_LOGIN_LOGIN => NotifyLoginLogin(EventLoginLogin [_ => None] { raw: raw_event.login_login.as_opt()?, }),
333        /// Notify about an authenticated logout event from `/usr/bin/login`.
334        ES_EVENT_TYPE_NOTIFY_LOGIN_LOGOUT => NotifyLoginLogout(EventLoginLogout [_ => None] { raw: raw_event.login_logout.as_opt()?, }),
335        /// Notify for a launch item being made known to background task management.
336        ES_EVENT_TYPE_NOTIFY_BTM_LAUNCH_ITEM_ADD => NotifyBtmLaunchItemAdd(EventBtmLaunchItemAdd [_ => None] { raw: raw_event.btm_launch_item_add.as_opt()?, version, }),
337        /// Notify for a launch item being removed from background task management.
338        ES_EVENT_TYPE_NOTIFY_BTM_LAUNCH_ITEM_REMOVE => NotifyBtmLaunchItemRemove(EventBtmLaunchItemRemove [_ => None] { raw: raw_event.btm_launch_item_remove.as_opt()?, version, }),
339
340        == #[cfg(feature = "macos_14_0_0")]
341        /// Notify about Profiles installed on the system.
342        ES_EVENT_TYPE_NOTIFY_PROFILE_ADD => NotifyProfileAdd (EventProfileAdd [_ => None] { raw: raw_event.profile_add.as_opt()?, version, }),
343        /// Notify about Profiles removed on the system.
344        ES_EVENT_TYPE_NOTIFY_PROFILE_REMOVE => NotifyProfileRemove (EventProfileRemove [_ => None] { raw: raw_event.profile_remove.as_opt()?, version, }),
345        /// Notify about a su policy decisions event.
346        ES_EVENT_TYPE_NOTIFY_SU => NotifySu(EventSu [_ => None] { raw: raw_event.su.as_opt()?, }),
347        /// Notify about a process petitioned for certain authorization rights.
348        ES_EVENT_TYPE_NOTIFY_AUTHORIZATION_PETITION => NotifyAuthorizationPetition (EventAuthorizationPetition [_ => None] { raw: raw_event.authorization_petition.as_opt()?, version, }),
349        /// Notification that a process had it's right petition judged
350        ES_EVENT_TYPE_NOTIFY_AUTHORIZATION_JUDGEMENT => NotifyAuthorizationJudgement (EventAuthorizationJudgement [_ => None] { raw: raw_event.authorization_judgement.as_opt()?, version, }),
351        /// Notification about a sudo event.
352        ES_EVENT_TYPE_NOTIFY_SUDO => NotifySudo (EventSudo [_ => None] { raw: raw_event.sudo.as_opt()?, }),
353        /// Notification about an OD group add event.
354        ES_EVENT_TYPE_NOTIFY_OD_GROUP_ADD => NotifyOdGroupAdd (EventOdGroupAdd [_ => None] { raw: raw_event.od_group_add.as_opt()?, version, }),
355        /// Notification about an OD group remove event.
356        ES_EVENT_TYPE_NOTIFY_OD_GROUP_REMOVE => NotifyOdGroupRemove (EventOdGroupRemove [_ => None] { raw: raw_event.od_group_remove.as_opt()?, version, }),
357        /// Notification about a group that had its members initialised or replaced.
358        ES_EVENT_TYPE_NOTIFY_OD_GROUP_SET => NotifyOdGroupSet (EventOdGroupSet [_ => None] { raw: raw_event.od_group_set.as_opt()?, version, }),
359        /// Notification about a account that had its password modified.
360        ES_EVENT_TYPE_NOTIFY_OD_MODIFY_PASSWORD => NotifyOdModifyPassword (EventOdModifyPassword [_ => None] { raw: raw_event.od_modify_password.as_opt()?, version, }),
361        /// Notification about a user account that was disabled.
362        ES_EVENT_TYPE_NOTIFY_OD_DISABLE_USER => NotifyOdDisableUser (EventOdDisableUser [_ => None] { raw: raw_event.od_disable_user.as_opt()?, version, }),
363        /// Notification about a user account that was enabled.
364        ES_EVENT_TYPE_NOTIFY_OD_ENABLE_USER => NotifyOdEnableUser (EventOdEnableUser [_ => None] { raw: raw_event.od_enable_user.as_opt()?, version, }),
365        /// Notification about an attribute value that was added to a record.
366        ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_VALUE_ADD => NotifyOdAttributeValueAdd (EventOdAttributeValueAdd [_ => None] { raw: raw_event.od_attribute_value_add.as_opt()?, version, }),
367        /// Notification about an attribute value that was removed from a record.
368        ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_VALUE_REMOVE => NotifyOdAttributeValueRemove (EventOdAttributeValueRemove [_ => None] { raw: raw_event.od_attribute_value_remove.as_opt()?, version, }),
369        /// Notification about an attribute that was set.
370        ES_EVENT_TYPE_NOTIFY_OD_ATTRIBUTE_SET => NotifyOdAttributeSet (EventOdAttributeSet [_ => None] { raw: raw_event.od_attribute_set.as_opt()?, version, }),
371        /// Notification about an account that was created.
372        ES_EVENT_TYPE_NOTIFY_OD_CREATE_USER => NotifyOdCreateUser (EventOdCreateUser [_ => None] { raw: raw_event.od_create_user.as_opt()?, version, }),
373        /// Notification about a group that was created.
374        ES_EVENT_TYPE_NOTIFY_OD_CREATE_GROUP => NotifyOdCreateGroup (EventOdCreateGroup [_ => None] { raw: raw_event.od_create_group.as_opt()?, version, }),
375        /// Notification about an account that was deleted.
376        ES_EVENT_TYPE_NOTIFY_OD_DELETE_USER => NotifyOdDeleteUser (EventOdDeleteUser [_ => None] { raw: raw_event.od_delete_user.as_opt()?, version, }),
377        /// Notification about a group that was deleted.
378        ES_EVENT_TYPE_NOTIFY_OD_DELETE_GROUP => NotifyOdDeleteGroup (EventOdDeleteGroup [_ => None] { raw: raw_event.od_delete_group.as_opt()?, version, }),
379        /// Notification for an XPC connection being established to a named service.
380        ES_EVENT_TYPE_NOTIFY_XPC_CONNECT => NotifyXpcConnect (EventXpcConnect [_ => None] { raw: raw_event.xpc_connect.as_opt()?, }),
381    }
382);
383
384/// Type of response function to use for this event.
385///
386/// - [`Client::respond_auth_result()`][crate::Client::respond_auth_result]
387/// - [`Client::respond_flags_result()`][crate::Client::respond_flags_result]
388#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
389pub enum ExpectedResponseType {
390    /// Respond with [`Client::respond_auth_result()`][crate::Client::respond_auth_result]
391    Auth,
392    /// Respond with [`Client::respond_flags_result()`][crate::Client::respond_flags_result]
393    Flags {
394        /// Flags used by the original event
395        flags: u32,
396    },
397}
398
399/// Generate an iterator implementation for an array component of an event.
400///
401/// Safety:
402///
403/// - `raw_element_func` will be called like this: `raw_element_func(&raw_es_event, valid index)`,
404///   it must be safe to call under these conditions.
405/// - `raw_to_wrapped` will be called with the result of the preceding operation like this:
406///   `raw_to_wrapped(raw_token)`. This token COULD be null if `raw_element_func` can return `null`
407///   when called in the conditions described above. Usually Apple documents that if the event is
408///   a valid pointer and the index is correct, the function cannot return `null` and that calling
409///   outside the bounds is undefined behaviour.
410macro_rules! make_event_data_iterator {
411    ($wrapped_event: ident; $(#[$enum_doc:meta])+ $name:ident with $element_count: ident ($count_ty: ty); $item: ty; $raw_element_func: ident, $raw_to_wrapped: path$(,)?) => {
412        $(#[$enum_doc])*
413        pub struct $name<'event, 'raw> {
414            /// Wrapped event
415            ev: &'event $wrapped_event<'raw>,
416            /// Element count. When `current >= count`, the iterator is done and will only return
417            /// `None` for all subsequent calls to `next`.
418            count: $count_ty,
419            /// A call to `next` will yield element `current`
420            current: $count_ty,
421        }
422
423        impl $name<'_, '_> {
424            /// New iterator from event
425            fn new<'ev, 'raw>(ev: &'ev $wrapped_event<'raw>) -> $name<'ev, 'raw> {
426                $name {
427                    ev,
428                    count: ev.$element_count(),
429                    current: 0,
430                }
431            }
432        }
433
434        impl<'raw> std::iter::Iterator for $name<'_, 'raw> {
435            type Item = $item;
436
437            #[allow(unused_unsafe)]
438            fn next(&mut self) -> Option<Self::Item> {
439                if self.current < self.count {
440                    // Safety: Safe as raw is a reference and therefore cannot be null
441                    let raw_token = unsafe { $raw_element_func(self.ev.raw, self.current) };
442
443                    self.current = self.current.saturating_add(1);
444                    // Safety: Safe as we ensure the lifetime is rebound correctly in our wrappers
445                    Some(unsafe { $raw_to_wrapped(raw_token) })
446                } else {
447                    None
448                }
449            }
450
451            #[inline(always)]
452            fn nth(&mut self, n: usize) -> Option<Self::Item> {
453                // Overflow: the only `count_ty` used are u32 and usize. Since Apple machines are
454                // always 64-bits now (or more in the future, but that's still not a problem) it
455                // works out okay:
456                //
457                // - usize: the line does not change anything: `self.current = n`
458                // - u32: if `n > u32::MAX` is true, we clamp to `u32::MAX` to avoid something like
459                //   `.nth((u32::MAX + 1) as usize)` yielding `0` because of the truncation of
460                //   `as $count_ty`. Since the check in `.next()` is `<`, not `<=`, this will always
461                //   return `None` in that case and work correctly for valid `n`s.
462                self.current = n.min(<$count_ty>::MAX as usize) as $count_ty;
463                self.next()
464            }
465
466            #[inline(always)]
467            fn last(mut self) -> Option<Self::Item>
468            where
469                Self: Sized,
470            {
471                self.current = self.count.saturating_sub(1);
472                self.next()
473            }
474
475            #[inline(always)]
476            fn size_hint(&self) -> (usize, Option<usize>) {
477                let len = self.len();
478                (len, Some(len))
479            }
480
481            #[inline(always)]
482            fn count(mut self) -> usize {
483                let len = self.len();
484                self.current = self.count;
485                len
486            }
487        }
488
489        impl std::iter::ExactSizeIterator for $name<'_, '_> {
490            #[inline(always)]
491            fn len(&self) -> usize {
492                // Casting to usize if ok: all macOS machines are 64 bits now so a u32 will always
493                // fit into a usize
494                self.count.saturating_sub(self.current) as usize
495            }
496        }
497
498        impl std::iter::FusedIterator for $name<'_, '_> {}
499    };
500}
501
502/// Wrapper for the `.as_ref()` call on `es_string_token_t` with lifetime extension.
503///
504/// This is **only** intended for `make_event_data_iterator!`, which ensures lifetimes are correctly
505/// bound to avoid use-after-free shenanigans.
506///
507/// # Safety
508///
509/// This is a horrible horrible hack. Apple documents that the `es_string_token_t` returned by
510/// both [`es_exec_env`] and [`es_exec_arg`] are zero-allocation when in bounds and that the
511/// returned string token must not outlive the original event, which it cannot do in our
512/// iterator so it's safe. Thanks Rust for references and the borrow checker.
513unsafe fn as_os_str<'a>(x: endpoint_sec_sys::es_string_token_t) -> &'a std::ffi::OsStr {
514    // Safety: this is only called inside the iterator where `'a` will be the lifetime of `&mut self`
515    unsafe { &*(x.as_os_str() as *const _) }
516}
517
518/// Helper macro to define the event modules without copying the cfgs dozens of times.
519macro_rules! cfg_mod {
520    (
521        $( mod $b_name: ident; )*
522        $(
523            == #[$cfg: meta];
524            $( mod $name: ident; )+
525        )*
526    ) => {
527        $( mod $b_name; pub use $b_name::*; )*
528        $( $( #[$cfg] mod $name; #[$cfg] pub use $name::*; )+ )*
529    };
530}
531
532cfg_mod! {
533    mod event_close;
534    mod event_create;
535    mod event_exchangedata;
536    mod event_exec;
537    mod event_exit;
538    mod event_file_provider_materialize;
539    mod event_file_provider_update;
540    mod event_fork;
541    mod event_get_task;
542    mod event_iokit_open;
543    mod event_kextload;
544    mod event_kextunload;
545    mod event_link;
546    mod event_lookup;
547    mod event_mmap;
548    mod event_mount;
549    mod event_mprotect;
550    mod event_open;
551    mod event_read_link;
552    mod event_rename;
553    mod event_setattrlist;
554    mod event_setextattr;
555    mod event_setflags;
556    mod event_setmode;
557    mod event_setowner;
558    mod event_signal;
559    mod event_truncate;
560    mod event_unlink;
561    mod event_unmount;
562    mod event_write;
563
564    == #[cfg(feature = "macos_10_15_1")];
565    mod event_access;
566    mod event_chdir;
567    mod event_chroot;
568    mod event_clone;
569    mod event_deleteextattr;
570    mod event_dup;
571    mod event_fcntl;
572    mod event_fsgetpath;
573    mod event_getattrlist;
574    mod event_getextattr;
575    mod event_listextattr;
576    mod event_readdir;
577    mod event_setacl;
578    mod event_settime;
579    mod event_stat;
580    mod event_uipc_bind;
581    mod event_uipc_connect;
582    mod event_utimes;
583
584    == #[cfg(feature = "macos_10_15_4")];
585    mod event_pty_grant;
586    mod event_proc_check;
587    mod event_pty_close;
588
589    == #[cfg(feature = "macos_11_0_0")];
590    mod event_cs_invalidated;
591    mod event_get_task_name;
592    mod event_proc_suspend_resume;
593    mod event_remote_thread_create;
594    mod event_remount;
595    mod event_searchfs;
596    mod event_trace;
597
598    == #[cfg(feature = "macos_11_3_0")];
599    mod event_get_task_inspect;
600    mod event_get_task_read;
601
602    == #[cfg(feature = "macos_12_0_0")];
603    mod event_copyfile;
604    mod event_setegid;
605    mod event_seteuid;
606    mod event_setgid;
607    mod event_setregid;
608    mod event_setreuid;
609    mod event_setuid;
610
611    == #[cfg(feature = "macos_13_0_0")];
612    mod event_authentication;
613    mod event_xp_malware_detected;
614    mod event_xp_malware_remediated;
615    mod event_lw_session_login;
616    mod event_lw_session_logout;
617    mod event_lw_session_lock;
618    mod event_lw_session_unlock;
619    mod event_screesharing_attach;
620    mod event_screesharing_detach;
621    mod event_openssh_login;
622    mod event_openssh_logout;
623    mod event_login_login;
624    mod event_login_logout;
625    mod event_btm_launch_item_add;
626    mod event_btm_launch_item_remove;
627
628    == #[cfg(feature = "macos_14_0_0")];
629    mod event_profile_add;
630    mod event_profile_remove;
631    mod event_su;
632    mod event_authorization_petition;
633    mod event_authorization_judgement;
634    mod event_sudo;
635    mod event_od_group_add;
636    mod event_od_group_remove;
637    mod event_od_group_set;
638    mod event_od_modify_password;
639    mod event_od_disable_user;
640    mod event_od_enable_user;
641    mod event_od_attribute_value_add;
642    mod event_od_attribute_value_remove;
643    mod event_od_attribute_set;
644    mod event_od_create_user;
645    mod event_od_create_group;
646    mod event_od_delete_user;
647    mod event_od_delete_group;
648    mod event_xpc_connect;
649}