Skip to content

Commit

Permalink
edriver & edriver-rs: support kernel version v6.x
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskaliX committed Nov 29, 2024
1 parent 1fab004 commit bc3712b
Show file tree
Hide file tree
Showing 62 changed files with 283 additions and 249 deletions.
2 changes: 1 addition & 1 deletion plugins/edriver-rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "edriver"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
authors = ["chriskali <chriskalix@protonmail.com>"]
description = "Rust version of hades edriver"
Expand Down
9 changes: 9 additions & 0 deletions plugins/edriver-rust/src/bpf/common/edriver.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ int rtp__process_exec(struct bpf_raw_tracepoint_args *ctx)
return report_event(&c);
}

// SEC("raw_tracepoint/sys_exit")
// int rtp__sys_exit(struct bpf_raw_tracepoint_args *ctx)
// {
// /* skip failed syscalls */
// if (ctx->args[1])
// return 0;
// return 0;
// }

/* proc_info init */
static struct proc_info *proc_info_init(struct task_struct *task)
{
Expand Down
77 changes: 47 additions & 30 deletions plugins/edriver-rust/src/bpfmgr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,45 +30,26 @@ lazy_static! {
pub struct Bpfmanager {}

impl Bpfmanager {
pub fn new(mut client: Client) -> Result<Self> {
pub fn new(client: Client) -> Result<Self> {
Self::bump_rlimit()?;

let skel_builder = HadesSkelBuilder::default();
let open_skel: OpenHadesSkel<'_> =
skel_builder.open().context("fail to open BPF program")?;
let mut skel = open_skel.load().context("failed to load BPF program")?;
skel.attach()?;
/* loss cnt */
let open_skel = skel_builder.open().context("Skel open failed")?;
let mut skel = open_skel.load().context("Load skel failed")?;

skel.attach().context("Skel attach failed")?;

let loss_cnt_c = LOSS_CNT.clone();
/* transformer */
let mut trans = Transformer::new();

/* event handle wrap */
let handle = |_cpu: i32, data: &[u8]| {
let map = Execve::parse(&data[4..], &mut trans).unwrap();
println!("{:?}", map);
};

let _ = thread::Builder::new()
.name("heartbeat".to_string())
.spawn(move || loop {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let mut rec = Record::new();
rec.timestamp = timestamp as i64;
rec.data_type = 900;
let pld = rec.mut_data();
pld.fields.insert(
"loss_cnt".to_string(),
loss_cnt_c.lock().unwrap().to_string(),
);
if let Err(err) = client.send_record(&rec) {
warn!("heartbeat will exit: {}", err);
break;
};
*LOSS_CNT.lock().unwrap() = 0;
thread::sleep(Duration::from_secs(30))
});
Self::start_heartbeat_thread(client, loss_cnt_c)?;

let binding = skel.maps();
let map = binding.events();
let events = PerfBufferBuilder::new(map)
Expand All @@ -82,7 +63,8 @@ impl Bpfmanager {
}

fn handle_lost_events(_cpu: i32, cnt: u64) {
*LOSS_CNT.lock().unwrap() += cnt;
let mut loss_count = LOSS_CNT.lock().unwrap();
*loss_count += cnt;
}

fn bump_rlimit() -> Result<()> {
Expand All @@ -95,4 +77,39 @@ impl Bpfmanager {
}
Ok(())
}

fn start_heartbeat_thread(mut client: Client, loss_counter: Arc<Mutex<u64>>) -> Result<()> {
thread::Builder::new()
.name("heartbeat".to_string())
.spawn(move || loop {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64;

let mut rec = Record::new();
rec.timestamp = timestamp;
rec.data_type = 900;

let pld = rec.mut_data();
if let Ok(loss_count) = loss_counter.lock() {
pld.fields
.insert("loss_cnt".to_string(), loss_count.to_string());
} else {
warn!("Failed to lock loss_counter");
continue;
}

if let Err(err) = client.send_record(&rec) {
warn!("Heartbeat will exit: {}", err);
break;
}

*loss_counter.lock().unwrap() = 0;
thread::sleep(Duration::from_secs(30));
})
.context("Failed to spawn heartbeat thread")?;

Ok(())
}
}
2 changes: 1 addition & 1 deletion plugins/edriver-rust/src/events/execve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ impl Event for Execve {
}

fn parse(data: &[u8], trans: &mut Transformer) -> Result<HashMap<String, String>> {
let mut m: HashMap<_, _> = HashMap::new();
let mut m: HashMap<String, String> = HashMap::new();
let mut idx: usize = 0;
let pid = parse_u32(data, &mut idx)?;
m.insert("pid".to_string(), pid.to_string());
Expand Down
1 change: 0 additions & 1 deletion plugins/edriver-rust/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use std::{
};

pub mod execve;
pub mod rasp_java;

pub trait Event {
fn init() -> Result<()>;
Expand Down
13 changes: 0 additions & 13 deletions plugins/edriver-rust/src/events/rasp_java.rs

This file was deleted.

34 changes: 17 additions & 17 deletions plugins/edriver-rust/src/process/process.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use anyhow::Result;
// use anyhow::Result;

#[derive(Debug, Clone, Default)]
pub struct ProcessInfo {
pub pid: u32,
pub cmdline: Option<String>,
pub exe_name: Option<String>,
pub exe_path: Option<String>,
pub maps: Option<Vec<Map>>,
}
// #[derive(Debug, Clone, Default)]
// pub struct ProcessInfo {
// pub pid: u32,
// pub cmdline: Option<String>,
// pub exe_name: Option<String>,
// pub exe_path: Option<String>,
// pub maps: Option<Vec<Map>>,
// }

impl ProcessInfo {
pub fn from_pid(pid: u32) -> Result<Self> {
Ok(())
}
// impl ProcessInfo {
// pub fn from_pid(pid: u32) -> Result<Self> {
// Ok(())
// }

pub fn read_cmdline(&mut self) -> Option<String> {
format!("/proc/{}/cmdline", self::pid);
}
}
// pub fn read_cmdline(&mut self) -> Result<String> {
// let cmdline = fs::read_to_string(format!("/proc/{}/cmdline", pid))?;
// }
// }
10 changes: 5 additions & 5 deletions plugins/edriver/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ EBPF_BUILD := +$(MAKE) -C bpf
EBPF_CO-RE_FLAG := core
EBPF_SOURCE_PATH = bpf/hades_ebpf_driver.bpf.o
EBPF_SOURCE_CO-RE_PATH = bpf/hades_ebpf_driver.bpf.core.o
EBPF_TARGET_PATH = user/hades_ebpf_driver.o
EBPF_TARGET_PATH = pkg/hades_ebpf_driver.o
GO_TARGET_PATH := -o edriver
VERSION := v1.1.1
VERSION := v1.1.2

.PHONY: mod-tidy
mod-tidy:
Expand All @@ -14,11 +14,11 @@ mod-tidy:
no-core: mod-tidy
$(EBPF_BUILD)
mv $(EBPF_SOURCE_PATH) $(EBPF_TARGET_PATH)
CGO_ENABLED=0 go build -ldflags "-X 'hades-ebpf/conf.VERSION=$(VERSION)'" $(GO_TARGET_PATH) .
CGO_ENABLED=0 go build -ldflags "-X 'edriver/constants.VERSION=$(VERSION)'" $(GO_TARGET_PATH) .
core: mod-tidy
$(EBPF_BUILD) $(EBPF_CO-RE_FLAG)
mv $(EBPF_SOURCE_CO-RE_PATH) $(EBPF_TARGET_PATH)
CGO_ENABLED=0 go build -ldflags "-X 'hades-ebpf/conf.VERSION=$(VERSION)'" $(GO_TARGET_PATH) .
CGO_ENABLED=0 go build -ldflags "-X 'edriver/constants.VERSION=$(VERSION)'" $(GO_TARGET_PATH) .
testing: mod-tidy
cp $(EBPF_TARGET_PATH) test/hades_ebpf_driver.o
cp $(EBPF_TARGET_PATH) tests/hades_ebpf_driver.o
CGO_ENABLED=0 go test -v -exec sudo ./...
2 changes: 1 addition & 1 deletion plugins/edriver/cmd/list.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cmd

import (
"hades-ebpf/user/decoder"
"edriver/pkg/decoder"
"os"
"sort"

Expand Down
8 changes: 4 additions & 4 deletions plugins/edriver/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package cmd

import (
"hades-ebpf/conf"
"edriver/constants"
"os"

"github.com/spf13/cobra"
)

var RootCmd = &cobra.Command{
Use: "edriver",
Version: conf.VERSION,
Version: constants.VERSION,
}

func Execute() {
Expand All @@ -23,6 +23,6 @@ func Execute() {

func init() {
cobra.EnablePrefixMatching = true
RootCmd.PersistentFlags().BoolVar(&conf.Debug, "debug", false, "set true send output to console")
RootCmd.Flags().StringSliceVarP(&conf.EventFilter, "filter", "f", []string{}, "set filters, like 1203,1201")
RootCmd.PersistentFlags().BoolVar(&constants.Debug, "debug", false, "set true send output to console")
RootCmd.Flags().StringSliceVarP(&constants.EventFilter, "filter", "f", []string{}, "set filters, like 1203,1201")
}
12 changes: 0 additions & 12 deletions plugins/edriver/conf/conf.go

This file was deleted.

5 changes: 5 additions & 0 deletions plugins/edriver/constants/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package constants

// Debug flag
var Debug bool
var EventFilter []string
5 changes: 5 additions & 0 deletions plugins/edriver/constants/url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package constants

// The hadesoss is now hold by Hades team.
// Add local address to DNS if you deploy Hades in prod
const DOWNLOAD_URL = "http://hadesoss.com/"
3 changes: 3 additions & 0 deletions plugins/edriver/constants/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package constants

var VERSION string
8 changes: 5 additions & 3 deletions plugins/edriver/go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
module hades-ebpf
module edriver

replace github.com/chriskaliX/SDK => ../../SDK/go

go 1.22
go 1.22.0

toolchain go1.22.2

require (
github.com/aquasecurity/libbpfgo/helpers v0.4.5
Expand All @@ -16,7 +18,6 @@ require (
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.10.0
go.uber.org/zap v1.27.0
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f
golang.org/x/time v0.8.0
k8s.io/apimachinery v0.31.3
k8s.io/utils v0.0.0-20241104163129-6fe5fd82f078
Expand Down Expand Up @@ -49,6 +50,7 @@ require (
github.com/vishvananda/netns v0.0.5 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/arch v0.12.0 // indirect
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirect
golang.org/x/net v0.31.0 // indirect
golang.org/x/sync v0.9.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
20 changes: 10 additions & 10 deletions plugins/edriver/main.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package main

import (
"hades-ebpf/conf"
"hades-ebpf/user"
"hades-ebpf/user/decoder"
_ "hades-ebpf/user/event"
"edriver/constants"
user "edriver/pkg"
"edriver/pkg/decoder"
_ "edriver/pkg/events"

"hades-ebpf/cmd"
"edriver/cmd"

"github.com/chriskaliX/SDK"
"github.com/chriskaliX/SDK/logger"
Expand All @@ -20,7 +20,7 @@ import (
var driver *user.Driver

func appRun(s SDK.ISandbox) (err error) {
decoder.SetAllowList(conf.EventFilter)
decoder.SetAllowList(constants.EventFilter)
driver, err = user.NewDriver(s)
if err != nil {
zap.S().Error(err)
Expand All @@ -40,11 +40,11 @@ func appRun(s SDK.ISandbox) (err error) {
func main() {
// inject into sandbox
cmd.RootCmd.Run = (func(_ *cobra.Command, _ []string) {
if !conf.Debug {
if !constants.Debug {
SDK.RuntimeOpt()
}
sconfig := &SDK.SandboxConfig{
Debug: conf.Debug,
sconstantsig := &SDK.SandboxConfig{
Debug: constants.Debug,
Name: "edriver",
LogConfig: &logger.Config{
Path: "edriver.log",
Expand All @@ -56,7 +56,7 @@ func main() {
},
}
// sandbox init
sandbox := SDK.NewSandbox(sconfig)
sandbox := SDK.NewSandbox(sconstantsig)
// Better UI for command line usage
sandbox.Run(appRun)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package cache

import (
"bytes"
"edriver/utils"
"fmt"
"hades-ebpf/utils"
"os"
"strings"
"time"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cache

import (
"hades-ebpf/utils"
"edriver/utils"

"github.com/chriskaliX/SDK/utils/hash"
)
Expand Down
Loading

0 comments on commit bc3712b

Please sign in to comment.