From f726a6920d85f149efeae9ca1624138e9e374938 Mon Sep 17 00:00:00 2001 From: rorka900 Date: Mon, 27 Apr 2026 17:54:12 +0000 Subject: refactor: replace shell commands with native Rust crates and harden security --- src/rootfs.rs | 199 ++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 132 insertions(+), 67 deletions(-) (limited to 'src/rootfs.rs') diff --git a/src/rootfs.rs b/src/rootfs.rs index b408741..027cce1 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,14 +1,12 @@ use crate::apply::SystemConfig; -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::HashMap; use std::fs; -use std::path::Path; -use std::process::Command; +use std::path::{Path}; use std::os::unix::fs::symlink; use std::sync::{Arc, Mutex}; use std::thread; use colored::Colorize; use serde::Serialize; -use serde_json; use crate::config; use crate::progress::ProgressBar; use chrono::Local; @@ -17,7 +15,14 @@ use crate::install::{ extract_native, extract_ror, install_files_with_root, select_binary_for_arch, InstalledDB, InstalledPackage, }; - +use nix::mount::{mount, umount2, MntFlags, MsFlags}; +use nix::unistd::{chroot, chdir, fork, ForkResult, execve}; +use nix::sys::wait::{waitpid, WaitStatus}; +use std::io::Write; +use std::ffi::CString; +use std::ffi::CStr; +use std::collections::HashSet; +use std::collections::VecDeque; struct DownloadTask { pkg_name: String, urls: Vec, @@ -167,7 +172,6 @@ fn download_parallel( total, task.pkg_name ); - use std::io::Write; std::io::stderr().flush().ok(); break; } @@ -283,7 +287,7 @@ fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { ("lib", "usr/lib"), ("lib64", "usr/lib64"), ("sbin", "usr/sbin"), -] { + ] { symlink(target, target_dir.join(link)) .map_err(|e| format!("Failed to create symlink {} -> {}: {}", link, target, e))?; } @@ -329,27 +333,29 @@ fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { ("proc", "proc", "proc", false), ("sysfs", "sys", "sysfs", false), ]; - for (src, rel, fstype, bind) in mounts { let target = root_dir.join(rel); fs::create_dir_all(&target) .map_err(|e| format!("Failed to create mountpoint {}: {}", rel, e))?; - let status = if *bind { - Command::new("mount") - .args(["--bind", src, target.to_str().unwrap()]) - .status() + if *bind { + mount( + Some(Path::new(src)), + &target, + None::<&str>, + MsFlags::MS_BIND | MsFlags::MS_REC, + None::<&Path>, + ) } else { - Command::new("mount") - .args(["-t", fstype, src, target.to_str().unwrap()]) - .status() - }; - - match status { - Ok(s) if s.success() => {} - Ok(_) => eprintln!("{} Warning: failed to mount {} (non-fatal)", "[ror]".yellow(), rel), - Err(e) => eprintln!("{} Warning: mount {}: {} (non-fatal)", "[ror]".yellow(), rel, e), + mount( + Some(Path::new(src)), + &target, + Some(*fstype), + MsFlags::empty(), + None::<&Path>, + ) } + .map_err(|e| format!("Failed to mount {}: {}", rel, e))?; } Ok(()) } @@ -358,7 +364,7 @@ fn umount_virtual_fs(root_dir: &Path) { for rel in &["dev/pts", "dev/shm", "dev", "proc", "sys"] { let target = root_dir.join(rel); if target.exists() { - let _ = Command::new("umount").args(["-l", target.to_str().unwrap()]).status(); + let _ = umount2(&target, MntFlags::MNT_DETACH); } } } @@ -378,39 +384,56 @@ const SHELL_CANDIDATES: &[(&str, Option<&str>)] = &[ ]; fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { - for &(shell_path, subcmd) in SHELL_CANDIDATES { - if !root_dir.join(shell_path.trim_start_matches('/')).exists() { + for (shell_path, subcmd) in SHELL_CANDIDATES { + let full = root_dir.join(shell_path.trim_start_matches('/')); + if !full.exists() { continue; } - - let mut cmd = Command::new("chroot"); - cmd.arg(root_dir).arg(shell_path); - if let Some(sub) = subcmd { - cmd.arg(sub); + let test_script = "exit 0"; + let script_path = root_dir.join(".ror-shell-test.sh"); + if fs::write(&script_path, format!("#!/bin/sh\n{}", test_script)).is_err() { + continue; } - cmd.arg("-c").arg("exit 0"); - - match cmd.output() { - Ok(out) if out.status.success() => return Some((shell_path, subcmd)), - Ok(out) => { - let stderr = String::from_utf8_lossy(&out.stderr); - eprintln!( - "{} Shell {} failed in chroot ({}), trying next...", - "[ror]".yellow(), - shell_path, - stderr.lines().next().unwrap_or("unknown error").trim() - ); + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let shell_c = CString::new(*shell_path).unwrap(); + let arg0 = CString::new(*shell_path).unwrap(); + let args = if let Some(sub) = subcmd { + let sub_c = CString::new(*sub).unwrap(); + let script_c = CString::new(".ror-shell-test.sh").unwrap(); + vec![arg0, sub_c, script_c] + } else { + let script_c = CString::new(".ror-shell-test.sh").unwrap(); + vec![arg0, script_c] + }; + let args_refs: Vec<&CStr> = args.iter().map(|s| s.as_c_str()).collect(); + let _ = execve::<&CStr, &CStr>(&shell_c, &args_refs, &[]); + std::process::exit(1); } - Err(e) => { - eprintln!("{} Cannot test shell {}: {}, trying next...", "[ror]".yellow(), shell_path, e); + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, 0)) => { + let _ = fs::remove_file(&script_path); + return Some((*shell_path, *subcmd)); + } + Ok(_) => { + let _ = fs::remove_file(&script_path); + } + Err(_) => { + let _ = fs::remove_file(&script_path); + } + } } + Err(_) => { let _ = fs::remove_file(&script_path); } } } None } fn run_install_steps_in_chroot( - pkg_name: &str, + _pkg_name: &str, steps: &str, root_dir: &Path, shell: &str, @@ -418,29 +441,70 @@ fn run_install_steps_in_chroot( ) -> Result<(), String> { let script_rel = "/.ror-install-steps.sh"; let script_host = root_dir.join(script_rel.trim_start_matches('/')); - fs::write(&script_host, format!("#!/bin/sh\nset -e\n{}", steps)) - .map_err(|e| format!("Failed to write install script: {}", e))?; - - let mut cmd = Command::new("chroot"); - cmd.arg(root_dir).arg(shell); - if let Some(sub) = subcmd { - cmd.arg(sub); + .map_err(|e| format!("Failed to write script: {}", e))?; + + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let shell_c = CString::new(shell).unwrap(); + let arg0 = CString::new(shell).unwrap(); + let script_c = CString::new(script_rel).unwrap(); + let args = if let Some(sub) = subcmd { + let sub_c = CString::new(sub).unwrap(); + vec![arg0, sub_c, script_c] + } else { + vec![arg0, script_c] + }; + let _ = execve::<&CStr, &CStr>(&shell_c, &args.iter().map(|s| s.as_ref()).collect::>(), &[]); + std::process::exit(1); + } + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, code)) => { + let _ = fs::remove_file(&script_host); + if code == 0 { + Ok(()) + } else { + Err(format!("install_steps failed with exit code {}", code)) + } + } + Ok(_) => { + let _ = fs::remove_file(&script_host); + Err("install_steps terminated by signal".to_string()) + } + Err(e) => { + let _ = fs::remove_file(&script_host); + Err(format!("waitpid failed: {}", e)) + } + } + } + Err(e) => { + let _ = fs::remove_file(&script_host); + Err(format!("Fork failed: {}", e)) + } } - cmd.arg(script_rel); - - let status = cmd.status() - .map_err(|e| format!("Failed to execute chroot for {}: {}", pkg_name, e))?; - - let _ = fs::remove_file(&script_host); +} - if status.success() { - Ok(()) - } else { - Err(format!( - "install_steps for '{}' failed with exit code {:?}", - pkg_name, status.code() - )) +fn run_ldconfig_in_root(root_dir: &Path) -> Result<(), String> { + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let ldconfig = CString::new("/sbin/ldconfig").unwrap(); + let arg0 = CString::new("ldconfig").unwrap(); + let _ = execve::<&CString, &CStr>(&ldconfig, &[&arg0], &[]); + std::process::exit(1); + } + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, 0)) => Ok(()), + Ok(_) => Err("ldconfig terminated abnormally".to_string()), + Err(e) => Err(format!("waitpid ldconfig failed: {}", e)), + } + } + Err(e) => Err(format!("Fork for ldconfig failed: {}", e)), } } @@ -649,9 +713,10 @@ pub fn build_rootfs( if !ld_conf.exists() { let _ = fs::write(&ld_conf, "/usr/lib\n/usr/lib64\n"); } - match Command::new("ldconfig").arg("-r").arg(target_dir).status() { - Ok(s) if s.success() => println!("{} ldconfig done.", ">>>".green()), - _ => eprintln!("{} ldconfig failed (non-fatal)", "[ror]".yellow()), + if let Err(e) = run_ldconfig_in_root(target_dir) { + eprintln!("{} ldconfig failed: {} (non-fatal)", "[ror]".yellow(), e); + } else { + println!("{} ldconfig done.", ">>>".green()); } } -- cgit v1.2.3