tracexec-core 1.0.0

Core crate of tracexec [Internal implementation! DO NOT DEPEND ON!]
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
use std::{
  collections::BTreeMap,
  fmt::Display,
  sync::Arc,
};

use chrono::{
  DateTime,
  Local,
};
use enumflags2::BitFlags;
use nix::{
  errno::Errno,
  libc::{
    SIGRTMIN,
    c_int,
  },
  unistd::{
    Pid,
    User,
  },
};
use tokio::sync::mpsc::UnboundedSender;

use crate::{
  cli::{
    args::{
      LogModeArgs,
      ModifierArgs,
      PtraceArgs,
    },
    options::SeccompBpf,
  },
  elevate::EnvVars,
  event::{
    OutputMsg,
    TracerEventDetailsKind,
    TracerMessage,
  },
  printer::{
    Printer,
    PrinterArgs,
  },
  proc::{
    BaselineInfo,
    CgroupInfo,
    Cred,
    CredInspectError,
    FileDescriptorInfoCollection,
    Interpreter,
  },
  pty::UnixSlavePty,
};

pub type InspectError = Errno;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Signal {
  Standard(nix::sys::signal::Signal),
  Realtime(u8), // u8 is enough for Linux
}

impl Signal {
  pub fn from_raw(raw: c_int) -> Self {
    match nix::sys::signal::Signal::try_from(raw) {
      Ok(sig) => Self::Standard(sig),
      // libc might reserve some RT signals for itself.
      // But from a tracer's perspective we don't need to care about it.
      // So here no validation is done for the RT signal value.
      Err(_) => Self::Realtime(raw as u8),
    }
  }

  pub fn as_raw(self) -> i32 {
    match self {
      Self::Standard(signal) => signal as i32,
      Self::Realtime(raw) => raw as i32,
    }
  }
}

impl From<nix::sys::signal::Signal> for Signal {
  fn from(value: nix::sys::signal::Signal) -> Self {
    Self::Standard(value)
  }
}

impl Display for Signal {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Self::Standard(signal) => signal.fmt(f),
      Self::Realtime(sig) => {
        let min = SIGRTMIN();
        let delta = *sig as i32 - min;
        match delta.signum() {
          0 => write!(f, "SIGRTMIN"),
          1 => write!(f, "SIGRTMIN+{delta}"),
          -1 => write!(f, "SIGRTMIN{delta}"),
          _ => unreachable!(),
        }
      }
    }
  }
}

#[derive(Default)]
#[non_exhaustive]
pub struct TracerBuilder {
  pub user: Option<User>,
  pub modifier: ModifierArgs,
  pub mode: Option<TracerMode>,
  pub filter: Option<BitFlags<TracerEventDetailsKind>>,
  pub tx: Option<UnboundedSender<TracerMessage>>,
  // TODO: remove this.
  pub printer: Option<Printer>,
  pub baseline: Option<Arc<BaselineInfo>>,
  // --- ptrace specific ---
  pub seccomp_bpf: SeccompBpf,
  pub ptrace_polling_delay: Option<u64>,
  pub ptrace_blocking: Option<bool>,
  pub tracee_env: Option<EnvVars>,
  pub tracexec_override_env: Option<EnvVars>,
}

#[allow(clippy::unwrap_used)]
impl TracerBuilder {
  /// Initialize a new [`TracerBuilder`]
  pub fn new() -> Self {
    Default::default()
  }

  /// Use blocking waitpid calls instead of polling.
  ///
  /// This mode conflicts with ptrace polling delay option
  /// This option is not used in eBPF tracer.
  pub fn ptrace_blocking(mut self, enable: bool) -> Self {
    if self.ptrace_polling_delay.is_some() && enable {
      panic!(
        "Cannot enable blocking mode when ptrace polling delay implicitly specifys polling mode"
      );
    }
    self.ptrace_blocking = Some(enable);
    self
  }

  /// Sets ptrace polling delay (in microseconds)
  /// This options conflicts with ptrace blocking mode.
  ///
  /// This option is not used in eBPF tracer.
  pub fn ptrace_polling_delay(mut self, ptrace_polling_delay: Option<u64>) -> Self {
    if Some(true) == self.ptrace_blocking && ptrace_polling_delay.is_some() {
      panic!("Cannot set ptrace_polling_delay when operating in blocking mode")
    }
    self.ptrace_polling_delay = ptrace_polling_delay;
    self
  }

  /// Applies the ptrace-specific CLI options to this builder.
  pub fn ptrace_options(self, args: &PtraceArgs) -> Self {
    self
      .seccomp_bpf(args.seccomp_bpf)
      .ptrace_blocking(args.polling_interval.is_none_or(|value| value < 0))
      .ptrace_polling_delay(
        args
          .polling_interval
          .filter(|&value| value > 0)
          .map(|value| value as u64),
      )
  }

  /// Sets seccomp-bpf mode for ptrace tracer
  ///
  /// Default to auto.
  /// This option is not used in eBPF tracer.
  pub fn seccomp_bpf(mut self, seccomp_bpf: SeccompBpf) -> Self {
    self.seccomp_bpf = seccomp_bpf;
    self
  }

  /// Sets the `User` used when spawning the command.
  ///
  /// Default to current user.
  pub fn user(mut self, user: Option<User>) -> Self {
    self.user = user;
    self
  }

  /// Sets the environment passed to the root tracee at exec time.
  ///
  /// When unset, the tracee inherits tracexec's current process environment.
  pub fn tracee_env(mut self, env: Option<EnvVars>) -> Self {
    self.tracee_env = env;
    self
  }

  /// Sets the environment variables tracexec should consult for before using process env vars
  ///
  /// Or put it simply, this overrides std::env::vars for tracexec itself only.
  pub fn tracexec_override_env(mut self, env: Option<EnvVars>) -> Self {
    self.tracexec_override_env = env;
    self
  }

  pub fn modifier(mut self, modifier: ModifierArgs) -> Self {
    self.modifier = modifier;
    self
  }

  /// Sets the mode for the trace e.g. TUI or Log
  pub fn mode(mut self, mode: TracerMode) -> Self {
    self.mode = Some(mode);
    self
  }

  /// Sets a filter for wanted tracer events.
  pub fn filter(mut self, filter: BitFlags<TracerEventDetailsKind>) -> Self {
    self.filter = Some(filter);
    self
  }

  /// Passes the tx part of tracer event channel
  ///
  /// By default this is not set and tracer will not send events.
  pub fn tracer_tx(mut self, tx: UnboundedSender<TracerMessage>) -> Self {
    self.tx = Some(tx);
    self
  }

  pub fn printer(mut self, printer: Printer) -> Self {
    self.printer = Some(printer);
    self
  }

  /// Create a printer from CLI options,
  ///
  /// Requires `modifier` and `baseline` to be set before calling.
  pub fn printer_from_cli(mut self, tracing_args: &LogModeArgs) -> Self {
    self.printer = Some(Printer::new(
      PrinterArgs::from_cli(tracing_args, &self.modifier),
      self.baseline.clone().unwrap(),
    ));
    self
  }

  pub fn baseline(mut self, baseline: Arc<BaselineInfo>) -> Self {
    self.baseline = Some(baseline);
    self
  }
}

#[derive(Debug)]
pub struct ExecData {
  pub exec_pid: Pid,
  pub filename: OutputMsg,
  pub argv: Arc<Result<Vec<OutputMsg>, InspectError>>,
  pub envp: Arc<Result<BTreeMap<OutputMsg, OutputMsg>, InspectError>>,
  pub has_dash_env: bool,
  pub cred: Result<Cred, CredInspectError>,
  pub cwd: OutputMsg,
  pub interpreters: Option<Vec<Interpreter>>,
  pub fdinfo: Arc<FileDescriptorInfoCollection>,
  pub timestamp: DateTime<Local>,
  pub cgroup: CgroupInfo,
}

impl ExecData {
  #[allow(clippy::too_many_arguments)]
  pub fn new(
    exec_pid: Pid,
    filename: OutputMsg,
    argv: Result<Vec<OutputMsg>, InspectError>,
    envp: Result<BTreeMap<OutputMsg, OutputMsg>, InspectError>,
    has_dash_env: bool,
    cred: Result<Cred, CredInspectError>,
    cwd: OutputMsg,
    interpreters: Option<Vec<Interpreter>>,
    fdinfo: FileDescriptorInfoCollection,
    timestamp: DateTime<Local>,
    cgroup: CgroupInfo,
  ) -> Self {
    Self {
      exec_pid,
      filename,
      argv: Arc::new(argv),
      envp: Arc::new(envp),
      has_dash_env,
      cred,
      cwd,
      interpreters,
      fdinfo: Arc::new(fdinfo),
      timestamp,
      cgroup,
    }
  }
}

#[derive(Debug)]
pub enum TracerMode {
  Tui(Option<UnixSlavePty>),
  Log { foreground: bool },
}

impl PartialEq for TracerMode {
  fn eq(&self, other: &Self) -> bool {
    // I think a plain match is more readable here
    #[allow(clippy::match_like_matches_macro)]
    match (self, other) {
      (Self::Log { foreground: a }, Self::Log { foreground: b }) => a == b,
      _ => false,
    }
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessExit {
  Code(i32),
  Signal(Signal),
}

#[cfg(test)]
mod tests {
  use std::{
    collections::BTreeMap,
    sync::Arc,
  };

  use chrono::Local;
  use nix::sys::signal::Signal as NixSignal;
  use test_that::prelude::*;

  use super::*;
  use crate::event::OutputMsg;

  /* ---------------- Signal ---------------- */

  #[test]
  fn signal_from_raw_standard() {
    let sig = Signal::from_raw(NixSignal::SIGINT as i32);
    assert_eq!(sig, Signal::Standard(NixSignal::SIGINT));
    assert_eq!(sig.as_raw(), NixSignal::SIGINT as i32);
  }

  #[test]
  fn signal_from_raw_realtime() {
    let raw = SIGRTMIN() + 3;
    let sig = Signal::from_raw(raw);
    assert_eq!(sig, Signal::Realtime(raw as u8));
    assert_eq!(sig.as_raw(), raw);
  }

  #[test]
  fn signal_display_standard() {
    let sig = Signal::Standard(NixSignal::SIGTERM);
    assert_eq!(sig.to_string(), "SIGTERM");
  }

  #[test]
  fn signal_display_realtime_variants() {
    let min = SIGRTMIN();

    let sig_min = Signal::Realtime(min as u8);
    assert_eq!(sig_min.to_string(), "SIGRTMIN");

    let sig_plus = Signal::Realtime((min + 2) as u8);
    assert_eq!(sig_plus.to_string(), "SIGRTMIN+2");

    let sig_minus = Signal::Realtime((min - 1) as u8);
    assert_eq!(sig_minus.to_string(), "SIGRTMIN-1");
  }

  /* ---------------- TracerBuilder ---------------- */
  #[test]
  #[should_panic(expected = "Cannot enable blocking mode")]
  fn tracer_builder_blocking_conflict_panics() {
    TracerBuilder::new()
      .ptrace_polling_delay(Some(10))
      .ptrace_blocking(true);
  }

  #[test]
  #[should_panic(expected = "Cannot set ptrace_polling_delay")]
  fn tracer_builder_polling_conflict_panics() {
    TracerBuilder::new()
      .ptrace_blocking(true)
      .ptrace_polling_delay(Some(10));
  }

  #[test]
  fn tracer_builder_chaining_works() {
    let builder = TracerBuilder::new()
      .ptrace_blocking(false)
      .ptrace_polling_delay(None)
      .seccomp_bpf(SeccompBpf::Auto);

    assert_eq!(builder.ptrace_blocking, Some(false));
    assert_eq!(builder.ptrace_polling_delay, None);
  }

  #[test]
  fn tracer_builder_applies_ptrace_cli_options() {
    let blocking = TracerBuilder::new().ptrace_options(&PtraceArgs::default());
    assert_eq!(blocking.ptrace_blocking, Some(true));
    assert_eq!(blocking.ptrace_polling_delay, None);

    let polling = TracerBuilder::new().ptrace_options(&PtraceArgs {
      seccomp_bpf: SeccompBpf::Off,
      polling_interval: Some(250),
    });
    assert_eq!(polling.seccomp_bpf, SeccompBpf::Off);
    assert_eq!(polling.ptrace_blocking, Some(false));
    assert_eq!(polling.ptrace_polling_delay, Some(250));

    let no_delay = TracerBuilder::new().ptrace_options(&PtraceArgs {
      polling_interval: Some(0),
      ..Default::default()
    });
    assert_eq!(no_delay.ptrace_blocking, Some(false));
    assert_eq!(no_delay.ptrace_polling_delay, None);
  }

  /* ---------------- ExecData ---------------- */

  #[test]
  fn exec_data_new_populates_fields() {
    let filename = OutputMsg::Ok("bin".into());
    let argv = Ok(vec![
      OutputMsg::Ok("bin".into()),
      OutputMsg::Ok("-h".into()),
    ]);

    let mut envp_map = BTreeMap::new();
    envp_map.insert(OutputMsg::Ok("A".into()), OutputMsg::Ok("B".into()));
    let envp = Ok(envp_map);

    let cwd = OutputMsg::Ok("/".into());
    let fdinfo = FileDescriptorInfoCollection::default();
    let timestamp = Local::now();

    let exec = ExecData::new(
      Pid::from_raw(1234),
      filename.clone(),
      argv,
      envp,
      false,
      Err(CredInspectError::Inspect),
      cwd.clone(),
      None,
      fdinfo,
      timestamp,
      CgroupInfo::V2 {
        path: "/".to_string(),
      },
    );

    assert_eq!(exec.exec_pid, Pid::from_raw(1234));
    assert_eq!(exec.filename, filename);
    assert_eq!(exec.cwd, cwd);
    assert_that!(exec.argv, points_to(ok(anything())));
    assert_that!(exec.envp, points_to(ok(anything())));
    assert!(!exec.has_dash_env);
    assert_that!(exec.interpreters, none());
    assert_that!(Arc::strong_count(&exec.argv), ge(1));
    assert_that!(Arc::strong_count(&exec.envp), ge(1));
    assert_that!(Arc::strong_count(&exec.fdinfo), ge(1));
  }

  /* ---------------- ProcessExit ---------------- */

  #[test]
  fn process_exit_equality() {
    let a = ProcessExit::Code(0);
    let b = ProcessExit::Code(0);
    let c = ProcessExit::Code(1);

    assert_eq!(a, b);
    assert_ne!(a, c);

    let s1 = ProcessExit::Signal(Signal::Standard(NixSignal::SIGKILL));
    let s2 = ProcessExit::Signal(Signal::Standard(NixSignal::SIGKILL));
    let s3 = ProcessExit::Signal(Signal::Standard(NixSignal::SIGTERM));

    assert_eq!(s1, s2);
    assert_ne!(s1, s3);
  }
}