Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

file.find() #405

Merged
merged 7 commits into from
Jan 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/_docs/user-guide/eldritch.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,18 @@ The <b>file.timestomp</b> method is very cool, and will be even cooler when Nick
The <b>file.write</b> method writes to a given file path with the given content.
If a file or directory already exists at this path, the method will fail.

### file.find

`file.find(path: str, name: Option<str>, file_type: Option<str>, permissions: Option<int>, modified_time: Option<int>, create_time: Option<int>) -> Vec<str>`

The <b>file.find</b> method finds all files matching the used paramters. Returns file path for all matching items.

- name: Checks if file name contains provided input
- file_type: Checks for 'file' or 'dir' for files or directories, respectively.
- permissions: On UNIX systems, takes numerical input of standard unix permissions (rwxrwxrwx == 777). On Windows, takes 1 or 0, 1 if file is read only.
- modified_time: Checks if last modified time matches input specified in time since EPOCH
- create_time: Checks if last modified time matches input specified in time since EPOCH

---

## Pivot
Expand Down
5 changes: 5 additions & 0 deletions implants/lib/eldritch/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
mod template_impl;
mod timestomp_impl;
mod write_impl;
mod find_impl;

use allocative::Allocative;
use derive_more::Display;
Expand Down Expand Up @@ -180,4 +181,8 @@
write_impl::write(path, content)?;
Ok(NoneType{})
}
fn find(this: FileLibrary, path: String, name: Option<String>, file_type: Option<String>, permissions: Option<u64>, modified_time: Option<u64>, create_time: Option<u64>) -> anyhow::Result<Vec<String>> {
if false { println!("Ignore unused this var. _this isn't allowed by starlark. {:?}", this); }

Check warning on line 185 in implants/lib/eldritch/src/file.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file.rs#L185

Added line #L185 was not covered by tests
find_impl::find(path, name, file_type, permissions, modified_time, create_time)
}

Check warning on line 187 in implants/lib/eldritch/src/file.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file.rs#L187

Added line #L187 was not covered by tests
}
81 changes: 81 additions & 0 deletions implants/lib/eldritch/src/file/find_impl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use std::{path::{Path, PathBuf}, time::{SystemTime, UNIX_EPOCH}};
use anyhow::{anyhow, Result};
use std::fs::canonicalize;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

fn check_path(path: &PathBuf, name: Option<String>, file_type: Option<String>, permissions: Option<u64>, modified_time: Option<u64>, create_time: Option<u64>) -> Result<bool> {
if let Some(name) = name {
if !path.file_name().ok_or(anyhow!("Failed to get item file name"))?.to_str().ok_or(anyhow!("Failed to convert file name to str"))?.contains(&name) {
return Ok(false);
}
}
if let Some(file_type) = file_type {
if !path.is_file() && file_type == "file" {
return Ok(false);
}
if !path.is_dir() && file_type == "dir" {
return Ok(false);
}
}
if let Some(permissions) = permissions {
let metadata = path.metadata()?.permissions();
#[cfg(unix)]
{
if metadata.mode() != (permissions as u32) {
return Ok(false);
}
}
#[cfg(windows)]
{
if permissions == 0 && metadata.readonly() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be cleaner to switch to a match.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Problem is that for unix I'm making calls to a permissions trait in PermissionsExt, so if we don't do this then the Windows version will try and compile with the use of the unix-only trait and error

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't it still be bound in the #[cfg(windows)] ?
I'm thinking

#[cfg(windows)]
{
    match permissions {
        0 => {
            if metadata.readonly() { return Ok(false) }
        }
       1 => {
            if !metadata.readonly() { return Ok(false) }
       }
       _ => {
          return anyhow::anyhow!("Windows only supports readonly (0) or not-readonly (1)")
      }
    }
}

return Ok(false);
}
if permissions == 1 && !metadata.readonly() {
return Ok(false);
}

Check warning on line 36 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L8-L36

Added lines #L8 - L36 were not covered by tests
}
}
if let Some(modified_time) = modified_time {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Outside the scope of this PR but in the future is it possible to add newer than or older than?

Seeing this I realized it'll be be rare files match a specific second.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that was what I was curious about with these. Do we want older/newer to be the default action?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to make the changes in this PR i would:

  • Remove the modified time and created time fields
  • Replace modified time with a modified_before and modified_after option
  • Replace created time with a created_before and created_after option

This would make it possible to time bound your search for things created within a specifir and or modified in a specific range.

if path.metadata()?.modified()?.duration_since(UNIX_EPOCH)?.as_secs() != modified_time {
return Ok(false);
}
}
if let Some(create_time) = create_time {
if path.metadata()?.created()?.duration_since(UNIX_EPOCH)?.as_secs() != create_time {
return Ok(false);
}
}
Ok(true)
}

Check warning on line 50 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L38-L50

Added lines #L38 - L50 were not covered by tests

fn search_dir(path: &str, name: Option<String>, file_type: Option<String>, permissions: Option<u64>, modified_time: Option<u64>, create_time: Option<u64>) -> Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
let res = Path::new(&path);
if !res.is_dir() {
return Err(anyhow!("Search path is not a directory"));
}
if res.is_dir() {
for entry in res.read_dir()? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
out.append(&mut search_dir(path.to_str().ok_or(anyhow!("Failed to convert path to str"))?, name.clone(), file_type.clone(), permissions, modified_time, create_time)?);

Check warning on line 63 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L52-L63

Added lines #L52 - L63 were not covered by tests
} else {
if check_path(&path, name.clone(), file_type.clone(), permissions, modified_time, create_time)? {
out.push(canonicalize(path)?.to_str().ok_or(anyhow!("Failed to convert path to str"))?.to_owned());
}

Check warning on line 67 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L65-L67

Added lines #L65 - L67 were not covered by tests
}
}
}
Ok(out)
}

Check warning on line 72 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L70-L72

Added lines #L70 - L72 were not covered by tests

pub fn find(path: String, name: Option<String>, file_type: Option<String>, permissions: Option<u64>, modified_time: Option<u64>, create_time: Option<u64>) -> Result<Vec<String>> {
if let Some(perms) = permissions {
if !cfg!(unix) && (perms != 0 || perms != 1) {
return Err(anyhow::anyhow!("Only readonly permissions are available on non-unix systems. Please use 0 or 1."));
jabbate19 marked this conversation as resolved.
Show resolved Hide resolved
}
}
search_dir(&path, name, file_type, permissions, modified_time, create_time)
}

Check warning on line 81 in implants/lib/eldritch/src/file/find_impl.rs

View check run for this annotation

Codecov / codecov/patch

implants/lib/eldritch/src/file/find_impl.rs#L75-L81

Added lines #L75 - L81 were not covered by tests
2 changes: 1 addition & 1 deletion implants/lib/eldritch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ mod tests {
a.globals(globals);
a.all_true(
r#"
dir(file) == ["append", "compress", "copy", "download", "exists", "hash", "is_dir", "is_file", "list", "mkdir", "moveto", "read", "remove", "replace", "replace_all", "template", "timestomp", "write"]
dir(file) == ["append", "compress", "copy", "download", "exists", "find", "hash", "is_dir", "is_file", "list", "mkdir", "moveto", "read", "remove", "replace", "replace_all", "template", "timestomp", "write"]
dir(process) == ["info", "kill", "list", "name", "netstat"]
dir(sys) == ["dll_inject", "dll_reflect", "exec", "get_env", "get_ip", "get_os", "get_pid", "get_reg", "get_user", "hostname", "is_linux", "is_macos", "is_windows", "shell", "write_reg_hex", "write_reg_int", "write_reg_str"]
dir(pivot) == ["arp_scan", "bind_proxy", "ncat", "port_forward", "port_scan", "smb_exec", "ssh_copy", "ssh_exec", "ssh_password_spray"]
Expand Down
Loading