Drop privileges from root to the `clawshell` system user. This resolves the `clawshell` user, then calls `setgid` followed by `setuid` so the process runs with minimal privileges. Only acts when running as root; returns `Ok(())` immediately otherwise.
()
| 46 | /// so the process runs with minimal privileges. Only acts when running as root; |
| 47 | /// returns `Ok(())` immediately otherwise. |
| 48 | pub fn drop_privileges() -> Result<(), Box<dyn std::error::Error>> { |
| 49 | if !getuid().is_root() { |
| 50 | return Ok(()); |
| 51 | } |
| 52 | |
| 53 | let user = User::from_name("clawshell")? |
| 54 | .ok_or("system user 'clawshell' not found — run `sudo clawshell onboard` first")?; |
| 55 | |
| 56 | setgid(Gid::from_raw(user.gid.as_raw())).map_err(|e| format!("setgid({}): {}", user.gid, e))?; |
| 57 | setuid(Uid::from_raw(user.uid.as_raw())).map_err(|e| format!("setuid({}): {}", user.uid, e))?; |
| 58 | |
| 59 | info!( |
| 60 | uid = user.uid.as_raw(), |
| 61 | gid = user.gid.as_raw(), |
| 62 | "Dropped privileges to 'clawshell'" |
| 63 | ); |
| 64 | Ok(()) |
| 65 | } |
| 66 | |
| 67 | #[cfg(test)] |
| 68 | mod tests { |
no outgoing calls