Skip to content

Commit

Permalink
Merge pull request #158 from kunai-project/refactor-ebpf-log
Browse files Browse the repository at this point in the history
refactor: turn error event into log event
  • Loading branch information
qjerome authored Dec 19, 2024
2 parents 4d13bcc + 7709467 commit 6aca3c8
Show file tree
Hide file tree
Showing 13 changed files with 66 additions and 69 deletions.
4 changes: 2 additions & 2 deletions kunai-common/src/bpf_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ pub enum Type {
Correlation,
#[str("cache_hash")]
CacheHash,
#[str("error")]
Error,
#[str("log")]
Log,
#[str("syscore_resume")]
SyscoreResume,

Expand Down
6 changes: 3 additions & 3 deletions kunai-common/src/bpf_events/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ mod mount;
pub use mount::*;
mod prctl;
pub use prctl::*;
pub mod error;
pub use error::{ErrorData, ErrorEvent};
pub mod log;
pub use log::{LogData, LogEvent};
mod syscore_resume;
pub use syscore_resume::*;
mod kill;
Expand Down Expand Up @@ -85,7 +85,7 @@ const fn max_bpf_event_size() -> usize {
| Type::FileCreate => FileEvent::size_of(),
Type::FileRename => FileRenameEvent::size_of(),
Type::FileUnlink => UnlinkEvent::size_of(),
Type::Error => ErrorEvent::size_of(),
Type::Log => LogEvent::size_of(),
Type::SyscoreResume => SysCoreResumeEvent::size_of(),
// these are event types only used in user land
Type::Unknown
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@ use crate::{
string::String,
};

pub type ErrorEvent = Event<ErrorData>;
pub type LogEvent = Event<LogData>;

#[repr(C)]
#[derive(Clone, Copy)]
pub enum Level {
Info,
Warn,
Error,
}

#[repr(C)]
pub struct ErrorData {
pub struct LogData {
pub location: String<32>,
pub line: u32,
pub level: Level,
Expand All @@ -28,7 +30,7 @@ bpf_target_code! {

const DEFAULT_COMM: String<16> = string::from_static("?");

impl ErrorEvent {
impl LogEvent {
#[inline(always)]
pub fn init_with_level(&mut self, level: Level){
let pid_tgid = bpf_get_current_pid_tgid();
Expand All @@ -41,7 +43,7 @@ bpf_target_code! {
}

not_bpf_target_code! {
impl core::fmt::Display for ErrorEvent {
impl core::fmt::Display for LogEvent {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
Expand Down
4 changes: 2 additions & 2 deletions kunai-common/src/bpf_events/events/perfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub const KUNAI_EVENTS_MAP: &str = "KUNAI_EVENTS";
pub const KUNAI_STATS_MAP: &str = "KUNAI_STATS";

bpf_target_code! {
use crate::bpf_events::{Event,Type, ErrorEvent};
use crate::bpf_events::{Event,Type, LogEvent};
use aya_ebpf::{macros::map, maps::{HashMap,PerfEventByteArray}, EbpfContext};

#[map(name = "KUNAI_EVENTS")]
Expand All @@ -15,7 +15,7 @@ bpf_target_code! {


#[inline(always)]
pub unsafe fn pipe_error<C: EbpfContext>(ctx: &C, e: &ErrorEvent) {
pub unsafe fn pipe_log<C: EbpfContext>(ctx: &C, e: &LogEvent) {
EVENTS.output(ctx, e.encode(), 0);
}

Expand Down
66 changes: 28 additions & 38 deletions kunai-common/src/errors/bpf.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
use aya_ebpf::{macros::map, maps::LruPerCpuHashMap, EbpfContext};

use crate::{
bpf_events::{error, ErrorEvent},
bpf_events::{log, LogEvent},
string::String,
};

#[allow(unused_imports)]
use super::*;

#[map]
pub static mut ERRORS: LruPerCpuHashMap<u32, ErrorEvent> =
LruPerCpuHashMap::with_max_entries(16, 0);
pub static mut LOGS: LruPerCpuHashMap<u32, LogEvent> = LruPerCpuHashMap::with_max_entries(16, 0);

const SIZE: usize = ErrorEvent::size_of();
pub static EMPTY_ERROR: [u8; SIZE] = [0; SIZE];
const SIZE: usize = LogEvent::size_of();
pub static EMPTY_LOG: [u8; SIZE] = [0; SIZE];

#[macro_export]
macro_rules! probe_name {
Expand Down Expand Up @@ -90,27 +89,27 @@ pub struct Args {
pub location: String<32>,
pub message: Option<String<64>>,
pub err: Option<ProbeError>,
pub level: error::Level,
pub level: log::Level,
}

#[inline(always)]
pub unsafe fn error_with_args<C: EbpfContext>(ctx: &C, args: &Args) {
let _ = ERRORS.insert(&0, &(*(EMPTY_ERROR.as_ptr() as *const ErrorEvent)), 0);
if let Some(e) = ERRORS.get_ptr_mut(&0) {
pub unsafe fn log_with_args<C: EbpfContext>(ctx: &C, args: &Args) {
let _ = LOGS.insert(&0, &(*(EMPTY_LOG.as_ptr() as *const LogEvent)), 0);
if let Some(e) = LOGS.get_ptr_mut(&0) {
let e = &mut *e;
e.init_with_level(args.level);
e.info.etype = bpf_events::Type::Error;
e.info.etype = bpf_events::Type::Log;
e.data.location.copy_from(&args.location);
e.data.line = args.line;
e.data.error = args.err;
e.data.message = args.message;

bpf_events::pipe_error(ctx, e);
bpf_events::pipe_log(ctx, e);
}
}

#[macro_export]
macro_rules! _error {
macro_rules! log {
($ctx:expr, $msg:literal, $err:expr, $level:expr) => {{
unsafe {
const _PROBE_NAME: $crate::string::String<32> = $crate::probe_name!();
Expand All @@ -130,53 +129,44 @@ macro_rules! _error {
level: $level,
};

$crate::errors::error_with_args($ctx, &args);
$crate::errors::log_with_args($ctx, &args);
};
}};
}

#[macro_export]
macro_rules! error {
($ctx:expr, $err:expr) => {{
$crate::error!($ctx, "", $err)
}};

($ctx:expr, $msg:literal, $err:expr) => {{
$crate::_error!(
$ctx,
$msg,
Some($err),
$crate::bpf_events::error::Level::Error
);
}};
}

#[macro_export]
macro_rules! error_msg {
// literal must be evaluated first
($ctx:expr, $msg:literal) => {
$crate::_error!($ctx, $msg, None, $crate::bpf_events::error::Level::Error)
$crate::log!($ctx, $msg, None, $crate::bpf_events::log::Level::Error)
};
}

#[macro_export]
macro_rules! warn {
($ctx:expr, $err:expr) => {
$crate::warn!($ctx, "", $err);
$crate::log!($ctx, "", Some($err), $crate::bpf_events::log::Level::Error)
};

($ctx:expr, $msg:literal, $err:expr) => {
$crate::_error!(
$crate::log!(
$ctx,
$msg,
Some($err),
$crate::bpf_events::error::Level::Warn
$crate::bpf_events::log::Level::Error
);
};
}

#[macro_export]
macro_rules! warn_msg {
macro_rules! warn {
// literal must be evaluated first
($ctx:expr, $msg:literal) => {
$crate::_error!($ctx, $msg, None, $crate::bpf_events::error::Level::Warn)
$crate::log!($ctx, $msg, None, $crate::bpf_events::log::Level::Warn)
};

($ctx:expr, $err:expr) => {
$crate::log!($ctx, "", Some($err), $crate::bpf_events::log::Level::Warn);
};

($ctx:expr, $msg:literal, $err:expr) => {
$crate::log!($ctx, $msg, Some($err), $crate::bpf_events::log::Level::Warn);
};
}
4 changes: 2 additions & 2 deletions kunai-ebpf/src/probes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use kunai_common::{
bpf_events::*,
co_re,
consts::*,
error, error_msg,
error,
errors::{self, *},
inspect_err,
path::{self, *},
utils::*,
warn, warn_msg,
warn,
};

#[cfg(feature = "debug")]
Expand Down
6 changes: 3 additions & 3 deletions kunai-ebpf/src/probes/bpf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ unsafe fn try_bpf_prog_load(ctx: &RetProbeContext) -> ProbeResult<()> {
if let Some(p_name) = bpf_prog_aux.name() {
ignore_result!(inspect_err!(
event.data.name.read_kernel_str_bytes(p_name),
|_| warn_msg!(ctx, "failed to read program name")
|_| warn!(ctx, "failed to read program name")
));
}

Expand All @@ -90,7 +90,7 @@ unsafe fn try_bpf_prog_load(ctx: &RetProbeContext) -> ProbeResult<()> {
if let Some(afn) = bpf_prog_aux.attach_func_name() {
ignore_result!(inspect_err!(
event.data.attached_func_name.read_kernel_str_bytes(afn),
|_| warn_msg!(ctx, "failed to read attach_func_name")
|_| warn!(ctx, "failed to read attach_func_name")
));
}

Expand All @@ -102,7 +102,7 @@ unsafe fn try_bpf_prog_load(ctx: &RetProbeContext) -> ProbeResult<()> {

pipe_event(ctx, event);
} else {
error_msg!(ctx, "failed to retrieve BPF program load event")
error!(ctx, "failed to retrieve BPF program load event")
}

// we use a LruHashmap so we can safely ignore result
Expand Down
2 changes: 1 addition & 1 deletion kunai-ebpf/src/probes/bpf_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ unsafe fn handle_socket_attach_prog(
}

//handle loading of regular bpf program
warn_msg!(exit_ctx, "bpf program attached to socket not yet supported");
warn!(exit_ctx, "bpf program attached to socket not yet supported");

Ok(())
}
2 changes: 1 addition & 1 deletion kunai-ebpf/src/probes/execve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ unsafe fn execve_event<C: EbpfContext>(ctx: &C, rc: i32) -> ProbeResult<()> {
.read_user_at(arg_start as *const u8, arg_len as u32)
.is_err()
{
warn_msg!(ctx, "failed to read argv")
warn!(ctx, "failed to read argv")
}

// cgroup parsing
Expand Down
8 changes: 4 additions & 4 deletions kunai-ebpf/src/probes/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,15 @@ unsafe fn limit_eps_with_context<C: EbpfContext>(ctx: &C) -> ProbeResult<bool> {
// we allow a process to take alone half of this otherwise we report it
if let (true, limit) = is_task_io_limit_reach(task_limit) {
if limit {
error_msg!(ctx, "current task i/o limit reached");
error!(ctx, "current task i/o limit reached");
}
return Ok(true);
}

// if there are too many I/O globally a random task can see its I/O ignored
if let (true, limit) = is_global_io_limit_reach(glob_limit) {
if limit {
error_msg!(ctx, "global i/o limit reached");
error!(ctx, "global i/o limit reached");
}
return Ok(true);
}
Expand Down Expand Up @@ -221,7 +221,7 @@ unsafe fn try_vfs_read(ctx: &ProbeContext) -> ProbeResult<()> {
}

// we mark file as being tracked
ignore_result!(inspect_err!(file_set_flag(&file, READ), |_| warn_msg!(
ignore_result!(inspect_err!(file_set_flag(&file, READ), |_| warn!(
ctx,
"failed to track file read"
)));
Expand Down Expand Up @@ -297,7 +297,7 @@ unsafe fn try_vfs_write(ctx: &ProbeContext) -> ProbeResult<()> {
}

// we mark file as being tracked
ignore_result!(inspect_err!(file_set_flag(&file, WRITE), |_| warn_msg!(
ignore_result!(inspect_err!(file_set_flag(&file, WRITE), |_| warn!(
ctx,
"failed to track file write"
)));
Expand Down
2 changes: 1 addition & 1 deletion kunai-ebpf/src/probes/init_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ unsafe fn handle_init_module(ctx: &TracePointContext, args: InitModuleArgs) -> P
.data
.uargs
.read_user_str_bytes(args.uargs() as *const u8),
|_| warn_msg!(ctx, "failed to read uargs")
|_| warn!(ctx, "failed to read uargs")
));

// setting event data
Expand Down
2 changes: 1 addition & 1 deletion kunai-ebpf/src/probes/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ unsafe fn try_schedule(ctx: &ProbeContext) -> ProbeResult<()> {

// we do not really care if that is failing
ignore_result!(inspect_err!(MARKED.insert(&task_uuid, &true, 0), |_| {
warn_msg!(ctx, "failed to track task")
warn!(ctx, "failed to track task")
}));

// we send event to userland
Expand Down
19 changes: 12 additions & 7 deletions kunai/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use kunai::util::uname::Utsname;
use kunai::yara::{Scanner, SourceCode};
use kunai::{cache, util};
use kunai_common::bpf_events::{
self, error, event, mut_event, EncodedEvent, Event, PrctlOption, Signal, TaskInfo, Type,
self, event, mut_event, EncodedEvent, Event, PrctlOption, Signal, TaskInfo, Type,
MAX_BPF_EVENT_SIZE,
};
use kunai_common::config::Filter;
Expand Down Expand Up @@ -2104,7 +2104,11 @@ impl EventConsumer<'_> {
Err(e) => error!("failed to decode {} event: {:?}", etype, e),
},

Type::Error => panic!("error events should be processed earlier"),
Type::Log => {
// only panic in debug
#[cfg(debug_assertions)]
panic!("log events should be processed earlier")
}
Type::SyscoreResume => { /* just ignore it */ }
}
}
Expand Down Expand Up @@ -2295,11 +2299,12 @@ impl EventProducer {
}
}
}
Type::Error => {
let e = event!(e, bpf_events::ErrorEvent).unwrap();
Type::Log => {
let e = event!(e, bpf_events::LogEvent).unwrap();
match e.data.level {
error::Level::Warn => warn!("{}", e),
error::Level::Error => error!("{}", e),
bpf_events::log::Level::Info => info!("{}", e),
bpf_events::log::Level::Warn => warn!("{}", e),
bpf_events::log::Level::Error => error!("{}", e),
}
// we don't need to process such event further
return true;
Expand Down Expand Up @@ -2966,7 +2971,7 @@ impl Command {
Type::Unknown
| Type::CacheHash
| Type::Correlation
| Type::Error
| Type::Log
| Type::EndConfigurable
| Type::TaskSched
| Type::SyscoreResume
Expand Down

0 comments on commit 6aca3c8

Please sign in to comment.