diff options
author | Tyler Murphy <tylermurphy534@gmail.com> | 2022-11-09 16:48:36 -0500 |
---|---|---|
committer | Tyler Murphy <tylermurphy534@gmail.com> | 2022-11-09 16:48:36 -0500 |
commit | 5ea42e3463271f0cee2968557e8220a0b39a0bc2 (patch) | |
tree | 3ff0b009a0d81564f8017ed2e06c2757595696f9 /src/secure.rs | |
parent | move persist data to /var/run/crab (diff) | |
download | crab-5ea42e3463271f0cee2968557e8220a0b39a0bc2.tar.gz crab-5ea42e3463271f0cee2968557e8220a0b39a0bc2.tar.bz2 crab-5ea42e3463271f0cee2968557e8220a0b39a0bc2.zip |
move secure files to secure handler
Diffstat (limited to 'src/secure.rs')
-rw-r--r-- | src/secure.rs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/secure.rs b/src/secure.rs new file mode 100644 index 0000000..1fc3a11 --- /dev/null +++ b/src/secure.rs @@ -0,0 +1,51 @@ +use std::{os::{unix::prelude::PermissionsExt, linux::fs::MetadataExt}, fs, io::ErrorKind}; +use nix::unistd; + +pub fn write_file(dir: &str, file: &str, data: &str) -> Result<(), Box<dyn std::error::Error>> { + std::fs::create_dir_all(dir)?; + make_file_root(dir)?; + let path = path(dir, file); + std::fs::write(&path, "")?; + make_file_root(&path)?; + std::fs::write(&path, data)?; + Ok(()) +} + +pub fn read_file(dir: &str, file: &str) -> Option<String> { + let path = path(dir,file); + if !is_file_root(&path) { + return None; + } + match std::fs::read_to_string(&path) { + Ok(data) => return Some(data), + Err(_) => return None + }; +} + +fn make_file_root(path: &str) -> Result<(), Box<dyn std::error::Error>> { + unistd::chown(std::path::Path::new(path), Some(unistd::Uid::from(0)), Some(unistd::Gid::from(0)))?; + let metadata = std::fs::metadata(path)?; + let mut perms = metadata.permissions(); + perms.set_mode(0o100600); + fs::set_permissions(path, perms)?; + Ok(()) +} + +fn is_file_root(path: &str) -> bool { + return check_file_permissions(0, 0, 0o100600, path); +} + +fn check_file_permissions(uid: u32, gid: u32, mode: u32, path: &str) -> bool { + let metadata = match std::fs::metadata(path) { + Ok(data) => data, + Err(e) => { + return e.kind() == ErrorKind::NotFound + } + }; + let perms = metadata.permissions(); + return perms.mode() == mode && metadata.st_uid() == uid && metadata.st_gid() == gid; +} + +fn path(dir: &str, file: &str) -> String { + return format!("{}/{}", dir, file); +}
\ No newline at end of file |