neli 0.7.4

Type safe netlink library written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Connector module for Linux Netlink connector messages.
//!
//! This module provides support for the Linux Netlink connector subsystem,
//! which creates a communication channel between userspace programs and the kernel.
//! It allows applications to receive notifications about various kernel events.
//!
//! This module currently provides full support for the Linux proc connector protocol,
//! enabling the reception and handling of process lifecycle events such as creation,
//! termination, exec, UID/GID/sid changes, tracing, name changes, and core dumps.
//!
//! ## Supported protocols
//! At this time, only the proc connector (`PROC_CN`) protocol is fully implemented.
//!
//! ## Extensibility
//! The implementation can be extended in two ways:
//! 1. By defining additional types and logic in your own crate and using them with this module.
//! 2. By using a `Vec<u8>` as a payload and manually parsing protocol messages to suit other connector protocols.
//!
//! This design allows both high-level ergonomic handling of proc events and low-level manual parsing for custom needs.

use std::{io::Cursor, io::Read};

use derive_builder::{Builder, UninitializedFieldError};
use getset::Getters;
use log::trace;

use crate::{
    self as neli,
    consts::connector::{CnMsgIdx, CnMsgVal, ProcEventType},
    err::{DeError, MsgError, SerError},
    FromBytes, FromBytesWithInput, Header, Size, ToBytes,
};

/// Netlink connector message header and payload.
#[derive(
    Builder, Getters, Clone, Debug, PartialEq, Eq, Size, ToBytes, FromBytesWithInput, Header,
)]
#[neli(from_bytes_bound = "P: Size + FromBytesWithInput<Input = usize>")]
#[builder(pattern = "owned")]
pub struct CnMsg<P: Size> {
    /// Index of the connector (idx)
    #[getset(get = "pub")]
    idx: CnMsgIdx,
    /// Value (val)
    #[getset(get = "pub")]
    val: CnMsgVal,
    /// Sequence number
    #[builder(default)]
    #[getset(get = "pub")]
    seq: u32,
    /// Acknowledgement number
    #[builder(default)]
    #[getset(get = "pub")]
    ack: u32,
    /// Length of the payload
    #[builder(
        setter(skip),
        default = "self.payload.as_ref().ok_or_else(|| UninitializedFieldError::new(\"payload\"))?.unpadded_size() as _"
    )]
    #[getset(get = "pub")]
    len: u16,
    /// Flags
    #[builder(default)]
    #[getset(get = "pub")]
    flags: u16,
    /// Payload of the netlink message
    ///
    /// You can either use predefined types like `ProcCnMcastOp` or `ProcEventHeader`,
    /// a custom type defined by you or `Vec<u8>` for raw payload.
    #[neli(size = "len as usize")]
    #[neli(input = "input - Self::header_size()")]
    #[getset(get = "pub")]
    pub(crate) payload: P,
}

// -- proc connector structs --

/// Header for process event messages.
#[derive(Debug, Size)]
pub struct ProcEventHeader {
    /// The CPU on which the event occurred.
    pub cpu: u32,
    /// Nanosecond timestamp of the event.
    pub timestamp_ns: u64,
    /// The process event data.
    pub event: ProcEvent,
}

/// Ergonomic enum for process event data.
#[derive(Debug, Size, Copy, Clone)]
pub enum ProcEvent {
    /// Acknowledgement event, typically for PROC_EVENT_NONE.
    Ack {
        /// Error code (0 for success).
        err: u32,
    },
    /// Fork event, triggered when a process forks.
    Fork {
        /// Parent process PID.
        parent_pid: i32,
        /// Parent process TGID (thread group ID).
        parent_tgid: i32,
        /// Child process PID.
        child_pid: i32,
        /// Child process TGID.
        child_tgid: i32,
    },
    /// Exec event, triggered when a process calls exec().
    Exec {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
    },
    /// UID change event, triggered when a process changes its UID.
    Uid {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Real UID.
        ruid: u32,
        /// Effective UID.
        euid: u32,
    },
    /// GID change event, triggered when a process changes its GID.
    Gid {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Real GID.
        rgid: u32,
        /// Effective GID.
        egid: u32,
    },
    /// SID change event, triggered when a process changes its session ID.
    Sid {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
    },
    /// Ptrace event, triggered when a process is traced.
    Ptrace {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Tracer process PID.
        tracer_pid: i32,
        /// Tracer process TGID.
        tracer_tgid: i32,
    },
    /// Comm event, triggered when a process changes its command name.
    Comm {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Command name (null-terminated, max 16 bytes).
        comm: [u8; 16],
    },
    /// Coredump event, triggered when a process dumps core.
    Coredump {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Parent process PID.
        parent_pid: i32,
        /// Parent process TGID.
        parent_tgid: i32,
    },
    /// Exit event, triggered when a process exits.
    Exit {
        /// Process PID.
        process_pid: i32,
        /// Process TGID.
        process_tgid: i32,
        /// Exit code.
        exit_code: u32,
        /// Exit signal.
        exit_signal: u32,
        /// Parent process PID.
        parent_pid: i32,
        /// Parent process TGID.
        parent_tgid: i32,
    },
}

impl From<&ProcEvent> for ProcEventType {
    fn from(ev: &ProcEvent) -> Self {
        match ev {
            ProcEvent::Ack { .. } => ProcEventType::None,
            ProcEvent::Fork { .. } => ProcEventType::Fork,
            ProcEvent::Exec { .. } => ProcEventType::Exec,
            ProcEvent::Uid { .. } => ProcEventType::Uid,
            ProcEvent::Gid { .. } => ProcEventType::Gid,
            ProcEvent::Sid { .. } => ProcEventType::Sid,
            ProcEvent::Ptrace { .. } => ProcEventType::Ptrace,
            ProcEvent::Comm { .. } => ProcEventType::Comm,
            ProcEvent::Coredump { .. } => ProcEventType::Coredump,
            ProcEvent::Exit { exit_code, .. } => {
                if *exit_code == 0 {
                    ProcEventType::Exit
                } else {
                    ProcEventType::NonzeroExit
                }
            }
        }
    }
}

impl ToBytes for ProcEventHeader {
    fn to_bytes(&self, buffer: &mut Cursor<Vec<u8>>) -> Result<(), SerError> {
        ProcEventType::from(&self.event).to_bytes(buffer)?;
        self.cpu.to_bytes(buffer)?;
        self.timestamp_ns.to_bytes(buffer)?;

        match self.event {
            ProcEvent::Ack { err } => {
                err.to_bytes(buffer)?;
            }
            ProcEvent::Fork {
                parent_pid,
                parent_tgid,
                child_pid,
                child_tgid,
            } => {
                parent_pid.to_bytes(buffer)?;
                parent_tgid.to_bytes(buffer)?;
                child_pid.to_bytes(buffer)?;
                child_tgid.to_bytes(buffer)?;
            }
            ProcEvent::Exec {
                process_pid,
                process_tgid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
            }
            ProcEvent::Uid {
                process_pid,
                process_tgid,
                ruid,
                euid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                ruid.to_bytes(buffer)?;
                euid.to_bytes(buffer)?;
            }
            ProcEvent::Gid {
                process_pid,
                process_tgid,
                rgid,
                egid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                rgid.to_bytes(buffer)?;
                egid.to_bytes(buffer)?;
            }
            ProcEvent::Sid {
                process_pid,
                process_tgid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
            }
            ProcEvent::Ptrace {
                process_pid,
                process_tgid,
                tracer_pid,
                tracer_tgid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                tracer_pid.to_bytes(buffer)?;
                tracer_tgid.to_bytes(buffer)?;
            }
            ProcEvent::Comm {
                process_pid,
                process_tgid,
                comm,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                comm.to_bytes(buffer)?;
            }
            ProcEvent::Coredump {
                process_pid,
                process_tgid,
                parent_pid,
                parent_tgid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                parent_pid.to_bytes(buffer)?;
                parent_tgid.to_bytes(buffer)?;
            }
            ProcEvent::Exit {
                process_pid,
                process_tgid,
                exit_code,
                exit_signal,
                parent_pid,
                parent_tgid,
            } => {
                process_pid.to_bytes(buffer)?;
                process_tgid.to_bytes(buffer)?;
                exit_code.to_bytes(buffer)?;
                exit_signal.to_bytes(buffer)?;
                parent_pid.to_bytes(buffer)?;
                parent_tgid.to_bytes(buffer)?;
            }
        };

        Ok(())
    }
}

impl FromBytesWithInput for ProcEventHeader {
    type Input = usize;

    fn from_bytes_with_input(
        buffer: &mut Cursor<impl AsRef<[u8]>>,
        input: Self::Input,
    ) -> Result<Self, DeError> {
        let start = buffer.position();

        trace!("Parsing ProcEventHeader at position {start} with input size {input}");

        // Minimum size for header (16) + smallest event (ack: 4) is 20.
        if input < 16 || buffer.position() as usize + input > buffer.get_ref().as_ref().len() {
            return Err(DeError::InvalidInput(input));
        }

        // Read header fields: what (u32), cpu (u32), timestamp_ns (u64)
        fn parse(buffer: &mut Cursor<impl AsRef<[u8]>>) -> Result<ProcEventHeader, DeError> {
            let what_val = u32::from_bytes(buffer)?;
            let what = ProcEventType::from(what_val);
            let cpu = u32::from_bytes(buffer)?;
            let timestamp_ns = u64::from_bytes(buffer)?;

            let event = match what {
                ProcEventType::None => ProcEvent::Ack {
                    err: u32::from_bytes(buffer)?,
                },
                ProcEventType::Fork => ProcEvent::Fork {
                    parent_pid: i32::from_bytes(buffer)?,
                    parent_tgid: i32::from_bytes(buffer)?,
                    child_pid: i32::from_bytes(buffer)?,
                    child_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::Exec => ProcEvent::Exec {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::Uid => ProcEvent::Uid {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                    ruid: u32::from_bytes(buffer)?,
                    euid: u32::from_bytes(buffer)?,
                },
                ProcEventType::Gid => ProcEvent::Gid {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                    rgid: u32::from_bytes(buffer)?,
                    egid: u32::from_bytes(buffer)?,
                },
                ProcEventType::Sid => ProcEvent::Sid {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::Ptrace => ProcEvent::Ptrace {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                    tracer_pid: i32::from_bytes(buffer)?,
                    tracer_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::Comm => {
                    let process_pid = i32::from_bytes(buffer)?;
                    let process_tgid = i32::from_bytes(buffer)?;
                    let mut comm = [0u8; 16];
                    buffer.read_exact(&mut comm)?;
                    ProcEvent::Comm {
                        process_pid,
                        process_tgid,
                        comm,
                    }
                }
                ProcEventType::Coredump => ProcEvent::Coredump {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                    parent_pid: i32::from_bytes(buffer)?,
                    parent_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::Exit | ProcEventType::NonzeroExit => ProcEvent::Exit {
                    process_pid: i32::from_bytes(buffer)?,
                    process_tgid: i32::from_bytes(buffer)?,
                    exit_code: u32::from_bytes(buffer)?,
                    exit_signal: u32::from_bytes(buffer)?,
                    parent_pid: i32::from_bytes(buffer)?,
                    parent_tgid: i32::from_bytes(buffer)?,
                },
                ProcEventType::UnrecognizedConst(i) => {
                    return Err(DeError::Msg(MsgError::new(format!(
                        "Unrecognized Proc event type: {i} (raw value: {what_val})"
                    ))));
                }
            };
            Ok(ProcEventHeader {
                cpu,
                timestamp_ns,
                event,
            })
        }

        let event = match parse(buffer) {
            Ok(ev) => ev,
            Err(e) => {
                buffer.set_position(start);
                return Err(e);
            }
        };

        buffer.set_position(start + input as u64);

        // consume the entire len, because the kernel can pad the event data with zeros

        Ok(event)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn build_endian_agnostic_response() -> Vec<u8> {
        let mut cursor = Cursor::new(vec![]);
        let msg = CnMsg {
            idx: CnMsgIdx::Proc,
            val: CnMsgVal::Proc,
            seq: 643,
            ack: 0,
            len: 40,
            flags: 0,
            payload: ProcEventHeader {
                cpu: 1,
                timestamp_ns: 2504390882488,
                event: ProcEvent::Exec {
                    process_pid: 5759,
                    process_tgid: 5759,
                },
            },
        };
        msg.to_bytes(&mut cursor).unwrap();
        cursor.into_inner()
    }

    #[test]
    fn parse_static_proc_header() {
        let mut cursor = Cursor::new(build_endian_agnostic_response());

        let len = cursor.get_ref().len();
        let msg: CnMsg<ProcEventHeader> = CnMsg::from_bytes_with_input(&mut cursor, len).unwrap();

        assert_eq!(msg.idx(), &CnMsgIdx::Proc);
        assert_eq!(msg.val(), &CnMsgVal::Proc);
        assert_eq!(msg.payload.cpu, 1);
        assert_eq!(msg.payload.timestamp_ns, 2504390882488);
        match &msg.payload.event {
            ProcEvent::Exec {
                process_pid,
                process_tgid,
            } => {
                assert_eq!(*process_pid, 5759);
                assert_eq!(*process_tgid, 5759);
            }
            _ => panic!("Expected Exec event"),
        }
    }

    #[test]
    fn parse_static_raw_data() {
        let mut cursor = Cursor::new(build_endian_agnostic_response());

        let len = cursor.get_ref().len();
        let msg: CnMsg<Vec<u8>> = CnMsg::from_bytes_with_input(&mut cursor, len).unwrap();

        assert_eq!(msg.idx(), &CnMsgIdx::Proc);
        assert_eq!(msg.val(), &CnMsgVal::Proc);
    }
}