Skip to content
Merged
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
1 change: 1 addition & 0 deletions implants/lib/eldritch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod crypto;
pub mod file;
pub mod pivot;
pub mod process;
mod report;
mod runtime;
pub mod sys;
pub mod time;
Expand Down
128 changes: 128 additions & 0 deletions implants/lib/eldritch/src/report/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
mod process_list_impl;

use allocative::Allocative;
use derive_more::Display;
use serde::{Serialize, Serializer};
use starlark::collections::SmallMap;
use starlark::environment::{Methods, MethodsBuilder, MethodsStatic};
use starlark::eval::Evaluator;
use starlark::values::none::NoneType;
use starlark::values::{
starlark_value, ProvidesStaticType, StarlarkValue, UnpackValue, Value, ValueLike,
};
use starlark::{starlark_module, starlark_simple_value};

#[derive(Copy, Clone, Debug, PartialEq, Display, ProvidesStaticType, Allocative)]
#[display(fmt = "ReportLibrary")]
pub struct ReportLibrary();
starlark_simple_value!(ReportLibrary);

#[allow(non_upper_case_globals)]
#[starlark_value(type = "report_library")]
impl<'v> StarlarkValue<'v> for ReportLibrary {
fn get_methods() -> Option<&'static Methods> {
static RES: MethodsStatic = MethodsStatic::new();
RES.methods(methods)
}
}

impl Serialize for ReportLibrary {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_none()
}
}

impl<'v> UnpackValue<'v> for ReportLibrary {
fn expected() -> String {
ReportLibrary::get_type_value_static().as_str().to_owned()
}

fn unpack_value(value: Value<'v>) -> Option<Self> {
Some(*value.downcast_ref::<ReportLibrary>().unwrap())
}
}

// This is where all of the "report.X" impl methods are bound
#[starlark_module]
#[rustfmt::skip]
#[allow(clippy::needless_lifetimes, clippy::type_complexity, clippy::too_many_arguments)]
fn methods(builder: &mut MethodsBuilder) {
fn process_list(this: ReportLibrary, starlark_eval: &mut Evaluator<'v, '_>, process_list: Vec<SmallMap<String, Value>>) -> anyhow::Result<NoneType> {
if false { println!("Ignore unused this var. _this isn't allowed by starlark. {:?}", this); }
process_list_impl::process_list(starlark_eval, process_list)?;
Ok(NoneType{})
}
}

#[cfg(test)]
mod test {
use std::collections::HashMap;

use crate::pb::process::Status;
use crate::pb::{Process, ProcessList, Tome};
use crate::Runtime;
use anyhow::Error;

macro_rules! process_list_tests {
($($name:ident: $value:expr,)*) => {
$(
#[tokio::test]
async fn $name() {
let tc: TestCase = $value;
let (runtime, broker) = Runtime::new();
let handle = tokio::task::spawn_blocking(move || {
runtime.run(tc.tome);
});

let want_err_str = match tc.want_error {
Some(err) => err.to_string(),
None => "".to_string(),
};
let err_str = match broker.collect_errors().pop() {
Some(err) => err.to_string(),
None => "".to_string(),
};
assert_eq!(want_err_str, err_str);
assert_eq!(tc.want_output, broker.collect_text().join(""));
assert_eq!(Some(tc.want_proc_list), broker.collect_process_lists().pop());
handle.await.unwrap();
}
)*
}
}

struct TestCase {
pub tome: Tome,
pub want_output: String,
pub want_error: Option<Error>,
pub want_proc_list: ProcessList,
}

process_list_tests! {
one_process: TestCase{
tome: Tome{
eldritch: String::from(r#"report.process_list([{"pid":5,"ppid":101,"name":"test","username":"root","path":"/bin/cat","env":"COOL=1","command":"cat","cwd":"/home/meow","status":"IDLE"}])"#),
parameters: HashMap::new(),
file_names: Vec::new(),
},
want_proc_list: ProcessList{list: vec![
Process{
pid: 5,
ppid: 101,
name: "test".to_string(),
principal: "root".to_string(),
path: "/bin/cat".to_string(),
env: "COOL=1".to_string(),
cmd: "cat".to_string(),
cwd: "/home/meow".to_string(),
status: Status::Idle.into(),
},
]},
want_output: String::from(""),
want_error: None,
},
}
}
56 changes: 56 additions & 0 deletions implants/lib/eldritch/src/report/process_list_impl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use anyhow::Result;
use starlark::values::Value;
use starlark::{collections::SmallMap, eval::Evaluator};

use crate::{
pb::{process::Status, Process, ProcessList},
runtime::Client,
};

pub fn process_list(
starlark_eval: &Evaluator<'_, '_>,
process_list: Vec<SmallMap<String, Value>>,
) -> Result<()> {
let client = Client::from_extra(starlark_eval.extra)?;

let mut pb_process_list = ProcessList { list: Vec::new() };
for proc in process_list {
pb_process_list.list.push(Process {
pid: unpack_u64(&proc, "pid"),
ppid: unpack_u64(&proc, "ppid"),
name: unpack_string(&proc, "name"),
principal: unpack_string(&proc, "username"),
path: unpack_string(&proc, "path"),
cmd: unpack_string(&proc, "command"),
env: unpack_string(&proc, "env"),
cwd: unpack_string(&proc, "cwd"),
status: unpack_status(&proc).into(),
})
}

client.report_process_list(pb_process_list)?;
Ok(())
}

fn unpack_i32(proc: &SmallMap<String, Value>, key: &str) -> i32 {
match proc.get(key) {
Some(val) => val.unpack_i32().unwrap_or(0),
None => 0,
}
}
fn unpack_u64(proc: &SmallMap<String, Value>, key: &str) -> u64 {
unpack_i32(proc, key) as u64
}

fn unpack_string(proc: &SmallMap<String, Value>, key: &str) -> String {
match proc.get(key) {
Some(v) => v.unpack_str().unwrap_or("").to_string(),
None => String::from(""),
}
}

fn unpack_status(proc: &SmallMap<String, Value>) -> Status {
let val = unpack_string(proc, "status");
let status_str = format!("STATUS_{}", val).to_uppercase();
Status::from_str_name(status_str.as_str()).unwrap_or(Status::Unknown)
}
3 changes: 2 additions & 1 deletion implants/lib/eldritch/src/runtime/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Broker, Client, FileRequest};
use crate::pb::{File, ProcessList};
use crate::{
assets::AssetsLibrary, crypto::CryptoLibrary, file::FileLibrary, pb::Tome, pivot::PivotLibrary,
process::ProcessLibrary, sys::SysLibrary, time::TimeLibrary,
process::ProcessLibrary, report::ReportLibrary, sys::SysLibrary, time::TimeLibrary,
};
use anyhow::{Error, Result};
use chrono::Utc;
Expand Down Expand Up @@ -138,6 +138,7 @@ impl Runtime {
const assets: AssetsLibrary = AssetsLibrary();
const crypto: CryptoLibrary = CryptoLibrary();
const time: TimeLibrary = TimeLibrary();
const report: ReportLibrary = ReportLibrary();
}

GlobalsBuilder::extended_by(&[
Expand Down
2 changes: 2 additions & 0 deletions tavern/internal/ent/schema/host_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ func (HostProcess) Fields() []ent.Field {
return []ent.Field{
field.Uint64("pid").
Annotations(
entgql.Type("Uint64"),
entgql.OrderField("PROCESS_ID"),
).
Comment("ID of the process."),
field.Uint64("ppid").
Annotations(
entgql.Type("Uint64"),
entgql.OrderField("PARENT_PROCESS_ID"),
).
Comment("ID of the parent process."),
Expand Down
100 changes: 0 additions & 100 deletions tavern/internal/graphql/ent.resolvers.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading