Skip to content

Commit

Permalink
rust: wrapper check executables in PATH
Browse files Browse the repository at this point in the history
  • Loading branch information
rizsotto committed Jan 18, 2025
1 parent 8dc417a commit 2f6104c
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions rust/bear/src/bin/wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ use bear::intercept::tcp::ReporterOnTcp;
use bear::intercept::Reporter;
use bear::intercept::KEY_DESTINATION;
use bear::intercept::{Event, Execution, ProcessId};
use std::ffi::OsStr;
#[cfg(target_os = "windows")]
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

/// Implementation of the wrapper process.
Expand Down Expand Up @@ -85,8 +88,7 @@ fn next_in_path(target: &Path) -> Result<PathBuf> {

path.split(':')
.map(|dir| Path::new(dir).join(target))
// FIXME: check if it is executable
.filter(|path| path.is_file())
.filter(|path| is_executable_file(path))
.find(|path| {
// We need to compare it with the real path of the candidate executable to avoid
// calling the same executable again.
Expand Down Expand Up @@ -127,3 +129,34 @@ fn into_execution(path_buf: &Path) -> Result<Execution> {
environment: std::env::vars().collect(),
})
}

/// Checks if the given path is an executable file.
fn is_executable_file(path: &Path) -> bool {
if !path.is_file() {
return false;
}

#[cfg(target_os = "windows")]
{
path.extension()
.map(|ext| EXECUTABLE_EXTENSIONS.contains(&ext))
.unwrap_or(false)
}

#[cfg(not(target_os = "windows"))]
{
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|metadata| metadata.permissions().mode() & 0o100 != 0)
.unwrap_or(false)
}
}

#[cfg(target_os = "windows")]
const EXECUTABLE_EXTENSIONS: &[&OsStr] = &[
OsStr::new("exe"),
OsStr::new("com"),
OsStr::new("bat"),
OsStr::new("cmd"),
OsStr::new("ps1"),
];

0 comments on commit 2f6104c

Please sign in to comment.