| 1 | use std::ffi::{CString, OsStr, OsString}; |
| 2 | use std::os::unix::ffi::OsStrExt; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | |
| 5 | use nix::unistd; |
| 6 | |
| 7 | use super::errors::*; |
| 8 | |
| 9 | #[test] |
| 10 | fn test_privdrop() { |
| 11 | if unistd::geteuid().is_root() { |
| 12 | PrivDrop::default() |
| 13 | .chroot("/var/empty") |
| 14 | .user("nobody") |
| 15 | .apply() |
| 16 | .unwrap_or_else(|e| panic!("Failed to drop privileges: {}", e)); |
| 17 | } else { |
| 18 | eprintln!("Test was skipped because it needs to be run as root."); |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /// `PrivDrop` structure |
| 23 | /// |
| 24 | /// # Example |
| 25 | /// ```ignore |
| 26 | /// privdrop::PrivDrop::default() |
| 27 | /// .chroot("/var/empty") |
| 28 | /// .user("nobody") |
| 29 | /// .apply() |
| 30 | /// .unwrap_or_else(|e| { panic!("Failed to drop privileges: {}", e) }); |
| 31 | /// ``` |
| 32 | #[derive(Default, Clone, Debug)] |
| 33 | pub struct PrivDrop { |
| 34 | chroot: Option<PathBuf>, |
| 35 | user: Option<OsString>, |
| 36 | group: Option<OsString>, |
| 37 | group_list: Option<Vec<OsString>>, |
| 38 | include_default_supplementary_groups: bool, |
| 39 | fallback_to_ids_if_names_are_numeric: bool, |
| 40 | } |
| 41 | |
| 42 | #[derive(Default, Clone, Debug)] |
| 43 | struct UserIds { |
| 44 | uid: Option<libc::uid_t>, |
| 45 | gid: Option<libc::gid_t>, |
| 46 | group_list: Option<Vec<libc::gid_t>>, |
| 47 | } |
| 48 | |
| 49 | impl PrivDrop { |
| 50 | /// chroot() to a specific directory before switching to a non-root user |
| 51 | pub fn chroot<T: AsRef<Path>>(mut self, path: T) -> Self { |
| 52 | self.chroot = Some(path.as_ref().to_owned()); |
| 53 | self |
| 54 | } |
| 55 | |
| 56 | /// Set the name of a user to switch to |
| 57 | pub fn user<S: AsRef<OsStr>>(mut self, user: S) -> Self { |
| 58 | self.user = Some(user.as_ref().to_owned()); |
| 59 | self |
| 60 | } |
| 61 | |
| 62 | /// Set a group name to switch to, if different from the primary group of the user |
| 63 | pub fn group<S: AsRef<OsStr>>(mut self, group: S) -> Self { |
| 64 | self.group = Some(group.as_ref().to_owned()); |
| 65 | self |
| 66 | } |
| 67 | |
| 68 | /// Include default supplementary groups |
| 69 | pub fn include_default_supplementary_groups(mut self) -> Self { |
| 70 | self.include_default_supplementary_groups = true; |
| 71 | self |
| 72 | } |
| 73 | |
| 74 | /// If a name is not found, try to parse it as a numeric identifier |
| 75 | pub fn fallback_to_ids_if_names_are_numeric(mut self) -> Self { |
| 76 | self.fallback_to_ids_if_names_are_numeric = true; |
| 77 | self |
| 78 | } |
| 79 | |
| 80 | /// Set the full list of groups to switch to |
| 81 | pub fn group_list<S: AsRef<OsStr>>(mut self, group_list: &[S]) -> Self { |
| 82 | self.group_list = Some(group_list.iter().map(|x| x.as_ref().to_owned()).collect()); |
| 83 | self |
| 84 | } |
| 85 | |
| 86 | /// Apply the changes |
| 87 | pub fn apply(self) -> Result<(), PrivDropError> { |
| 88 | Self::preload()?; |
| 89 | let ids = self.lookup_ids()?; |
| 90 | self.do_chroot()?.do_idchange(ids)?; |
| 91 | Ok(()) |
| 92 | } |
| 93 | |
| 94 | fn preload() -> Result<(), PrivDropError> { |
| 95 | let c_locale = CString::new("C").unwrap(); |
| 96 | unsafe { |
| 97 | libc::strerror(1); |
| 98 | libc::setlocale(libc::LC_CTYPE, c_locale.as_ptr()); |
| 99 | libc::setlocale(libc::LC_COLLATE, c_locale.as_ptr()); |
| 100 | let mut now: libc::time_t = 0; |
| 101 | libc::time(&mut now); |
| 102 | libc::localtime(&now); |
| 103 | } |
| 104 | Ok(()) |
| 105 | } |
| 106 | |
| 107 | fn uidcheck() -> Result<(), PrivDropError> { |
| 108 | if !unistd::geteuid().is_root() { |
| 109 | Err(PrivDropError::from(( |
| 110 | ErrorKind::SysError, |
| 111 | "Starting this application requires root privileges", |
| 112 | ))) |
| 113 | } else { |
| 114 | Ok(()) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn do_chroot(mut self) -> Result<Self, PrivDropError> { |
| 119 | if let Some(chroot) = self.chroot.take() { |
| 120 | Self::uidcheck()?; |
| 121 | unistd::chdir(&chroot)?; |
| 122 | unistd::chroot(&chroot)?; |
| 123 | unistd::chdir("/")? |
| 124 | } |
| 125 | Ok(self) |
| 126 | } |
| 127 | |
| 128 | fn lookup_user( |
| 129 | user: &OsStr, |
| 130 | fallback_to_ids_if_names_are_numeric: bool, |
| 131 | ) -> Result<UserIds, PrivDropError> { |
| 132 | let username = CString::new(user.as_bytes()) |
| 133 | .map_err(|_| PrivDropError::from((ErrorKind::SysError, "Invalid username")))?; |
| 134 | let mut pwd = unsafe { std::mem::zeroed::<libc::passwd>() }; |
| 135 | let mut pwbuf = vec![0; 4096]; |
| 136 | let mut pwent = std::ptr::null_mut::<libc::passwd>(); |
| 137 | let ret = unsafe { |
| 138 | libc::getpwnam_r( |
| 139 | username.as_ptr(), |
| 140 | &mut pwd, |
| 141 | pwbuf.as_mut_ptr(), |
| 142 | pwbuf.len(), |
| 143 | &mut pwent, |
| 144 | ) |
| 145 | }; |
| 146 | |
| 147 | if ret != 0 || pwent.is_null() { |
| 148 | if !fallback_to_ids_if_names_are_numeric { |
| 149 | return Err(PrivDropError::from((ErrorKind::SysError, "User not found"))); |
| 150 | } |
| 151 | let user_str = user.to_str().ok_or_else(|| { |
| 152 | PrivDropError::from(( |
| 153 | ErrorKind::SysError, |
| 154 | "User not found and username is not a valid number", |
| 155 | )) |
| 156 | })?; |
| 157 | let uid = user_str.parse().map_err(|_| { |
| 158 | PrivDropError::from(( |
| 159 | ErrorKind::SysError, |
| 160 | "User not found and username is not a valid number", |
| 161 | )) |
| 162 | })?; |
| 163 | return Ok(UserIds { |
| 164 | uid: Some(uid), |
| 165 | gid: None, |
| 166 | group_list: None, |
| 167 | }); |
| 168 | } |
| 169 | |
| 170 | let uid = unsafe { *pwent }.pw_uid; |
| 171 | let gid = unsafe { *pwent }.pw_gid; |
| 172 | |
| 173 | Ok(UserIds { |
| 174 | uid: Some(uid), |
| 175 | gid: Some(gid), |
| 176 | group_list: None, |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | fn default_group_list( |
| 181 | user: &OsStr, |
| 182 | gid: libc::gid_t, |
| 183 | ) -> Result<Option<Vec<libc::gid_t>>, PrivDropError> { |
| 184 | let username = CString::new(user.as_bytes()) |
| 185 | .map_err(|_| PrivDropError::from((ErrorKind::SysError, "Invalid username")))?; |
| 186 | let mut groups = vec![0; 256]; |
| 187 | let mut ngroups = groups.len() as _; |
| 188 | let ret = unsafe { |
| 189 | libc::getgrouplist( |
| 190 | username.as_ptr(), |
| 191 | gid as _, |
| 192 | groups.as_mut_ptr(), |
| 193 | &mut ngroups, |
| 194 | ) |
| 195 | }; |
| 196 | if ret == -1 { |
| 197 | return Ok(None); |
| 198 | } |
| 199 | groups.truncate(ngroups as _); |
| 200 | let mut groups_ = Vec::with_capacity(groups.len()); |
| 201 | for group in groups { |
| 202 | groups_.push(group as _); |
| 203 | } |
| 204 | Ok(Some(groups_)) |
| 205 | } |
| 206 | |
| 207 | fn lookup_group( |
| 208 | group: &OsStr, |
| 209 | fallback_to_ids_if_names_are_numeric: bool, |
| 210 | ) -> Result<libc::gid_t, PrivDropError> { |
| 211 | let groupname = CString::new(group.as_bytes()) |
| 212 | .map_err(|_| PrivDropError::from((ErrorKind::SysError, "Invalid group name")))?; |
| 213 | |
| 214 | let mut grp = unsafe { std::mem::zeroed::<libc::group>() }; |
| 215 | let mut grbuf = vec![0; 4096]; |
| 216 | let mut grent = std::ptr::null_mut::<libc::group>(); |
| 217 | let ret = unsafe { |
| 218 | libc::getgrnam_r( |
| 219 | groupname.as_ptr(), |
| 220 | &mut grp, |
| 221 | grbuf.as_mut_ptr(), |
| 222 | grbuf.len(), |
| 223 | &mut grent, |
| 224 | ) |
| 225 | }; |
| 226 | |
| 227 | if ret != 0 || grent.is_null() { |
| 228 | if !fallback_to_ids_if_names_are_numeric { |
| 229 | return Err(PrivDropError::from(( |
| 230 | ErrorKind::SysError, |
| 231 | "Group not found", |
| 232 | ))); |
| 233 | } |
| 234 | let group_str = group.to_str().ok_or_else(|| { |
| 235 | PrivDropError::from(( |
| 236 | ErrorKind::SysError, |
| 237 | "Group not found and group is not a valid number", |
| 238 | )) |
| 239 | })?; |
| 240 | let gid: libc::gid_t = group_str.parse().map_err(|_| { |
| 241 | PrivDropError::from(( |
| 242 | ErrorKind::SysError, |
| 243 | "Group not found and group is not a valid number", |
| 244 | )) |
| 245 | })?; |
| 246 | return Ok(gid); |
| 247 | } |
| 248 | |
| 249 | Ok(unsafe { *grent }.gr_gid) |
| 250 | } |
| 251 | |
| 252 | fn lookup_ids(&self) -> Result<UserIds, PrivDropError> { |
| 253 | let mut ids = UserIds::default(); |
| 254 | |
| 255 | if let Some(ref user) = self.user { |
| 256 | ids = PrivDrop::lookup_user(user, self.fallback_to_ids_if_names_are_numeric)?; |
| 257 | } |
| 258 | |
| 259 | if let Some(ref group) = self.group { |
| 260 | ids.gid = Some(PrivDrop::lookup_group( |
| 261 | group, |
| 262 | self.fallback_to_ids_if_names_are_numeric, |
| 263 | )?); |
| 264 | } |
| 265 | |
| 266 | if let Some(ref group_list) = self.group_list { |
| 267 | let mut groups = Vec::with_capacity(group_list.len()); |
| 268 | for group in group_list { |
| 269 | groups.push(PrivDrop::lookup_group( |
| 270 | group, |
| 271 | self.fallback_to_ids_if_names_are_numeric, |
| 272 | )?); |
| 273 | } |
| 274 | ids.group_list = Some(groups); |
| 275 | } |
| 276 | |
| 277 | Ok(ids) |
| 278 | } |
| 279 | |
| 280 | fn do_idchange(&self, ids: UserIds) -> Result<(), PrivDropError> { |
| 281 | Self::uidcheck()?; |
| 282 | |
| 283 | let mut groups = vec![]; |
| 284 | if self.include_default_supplementary_groups { |
| 285 | if let (Some(user), Some(gid)) = (&self.user, ids.gid) { |
| 286 | if let Some(group_list) = Self::default_group_list(user, gid)? { |
| 287 | groups.extend(group_list); |
| 288 | } |
| 289 | } else { |
| 290 | return Err(PrivDropError::from(( |
| 291 | ErrorKind::SysError, |
| 292 | "Unable to determine default supplementary groups without a user name and a base gid", |
| 293 | ))); |
| 294 | } |
| 295 | } |
| 296 | if let Some(ref group_list) = ids.group_list { |
| 297 | groups.extend(group_list.iter().cloned()); |
| 298 | } |
| 299 | if let Some(gid) = ids.gid { |
| 300 | groups.push(gid); |
| 301 | let mut unique_groups = vec![]; |
| 302 | for group in groups { |
| 303 | if !unique_groups.contains(&group) { |
| 304 | unique_groups.push(group); |
| 305 | } |
| 306 | } |
| 307 | if unsafe { libc::setgroups(unique_groups.len() as _, unique_groups.as_ptr()) } != 0 { |
| 308 | return Err(PrivDropError::from(( |
| 309 | ErrorKind::SysError, |
| 310 | "Unable to revoke supplementary groups", |
| 311 | ))); |
| 312 | } |
| 313 | unistd::setgid(unistd::Gid::from_raw(gid))?; |
| 314 | } |
| 315 | if let Some(uid) = ids.uid { |
| 316 | unistd::setuid(unistd::Uid::from_raw(uid))? |
| 317 | } |
| 318 | Ok(()) |
| 319 | } |
| 320 | } |