├── .gitignore ├── Cargo.toml ├── syswall-logo-sm.png ├── cli ├── src │ ├── logger.rs │ ├── main.rs │ └── app.rs ├── Cargo.toml └── Cargo.lock ├── lib ├── Cargo.toml ├── src │ ├── process_state │ │ ├── files.rs │ │ ├── sockets.rs │ │ └── mod.rs │ ├── platforms │ │ ├── mod.rs │ │ └── linux_x86_64 │ │ │ ├── sockets.rs │ │ │ └── mod.rs │ ├── user_response.rs │ ├── tracer_conf.rs │ ├── lib.rs │ ├── syscalls.rs │ └── child_process.rs └── Cargo.lock ├── README.md ├── Cargo.lock ├── COPYING.LESSER └── COPYING /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /cli/target 3 | /lib/target 4 | **/*.rs.bk 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "cli", 4 | "lib", 5 | ] 6 | -------------------------------------------------------------------------------- /syswall-logo-sm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/polaris64/syswall/HEAD/syswall-logo-sm.png -------------------------------------------------------------------------------- /cli/src/logger.rs: -------------------------------------------------------------------------------- 1 | use log::{Level, Metadata, Record}; 2 | 3 | pub struct AppLogger; 4 | 5 | impl log::Log for AppLogger { 6 | fn enabled(&self, _metadata: &Metadata) -> bool { 7 | true 8 | } 9 | 10 | fn log(&self, record: &Record) { 11 | let prefix = match record.level() { 12 | Level::Error => "ERROR: ", 13 | Level::Warn => "WARNING: ", 14 | _ => "", 15 | }; 16 | if self.enabled(record.metadata()) { 17 | eprintln!("{}{}", prefix, record.args()); 18 | } 19 | } 20 | 21 | fn flush(&self) {} 22 | } 23 | -------------------------------------------------------------------------------- /cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "syswall_cli" 3 | version = "0.1.2" 4 | authors = ["Simon Pugnet "] 5 | edition = "2018" 6 | description = "syswall_cli: a simple CLI to syswall" 7 | keywords = ["linux", "syscalls", "security", "analysis", "tracing"] 8 | categories = ["command-line-utilities", "development-tools::debugging", "os::unix-apis"] 9 | license = "LGPL-3.0-only" 10 | repository = "https://github.com/polaris64/syswall" 11 | homepage = "https://www.polaris64.net/blog/programming/2019/syswall-a-firewall-for-syscalls" 12 | 13 | [dependencies] 14 | clap = "2.32.0" 15 | log = "0.4.6" 16 | 17 | [dependencies.syswall] 18 | path = "../lib" 19 | version = "0.3.1" 20 | 21 | [[bin]] 22 | name = "syswall_cli" 23 | path = "src/main.rs" 24 | -------------------------------------------------------------------------------- /lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "syswall" 3 | version = "0.3.1" 4 | authors = ["Simon Pugnet "] 5 | edition = "2018" 6 | description = "syswall: a firewall for syscalls" 7 | keywords = ["linux", "syscalls", "security", "analysis", "tracing"] 8 | categories = ["command-line-utilities", "development-tools::debugging", "os::unix-apis"] 9 | license = "LGPL-3.0-only" 10 | repository = "https://github.com/polaris64/syswall" 11 | homepage = "https://www.polaris64.net/blog/programming/2019/syswall-a-firewall-for-syscalls" 12 | 13 | [dependencies] 14 | libc = "0.2.48" 15 | log = "0.4.6" 16 | nix = "0.13.0" 17 | serde = { version = "1.0.87", features = ["derive"] } 18 | serde_json = "1.0" 19 | signal-hook = "0.1.8" 20 | 21 | [lib] 22 | name = "syswall" 23 | path = "src/lib.rs" 24 | -------------------------------------------------------------------------------- /lib/src/process_state/files.rs: -------------------------------------------------------------------------------- 1 | use nix::errno::Errno; 2 | use nix::fcntl::OFlag; 3 | 4 | #[derive(Debug, PartialEq)] 5 | pub enum ProcessFileState { 6 | Closed, 7 | CouldNotOpen(Errno), 8 | OpenBlockedHard, 9 | OpenBlockedSoft, 10 | Opened(usize), 11 | PendingSyscall, 12 | } 13 | 14 | #[derive(Debug)] 15 | pub struct ProcessFileRec { 16 | pub state: ProcessFileState, 17 | pub filename: String, 18 | pub mode: Option, 19 | pub flags: Option, 20 | } 21 | 22 | impl ProcessFileRec { 23 | pub fn new(path: &str, flag_bits: isize, mode_bits: isize) -> Self { 24 | Self { 25 | state: ProcessFileState::PendingSyscall, 26 | filename: String::from(path), 27 | mode: OFlag::from_bits(mode_bits as libc::c_int), 28 | flags: OFlag::from_bits(flag_bits as libc::c_int), 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /lib/src/platforms/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod linux_x86_64; 2 | 3 | use nix::unistd::Pid; 4 | 5 | use crate::process_state::ProcessState; 6 | use crate::syscalls::SyscallRegs; 7 | 8 | pub trait PlatformHandler { 9 | fn block_syscall(&self, pid: Pid, regs: &mut SyscallRegs) -> Result<(), &'static str>; 10 | fn pre( 11 | &self, 12 | state: &mut ProcessState, 13 | regs: &mut SyscallRegs, 14 | pid: Pid, 15 | ) -> SyscallEntryResult; 16 | fn post( 17 | &self, 18 | state: &mut ProcessState, 19 | regs: &mut SyscallRegs, 20 | pid: Pid, 21 | ); 22 | fn update_regs_hard_block(&self, pid: Pid, regs: &mut SyscallRegs) -> Result<(), &'static str>; 23 | } 24 | 25 | pub struct SyscallEntryResult { 26 | pub description: String, 27 | pub handled: bool, 28 | } 29 | 30 | impl SyscallEntryResult { 31 | pub fn new(handled: bool, description: String) -> Self { 32 | Self { description, handled } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/src/user_response.rs: -------------------------------------------------------------------------------- 1 | /// A response to a decision about a single syscall obtained from the user 2 | pub enum UserResponse { 3 | AllowAllSyscall, 4 | AllowOnce, 5 | BlockAllSyscallHard, 6 | BlockAllSyscallSoft, 7 | BlockOnceHard, 8 | BlockOnceSoft, 9 | Empty, 10 | ShowCommands, 11 | Unknown(String), 12 | } 13 | 14 | impl From<&str> for UserResponse { 15 | 16 | /// Converts a command-line user input to a `UserResponse` 17 | fn from(s: &str) -> Self { 18 | match s { 19 | "a" => UserResponse::AllowOnce, 20 | "aa" => UserResponse::AllowAllSyscall, 21 | "bh" => UserResponse::BlockOnceHard, 22 | "bs" => UserResponse::BlockOnceSoft, 23 | "bah" => UserResponse::BlockAllSyscallHard, 24 | "bas" => UserResponse::BlockAllSyscallSoft, 25 | "" => UserResponse::Empty, 26 | "?" => UserResponse::ShowCommands, 27 | _ => UserResponse::Unknown(String::from(s)), 28 | } 29 | } 30 | } 31 | 32 | impl From<&UserResponse> for String { 33 | 34 | /// Converts a `UserResponse` to the equivalent command-line input 35 | fn from(x: &UserResponse) -> Self { 36 | match x { 37 | UserResponse::AllowOnce => String::from("a"), 38 | UserResponse::AllowAllSyscall => String::from("aa"), 39 | UserResponse::BlockOnceHard => String::from("bh"), 40 | UserResponse::BlockOnceSoft => String::from("bs"), 41 | UserResponse::BlockAllSyscallHard => String::from("bah"), 42 | UserResponse::BlockAllSyscallSoft => String::from("bas"), 43 | UserResponse::Empty => String::from(""), 44 | UserResponse::ShowCommands => String::from("?"), 45 | UserResponse::Unknown(_) => String::new(), 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /lib/src/tracer_conf.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use serde_json; 3 | use std::collections::HashMap; 4 | use std::fs::File; 5 | use std::io::{Read, Write}; 6 | use std::path::Path; 7 | 8 | use crate::syscalls::SyscallQuery; 9 | use crate::user_response::UserResponse; 10 | 11 | /// Configuration for a single syscall used to make a decision when that syscall is observed in the 12 | /// tracee. 13 | #[derive(Debug, Deserialize, Serialize)] 14 | pub enum SyscallConfig { 15 | Allowed, 16 | HardBlocked, 17 | SoftBlocked, 18 | } 19 | 20 | /// Mapping of syscall IDs to `SyscallConfig` 21 | pub type SyscallConfigMap = HashMap; 22 | 23 | /// Configuration for the tracer while it is tracing a child process 24 | /// 25 | /// Currently contains a `SyscallConfigMap` mapping syscalls with decisions (allowed, blocked, 26 | /// etc.) 27 | #[derive(Debug, Default, Deserialize, Serialize)] 28 | pub struct TracerConf { 29 | pub syscalls: SyscallConfigMap, 30 | } 31 | 32 | impl TracerConf { 33 | /// Loads the `TracerConf` from a JSON file 34 | pub fn from_file(filename: &str) -> Result> { 35 | let path = Path::new(filename); 36 | let mut file = File::open(&path)?; 37 | let mut ser = String::new(); 38 | file.read_to_string(&mut ser)?; 39 | serde_json::from_str(ser.as_str()).map_err(|e| e.into()) 40 | } 41 | 42 | /// Sets a `SyscallConfig` for a specific syscall ID 43 | pub fn add_syscall_conf(&mut self, id: usize, conf: SyscallConfig) { 44 | *self.syscalls.entry(id).or_insert(SyscallConfig::Allowed) = conf; 45 | } 46 | 47 | /// Saves the `TracerConf` to a JSON file 48 | pub fn write_to_file(&self, filename: &str) -> Result<(), Box> { 49 | let ser: String = serde_json::to_string(self)?; 50 | let path = Path::new(filename); 51 | let mut file = File::create(&path)?; 52 | file.write_all(ser.as_bytes()).map_err(|e| e.into()) 53 | } 54 | } 55 | 56 | /// Configuration of the runtime environment using the `syswall` library. Currently contains an 57 | /// optional callback function which accepts a `SyscallQuery` and can optionally return a 58 | /// [`UserResponse`]. 59 | /// 60 | /// [`UserResponse`]: ../user_response/enum.UserResponse.html 61 | #[derive(Default)] 62 | pub struct RuntimeConf<'a> { 63 | pub syscall_cb: Option Option + 'a>>, 64 | } 65 | 66 | impl<'a> RuntimeConf<'a> { 67 | 68 | /// Assigns the callback function reference 69 | pub fn set_syscall_cb(&mut self, cb: Box Option + 'a>) { 70 | self.syscall_cb = Some(cb); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /cli/src/main.rs: -------------------------------------------------------------------------------- 1 | mod app; 2 | mod logger; 3 | 4 | use log::{debug, error, info, warn}; 5 | 6 | use syswall; 7 | use syswall::tracer_conf::{RuntimeConf, TracerConf}; 8 | use syswall::user_response::UserResponse; 9 | 10 | use crate::app::App; 11 | 12 | fn main() -> Result<(), String> { 13 | let app = App::new(); 14 | 15 | // Get the tracee command as a Vec<&str> 16 | let child_cmd = app 17 | .args 18 | .values_of("tracee_cmd") 19 | .ok_or("Unable to get tracee command")? 20 | .collect::>(); 21 | 22 | // Load TracerConf from file if necessary 23 | let mut conf: TracerConf = if app.args.is_present("load_config") { 24 | match app.args.value_of("config_file") { 25 | Some(filename) => match TracerConf::from_file(filename) { 26 | Ok(c) => { 27 | debug!("Configuration loaded from {}", filename); 28 | c 29 | } 30 | Err(e) => { 31 | error!( 32 | "Unable to read process configuration from file {}: {}", 33 | filename, e 34 | ); 35 | TracerConf::default() 36 | } 37 | }, 38 | None => TracerConf::default(), 39 | } 40 | } else { 41 | TracerConf::default() 42 | }; 43 | 44 | // Build a RuntimeConf and create a syscall_cb closure to ask the user for decisions via stdin 45 | // when necessary. 46 | let mut runtime_conf = RuntimeConf::default(); 47 | runtime_conf.set_syscall_cb(Box::new(|query| { 48 | info!("{}", query.description); 49 | match query.configured_choice { 50 | None => Some( 51 | app.get_user_input(UserResponse::AllowOnce) 52 | .unwrap_or(UserResponse::AllowOnce), 53 | ), 54 | Some(_) => None, 55 | } 56 | })); 57 | 58 | // Trace the process 59 | let process_states = syswall::trace(child_cmd, &mut conf, &runtime_conf)?; 60 | 61 | // Print final report 62 | info!( 63 | "\n{}", 64 | process_states 65 | .0 66 | .iter() 67 | .map(|(pid, st)| { 68 | let report = st.report(); 69 | if report.is_empty() { 70 | format!("Nothing to report for {:?}", pid) 71 | } else { 72 | format!("Final state for {:?}: -{}", pid, report) 73 | } 74 | }) 75 | .collect::>() 76 | .join("\n\n") 77 | ); 78 | 79 | // Save the process config based on args 80 | if app.args.is_present("save_config") { 81 | match app.args.value_of("config_file") { 82 | Some(filename) => { 83 | if let Err(e) = conf.write_to_file(filename) { 84 | error!("Unable to write process configuration to file {}: {}", filename, e); 85 | } 86 | }, 87 | None => warn!("The program was requested to save the tracee configuration, but no filename was specified"), 88 | }; 89 | } 90 | 91 | Ok(()) 92 | } 93 | -------------------------------------------------------------------------------- /lib/src/platforms/linux_x86_64/sockets.rs: -------------------------------------------------------------------------------- 1 | use nix::sys::socket; 2 | use nix::unistd::Pid; 3 | use std::ptr; 4 | 5 | use crate::child_process::{self, ChildProcessBuffer}; 6 | use crate::process_state::ProcessState; 7 | use crate::process_state::sockets::{SocketProtocol, SocketType}; 8 | use crate::syscalls::SyscallRegs; 9 | 10 | impl Into> for ChildProcessBuffer { 11 | fn into(self) -> Option { 12 | 13 | // First interpret buffer as sockaddr in order to get sa_family and generic sa_data 14 | #[allow(clippy::cast_ptr_alignment)] 15 | let sockaddr: libc::sockaddr = unsafe { ptr::read_unaligned(self.0.as_ptr() as *const libc::sockaddr) }; 16 | 17 | match libc::c_int::from(sockaddr.sa_family) { 18 | libc::AF_INET => Some( 19 | // sa_data contains necessary additional fields 20 | socket::SockAddr::new_inet( 21 | socket::InetAddr::new( 22 | 23 | // Extract IPv4 address bytes from sa_data 24 | socket::IpAddr::new_v4( 25 | sockaddr.sa_data[2] as u8, 26 | sockaddr.sa_data[3] as u8, 27 | sockaddr.sa_data[4] as u8, 28 | sockaddr.sa_data[5] as u8, 29 | ), 30 | 31 | // Extract 16-bit port from sa_data (big-endian) 32 | ((sockaddr.sa_data[0] as u16) << 8) | (sockaddr.sa_data[1] as u16), 33 | ), 34 | ), 35 | ), 36 | libc::AF_UNIX => { 37 | // Interpret buffer as sockaddr_un 38 | #[allow(clippy::cast_ptr_alignment)] 39 | let sockaddr: libc::sockaddr_un = unsafe { ptr::read_unaligned(self.0.as_ptr() as *const libc::sockaddr_un) }; 40 | 41 | match socket::SockAddr::new_unix( 42 | 43 | // Collect sun_path as Vec while element is non-zero. sun_path can be a 44 | // maximum of 108 characters and is null-terminated if smaller. 45 | sockaddr.sun_path 46 | .iter() 47 | .map(|x| *x as u8) 48 | .take_while(|x| *x != 0) 49 | .collect::>() 50 | .as_slice() 51 | ) { 52 | Ok(x) => Some(x), 53 | Err(_) => None, 54 | } 55 | } 56 | 57 | // TODO: decode other sa_family types: AF_INET6, AF_NETLINK 58 | _ => None, 59 | } 60 | } 61 | } 62 | 63 | pub fn handle_connect_pre( 64 | state: &mut ProcessState, 65 | regs: &SyscallRegs, 66 | pid: Pid, 67 | ) -> String { 68 | let mut desc = format!("Child process {} wants to connect socket {}", pid, regs.rdi); 69 | match child_process::get_child_buffer(pid, regs.rsi as usize, regs.rdx as usize) { 70 | Ok(buf) => { 71 | let sockaddr: Option = buf.into(); 72 | desc = format!("{}\n{}", desc, format!(" - Socket address: {:?}", sockaddr)); 73 | 74 | // Update socket's address in state 75 | if let Some(ref mut sock) = state.socket_by_fd(regs.rdi as usize) { 76 | sock.address = sockaddr; 77 | } 78 | }, 79 | Err(e) => { 80 | desc = format!("{}\n{}", desc, format!(" - Unable to read from child process buffer: {}", e)); 81 | } 82 | }; 83 | desc 84 | } 85 | 86 | pub fn handle_socket_pre( 87 | state: &mut ProcessState, 88 | regs: &SyscallRegs, 89 | pid: Pid, 90 | ) -> String { 91 | state.add_pending_socket(regs.rdi as isize, regs.rsi as isize, regs.rdx as isize); 92 | format!( 93 | "Child process {} wants to create a socket (family: {:?}, type: {:?}, protocol: {:?})", 94 | pid, 95 | socket::AddressFamily::from_i32(regs.rdi as libc::c_int), 96 | SocketType::from_i32(regs.rsi as libc::c_int), 97 | SocketProtocol::from_i32(regs.rdx as libc::c_int), 98 | ) 99 | } 100 | -------------------------------------------------------------------------------- /lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod child_process; 2 | mod platforms; 3 | mod process_state; 4 | mod syscalls; 5 | pub mod tracer_conf; 6 | pub mod user_response; 7 | 8 | use log::info; 9 | use nix::sys::ptrace; 10 | use nix::unistd; 11 | 12 | use crate::child_process::ProcessList; 13 | use crate::platforms::linux_x86_64::Handler; 14 | use crate::syscalls::SyscallHandler; 15 | use crate::tracer_conf::{RuntimeConf, TracerConf}; 16 | 17 | /// Main syswall tracing function: allows a child process to be executed and traced by syswall 18 | /// 19 | /// [`ProcessList`]: ./child_process/struct.ProcessList.html 20 | /// [`RuntimeConf`]: ./tracer_conf/struct.RuntimeConf.html 21 | /// [`TracerConf`]: ./tracer_conf/struct.TracerConf.html 22 | /// 23 | /// When called, the current process will fork and the child will execute `cmd`. The parent will 24 | /// then enter the trace loop which processes the syscalls for the child (tracee) process. When 25 | /// the child process terminates, this function will return. 26 | /// 27 | /// # Arguments 28 | /// 29 | /// - `cmd`: command and arguments used for running the child process (e.g. ["ls", "-l"]) 30 | /// - `conf`: [`TracerConf`] instance which will be used and modified during the trace 31 | /// - `runtime_conf`: [`RuntimeConf`] instance which provides details of the runtime interface 32 | /// 33 | /// # Returns 34 | /// 35 | /// Upon success, returns an Ok([`ProcessList`]) containing the states of all tracee processes. 36 | /// 37 | /// # Example 38 | /// 39 | /// ``` 40 | /// use syswall::trace; 41 | /// use syswall::tracer_conf::{RuntimeConf, TracerConf}; 42 | /// 43 | /// let cmd = vec!["ls", "-l"]; 44 | /// let mut conf = TracerConf::default(); 45 | /// let runtime_conf = RuntimeConf::default(); 46 | /// if let Ok(process_states) = trace(cmd, &mut conf, &runtime_conf) { 47 | /// // Handle final process status reports 48 | /// } 49 | /// ``` 50 | pub fn trace(cmd: Vec<&str>, conf: &mut TracerConf, runtime_conf: &RuntimeConf) -> Result { 51 | let mut syscall_handler = SyscallHandler::new( 52 | conf, runtime_conf, Box::new(Handler::new()), 53 | ); 54 | 55 | // Fork this process 56 | let fork_res = unistd::fork().map_err(|_| "Unable to fork")?; 57 | 58 | match fork_res { 59 | unistd::ForkResult::Parent { child } => { 60 | info!("Tracing child process {} ({:?})", child, cmd); 61 | 62 | // Wait for child and set trace options 63 | child_process::wait_child(child, false)?; 64 | ptrace::setoptions( 65 | child, 66 | ptrace::Options::PTRACE_O_EXITKILL 67 | 68 | // Trace sub-processes of tracee 69 | | ptrace::Options::PTRACE_O_TRACECLONE 70 | | ptrace::Options::PTRACE_O_TRACEFORK 71 | | ptrace::Options::PTRACE_O_TRACEVFORK 72 | | ptrace::Options::PTRACE_O_TRACEVFORKDONE 73 | 74 | | ptrace::Options::PTRACE_O_TRACEEXEC 75 | 76 | // PTRACE_O_TRACESYSGOOD: recommended by strace README-linux-ptrace. Causes 77 | // WaitStatus::PtraceSyscall to be generated instead of WaitStatus::Stopped 78 | // upon syscall in tracee. 79 | | ptrace::Options::PTRACE_O_TRACESYSGOOD, 80 | 81 | // PTRACE_O_TRACEEXIT will stop the tracee before exit in order to examine 82 | // registers. This is not required; without this option the tracer will be notified 83 | // after tracee exit. 84 | // ptrace::Options::PTRACE_O_TRACEEXIT 85 | ) 86 | .map_err(|_| "Unable to set PTRACE_O_* options for child process")?; 87 | 88 | // Await next child syscall for main tracee 89 | ptrace::syscall(child) 90 | .map_err(|_| "Unable to set child process to run until first syscall")?; 91 | 92 | // Execute main child process control loop 93 | child_process::child_loop(child, &mut syscall_handler) 94 | } 95 | unistd::ForkResult::Child => { 96 | child_process::exec_child(cmd).map_err(|_| "Unable to execute child process")?; 97 | Ok(ProcessList::default()) 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /cli/src/app.rs: -------------------------------------------------------------------------------- 1 | use clap::{crate_version, App as ClapApp, AppSettings, Arg, ArgMatches}; 2 | use log::{info, LevelFilter}; 3 | use std::io; 4 | 5 | use syswall::user_response::UserResponse; 6 | 7 | use crate::logger::AppLogger; 8 | 9 | static LOGGER: AppLogger = AppLogger; 10 | 11 | #[derive(Debug)] 12 | pub struct App<'a> { 13 | pub args: ArgMatches<'a>, 14 | } 15 | 16 | impl<'a> App<'a> { 17 | pub fn new() -> Self { 18 | let matches = ClapApp::new("syswall") 19 | .version(crate_version!()) 20 | .about("Syswall: a firewall for syscalls") 21 | .author("Simon Pugnet") 22 | .setting(AppSettings::TrailingVarArg) 23 | .arg( 24 | Arg::with_name("verbose") 25 | .short("v") 26 | .long("verbose") 27 | .help("Increases verbosity of program output (can be specified multiple times)") 28 | .takes_value(false) 29 | .multiple(true) 30 | ) 31 | .arg( 32 | Arg::with_name("load_config") 33 | .short("l") 34 | .long("load-config") 35 | .help("Whether to load a previously saved config (see --config-file)") 36 | .takes_value(false) 37 | .requires("config_file") 38 | ) 39 | .arg( 40 | Arg::with_name("save_config") 41 | .short("s") 42 | .long("save-config") 43 | .help( 44 | "Whether to save the resulting tracee config to a file (see --config-file)", 45 | ) 46 | .takes_value(false) 47 | .requires("config_file") 48 | ) 49 | .arg( 50 | Arg::with_name("config_file") 51 | .short("f") 52 | .long("config-file") 53 | .value_name("FILENAME") 54 | .help("Name of process config JSON to load/save") 55 | .takes_value(true) 56 | ) 57 | .arg( 58 | Arg::with_name("tracee_cmd") 59 | .raw(true) 60 | .help("Full tracee command and arguments (e.g. \"ls -l\")") 61 | .required(true) 62 | ) 63 | .get_matches(); 64 | 65 | // Set up logger 66 | let level_filter = match matches.occurrences_of("verbose") { 67 | 0 => LevelFilter::Info, 68 | 1 => LevelFilter::Debug, 69 | _ => LevelFilter::Trace, 70 | }; 71 | if log::set_logger(&LOGGER) 72 | .map(|()| log::set_max_level(level_filter)) 73 | .is_err() 74 | { 75 | eprintln!("ERROR: unable to set application logger instance"); 76 | } 77 | 78 | Self { args: matches } 79 | } 80 | 81 | pub fn get_user_input(&self, default: UserResponse) -> Result { 82 | let mut buffer = String::new(); 83 | let def_str: String = String::from(&default); 84 | loop { 85 | eprint!(" - Choice (\"{}\" default, ? for help): ", def_str); 86 | buffer.clear(); 87 | io::stdin() 88 | .read_line(&mut buffer) 89 | .map_err(|_| "Unable to read from stdin")?; 90 | let inp = buffer.trim(); 91 | let resp = UserResponse::from(inp); 92 | match resp { 93 | UserResponse::ShowCommands => self.show_commands(), 94 | UserResponse::Empty => return Ok(default), 95 | UserResponse::Unknown(s) => { 96 | info!("Unknown command \"{}\"", s); 97 | self.show_commands(); 98 | } 99 | _ => return Ok(resp), 100 | } 101 | } 102 | } 103 | 104 | pub fn show_commands(&self) { 105 | info!(" - Available commands: -"); 106 | info!(" a: allow this syscall once"); 107 | info!(" aa: allow this syscall always from now on"); 108 | info!(" bh: hard-block this syscall once (tracee sees error)"); 109 | info!(" bs: soft-block this syscall once (tracee sees success)"); 110 | info!(" bah: always hard-block this syscall from now on"); 111 | info!(" bas: always soft-block this syscall from now on"); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![syswall](syswall-logo-sm.png) 2 | 3 | A work in progress firewall for Linux syscalls, written in Rust. 4 | 5 | ## Introduction 6 | `syswall` functions similarly to the *nix `strace` tool, however for each syscall the program blocks the child process's execution and asks the user if the syscall should be allowed or not. As such, `syswall` can act as a safety barrier between a process and the OS kernel. 7 | 8 | `syswall` also collects statistics about the handled syscalls and is able to produce a report after the child process finishes execution. 9 | 10 | For more information about what `syswall` does, what is planned, and why, please see [this blog post on my website](https://www.polaris64.net/blog/programming/2019/syswall-a-firewall-for-syscalls) 11 | 12 | ## Structure 13 | This repository is split as a Cargo workspace into two separate projects: - 14 | 15 | - `lib`: the main `syswall` library containing the main functionality which can be used in other applications as [a Cargo crate](https://crates.io/crates/syswall). 16 | - `cli`: a simple CLI to the `syswall` library, allowing a single program to be traced similarly to the `strace` tool but with additonal `syswall` functionality. 17 | 18 | The project has been split in this way in order to allow for easier integration of other interfaces. For example, a graphical, web-based or scripting interface could easily be written for the `syswall` library allowing for usage in environments other than the command-line. 19 | 20 | ## Installation 21 | If you just want to use the CLI, the simplest method of installation is to use `cargo install`: - 22 | 23 | ``` 24 | cargo install syswall_cli 25 | ``` 26 | 27 | This will download the latest version of `syswall_cli` and all dependencies, build them and install them to your local Cargo binary directory. As long as this directory is in your path, you can now simply run `syswall_cli` on the command-line. 28 | 29 | This method requires you to have installed the Rust toolchain. If you haven't already done this, please follow [these official instructions](https://rustup.rs/) to do so. 30 | 31 | ## Current progress 32 | `syswall` is a very early prototype and as such only a small amount of the planned functionality is currently implemented. 33 | 34 | The handling of syscalls is of course very much platform-dependent. `syswall` separates the library fuctionality from the actual code to handle particular syscalls, meaning that support for other platforms shold be relatively easy to integrate. So far however only the Linux x86_64 platform is supported. 35 | 36 | From the Linux x86_64 platform, only a relatively small number of syscalls are actively handled at present. Currently this includes file I/O and some socket syscalls only. 37 | 38 | ### `strace` 39 | The syswall CLI can be run with the -vv switch causing it to display all syscalls and results. This provides similar functionality to the `strace` tool, without the interpretation of syscall arguments as yet. 40 | 41 | ### Interactive execution 42 | For supported syscalls, `syswall` allows the user to perform the following actions: - 43 | 44 | - Allow the syscall once 45 | - Always allow that particular syscall 46 | - Block the syscall once (hard or soft) 47 | - Always block that particular syscall (hard or soft) 48 | 49 | When blocking, the program can perform either a "hard" or a "soft" block. A hard block prevents the syscall from executing and returns an permission denied error to the child process. A soft block on the other hand prevents the syscall but attempts to return a suitable response to the child process in order to pretend that the syscall was actually executed. 50 | 51 | ### Saving and loading of a process configuration 52 | The choices made during execution can be saved to a JSON file. This file can then be loaded during another execution so that the previous choices are used. 53 | 54 | This is a work in progress: only always allowed/blocked answers will be saved. 55 | 56 | ### Reporting 57 | When the child process terminates, `syswall` will output a brief report about the child process's syscalls. Currently this consists of all files and sockets opened or blocked but will be expanded upon in future versions. 58 | 59 | ## Future plans 60 | There is a large to-do list for the project, but some of the highlights are: - 61 | 62 | - Allowing more fine-grained choices, such as always allowing a particular syscall with one or more matching arguments 63 | - Allowing the child process's state (list of files, sockets, etc) to be saved to a file. This will eventually allow different executions of a program to be compared. 64 | - Adding an option to ignore all dynamic .so loads. 65 | - Adding a set of default configurations (e.g. block all sockets but allow file access). 66 | - Adding of new interfaces, such as graphical, web-based and scripting (Python) interfaces. 67 | -------------------------------------------------------------------------------- /lib/src/process_state/sockets.rs: -------------------------------------------------------------------------------- 1 | use nix::errno::Errno; 2 | use nix::sys::socket; 3 | use std::fmt; 4 | 5 | #[derive(Debug, PartialEq)] 6 | pub enum ProcessSocketState { 7 | Closed, 8 | CouldNotCreate(Errno), 9 | CreateBlockedHard, 10 | CreateBlockedSoft, 11 | Created(usize), 12 | PendingSyscall, 13 | } 14 | 15 | impl fmt::Display for ProcessSocketState { 16 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 17 | match self { 18 | ProcessSocketState::Created(fd) => { 19 | write!(f, "open with FD {}", fd) 20 | }, 21 | ProcessSocketState::Closed => { 22 | write!(f, "closed") 23 | }, 24 | ProcessSocketState::CouldNotCreate(errno) => { 25 | write!(f, "creation error: {:?}", errno) 26 | }, 27 | _ => { 28 | write!(f, "unknown state") 29 | } 30 | } 31 | } 32 | } 33 | 34 | #[derive(Debug)] 35 | pub enum SocketConnectionState { 36 | Connected, 37 | ConnectBlockedHard, 38 | ConnectBlockedSoft, 39 | ConnectError(Errno), 40 | Disconnected, 41 | } 42 | 43 | #[derive(Debug)] 44 | pub enum SocketType { 45 | Datagram, 46 | Raw, 47 | RDM, 48 | SeqPacket, 49 | Stream, 50 | } 51 | 52 | impl SocketType { 53 | pub fn from_i32(x: i32) -> Option { 54 | 55 | // Socket flags are combined with the type i32 (bitwise OR), so only match on the non-flag 56 | // bits. See socket(2) manpage for details. 57 | match x & (!libc::SOCK_NONBLOCK) & (!libc::SOCK_CLOEXEC) { 58 | libc::SOCK_DGRAM => Some(SocketType::Datagram), 59 | libc::SOCK_RAW => Some(SocketType::Raw), 60 | libc::SOCK_RDM => Some(SocketType::RDM), 61 | libc::SOCK_SEQPACKET => Some(SocketType::SeqPacket), 62 | libc::SOCK_STREAM => Some(SocketType::Stream), 63 | _ => None, 64 | } 65 | } 66 | } 67 | 68 | #[derive(Debug)] 69 | pub enum SocketProtocol { 70 | IP, 71 | TCP, 72 | UDP, 73 | } 74 | 75 | impl SocketProtocol { 76 | pub fn from_i32(x: i32) -> Option { 77 | match x { 78 | libc::IPPROTO_IP => Some(SocketProtocol::IP), 79 | libc::IPPROTO_TCP => Some(SocketProtocol::TCP), 80 | libc::IPPROTO_UDP => Some(SocketProtocol::UDP), 81 | _ => None, 82 | } 83 | } 84 | } 85 | 86 | #[derive(Debug)] 87 | pub struct ProcessSocketRec { 88 | pub address: Option, 89 | pub connection_state: SocketConnectionState, 90 | pub sock_af: Option, 91 | pub sock_flags: socket::SockFlag, 92 | pub sock_proto: Option, 93 | pub sock_type: Option, 94 | pub state: ProcessSocketState, 95 | } 96 | 97 | impl ProcessSocketRec { 98 | pub fn new(af_bits: isize, type_bits: isize, proto_bits: isize) -> Self { 99 | Self { 100 | address: None, 101 | connection_state: SocketConnectionState::Disconnected, 102 | sock_af: socket::AddressFamily::from_i32(af_bits as i32), 103 | sock_flags: socket::SockFlag::from_bits_truncate(type_bits as libc::c_int), 104 | sock_proto: SocketProtocol::from_i32(proto_bits as i32), 105 | sock_type: SocketType::from_i32(type_bits as i32), 106 | state: ProcessSocketState::PendingSyscall, 107 | } 108 | } 109 | } 110 | 111 | impl fmt::Display for ProcessSocketRec { 112 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 113 | match self.state { 114 | ProcessSocketState::Created(_) | ProcessSocketState::Closed => { 115 | write!( 116 | f, 117 | "Socket: {} ({:?}, {}, {:?}, {}, {}), address: {}", 118 | self.state, 119 | self.connection_state, 120 | match &self.sock_af { 121 | Some(v) => format!("{:?}", &v), 122 | None => String::from("No address family"), 123 | }, 124 | self.sock_flags, 125 | match &self.sock_proto { 126 | Some(v) => format!("{:?}", &v), 127 | None => String::from("No protocol"), 128 | }, 129 | match &self.sock_type { 130 | Some(v) => format!("{:?}", &v), 131 | None => String::from("No socket type"), 132 | }, 133 | match self.address { 134 | Some(v) => format!("{:?}", &v), 135 | None => String::from("Not bound to an address"), 136 | }, 137 | ) 138 | }, 139 | _ => write!(f, "Socket: {}", self.state) 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /lib/src/process_state/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod files; 2 | pub mod sockets; 3 | 4 | use files::{ProcessFileRec, ProcessFileState}; 5 | use sockets::{ProcessSocketRec, ProcessSocketState}; 6 | use crate::syscalls::HandleSyscallResult; 7 | 8 | #[derive(Debug, PartialEq)] 9 | pub enum ProcessTraceState { 10 | Created, 11 | Stopped, 12 | TraceSyscallEnterStop, 13 | TraceSyscallExitStop, 14 | RunningAwaitSyscall, 15 | Terminated(isize), 16 | } 17 | 18 | #[derive(Debug, Clone, Copy, PartialEq)] 19 | pub enum ProcessType { 20 | ClonedThread, 21 | ForkedProcess, 22 | MainTracee, 23 | VForkedProcess, 24 | } 25 | 26 | #[derive(Debug)] 27 | pub struct ProcessState { 28 | files: Vec, 29 | sockets: Vec, 30 | pub process_type: ProcessType, 31 | pub handler_res: Option, 32 | pub syscall_id: Option, 33 | pub trace_state: ProcessTraceState, 34 | } 35 | 36 | impl ProcessState { 37 | pub fn new(trace_state: ProcessTraceState, process_type: ProcessType) -> Self { 38 | Self { 39 | files: Vec::new(), 40 | sockets: Vec::new(), 41 | handler_res: None, 42 | syscall_id: None, 43 | process_type, 44 | trace_state, 45 | } 46 | } 47 | 48 | pub fn file_by_fd(&mut self, fd: usize) -> Option<&mut ProcessFileRec> { 49 | self.files 50 | .iter_mut() 51 | .find(|x| x.state == ProcessFileState::Opened(fd)) 52 | } 53 | 54 | pub fn socket_by_fd(&mut self, fd: usize) -> Option<&mut ProcessSocketRec> { 55 | self.sockets 56 | .iter_mut() 57 | .find(|x| x.state == ProcessSocketState::Created(fd)) 58 | } 59 | 60 | pub fn file_by_path(&mut self, path: &str) -> Option<&mut ProcessFileRec> { 61 | self.files.iter_mut().find(|x| x.filename == path) 62 | } 63 | 64 | pub fn add_pending_file(&mut self, path: &str, flags: isize, mode: isize) { 65 | if self.file_by_path(path).is_none() { 66 | self.files.push(ProcessFileRec::new(path, flags, mode)); 67 | } 68 | } 69 | 70 | pub fn add_pending_socket(&mut self, af: isize, sock_type: isize, sock_proto: isize) { 71 | let v = ProcessSocketRec::new(af, sock_type, sock_proto); 72 | self.sockets.push(v); 73 | } 74 | 75 | pub fn first_pending_file(&mut self) -> Option<&mut ProcessFileRec> { 76 | self.files 77 | .iter_mut() 78 | .find(|x| x.state == ProcessFileState::PendingSyscall) 79 | } 80 | 81 | pub fn first_pending_socket(&mut self) -> Option<&mut ProcessSocketRec> { 82 | self.sockets 83 | .iter_mut() 84 | .find(|x| x.state == ProcessSocketState::PendingSyscall) 85 | } 86 | 87 | pub fn update_pending_file_state(&mut self, file_state: ProcessFileState) { 88 | if let Some(f) = self.first_pending_file() { 89 | f.state = file_state; 90 | } 91 | } 92 | 93 | pub fn update_pending_socket_state(&mut self, sock_state: ProcessSocketState) { 94 | if let Some(s) = self.first_pending_socket() { 95 | s.state = sock_state; 96 | } 97 | } 98 | 99 | pub fn update_file_state_by_fd(&mut self, fd: usize, state: ProcessFileState) { 100 | if let Some(f) = self.file_by_fd(fd) { 101 | f.state = state; 102 | } 103 | } 104 | 105 | pub fn update_socket_state_by_fd(&mut self, fd: usize, state: ProcessSocketState) { 106 | if let Some(s) = self.socket_by_fd(fd) { 107 | s.state = state; 108 | } 109 | } 110 | 111 | pub fn report_blocked_files(&self, join: &str, prefix: &str) -> String { 112 | self.files 113 | .iter() 114 | .filter(|x| match x.state { 115 | ProcessFileState::OpenBlockedHard | ProcessFileState::OpenBlockedSoft => true, 116 | _ => false, 117 | }) 118 | .map(|x| String::from(prefix) + &x.filename.clone()) 119 | .collect::>() 120 | .as_slice() 121 | .join(join) 122 | } 123 | 124 | pub fn report_opened_files(&self, join: &str, prefix: &str) -> String { 125 | self.files 126 | .iter() 127 | .filter(|x| match x.state { 128 | ProcessFileState::Opened(_) | ProcessFileState::Closed => true, 129 | _ => false, 130 | }) 131 | .map(|x| String::from(prefix) + &x.filename.clone()) 132 | .collect::>() 133 | .as_slice() 134 | .join(join) 135 | } 136 | 137 | pub fn report_sockets(&self, join: &str, prefix: &str) -> String { 138 | self.sockets 139 | .iter() 140 | .map(|x| String::from(prefix) + &format!("{}", &x)) 141 | .collect::>() 142 | .as_slice() 143 | .join(join) 144 | } 145 | 146 | pub fn report(&self) -> String { 147 | let blocked_files = self.report_blocked_files("\n", " - "); 148 | let opened_files = self.report_opened_files("\n", " - "); 149 | let sockets = self.report_sockets("\n", " - "); 150 | let mut res = String::new(); 151 | if !blocked_files.is_empty() { 152 | res += &format!( 153 | "\nThe process was blocked from opening the following files: -\n{}", 154 | blocked_files 155 | ); 156 | } 157 | if !opened_files.is_empty() { 158 | res += &format!( 159 | "\nThe process opened the following files: -\n{}", 160 | opened_files 161 | ); 162 | } 163 | if !sockets.is_empty() { 164 | res += &format!( 165 | "\nThe process created the following sockets: -\n{}", 166 | sockets 167 | ); 168 | } 169 | res 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /lib/Cargo.lock: -------------------------------------------------------------------------------- 1 | [[package]] 2 | name = "arc-swap" 3 | version = "0.3.7" 4 | source = "registry+https://github.com/rust-lang/crates.io-index" 5 | 6 | [[package]] 7 | name = "bitflags" 8 | version = "1.0.4" 9 | source = "registry+https://github.com/rust-lang/crates.io-index" 10 | 11 | [[package]] 12 | name = "cc" 13 | version = "1.0.31" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | 16 | [[package]] 17 | name = "cfg-if" 18 | version = "0.1.7" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | 21 | [[package]] 22 | name = "itoa" 23 | version = "0.4.3" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | 26 | [[package]] 27 | name = "libc" 28 | version = "0.2.50" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | 31 | [[package]] 32 | name = "log" 33 | version = "0.4.6" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | dependencies = [ 36 | "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 37 | ] 38 | 39 | [[package]] 40 | name = "nix" 41 | version = "0.13.0" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | dependencies = [ 44 | "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", 45 | "cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)", 46 | "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 47 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 48 | "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", 49 | ] 50 | 51 | [[package]] 52 | name = "proc-macro2" 53 | version = "0.4.27" 54 | source = "registry+https://github.com/rust-lang/crates.io-index" 55 | dependencies = [ 56 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 57 | ] 58 | 59 | [[package]] 60 | name = "quote" 61 | version = "0.6.11" 62 | source = "registry+https://github.com/rust-lang/crates.io-index" 63 | dependencies = [ 64 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 65 | ] 66 | 67 | [[package]] 68 | name = "ryu" 69 | version = "0.2.7" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | 72 | [[package]] 73 | name = "serde" 74 | version = "1.0.89" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | dependencies = [ 77 | "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 78 | ] 79 | 80 | [[package]] 81 | name = "serde_derive" 82 | version = "1.0.89" 83 | source = "registry+https://github.com/rust-lang/crates.io-index" 84 | dependencies = [ 85 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 86 | "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)", 87 | "syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)", 88 | ] 89 | 90 | [[package]] 91 | name = "serde_json" 92 | version = "1.0.39" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | dependencies = [ 95 | "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", 96 | "ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", 97 | "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 98 | ] 99 | 100 | [[package]] 101 | name = "signal-hook" 102 | version = "0.1.8" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | dependencies = [ 105 | "arc-swap 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", 106 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 107 | ] 108 | 109 | [[package]] 110 | name = "syn" 111 | version = "0.15.29" 112 | source = "registry+https://github.com/rust-lang/crates.io-index" 113 | dependencies = [ 114 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 115 | "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)", 116 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 117 | ] 118 | 119 | [[package]] 120 | name = "syswall" 121 | version = "0.2.0" 122 | dependencies = [ 123 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 124 | "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", 125 | "nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", 126 | "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 127 | "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", 128 | "signal-hook 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", 129 | ] 130 | 131 | [[package]] 132 | name = "unicode-xid" 133 | version = "0.1.0" 134 | source = "registry+https://github.com/rust-lang/crates.io-index" 135 | 136 | [[package]] 137 | name = "void" 138 | version = "1.0.2" 139 | source = "registry+https://github.com/rust-lang/crates.io-index" 140 | 141 | [metadata] 142 | "checksum arc-swap 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1025aeae2b664ca0ea726a89d574fe8f4e77dd712d443236ad1de00379450cf6" 143 | "checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" 144 | "checksum cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)" = "c9ce8bb087aacff865633f0bd5aeaed910fe2fe55b55f4739527f2e023a2e53d" 145 | "checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4" 146 | "checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" 147 | "checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)" = "aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1" 148 | "checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" 149 | "checksum nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46f0f3210768d796e8fa79ec70ee6af172dacbe7147f5e69be5240a47778302b" 150 | "checksum proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)" = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915" 151 | "checksum quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "cdd8e04bd9c52e0342b406469d494fcb033be4bdbe5c606016defbb1681411e1" 152 | "checksum ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7" 153 | "checksum serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "92514fb95f900c9b5126e32d020f5c6d40564c27a5ea6d1d7d9f157a96623560" 154 | "checksum serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6eabf4b5914e88e24eea240bb7c9f9a2cbc1bbbe8d961d381975ec3c6b806c" 155 | "checksum serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)" = "5a23aa71d4a4d43fdbfaac00eff68ba8a06a51759a89ac3304323e800c4dd40d" 156 | "checksum signal-hook 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "97a47ae722318beceb0294e6f3d601205a1e6abaa4437d9d33e3a212233e3021" 157 | "checksum syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)" = "1825685f977249735d510a242a6727b46efe914bb67e38d30c071b1b72b1d5c2" 158 | "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" 159 | "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 160 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "ansi_term" 7 | version = "0.12.1" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" 10 | dependencies = [ 11 | "winapi", 12 | ] 13 | 14 | [[package]] 15 | name = "atty" 16 | version = "0.2.14" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 19 | dependencies = [ 20 | "hermit-abi", 21 | "libc", 22 | "winapi", 23 | ] 24 | 25 | [[package]] 26 | name = "bitflags" 27 | version = "1.3.2" 28 | source = "registry+https://github.com/rust-lang/crates.io-index" 29 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 30 | 31 | [[package]] 32 | name = "cc" 33 | version = "1.0.83" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" 36 | dependencies = [ 37 | "libc", 38 | ] 39 | 40 | [[package]] 41 | name = "cfg-if" 42 | version = "0.1.10" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 45 | 46 | [[package]] 47 | name = "clap" 48 | version = "2.34.0" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 51 | dependencies = [ 52 | "ansi_term", 53 | "atty", 54 | "bitflags", 55 | "strsim", 56 | "textwrap", 57 | "unicode-width", 58 | "vec_map", 59 | ] 60 | 61 | [[package]] 62 | name = "hermit-abi" 63 | version = "0.1.19" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 66 | dependencies = [ 67 | "libc", 68 | ] 69 | 70 | [[package]] 71 | name = "itoa" 72 | version = "1.0.10" 73 | source = "registry+https://github.com/rust-lang/crates.io-index" 74 | checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" 75 | 76 | [[package]] 77 | name = "libc" 78 | version = "0.2.151" 79 | source = "registry+https://github.com/rust-lang/crates.io-index" 80 | checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" 81 | 82 | [[package]] 83 | name = "log" 84 | version = "0.4.20" 85 | source = "registry+https://github.com/rust-lang/crates.io-index" 86 | checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" 87 | 88 | [[package]] 89 | name = "nix" 90 | version = "0.13.1" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "4dbdc256eaac2e3bd236d93ad999d3479ef775c863dbda3068c4006a92eec51b" 93 | dependencies = [ 94 | "bitflags", 95 | "cc", 96 | "cfg-if", 97 | "libc", 98 | "void", 99 | ] 100 | 101 | [[package]] 102 | name = "proc-macro2" 103 | version = "1.0.74" 104 | source = "registry+https://github.com/rust-lang/crates.io-index" 105 | checksum = "2de98502f212cfcea8d0bb305bd0f49d7ebdd75b64ba0a68f937d888f4e0d6db" 106 | dependencies = [ 107 | "unicode-ident", 108 | ] 109 | 110 | [[package]] 111 | name = "quote" 112 | version = "1.0.35" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" 115 | dependencies = [ 116 | "proc-macro2", 117 | ] 118 | 119 | [[package]] 120 | name = "ryu" 121 | version = "1.0.16" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" 124 | 125 | [[package]] 126 | name = "serde" 127 | version = "1.0.194" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "0b114498256798c94a0689e1a15fec6005dee8ac1f41de56404b67afc2a4b773" 130 | dependencies = [ 131 | "serde_derive", 132 | ] 133 | 134 | [[package]] 135 | name = "serde_derive" 136 | version = "1.0.194" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "a3385e45322e8f9931410f01b3031ec534c3947d0e94c18049af4d9f9907d4e0" 139 | dependencies = [ 140 | "proc-macro2", 141 | "quote", 142 | "syn", 143 | ] 144 | 145 | [[package]] 146 | name = "serde_json" 147 | version = "1.0.110" 148 | source = "registry+https://github.com/rust-lang/crates.io-index" 149 | checksum = "6fbd975230bada99c8bb618e0c365c2eefa219158d5c6c29610fd09ff1833257" 150 | dependencies = [ 151 | "itoa", 152 | "ryu", 153 | "serde", 154 | ] 155 | 156 | [[package]] 157 | name = "signal-hook" 158 | version = "0.1.17" 159 | source = "registry+https://github.com/rust-lang/crates.io-index" 160 | checksum = "7e31d442c16f047a671b5a71e2161d6e68814012b7f5379d269ebd915fac2729" 161 | dependencies = [ 162 | "libc", 163 | "signal-hook-registry", 164 | ] 165 | 166 | [[package]] 167 | name = "signal-hook-registry" 168 | version = "1.4.1" 169 | source = "registry+https://github.com/rust-lang/crates.io-index" 170 | checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" 171 | dependencies = [ 172 | "libc", 173 | ] 174 | 175 | [[package]] 176 | name = "strsim" 177 | version = "0.8.0" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 180 | 181 | [[package]] 182 | name = "syn" 183 | version = "2.0.46" 184 | source = "registry+https://github.com/rust-lang/crates.io-index" 185 | checksum = "89456b690ff72fddcecf231caedbe615c59480c93358a93dfae7fc29e3ebbf0e" 186 | dependencies = [ 187 | "proc-macro2", 188 | "quote", 189 | "unicode-ident", 190 | ] 191 | 192 | [[package]] 193 | name = "syswall" 194 | version = "0.3.1" 195 | dependencies = [ 196 | "libc", 197 | "log", 198 | "nix", 199 | "serde", 200 | "serde_json", 201 | "signal-hook", 202 | ] 203 | 204 | [[package]] 205 | name = "syswall_cli" 206 | version = "0.1.2" 207 | dependencies = [ 208 | "clap", 209 | "log", 210 | "syswall", 211 | ] 212 | 213 | [[package]] 214 | name = "textwrap" 215 | version = "0.11.0" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 218 | dependencies = [ 219 | "unicode-width", 220 | ] 221 | 222 | [[package]] 223 | name = "unicode-ident" 224 | version = "1.0.12" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 227 | 228 | [[package]] 229 | name = "unicode-width" 230 | version = "0.1.11" 231 | source = "registry+https://github.com/rust-lang/crates.io-index" 232 | checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" 233 | 234 | [[package]] 235 | name = "vec_map" 236 | version = "0.8.2" 237 | source = "registry+https://github.com/rust-lang/crates.io-index" 238 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 239 | 240 | [[package]] 241 | name = "void" 242 | version = "1.0.2" 243 | source = "registry+https://github.com/rust-lang/crates.io-index" 244 | checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 245 | 246 | [[package]] 247 | name = "winapi" 248 | version = "0.3.9" 249 | source = "registry+https://github.com/rust-lang/crates.io-index" 250 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 251 | dependencies = [ 252 | "winapi-i686-pc-windows-gnu", 253 | "winapi-x86_64-pc-windows-gnu", 254 | ] 255 | 256 | [[package]] 257 | name = "winapi-i686-pc-windows-gnu" 258 | version = "0.4.0" 259 | source = "registry+https://github.com/rust-lang/crates.io-index" 260 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 261 | 262 | [[package]] 263 | name = "winapi-x86_64-pc-windows-gnu" 264 | version = "0.4.0" 265 | source = "registry+https://github.com/rust-lang/crates.io-index" 266 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 267 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /lib/src/syscalls.rs: -------------------------------------------------------------------------------- 1 | use libc; 2 | use log::{debug, trace}; 3 | use nix::sys::ptrace; 4 | use nix::unistd; 5 | 6 | use crate::platforms::PlatformHandler; 7 | use crate::process_state::ProcessState; 8 | use crate::tracer_conf::{RuntimeConf, SyscallConfig, TracerConf}; 9 | use crate::user_response::UserResponse; 10 | 11 | /// A single query caused by a syscall which contains all necessary details required to make a 12 | /// decision 13 | pub struct SyscallQuery<'a> { 14 | pub configured_choice: Option<&'a SyscallConfig>, 15 | pub id: usize, 16 | pub pid: unistd::Pid, 17 | pub regs: &'a SyscallRegs, 18 | pub description: String, 19 | } 20 | 21 | impl<'a> SyscallQuery<'a> { 22 | 23 | /// Creates a new `SyscallQuery` based on a syscall event 24 | pub fn new( 25 | configured_choice: Option<&'a SyscallConfig>, 26 | id: usize, 27 | pid: unistd::Pid, 28 | regs: &'a SyscallRegs, 29 | description: String, 30 | ) -> Self { 31 | Self { 32 | configured_choice, 33 | id, 34 | pid, 35 | regs, 36 | description, 37 | } 38 | } 39 | } 40 | 41 | /// Result of handling a syscall 42 | #[derive(Debug)] 43 | pub enum HandleSyscallResult { 44 | BlockedHard, 45 | BlockedSoft, 46 | Unchanged, 47 | } 48 | 49 | /// Register state during a syscall 50 | pub type SyscallRegs = libc::user_regs_struct; 51 | 52 | /// Provides all necessary configuration for the tracer to handle syscalls from a tracee process 53 | pub struct SyscallHandler<'a> { 54 | config: &'a mut TracerConf, 55 | runtime_conf: &'a RuntimeConf<'a>, 56 | platform_handler: Box, 57 | } 58 | 59 | impl<'a> SyscallHandler<'a> { 60 | 61 | pub fn new(config: &'a mut TracerConf, runtime_conf: &'a RuntimeConf<'a>, platform_handler: Box) -> Self { 62 | Self { 63 | config, 64 | runtime_conf, 65 | platform_handler, 66 | } 67 | } 68 | 69 | /// Called before a syscall is executed in order to obtain a decision and to modify the syscall 70 | /// before execution as necessary. 71 | /// 72 | /// # Arguments 73 | /// 74 | /// - `state`: `ProcessState` of the specific child process triggering the syscall 75 | /// - `pid`: child process ID 76 | /// - `regs`: CPU registers at the time of syscall invocation 77 | pub fn handle_pre_syscall( 78 | &mut self, 79 | state: &mut ProcessState, 80 | pid: unistd::Pid, 81 | regs: &mut SyscallRegs, 82 | ) -> HandleSyscallResult { 83 | let entry_res = self.platform_handler.pre(state, regs, pid); 84 | 85 | if entry_res.handled { 86 | self.syscall_choice( 87 | pid, 88 | state.syscall_id, 89 | regs, 90 | entry_res.description, 91 | ) 92 | } else { 93 | trace!("{}", entry_res.description); 94 | HandleSyscallResult::Unchanged 95 | } 96 | } 97 | 98 | /// Called after a syscall is executed in order to update process states and to modify the 99 | /// syscall return value that the child process will see if necessary. 100 | /// 101 | /// # Arguments 102 | /// 103 | /// - `state`: `ProcessState` of the specific child process triggering the syscall 104 | /// - `pid`: child process ID 105 | /// - `regs`: CPU registers after syscall invocation 106 | pub fn handle_post_syscall( 107 | &self, 108 | state: &mut ProcessState, 109 | pid: unistd::Pid, 110 | regs: &mut SyscallRegs, 111 | ) { 112 | self.platform_handler.post(state, regs, pid); 113 | } 114 | 115 | /// Attempts to obtain a decision from the user for a syscall. The user's choice is used if 116 | /// available, otherwise either a configured choice (e.g. "always block") or a default 117 | /// ("allow") is used. 118 | /// 119 | /// # Arguments 120 | /// 121 | /// - `pid`: child process ID 122 | /// - `syscall_id`: ID of the syscall being triggered 123 | /// - `regs`: CPU registers prior to syscall invocation 124 | /// - `description`: a description of this syscall obtained from the current `PlatformHandler` 125 | fn syscall_choice( 126 | &mut self, 127 | pid: unistd::Pid, 128 | syscall_id: Option, 129 | regs: &mut SyscallRegs, 130 | description: String, 131 | ) -> HandleSyscallResult { 132 | 133 | // Get optional existing decision from configuration 134 | let conf_choice = self.config.syscalls.get(&(syscall_id.unwrap() as usize)); 135 | 136 | match self.runtime_conf.syscall_cb { 137 | 138 | // A decision callback exists, so call it to allow for an optional change in decision 139 | Some(ref cb) => { 140 | let query = SyscallQuery::new( 141 | conf_choice, 142 | syscall_id.unwrap() as usize, 143 | pid, 144 | regs, 145 | description, 146 | ); 147 | 148 | // Execute callback and get optional choice 149 | match cb(query) { 150 | Some(choice) => { 151 | self.handle_user_response( 152 | choice, 153 | syscall_id.unwrap(), 154 | pid, 155 | regs, 156 | ) 157 | } 158 | None => { 159 | self.handle_config_choice( 160 | conf_choice, 161 | pid, 162 | regs, 163 | ) 164 | } 165 | } 166 | } 167 | 168 | // No decision callback exists, so handle the syscall using default or configured decision 169 | None => { 170 | self.handle_config_choice( 171 | conf_choice, 172 | pid, 173 | regs, 174 | ) 175 | } 176 | } 177 | } 178 | 179 | /// Processes a user's reponse to a syscall 180 | /// 181 | /// # Arguments 182 | /// 183 | /// - `choice`: user's decision 184 | /// - `syscall_id`: ID of the syscall being triggered 185 | /// - `pid`: child process ID 186 | /// - `regs`: CPU registers which will be modified according to decision 187 | fn handle_user_response( 188 | &mut self, 189 | choice: UserResponse, 190 | syscall_id: u64, 191 | pid: unistd::Pid, 192 | regs: &mut SyscallRegs, 193 | ) -> HandleSyscallResult { 194 | match choice { 195 | UserResponse::AllowAllSyscall => { 196 | self.config.add_syscall_conf(syscall_id as usize, SyscallConfig::Allowed); 197 | HandleSyscallResult::Unchanged 198 | } 199 | UserResponse::BlockAllSyscallHard => { 200 | self.config.add_syscall_conf(syscall_id as usize, SyscallConfig::HardBlocked); 201 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 202 | HandleSyscallResult::BlockedHard 203 | } else { 204 | HandleSyscallResult::Unchanged 205 | } 206 | } 207 | UserResponse::BlockOnceHard => { 208 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 209 | HandleSyscallResult::BlockedHard 210 | } else { 211 | HandleSyscallResult::Unchanged 212 | } 213 | } 214 | UserResponse::BlockAllSyscallSoft => { 215 | self.config.add_syscall_conf(syscall_id as usize, SyscallConfig::SoftBlocked); 216 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 217 | HandleSyscallResult::BlockedSoft 218 | } else { 219 | HandleSyscallResult::Unchanged 220 | } 221 | } 222 | UserResponse::BlockOnceSoft => { 223 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 224 | HandleSyscallResult::BlockedSoft 225 | } else { 226 | HandleSyscallResult::Unchanged 227 | } 228 | } 229 | _ => HandleSyscallResult::Unchanged 230 | } 231 | } 232 | 233 | /// Processes a pre-configured decision for a syscall 234 | /// 235 | /// # Arguments 236 | /// 237 | /// - `syscall_conf`: the syscall's configuration 238 | /// - `pid`: child process ID 239 | /// - `regs`: CPU registers which will be modified according to decision 240 | fn handle_config_choice( 241 | &self, 242 | syscall_conf: Option<&SyscallConfig>, 243 | pid: unistd::Pid, 244 | regs: &mut SyscallRegs, 245 | ) -> HandleSyscallResult { 246 | match syscall_conf { 247 | Some(conf) => { 248 | match conf { 249 | SyscallConfig::Allowed => { 250 | debug!(" - Allowed by configuration"); 251 | HandleSyscallResult::Unchanged 252 | } 253 | SyscallConfig::HardBlocked => { 254 | debug!(" - Hard-blocked by configuration"); 255 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 256 | HandleSyscallResult::BlockedHard 257 | } else { 258 | HandleSyscallResult::Unchanged 259 | } 260 | } 261 | SyscallConfig::SoftBlocked => { 262 | debug!(" - Soft-blocked by configuration"); 263 | if let Ok(()) = self.platform_handler.block_syscall(pid, regs) { 264 | HandleSyscallResult::BlockedSoft 265 | } else { 266 | HandleSyscallResult::Unchanged 267 | } 268 | } 269 | } 270 | } 271 | None => HandleSyscallResult::Unchanged, 272 | } 273 | } 274 | } 275 | 276 | /// Updates the syscall registers for a child process 277 | /// 278 | /// # Arguments 279 | /// 280 | /// - `pid`: child process ID 281 | /// - `regs`: updated CPU registers to be set 282 | pub fn update_registers(pid: unistd::Pid, regs: &SyscallRegs) -> Result<(), &'static str> { 283 | ptrace::setregs(pid, *regs).map_err(|_| "Unable to modify syscall registers") 284 | } 285 | -------------------------------------------------------------------------------- /cli/Cargo.lock: -------------------------------------------------------------------------------- 1 | [[package]] 2 | name = "ansi_term" 3 | version = "0.11.0" 4 | source = "registry+https://github.com/rust-lang/crates.io-index" 5 | dependencies = [ 6 | "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 7 | ] 8 | 9 | [[package]] 10 | name = "arc-swap" 11 | version = "0.3.7" 12 | source = "registry+https://github.com/rust-lang/crates.io-index" 13 | 14 | [[package]] 15 | name = "atty" 16 | version = "0.2.11" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | dependencies = [ 19 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 20 | "termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", 21 | "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 22 | ] 23 | 24 | [[package]] 25 | name = "bitflags" 26 | version = "1.0.4" 27 | source = "registry+https://github.com/rust-lang/crates.io-index" 28 | 29 | [[package]] 30 | name = "cc" 31 | version = "1.0.31" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | 34 | [[package]] 35 | name = "cfg-if" 36 | version = "0.1.7" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | 39 | [[package]] 40 | name = "clap" 41 | version = "2.32.0" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | dependencies = [ 44 | "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", 45 | "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", 46 | "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", 47 | "strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", 48 | "textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", 49 | "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 50 | "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", 51 | ] 52 | 53 | [[package]] 54 | name = "itoa" 55 | version = "0.4.3" 56 | source = "registry+https://github.com/rust-lang/crates.io-index" 57 | 58 | [[package]] 59 | name = "libc" 60 | version = "0.2.50" 61 | source = "registry+https://github.com/rust-lang/crates.io-index" 62 | 63 | [[package]] 64 | name = "log" 65 | version = "0.4.6" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | dependencies = [ 68 | "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 69 | ] 70 | 71 | [[package]] 72 | name = "nix" 73 | version = "0.13.0" 74 | source = "registry+https://github.com/rust-lang/crates.io-index" 75 | dependencies = [ 76 | "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", 77 | "cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)", 78 | "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 79 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 80 | "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", 81 | ] 82 | 83 | [[package]] 84 | name = "proc-macro2" 85 | version = "0.4.27" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | dependencies = [ 88 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 89 | ] 90 | 91 | [[package]] 92 | name = "quote" 93 | version = "0.6.11" 94 | source = "registry+https://github.com/rust-lang/crates.io-index" 95 | dependencies = [ 96 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 97 | ] 98 | 99 | [[package]] 100 | name = "redox_syscall" 101 | version = "0.1.51" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | 104 | [[package]] 105 | name = "redox_termios" 106 | version = "0.1.1" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | dependencies = [ 109 | "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)", 110 | ] 111 | 112 | [[package]] 113 | name = "ryu" 114 | version = "0.2.7" 115 | source = "registry+https://github.com/rust-lang/crates.io-index" 116 | 117 | [[package]] 118 | name = "serde" 119 | version = "1.0.89" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | dependencies = [ 122 | "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 123 | ] 124 | 125 | [[package]] 126 | name = "serde_derive" 127 | version = "1.0.89" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | dependencies = [ 130 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 131 | "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)", 132 | "syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)", 133 | ] 134 | 135 | [[package]] 136 | name = "serde_json" 137 | version = "1.0.39" 138 | source = "registry+https://github.com/rust-lang/crates.io-index" 139 | dependencies = [ 140 | "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", 141 | "ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", 142 | "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 143 | ] 144 | 145 | [[package]] 146 | name = "signal-hook" 147 | version = "0.1.8" 148 | source = "registry+https://github.com/rust-lang/crates.io-index" 149 | dependencies = [ 150 | "arc-swap 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", 151 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 152 | ] 153 | 154 | [[package]] 155 | name = "strsim" 156 | version = "0.7.0" 157 | source = "registry+https://github.com/rust-lang/crates.io-index" 158 | 159 | [[package]] 160 | name = "syn" 161 | version = "0.15.29" 162 | source = "registry+https://github.com/rust-lang/crates.io-index" 163 | dependencies = [ 164 | "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)", 165 | "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)", 166 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 167 | ] 168 | 169 | [[package]] 170 | name = "syswall" 171 | version = "0.2.0" 172 | dependencies = [ 173 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 174 | "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", 175 | "nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", 176 | "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", 177 | "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", 178 | "signal-hook 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", 179 | ] 180 | 181 | [[package]] 182 | name = "syswall_cli" 183 | version = "0.2.0" 184 | dependencies = [ 185 | "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", 186 | "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", 187 | "syswall 0.2.0", 188 | ] 189 | 190 | [[package]] 191 | name = "termion" 192 | version = "1.5.1" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | dependencies = [ 195 | "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)", 196 | "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)", 197 | "redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 198 | ] 199 | 200 | [[package]] 201 | name = "textwrap" 202 | version = "0.10.0" 203 | source = "registry+https://github.com/rust-lang/crates.io-index" 204 | dependencies = [ 205 | "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 206 | ] 207 | 208 | [[package]] 209 | name = "unicode-width" 210 | version = "0.1.5" 211 | source = "registry+https://github.com/rust-lang/crates.io-index" 212 | 213 | [[package]] 214 | name = "unicode-xid" 215 | version = "0.1.0" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | 218 | [[package]] 219 | name = "vec_map" 220 | version = "0.8.1" 221 | source = "registry+https://github.com/rust-lang/crates.io-index" 222 | 223 | [[package]] 224 | name = "void" 225 | version = "1.0.2" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | 228 | [[package]] 229 | name = "winapi" 230 | version = "0.3.6" 231 | source = "registry+https://github.com/rust-lang/crates.io-index" 232 | dependencies = [ 233 | "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 234 | "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 235 | ] 236 | 237 | [[package]] 238 | name = "winapi-i686-pc-windows-gnu" 239 | version = "0.4.0" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | 242 | [[package]] 243 | name = "winapi-x86_64-pc-windows-gnu" 244 | version = "0.4.0" 245 | source = "registry+https://github.com/rust-lang/crates.io-index" 246 | 247 | [metadata] 248 | "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 249 | "checksum arc-swap 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1025aeae2b664ca0ea726a89d574fe8f4e77dd712d443236ad1de00379450cf6" 250 | "checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652" 251 | "checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" 252 | "checksum cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)" = "c9ce8bb087aacff865633f0bd5aeaed910fe2fe55b55f4739527f2e023a2e53d" 253 | "checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4" 254 | "checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e" 255 | "checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" 256 | "checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)" = "aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1" 257 | "checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" 258 | "checksum nix 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46f0f3210768d796e8fa79ec70ee6af172dacbe7147f5e69be5240a47778302b" 259 | "checksum proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)" = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915" 260 | "checksum quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "cdd8e04bd9c52e0342b406469d494fcb033be4bdbe5c606016defbb1681411e1" 261 | "checksum redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)" = "423e376fffca3dfa06c9e9790a9ccd282fafb3cc6e6397d01dbf64f9bacc6b85" 262 | "checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" 263 | "checksum ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7" 264 | "checksum serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "92514fb95f900c9b5126e32d020f5c6d40564c27a5ea6d1d7d9f157a96623560" 265 | "checksum serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6eabf4b5914e88e24eea240bb7c9f9a2cbc1bbbe8d961d381975ec3c6b806c" 266 | "checksum serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)" = "5a23aa71d4a4d43fdbfaac00eff68ba8a06a51759a89ac3304323e800c4dd40d" 267 | "checksum signal-hook 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "97a47ae722318beceb0294e6f3d601205a1e6abaa4437d9d33e3a212233e3021" 268 | "checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550" 269 | "checksum syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)" = "1825685f977249735d510a242a6727b46efe914bb67e38d30c071b1b72b1d5c2" 270 | "checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096" 271 | "checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6" 272 | "checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526" 273 | "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" 274 | "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" 275 | "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 276 | "checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" 277 | "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 278 | "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 279 | -------------------------------------------------------------------------------- /lib/src/platforms/linux_x86_64/mod.rs: -------------------------------------------------------------------------------- 1 | mod sockets; 2 | 3 | use log::{error, trace}; 4 | use nix::errno::Errno; 5 | use nix::fcntl::OFlag; 6 | use nix::unistd::Pid; 7 | 8 | use crate::child_process; 9 | use crate::platforms::{PlatformHandler, SyscallEntryResult}; 10 | use crate::process_state::ProcessState; 11 | use crate::process_state::files::ProcessFileState; 12 | use crate::process_state::sockets::{ProcessSocketState, SocketConnectionState}; 13 | use crate::syscalls::{update_registers, HandleSyscallResult, SyscallRegs}; 14 | 15 | pub struct Handler; 16 | 17 | impl Handler { 18 | pub fn new() -> Self { 19 | Self 20 | } 21 | } 22 | 23 | impl PlatformHandler for Handler { 24 | fn block_syscall(&self, pid: Pid, regs: &mut SyscallRegs) -> Result<(), &'static str> { 25 | regs.orig_rax = std::u64::MAX; 26 | update_registers(pid, regs) 27 | } 28 | 29 | fn pre( 30 | &self, 31 | state: &mut ProcessState, 32 | regs: &mut SyscallRegs, 33 | pid: Pid, 34 | ) -> SyscallEntryResult { 35 | match state.syscall_id { 36 | // read 37 | Some(0) => { 38 | SyscallEntryResult::new( 39 | true, 40 | format!( 41 | "Child process {} will read {} bytes from FD {} into buffer at 0x{:X}\n - File: {:?}", 42 | pid, regs.rdx, regs.rdi, regs.rsi, state.file_by_fd(regs.rdi as usize) 43 | ), 44 | ) 45 | } 46 | 47 | // write 48 | Some(1) => { 49 | SyscallEntryResult::new( 50 | true, 51 | format!( 52 | "Child process {} will write {} bytes to FD {} from buffer at 0x{:X}\n{}", 53 | pid, regs.rdx, regs.rdi, regs.rsi, 54 | match child_process::get_child_buffer(pid, regs.rsi as usize, regs.rdx as usize) { 55 | Ok(buf) => format!(" - To write: {:?}", String::from(buf)), 56 | Err(e) => format!(" - Unable to read from child process buffer: {}", e), 57 | }, 58 | ), 59 | ) 60 | } 61 | 62 | // open 63 | Some(2) => { 64 | let mut desc = format!( 65 | "Child process {} will open a file with flags {:?} and mode {:?}", 66 | pid, 67 | OFlag::from_bits(regs.rsi as libc::c_int), 68 | OFlag::from_bits(regs.rdx as libc::c_int), 69 | ); 70 | match child_process::get_child_buffer_cstr(pid, regs.rdi as usize) { 71 | Ok(filepath) => { 72 | desc = format!("{}\n{}", desc, format!(" - File path: {:?}", filepath)); 73 | 74 | // Add file to state 75 | state.add_pending_file(&filepath, regs.rsi as isize, regs.rdx as isize); 76 | } 77 | Err(e) => { 78 | desc = format!("{}\n{}", desc, format!(" - Could not get file path: {}", e)); 79 | } 80 | }; 81 | SyscallEntryResult::new(true, desc) 82 | } 83 | 84 | // close 85 | Some(3) => { 86 | let mut desc = format!("Child process {} wants to close FD {}", pid, regs.rdi); 87 | { 88 | let file = state.file_by_fd(regs.rdi as usize); 89 | if file.is_some() { 90 | desc = format!("{}\n{}", desc, format!(" - File: {:?}", file)); 91 | } 92 | } 93 | { 94 | let sock = state.socket_by_fd(regs.rdi as usize); 95 | if sock.is_some() { 96 | desc = format!("{}\n{}", desc, format!(" - Socket: {:?}", sock)); 97 | } 98 | } 99 | SyscallEntryResult::new(true, desc) 100 | } 101 | 102 | // socket 103 | Some(41) => { 104 | SyscallEntryResult::new(true, sockets::handle_socket_pre(state, regs, pid)) 105 | } 106 | 107 | // connect 108 | Some(42) => { 109 | SyscallEntryResult::new(true, sockets::handle_connect_pre(state, regs, pid)) 110 | } 111 | 112 | // openat 113 | Some(257) => { 114 | let mut desc = format!( 115 | "Child process {} will open a file with flags {:?} and mode {:?} at dirfd {}", 116 | pid, 117 | OFlag::from_bits(regs.rdx as libc::c_int), 118 | OFlag::from_bits(regs.r10 as libc::c_int), 119 | regs.rdi, 120 | ); 121 | match child_process::get_child_buffer_cstr(pid, regs.rsi as usize) { 122 | Ok(filepath) => { 123 | desc = format!("{}\n{}", desc, format!(" - File path: {:?}", filepath)); 124 | 125 | // Add file to state 126 | state.add_pending_file(&filepath, regs.rdx as isize, regs.r10 as isize); 127 | } 128 | Err(e) => { 129 | desc = format!("{}\n{}", desc, format!(" - Could not get file path: {}", e)); 130 | } 131 | }; 132 | SyscallEntryResult::new(true, desc) 133 | } 134 | _ => { 135 | SyscallEntryResult::new( 136 | false, 137 | format!( 138 | "Unhandled syscall {:?} ({:X}, {:X}, {:X}, {:X}, {:X}, {:X})", 139 | state.syscall_id, 140 | regs.rdi, 141 | regs.rsi, 142 | regs.rdx, 143 | regs.r10, 144 | regs.r8, 145 | regs.r9 146 | ), 147 | ) 148 | }, 149 | } 150 | } 151 | 152 | fn post( 153 | &self, 154 | state: &mut ProcessState, 155 | regs: &mut SyscallRegs, 156 | pid: Pid, 157 | ) { 158 | match state.handler_res { 159 | Some(HandleSyscallResult::BlockedHard) => { 160 | if let Ok(()) = self.update_regs_hard_block(pid, regs) { 161 | match state.syscall_id { 162 | // open 163 | Some(2) => { 164 | // Set the pending file open as blocked 165 | state.update_pending_file_state(ProcessFileState::OpenBlockedHard); 166 | } 167 | 168 | // socket 169 | Some(41) => { 170 | state.update_pending_socket_state(ProcessSocketState::CreateBlockedHard); 171 | } 172 | 173 | // connect 174 | Some(42) => { 175 | if let Some(ref mut sock) = state.socket_by_fd(regs.rdi as usize) { 176 | sock.connection_state = SocketConnectionState::ConnectBlockedHard; 177 | } 178 | } 179 | 180 | // openat 181 | Some(257) => { 182 | // Set the pending file open as blocked 183 | state.update_pending_file_state(ProcessFileState::OpenBlockedHard); 184 | } 185 | _ => (), 186 | }; 187 | }; 188 | } 189 | Some(HandleSyscallResult::BlockedSoft) => { 190 | match state.syscall_id { 191 | // read 192 | Some(0) => { 193 | // Set return value to number of bytes intended to be read to simulate success 194 | regs.rax = regs.rdx; 195 | update_registers(pid, regs).unwrap_or_else(|e| error!("{}", e)); 196 | } 197 | 198 | // write 199 | Some(1) => { 200 | // Set return value to number of bytes intended to be written to simulate 201 | // success 202 | regs.rax = regs.rdx; 203 | update_registers(pid, regs).unwrap_or_else(|e| error!("{}", e)); 204 | } 205 | 206 | // open 207 | Some(2) => { 208 | // TODO: simulate open return 209 | regs.rax = 5; 210 | update_registers(pid, regs).unwrap_or_else(|e| error!("{}", e)); 211 | 212 | // Set the pending file open as blocked 213 | state.update_pending_file_state(ProcessFileState::OpenBlockedSoft); 214 | } 215 | 216 | // socket 217 | Some(41) => { 218 | // TODO: simulate socket return 219 | regs.rax = 5; 220 | update_registers(pid, regs).unwrap_or_else(|e| error!("{}", e)); 221 | 222 | state.update_pending_socket_state(ProcessSocketState::CreateBlockedSoft); 223 | } 224 | 225 | // connect 226 | Some(42) => { 227 | // TODO: simulate connect return 228 | if let Some(ref mut sock) = state.socket_by_fd(regs.rdi as usize) { 229 | sock.connection_state = SocketConnectionState::ConnectBlockedSoft; 230 | } 231 | } 232 | 233 | // openat 234 | Some(257) => { 235 | // TODO: simulate openat return 236 | regs.rax = 5; 237 | update_registers(pid, regs).unwrap_or_else(|e| error!("{}", e)); 238 | 239 | // Set the pending file open as blocked 240 | state.update_pending_file_state(ProcessFileState::OpenBlockedSoft); 241 | } 242 | _ => (), 243 | } 244 | } 245 | Some(HandleSyscallResult::Unchanged) => { 246 | match state.syscall_id { 247 | // read 248 | Some(0) => { 249 | // TODO: update file read bytes in state 250 | } 251 | 252 | // write 253 | Some(1) => { 254 | // TODO: update file write bytes in state 255 | } 256 | 257 | // open 258 | Some(2) => { 259 | // Set file state according to return value 260 | if (regs.rax as isize) < 0 { 261 | state.update_pending_file_state(ProcessFileState::CouldNotOpen( 262 | Errno::from_i32(-(regs.rax as i32)), 263 | )); 264 | } else { 265 | state.update_pending_file_state(ProcessFileState::Opened( 266 | regs.rax as usize, 267 | )); 268 | } 269 | } 270 | 271 | // close 272 | Some(3) => { 273 | state.update_file_state_by_fd(regs.rdi as usize, ProcessFileState::Closed); 274 | state.update_socket_state_by_fd(regs.rdi as usize, ProcessSocketState::Closed); 275 | } 276 | 277 | // socket 278 | Some(41) => { 279 | // Set socket state according to return value 280 | if (regs.rax as isize) < 0 { 281 | state.update_pending_socket_state(ProcessSocketState::CouldNotCreate( 282 | Errno::from_i32(-(regs.rax as i32)), 283 | )); 284 | } else { 285 | state.update_pending_socket_state(ProcessSocketState::Created( 286 | regs.rax as usize, 287 | )); 288 | } 289 | } 290 | 291 | // connect 292 | Some(42) => { 293 | if let Some(ref mut sock) = state.socket_by_fd(regs.rdi as usize) { 294 | if (regs.rax as isize) < 0 { 295 | sock.connection_state = SocketConnectionState::ConnectError( 296 | Errno::from_i32(-(regs.rax as i32)), 297 | ); 298 | } else { 299 | sock.connection_state = SocketConnectionState::Connected; 300 | } 301 | } 302 | } 303 | 304 | // openat 305 | Some(257) => { 306 | // Set file state according to return value 307 | if (regs.rax as isize) < 0 { 308 | state.update_pending_file_state(ProcessFileState::CouldNotOpen( 309 | Errno::from_i32(-(regs.rax as i32)), 310 | )); 311 | } else { 312 | state.update_pending_file_state(ProcessFileState::Opened( 313 | regs.rax as usize, 314 | )); 315 | } 316 | } 317 | _ => { 318 | trace!("Unhandled syscall result: {:X}", regs.rax); 319 | }, 320 | }; 321 | } 322 | _ => {}, 323 | } 324 | } 325 | 326 | fn update_regs_hard_block(&self, pid: Pid, regs: &mut SyscallRegs) -> Result<(), &'static str> { 327 | regs.rax = (-libc::EPERM) as u64; 328 | update_registers(pid, regs) 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /lib/src/child_process.rs: -------------------------------------------------------------------------------- 1 | use log::{debug, info, trace, warn}; 2 | use nix::sys::ptrace; 3 | use nix::sys::signal; 4 | use nix::sys::uio; 5 | use nix::sys::wait; 6 | use nix::unistd::{execvp, Pid}; 7 | use signal_hook; 8 | use std::collections::HashMap; 9 | use std::ffi::CString; 10 | use std::sync::atomic::{AtomicBool, Ordering}; 11 | use std::sync::Arc; 12 | 13 | use crate::process_state::{ProcessState, ProcessTraceState, ProcessType}; 14 | use crate::syscalls; 15 | 16 | /// Mapping of PID to `ProcessState` 17 | #[derive(Default)] 18 | pub struct ProcessList(pub HashMap); 19 | 20 | impl ProcessList { 21 | /// Returns a flag which is set if all processes are of type `ClonedThread` 22 | pub fn all_threads(&self, tracee_pid: Pid) -> bool { 23 | self.0.iter().all(|(pid, child_state)| { 24 | *pid == tracee_pid 25 | || match child_state.process_type { 26 | ProcessType::ClonedThread => true, 27 | _ => false, 28 | } 29 | }) 30 | } 31 | 32 | /// Returns a flag which is set if all processes are `Terminated` 33 | pub fn all_terminated(&self) -> bool { 34 | self.0.values().map(|x| &x.trace_state).all(|x| match x { 35 | ProcessTraceState::Terminated(_) => true, 36 | _ => false, 37 | }) 38 | } 39 | } 40 | 41 | /// A copy of a chunk of memory read from a child process's virtual memory 42 | #[derive(Debug)] 43 | pub struct ChildProcessBuffer(pub Vec); 44 | 45 | impl From for String { 46 | 47 | /// Converts the `ChildProcessBuffer` String, interpreting the buffer as UTF-8 48 | fn from(b: ChildProcessBuffer) -> String { 49 | String::from_utf8_lossy(&b.0).into_owned() 50 | } 51 | } 52 | 53 | /// Reads a given amount child process memory into a `ChildProcessBuffer` 54 | /// 55 | /// # Arguments 56 | /// 57 | /// - `pid`: PID of the target child process 58 | /// - `base`: base VM address for read 59 | /// - `len`: length (in bytes) of read 60 | pub fn get_child_buffer( 61 | pid: Pid, 62 | base: usize, 63 | len: usize, 64 | ) -> Result { 65 | let mut rbuf: Vec = vec![0; len]; 66 | let remote_iovec = uio::RemoteIoVec { base, len }; 67 | uio::process_vm_readv( 68 | pid, 69 | &[uio::IoVec::from_mut_slice(rbuf.as_mut_slice())], 70 | &[remote_iovec], 71 | ) 72 | .map_err(|_| "Unable to read from child process virtual memory")?; 73 | Ok(ChildProcessBuffer(rbuf)) 74 | } 75 | 76 | /// Reads a null-terminated string from child process memory into a `ChildProcessBuffer` 77 | /// 78 | /// # Arguments 79 | /// 80 | /// - `pid`: PID of the target child process 81 | /// - `base`: base VM address for read 82 | pub fn get_child_buffer_cstr(pid: Pid, base: usize) -> Result { 83 | let mut final_buf: Vec = Vec::with_capacity(255); 84 | 85 | // Current RemoteIoVec base address 86 | let mut current_base = base; 87 | 88 | // Index of 0 byte in final_buf 89 | let mut nul_idx: isize = -1; 90 | 91 | // Keep reading 255-byte chunks from the process VM until one contains a 0 byte 92 | // (null-termination character) 93 | loop { 94 | // Read into a temporary buffer 95 | let mut rbuf: Vec = vec![0; 255]; 96 | let remote_iovec = uio::RemoteIoVec { 97 | base: current_base, 98 | len: 255, 99 | }; 100 | uio::process_vm_readv( 101 | pid, 102 | &[uio::IoVec::from_mut_slice(rbuf.as_mut_slice())], 103 | &[remote_iovec], 104 | ) 105 | .map_err(|_| "Unable to read from child process virtual memory")?; 106 | 107 | // Append temporary buffer to the final buffer and increase base address pointer 108 | final_buf.append(&mut rbuf); 109 | current_base += 255; 110 | 111 | // If final_buf contains a 0 byte, store the index and break from the read loop 112 | if final_buf.contains(&0) { 113 | if let Some(idx) = final_buf.iter().position(|&x| x == 0) { 114 | nul_idx = idx as isize; 115 | } 116 | break; 117 | } 118 | } 119 | if nul_idx > -1 { 120 | Ok(String::from_utf8_lossy(&final_buf[0..(nul_idx as usize)]).into_owned()) 121 | } else { 122 | Err("Null-terminated string not found") 123 | } 124 | } 125 | 126 | /// Executes a child process under ptrace using `execvp`. 127 | /// 128 | /// Should be called by the tracer child process after forking. 129 | /// 130 | /// # Arguments 131 | /// 132 | /// - `cmd`: command argv for `execvp()` call 133 | pub fn exec_child(cmd: Vec<&str>) -> Result<(), String> { 134 | ptrace::traceme() 135 | .map_err(|_| "CHILD: could not enable tracing by parent (PTRACE_TRACEME failed)")?; 136 | 137 | // Extract child command (first arg) 138 | let child_cmd = CString::new(*cmd.first().ok_or("Unable to extract tracee command")?) 139 | .map_err(|_| "Unable to extract tracee command")?; 140 | 141 | // Extract child arguments (including first command) 142 | let child_args = cmd 143 | .iter() 144 | .map(|v| CString::new(*v).unwrap_or_default()) 145 | .collect::>(); 146 | 147 | debug!( 148 | "CHILD: executing {:?} with argv {:?}...", 149 | child_cmd, child_args 150 | ); 151 | execvp(&child_cmd, &child_args).map_err(|e| format!("unable to execute {:?}: {}", child_cmd, e))?; 152 | Ok(()) 153 | } 154 | 155 | /// Waits for a child process event. 156 | /// 157 | /// Will block until an event is ready unless `nohang` is set 158 | /// 159 | /// # Arguments 160 | /// 161 | /// - `pid`: child process PID, or -1 to wait for all child processes 162 | /// - `nohang`: if set, function will not block if all child processes are running 163 | pub fn wait_child(pid: Pid, nohang: bool) -> Result { 164 | if nohang { 165 | wait::waitpid( 166 | pid, 167 | Some(wait::WaitPidFlag::__WALL | wait::WaitPidFlag::WNOHANG), 168 | ) 169 | .map_err(|e| format!("Unable to wait for child PID {}: {:?}", pid, e)) 170 | } else { 171 | wait::waitpid(pid, Some(wait::WaitPidFlag::__WALL)) 172 | .map_err(|e| format!("Unable to wait for child PID {}: {:?}", pid, e)) 173 | } 174 | } 175 | 176 | /// Handles a syscall ptrace event for a child process 177 | /// 178 | /// # Arguments 179 | /// 180 | /// - `child`: `ProcessState` of the child process receiving the event 181 | /// - `pid`: PID of the child process receiving the event 182 | /// - `syscall_handler`: current syscall handler 183 | fn handle_pid_syscall( 184 | child: &mut ProcessState, 185 | pid: Pid, 186 | syscall_handler: &mut syscalls::SyscallHandler, 187 | ) -> Result<(), String> { 188 | match child.trace_state { 189 | 190 | // Event must be a syscall-enter-stop 191 | ProcessTraceState::RunningAwaitSyscall => { 192 | child.trace_state = ProcessTraceState::TraceSyscallEnterStop; 193 | 194 | // Get syscall details 195 | match ptrace::getregs(pid) { 196 | Ok(mut regs) => { 197 | let syscall_id = regs.orig_rax; 198 | 199 | child.syscall_id = Some(syscall_id); 200 | child.handler_res = Some(syscall_handler.handle_pre_syscall(child, pid, &mut regs)); 201 | 202 | // Execute this child syscall 203 | ptrace::syscall(pid) 204 | .map_err(|_| format!("Unable to restart syscall exit for PID {:?}", pid)) 205 | } 206 | Err(err) => { 207 | if err.as_errno() == Some(nix::errno::Errno::ESRCH) { 208 | // If ESRCH error is received, child PID must no longer be running, so set 209 | // to Terminated 210 | child.trace_state = ProcessTraceState::Terminated(-1); 211 | Ok(()) 212 | } else { 213 | Err(String::from( 214 | "Unable to get syscall registers after servicing", 215 | )) 216 | } 217 | } 218 | } 219 | } 220 | 221 | // Event must be a syscall-exit-stop 222 | ProcessTraceState::TraceSyscallEnterStop => { 223 | child.trace_state = ProcessTraceState::TraceSyscallExitStop; 224 | 225 | // Get syscall result 226 | match ptrace::getregs(pid) { 227 | Ok(ref mut regs) => { 228 | syscall_handler.handle_post_syscall(child, pid, regs); 229 | 230 | child.syscall_id = None; 231 | child.handler_res = None; 232 | 233 | // Await next child syscall 234 | ptrace::syscall(pid).map_err(|_| { 235 | format!("Unable to restart syscall entry wait for PID {:?}", pid) 236 | })?; 237 | 238 | child.trace_state = ProcessTraceState::RunningAwaitSyscall; 239 | Ok(()) 240 | } 241 | Err(err) => { 242 | if err.as_errno() == Some(nix::errno::Errno::ESRCH) { 243 | // If ESRCH error is received, child PID must no longer be running, so set 244 | // to Terminated 245 | child.trace_state = ProcessTraceState::Terminated(-1); 246 | Ok(()) 247 | } else { 248 | Err(String::from( 249 | "Unable to get syscall registers after servicing", 250 | )) 251 | } 252 | } 253 | } 254 | } 255 | _ => Err(format!( 256 | "Unhandled process state for {:?} ({:?})", 257 | pid, child.trace_state 258 | )), 259 | } 260 | } 261 | 262 | /// Handles a stopped ptrace event for a child process 263 | /// 264 | /// # Arguments 265 | /// 266 | /// - `child`: `ProcessState` of the child process receiving the event 267 | /// - `pid`: PID of the child process receiving the event 268 | /// - `sig`: specific signal received by child process 269 | fn handle_pid_stop(child: &mut ProcessState, pid: Pid, sig: signal::Signal) { 270 | if let signal::Signal::SIGTERM = sig { 271 | info!("SIGTERM received for PID {:?}", pid); 272 | 273 | // TODO: get exit status 274 | child.trace_state = ProcessTraceState::Terminated(-1); 275 | }; 276 | } 277 | 278 | /// Handles all `WaitStatus` types returned by `wait_child()` for a specific child process 279 | /// 280 | /// # Arguments 281 | /// 282 | /// - `wait_status`: status returned by `wait_child()` 283 | /// - `processes`: `ProcessList` which can be modified if the child cloned/forked. 284 | /// - `syscall_handler`: current syscall handler 285 | fn handle_wait_status( 286 | wait_status: &wait::WaitStatus, 287 | processes: &mut ProcessList, 288 | syscall_handler: &mut syscalls::SyscallHandler, 289 | ) -> Result<(), String> { 290 | match wait_status { 291 | // Handle the continuation of a child process after a stop 292 | wait::WaitStatus::Continued(pid) => { 293 | info!("Child process {:?} continued", pid); 294 | Ok(()) 295 | } 296 | 297 | // Handle exit of a child process 298 | wait::WaitStatus::Exited(pid, code) => { 299 | info!("Child process {:?} exited with code {}", pid, code); 300 | let child = processes.0.get_mut(&pid).ok_or_else(|| format!( 301 | "Child process {:?} exited, however this process is not in the process list", 302 | pid 303 | ))?; 304 | child.trace_state = ProcessTraceState::Terminated(*code as isize); 305 | Ok(()) 306 | } 307 | 308 | // Handle ptrace events such as a clone, fork or exec 309 | wait::WaitStatus::PtraceEvent(pid, sig, ev_type) => { 310 | // DEBUG: ptrace events should always use a SIGTRAP 311 | assert!(*sig == signal::Signal::SIGTRAP); 312 | 313 | // Set flag to continue processing based on event type. Processing fetches the new PID 314 | // from the event and updates the child ProcessState accordigly, therefore processing 315 | // should only continue for clones and forks. 316 | // TODO: stop using Linux hard-coded event IDs 317 | let cont = match ev_type { 318 | 1 => { 319 | info!("Process {:?} forked", pid); 320 | true 321 | } 322 | 2 => { 323 | info!("Process {:?} vforked", pid); 324 | true 325 | } 326 | 3 => { 327 | info!("Process {:?} created clone", pid); 328 | true 329 | } 330 | 4 => { 331 | info!("Process {:?} called exec", pid); 332 | false 333 | } 334 | t => { 335 | warn!("Process {:?}: unknown event type {}", pid, t); 336 | false 337 | } 338 | }; 339 | 340 | if cont { 341 | let child_pid = 342 | ptrace::getevent(*pid).map_err(|_| "Unable to get ptrace event details")?; 343 | 344 | // Get new child PID for clone, fork, etc. 345 | let child_pid = Pid::from_raw(child_pid as i32); 346 | info!("New child PID: {:?}", child_pid); 347 | 348 | let child_type = match ev_type { 349 | 1 => ProcessType::ForkedProcess, 350 | 2 => ProcessType::VForkedProcess, 351 | 3 => ProcessType::ClonedThread, 352 | _ => ProcessType::ForkedProcess, 353 | }; 354 | 355 | // Update or insert child ProcessState 356 | processes.0.entry(child_pid) 357 | .and_modify(|ch| { 358 | if ch.trace_state == ProcessTraceState::Stopped { 359 | info!("Changing existing Stopped process {:?} to RunningAwaitSyscall ({:?})...", child_pid, ch); 360 | ch.trace_state = ProcessTraceState::RunningAwaitSyscall; 361 | ch.process_type = child_type; 362 | } 363 | }) 364 | .or_insert_with(|| { 365 | info!("Process {:?} does not exist, adding as Created...", child_pid); 366 | ProcessState::new(ProcessTraceState::Created, child_type) 367 | }); 368 | } 369 | 370 | // Restart PID that sent the event (parent of newly-created PID) 371 | ptrace::syscall(*pid) 372 | .map_err(|_| format!("Unable to restart PID {:?} for syscall entry wait", pid))?; 373 | 374 | Ok(()) 375 | } 376 | 377 | // When PTRACE_O_TRACESYSGOOD is set, PtraceSyscall will be generated when a process has 378 | // hit a syscall entery/exit. Handle the syscall via handle_pid_syscall(). 379 | wait::WaitStatus::PtraceSyscall(pid) => { 380 | let child = processes.0.get_mut(&pid).ok_or_else(|| format!( 381 | "Syscall was delivered by {:?} but process was not found in the process list", 382 | pid 383 | ))?; 384 | handle_pid_syscall(child, *pid, syscall_handler) 385 | } 386 | 387 | // Handle a generic signal to a child process: log signal and restart child via 388 | // ptrace::syscall(). 389 | wait::WaitStatus::Signaled(pid, sig, did_core_dump) => { 390 | info!("Child process {:?} was given signal {:?}", pid, sig); 391 | if *did_core_dump { 392 | info!("Child process {:?} produced a core dump", pid); 393 | } 394 | ptrace::syscall(*pid) 395 | .map_err(|_| format!("Unable to restart PID {:?} for syscall entry wait", pid))?; 396 | Ok(()) 397 | } 398 | 399 | // StillAlive will not be generated unless WNOHANG waitpid() option is set 400 | wait::WaitStatus::StillAlive => Ok(()), 401 | 402 | // Stopped: handle new PID, PID just created from PtraceEvent or existing PID by 403 | // (re)starting it via ptrace::syscall(). Also call handle_pid_stop() for existing PIDs to 404 | // handle any signals as necessary. 405 | wait::WaitStatus::Stopped(pid, signal) => { 406 | if !processes.0.contains_key(&pid) { 407 | // If the PID is not in the ProcessList, add it as ProcessTraceState::Stopped and 408 | // start it via ptrace::syscall(). State will be changed to RunningAwaitSyscall 409 | // when the PtraceEvent eventually arrives. 410 | trace!("New process (stopped): {:?}", pid); 411 | processes.0.insert( 412 | *pid, 413 | ProcessState::new(ProcessTraceState::Stopped, ProcessType::ForkedProcess), 414 | ); 415 | ptrace::syscall(*pid).map_err(|_| { 416 | format!("Unable to start new PID {:?} for syscall entry wait", pid) 417 | })?; 418 | } else if let Some(child) = processes.0.get_mut(&pid) { 419 | if child.trace_state == ProcessTraceState::Created { 420 | // If process has already been created via a WaitStatus::PtraceEvent, start it 421 | // via ptrace::syscall() and change its ProcessTraceState. 422 | trace!( 423 | "PID {:?} was previously marked as created, setting to RunningAwaitSyscall...", 424 | pid 425 | ); 426 | ptrace::syscall(*pid).map_err(|_| { 427 | format!( 428 | "Unable to start newly-created PID {:?} for syscall entry wait", 429 | pid 430 | ) 431 | })?; 432 | child.trace_state = ProcessTraceState::RunningAwaitSyscall; 433 | } else { 434 | // If the process already exists and is running, handle the signal and restart 435 | // it 436 | handle_pid_stop(child, *pid, *signal); 437 | ptrace::syscall(*pid).map_err(|_| { 438 | format!( 439 | "Unable to start newly-created PID {:?} for syscall entry wait", 440 | pid 441 | ) 442 | })?; 443 | } 444 | }; 445 | Ok(()) 446 | } 447 | } 448 | } 449 | 450 | /// Initiates and runs the main tracer loop on a child (tracee) PID 451 | /// 452 | /// # Arguments 453 | /// 454 | /// - `tracee_pid`: PID of the main tracee process (which should have been executed via `exec_child()`) 455 | /// - `syscall_handler`: current syscall handler 456 | pub fn child_loop(tracee_pid: Pid, syscall_handler: &mut syscalls::SyscallHandler) -> Result { 457 | let mut processes: ProcessList = ProcessList::default(); 458 | 459 | // Flag to indicate if a SIGINT has been received 460 | let sigint = Arc::new(AtomicBool::new(false)); 461 | 462 | // UNSAFE: register a handler for SIGINT to close stdin and set the "sigint" flag 463 | unsafe { 464 | // Clone the "sigint" Arc to move to closure 465 | let sigint = Arc::clone(&sigint); 466 | 467 | signal_hook::register(signal_hook::SIGINT, move || { 468 | // Close stdin explicitly. This will abort any user input (io::stdin().read_line()) 469 | // that is currently in progress. 470 | // 471 | // TODO: improve when support is available (see: 472 | // https://github.com/rust-lang/rust/issues/40032) 473 | libc::close(0); 474 | 475 | // Set the "sigint" flag 476 | sigint.store(true, Ordering::SeqCst); 477 | }) 478 | } 479 | .map_err(|_| "Unable to register SIGINT handler")?; 480 | 481 | // Insert main tracee process into ProcessList 482 | processes.0.insert( 483 | tracee_pid, 484 | ProcessState::new( 485 | ProcessTraceState::RunningAwaitSyscall, 486 | ProcessType::MainTracee, 487 | ), 488 | ); 489 | 490 | // Main tracing loop 491 | loop { 492 | // Check "sigint" flag: if set, kill the tracee process and break from the loop 493 | if sigint.load(Ordering::Relaxed) { 494 | warn!("SIGINT received, killing tracee process..."); 495 | if let Err(e) = signal::kill(tracee_pid, signal::Signal::SIGTERM) { 496 | warn!("Unable to send SIGTERM to tracee process: {}", e); 497 | } 498 | if let Err(e) = signal::kill(tracee_pid, signal::Signal::SIGKILL) { 499 | warn!("Unable to send SIGKILL to tracee process: {}", e); 500 | } 501 | break; 502 | } 503 | 504 | // Wait for any child process (-1) 505 | let wait_status = wait_child(Pid::from_raw(-1 as i32), false); 506 | if let Ok(ws) = wait_status { 507 | if let Err(s) = handle_wait_status(&ws, &mut processes, syscall_handler) { 508 | warn!("{}", s); 509 | break; 510 | } 511 | } else { 512 | warn!("{:?}", wait_status); 513 | break; 514 | } 515 | 516 | // If main process contains only clones (threads) then break from loop when this process 517 | // terminates. Otherwise (e.g. forks), only break when all processes have terminated. 518 | if let Some(main_child) = processes.0.get(&tracee_pid) { 519 | if let ProcessTraceState::Terminated(main_exit_status) = main_child.trace_state { 520 | // Check if all child processes are ClonedThread 521 | let mut exit = false; 522 | if processes.all_threads(tracee_pid) { 523 | info!("All remaining processes are threads, exiting trace loop..."); 524 | exit = true; 525 | } else if processes.all_terminated() { 526 | info!("All processes are now terminated, exiting trace loop..."); 527 | exit = true; 528 | } 529 | 530 | if exit { 531 | info!( 532 | "Main tracee process {:?} has terminated with code {}", 533 | tracee_pid, main_exit_status 534 | ); 535 | break; 536 | } 537 | } 538 | } 539 | } 540 | 541 | Ok(processes) 542 | } 543 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | --------------------------------------------------------------------------------