Class: Vivarium::Daemon

Inherits:
Object
  • Object
show all
Defined in:
lib/vivarium.rb

Constant Summary collapse

BPF_PROGRAM_TEMPLATE =
<<~CLANG
  struct path {
    void *mnt;
    void *dentry;
  };
  struct file {
    char __off[__VIVARIUM_F_PATH_OFFSET__];
    struct path f_path;
  };

  struct event_t {
    u32 pid;
    char event_name[16];
    char payload[64];
  };

  BPF_HASH(config_targets, u32, u32, 1024);
  BPF_ARRAY(event_invoked, struct event_t, 64);
  BPF_ARRAY(event_write_pos, u32, 1);

  static __always_inline int target_enabled(u32 pid)
  {
    u32 *enabled = config_targets.lookup(&pid);
    if (!enabled) {
      return 0;
    }
    return *enabled == 1;
  }

  LSM_PROBE(file_open, struct file *file)
  {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    if (!target_enabled(pid)) {
      return 0;
    }

    u32 zero = 0;
    u32 *write_pos = event_write_pos.lookup(&zero);
    if (!write_pos) {
      return 0;
    }

    u32 idx = *write_pos & 63;
    __sync_fetch_and_add(write_pos, 1);
    struct event_t ev = {};
    int path_ret;
    ev.pid = pid;
    __builtin_memcpy(ev.event_name, "path_open", 9);

    path_ret = bpf_d_path(&file->f_path, ev.payload, sizeof(ev.payload));
    if (path_ret < 0) {
      __builtin_memcpy(ev.payload, "<path_error>", 13);
    }

    event_invoked.update(&idx, &ev);

    return 0;
  }
CLANG

Instance Method Summary collapse

Constructor Details

#initialize(pin_dir: PIN_DIR) ⇒ Daemon

Returns a new instance of Daemon.



165
166
167
# File 'lib/vivarium.rb', line 165

def initialize(pin_dir: PIN_DIR)
  @pin_dir = pin_dir
end

Instance Method Details

#runObject



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
# File 'lib/vivarium.rb', line 169

def run
  ensure_root!
  FileUtils.mkdir_p(@pin_dir)

  f_path_offset = detect_f_path_offset
  program = BPF_PROGRAM_TEMPLATE.gsub("__VIVARIUM_F_PATH_OFFSET__", f_path_offset.to_s)

  bpf = RbBCC::BCC.new(text: program)

  config_targets = bpf["config_targets"]
  event_invoked = bpf["event_invoked"]
  event_write_pos = bpf["event_write_pos"]

  clear_event_slots(event_invoked)
  event_write_pos[0] = 0

  pin_map(config_targets, File.join(@pin_dir, "config_targets"))
  pin_map(event_invoked, File.join(@pin_dir, "event_invoked"))
  pin_map(event_write_pos, File.join(@pin_dir, "event_write_pos"))

  puts "[vivariumd] started"
  puts "[vivariumd] pinned maps in #{@pin_dir}"
  puts "[vivariumd] watching LSM file_open (f_path offset=#{f_path_offset})"

  loop do
    sleep 1
  end
rescue Interrupt
  puts "\n[vivariumd] stopping"
end