Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: user/group name in kunai events #150

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 93 additions & 15 deletions kunai/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ use kunai::events::{
BpfProgLoadData, BpfProgTypeInfo, BpfSocketFilterData, CloneData, ConnectData, DnsQueryData,
EventInfo, ExecveData, ExitData, FileData, FileRenameData, FileScanData, FilterInfo,
InitModuleData, KillData, KunaiEvent, MmapExecData, MprotectData, NetworkInfo, PrctlData,
PtraceData, ScanResult, SendDataData, SockAddr, SocketInfo, TargetTask, UnlinkData, UserEvent,
PtraceData, ScanResult, SendDataData, SockAddr, SocketInfo, TargetTask, TaskSection,
UnlinkData, UserEvent,
};
use kunai::info::{AdditionalInfo, ProcKey, StdEventInfo};
use kunai::info::{AdditionalInfo, ProcKey, StdEventInfo, TaskAdditionalInfo};
use kunai::ioc::IoC;
use kunai::util::uname::Utsname;

Expand Down Expand Up @@ -810,10 +811,8 @@ impl<'s> EventConsumer<'s> {
}

#[inline(always)]
/// method acting as a central place to get the mnt namespace of a
/// task and printing out an error if not found
fn task_mnt_ns(ei: &bpf_events::EventInfo) -> Option<Namespace> {
match ei.process.namespaces {
fn mnt_ns_from_task(ti: &bpf_events::TaskInfo) -> Option<Namespace> {
match ti.namespaces {
Some(ns) => Some(Namespace::mnt(ns.mnt)),
None => {
error!("task namespace must be known");
Expand All @@ -822,6 +821,20 @@ impl<'s> EventConsumer<'s> {
}
}

#[inline(always)]
/// method acting as a central place to get the mnt namespace of a
/// parent task and printing out an error if not found
fn task_mnt_ns(ei: &bpf_events::EventInfo) -> Option<Namespace> {
Self::mnt_ns_from_task(&ei.process)
}

#[inline(always)]
/// method acting as a central place to get the mnt namespace of a
/// task and printing out an error if not found
fn parent_mnt_ns(ei: &bpf_events::EventInfo) -> Option<Namespace> {
Self::mnt_ns_from_task(&ei.parent)
}

#[inline(always)]
fn execve_event(
&mut self,
Expand Down Expand Up @@ -910,6 +923,9 @@ impl<'s> EventConsumer<'s> {
// get the command line
let tk = ProcKey::from(target.tg_uuid);

let tai =
Self::mnt_ns_from_task(&target).map(|ns| self.build_task_additional_info(&ns, &target));

let data = KillData {
ancestors: self.get_ancestors_string(&info),
exe: exe.into(),
Expand All @@ -918,7 +934,7 @@ impl<'s> EventConsumer<'s> {
target: TargetTask {
command_line: self.get_command_line(tk),
exe: self.get_exe(tk).into(),
task: target.into(),
task: TaskSection::from_task_info_with_addition(target, tai.unwrap_or_default()),
},
};

Expand All @@ -939,6 +955,8 @@ impl<'s> EventConsumer<'s> {

// get the command line
let tk = ProcKey::from(target.tg_uuid);
let tai =
Self::mnt_ns_from_task(&target).map(|ns| self.build_task_additional_info(&ns, &target));

let data = PtraceData {
ancestors: self.get_ancestors_string(&info),
Expand All @@ -948,7 +966,7 @@ impl<'s> EventConsumer<'s> {
target: TargetTask {
command_line: self.get_command_line(tk),
exe: self.get_exe(tk).into(),
task: target.into(),
task: TaskSection::from_task_info_with_addition(target, tai.unwrap_or_default()),
},
};

Expand Down Expand Up @@ -1534,9 +1552,43 @@ impl<'s> EventConsumer<'s> {
}
}

#[inline(always)]
fn build_task_additional_info(
&mut self,
mnt_ns: &Namespace,
ti: &bpf_events::TaskInfo,
) -> TaskAdditionalInfo {
// getting user and group information for task
let user = self
.cache
.get_user_by_uid(mnt_ns, &ti.uid)
.inspect_err(|e| {
if !e.is_unknown_ns() {
error!("failed to get task user: {e}")
}
})
.unwrap_or_default()
.cloned();

// getting group information for task
let group = self
.cache
.get_group_by_gid(mnt_ns, &ti.gid)
.inspect_err(|e| {
if !e.is_unknown_ns() {
error!("failed to get task group: {e}")
}
})
.unwrap_or_default()
.cloned();

TaskAdditionalInfo::new(user, group)
}

#[inline(always)]
fn build_std_event_info(&mut self, i: bpf_events::EventInfo) -> StdEventInfo {
let opt_mnt_ns = Self::task_mnt_ns(&i);
let opt_parent_ns = Self::parent_mnt_ns(&i);

let mut std_info = StdEventInfo::from_bpf(i, self.random);

Expand All @@ -1546,6 +1598,8 @@ impl<'s> EventConsumer<'s> {
};

let mut container = None;
let mut task = None;
let mut parent = None;

if let Some(mnt_ns) = opt_mnt_ns {
if mnt_ns != self.system_info.mount_ns {
Expand All @@ -1555,11 +1609,23 @@ impl<'s> EventConsumer<'s> {
ty: t.and_then(|cd| cd.container),
});
}
// getting task additional info
task = Some(self.build_task_additional_info(&mnt_ns, &i.process));
}

// getting user and group information for parent task
if let Some(parent_ns) = opt_parent_ns {
parent = Some(self.build_task_additional_info(&parent_ns, &i.parent));
}

self.track_zombie_task(&mut std_info);

std_info.with_additional_info(AdditionalInfo { host, container })
std_info.with_additional_info(AdditionalInfo {
host,
container,
task: task.unwrap_or_default(),
parent: parent.unwrap_or_default(),
})
}

#[inline(always)]
Expand Down Expand Up @@ -1788,6 +1854,23 @@ impl<'s> EventConsumer<'s> {
printed
}

#[inline(always)]
fn cache_namespaces(&mut self, i: &bpf_events::EventInfo) {
if let Some(t_mnt_ns) = Self::task_mnt_ns(i) {
let pid = i.process.pid;
if let Err(e) = self.cache.cache_ns(pid, t_mnt_ns) {
debug!("failed to cache namespace pid={pid} ns={t_mnt_ns}: {e}");
}
}

if let Some(p_mnt_ns) = Self::parent_mnt_ns(i) {
let pid = i.parent.pid;
if let Err(e) = self.cache.cache_ns(pid, p_mnt_ns) {
debug!("failed to cache namespace pid={pid} ns={p_mnt_ns}: {e}");
}
}
}

#[inline(always)]
fn handle_event(&mut self, enc_event: &mut EncodedEvent) {
let i = unsafe { enc_event.info() }.unwrap();
Expand All @@ -1799,12 +1882,7 @@ impl<'s> EventConsumer<'s> {

let etype = i.etype;

if let Some(mnt_ns) = Self::task_mnt_ns(i) {
let pid = i.process.pid;
if let Err(e) = self.cache.cache_ns(pid, mnt_ns) {
debug!("failed to cache namespace pid={pid} ns={mnt_ns}: {e}");
}
}
self.cache_namespaces(i);

let std_info = self.build_std_event_info(*i);

Expand Down
115 changes: 113 additions & 2 deletions kunai/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ use std::{
use thiserror::Error;

use crate::{
util::namespaces::{self, Kind, Namespace, Switcher},
util::{
account::{Group, Groups, User, Users},
namespaces::{self, Kind, Namespace, Switcher},
},
yara::Scanner,
};

Expand All @@ -42,6 +45,12 @@ pub enum Error {
ScanError(#[from] yara_x::errors::ScanError),
}

impl Error {
pub fn is_unknown_ns(&self) -> bool {
matches!(self, Error::UnknownNs(_))
}
}

#[derive(Debug, Default, Clone, FieldGetter, Serialize, Deserialize)]
pub struct FileMeta {
pub md5: String,
Expand Down Expand Up @@ -266,21 +275,31 @@ struct CachedNs {
switcher: namespaces::Switcher,
}

#[derive(Debug)]
struct UsersAndGroups {
users: Users,
groups: Groups,
}

pub struct Cache {
namespaces: LruHashMap<Namespace, CachedNs>,
hashes: LruHashMap<Key, Hashes>,
users_groups: LruHashMap<Namespace, UsersAndGroups>,
// since hashes and signatures are not computed
// at the same time. It seems a better option
// to separate into two HashMaps to prevent
// any race
signatures: LruHashMap<Key, Vec<String>>,
}

const NS_CACHE_SIZE: usize = 256;

impl Cache {
// Constructs a new Hcache
pub fn with_max_entries(cap: usize) -> Self {
Cache {
namespaces: LruHashMap::with_max_entries(128),
namespaces: LruHashMap::with_max_entries(NS_CACHE_SIZE),
users_groups: LruHashMap::with_max_entries(NS_CACHE_SIZE),
hashes: LruHashMap::with_max_entries(cap),
signatures: LruHashMap::with_max_entries(cap),
}
Expand All @@ -300,6 +319,98 @@ impl Cache {
Ok(())
}

/// Get a [User] structure corresponding to user id `uid`
#[inline(always)]
pub fn get_user_by_uid(&mut self, ns: &Namespace, uid: &u32) -> Result<Option<&User>, Error> {
if !ns.is_kind(Kind::Mnt) {
return Err(Error::WrongNsKind {
exp: Kind::Mnt,
got: ns.kind,
});
}

let Some(entry) = self.namespaces.get(ns) else {
return Err(Error::UnknownNs(*ns));
};

// we have already parsed users and groups
if self.users_groups.contains_key(ns) {
// we have an entry for uid so we return it
if self
.users_groups
.get(ns)
.map(|ung| ung.users.contains_uid(uid))
.unwrap_or_default()
{
return Ok(self
.users_groups
.get(ns)
.and_then(|users| users.users.get_by_uid(uid)));
}
}

// we haven't yet parsed users and groups or we don't find an entry
let users = entry.switcher.do_in_namespace(|| {
Ok(UsersAndGroups {
users: Users::from_sys().map_err(namespaces::Error::other)?,
groups: Groups::from_sys().map_err(namespaces::Error::other)?,
})
})?;

self.users_groups.insert(*ns, users);

Ok(self
.users_groups
.get(ns)
.and_then(|ung| ung.users.get_by_uid(uid)))
}

/// Get a [Group] structure corresponding to group id `gid`
#[inline(always)]
pub fn get_group_by_gid(&mut self, ns: &Namespace, gid: &u32) -> Result<Option<&Group>, Error> {
if !ns.is_kind(Kind::Mnt) {
return Err(Error::WrongNsKind {
exp: Kind::Mnt,
got: ns.kind,
});
}

let Some(entry) = self.namespaces.get(ns) else {
return Err(Error::UnknownNs(*ns));
};

// we have already parsed users and groups
if self.users_groups.contains_key(ns) {
// we have an entry for uid so we return it
if self
.users_groups
.get(ns)
.map(|ung| ung.groups.contains_gid(gid))
.unwrap_or_default()
{
return Ok(self
.users_groups
.get(ns)
.and_then(|users| users.groups.get_by_gid(gid)));
}
}

// we haven't yet parsed users and groups or we don't find an entry
let users = entry.switcher.do_in_namespace(|| {
Ok(UsersAndGroups {
users: Users::from_sys().map_err(namespaces::Error::other)?,
groups: Groups::from_sys().map_err(namespaces::Error::other)?,
})
})?;

self.users_groups.insert(*ns, users);

Ok(self
.users_groups
.get(ns)
.and_then(|ung| ung.groups.get_by_gid(gid)))
}

#[inline(always)]
pub fn get_sig_or_cache(
&mut self,
Expand Down
Loading
Loading