Debian Codegraph @

src/system/audit.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #![cfg_attr(not(feature = "unstable-remote-sudoers"), allow(unused_imports))]
2 use std::collections::HashSet;
3 use std::ffi::{CStr, CString, c_int, c_uint};
4 use std::fs::{self, DirBuilder, File, Metadata, OpenOptions};
5 use std::io::{self, BufReader, Error, ErrorKind};
6 use std::net::Shutdown;
7 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
8 use std::os::unix::{
9 ffi::OsStrExt,
10 fs::{DirBuilderExt, MetadataExt, PermissionsExt},
11 net::UnixStream,
12 prelude::OpenOptionsExt,
13 };
14 use std::path::{Component, Path};
15
16 use super::{
17 Group, GroupId, User, UserId, cerr, inject_group, interface::UnixUser, set_supplementary_groups,
18 };
19 use crate::common::resolve::CurrentUser;
20
21 #[cfg(target_os = "linux")]
22 pub(crate) fn no_new_privs_enabled() -> io::Result<bool> {
23 // SAFETY: prctl(PR_GET_NO_NEW_PRIVS) can never cause UB
24 let no_new_privs =
25 crate::cutils::cerr(unsafe { libc::prctl(libc::PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) })?;
26 Ok(no_new_privs != 0)
27 }
28
29 /// Temporary change privileges --- essentially a 'mini sudo'
30 /// This is only used for sudoedit.
31 pub(crate) fn sudo_call<T>(
32 target_user: &User,
33 target_group: &Group,
34 operation: impl FnOnce() -> T,
35 ) -> io::Result<T> {
36 const KEEP_UID: libc::uid_t = -1i32 as libc::uid_t;
37 const KEEP_GID: libc::gid_t = -1i32 as libc::gid_t;
38
39 // SAFETY: these libc functions are always safe to call
40 let (cur_user_id, cur_group_id) =
41 unsafe { (UserId::new(libc::geteuid()), GroupId::new(libc::getegid())) };
42
43 let cur_groups = {
44 // SAFETY: calling with size 0 does not modify through the pointer, and is
45 // a documented way of getting the length needed.
46 let len = cerr(unsafe { libc::getgroups(0, std::ptr::null_mut()) })?;
47
48 let mut buf: Vec<GroupId> = vec![GroupId::new(KEEP_GID); len as usize];
49 // SAFETY: we pass a correct pointer to a slice of the given length
50 cerr(unsafe {
51 // We can cast to gid_t because `GroupId` is marked as transparent
52 libc::getgroups(len, buf.as_mut_ptr().cast::<libc::gid_t>())
53 })?;
54
55 buf
56 };
57
58 let mut target_groups = target_user.groups.clone();
59 inject_group(target_group.gid, &mut target_groups);
60
61 if cfg!(test)
62 && target_user.uid == cur_user_id
63 && target_group.gid == cur_group_id
64 && target_groups.iter().collect::<HashSet<_>>() == cur_groups.iter().collect::<HashSet<_>>()
65 {
66 // we are not actually switching users, simply run the closure
67 // (this would also be safe in production mode, but it is a needless check)
68 return Ok(operation());
69 }
70
71 struct ResetUserGuard(UserId, GroupId, Vec<GroupId>);
72
73 impl Drop for ResetUserGuard {
74 fn drop(&mut self) {
75 // restore privileges in reverse order
76 (|| {
77 // SAFETY: this function is always safe to call
78 cerr(unsafe { libc::setresuid(KEEP_UID, UserId::inner(&self.0), KEEP_UID) })?;
79 // SAFETY: this function is always safe to call
80 cerr(unsafe { libc::setresgid(KEEP_GID, GroupId::inner(&self.1), KEEP_GID) })?;
81 set_supplementary_groups(&self.2)
82 })()
83 .expect("could not restore to saved user id");
84 }
85 }
86
87 let guard = ResetUserGuard(cur_user_id, cur_group_id, cur_groups);
88
89 set_supplementary_groups(&target_groups)?;
90 // SAFETY: this function is always safe to call
91 cerr(unsafe { libc::setresgid(KEEP_GID, GroupId::inner(&target_group.gid), KEEP_GID) })?;
92 // SAFETY: this function is always safe to call
93 cerr(unsafe { libc::setresuid(KEEP_UID, UserId::inner(&target_user.uid), KEEP_UID) })?;
94
95 let result = operation();
96
97 std::mem::drop(guard);
98 Ok(result)
99 }
100
101 /// Drop root privileges by setting effective user id equal to the real user id.
102 /// This routine will panic if the process is not privileged.
103 pub fn irrevocably_drop_privileges() {
104 // SAFETY:
105 // - getuid() and geteuid() are always safe to call
106 // - setuid() does not change any memory and only affects OS state.
107 unsafe {
108 let real_uid = libc::getuid();
109 let effective_uid = libc::geteuid();
110 // we never use setuid/setgid/setgroups except in the pre_exec hook before exec'ing,
111 // or in sudo_call (which always resets the user state after the closure finishes).
112 // this extra check is here to punish programming mistakes due to sloppiness.
113 assert_eq!(effective_uid, UserId::ROOT.inner(), "setuid violation");
114
115 cerr(libc::setuid(real_uid)).expect("setuid violation");
116 }
117 }
118
119 // of course we can also write "file & 0o040 != 0", but this makes the intent explicit
120 enum Op {
121 Read = 4,
122 Write = 2,
123 Exec = 1,
124 }
125 enum Category {
126 Owner = 2,
127 Group = 1,
128 World = 0,
129 }
130
131 fn mode(who: Category, what: Op) -> u32 {
132 (what as u32) << (3 * who as u32)
133 }
134
135 /// Open sudo configuration using various security checks
136 pub fn secure_open_sudoers(path: impl AsRef<Path>) -> io::Result<File> {
137 let mut open_options = OpenOptions::new();
138 open_options.read(true);
139
140 secure_open_impl(path.as_ref(), &mut open_options, false)
141 }
142
143 #[cfg(feature = "unstable-remote-sudoers")]
144 pub fn secure_open_remote_sudoers(path: impl AsRef<Path>) -> io::Result<BufReader<UnixStream>> {
145 secure_open_socket_impl(path.as_ref())
146 }
147
148 /// Open a timestamp cookie file using various security checks
149 pub fn secure_open_cookie_file(path: impl AsRef<Path>) -> io::Result<File> {
150 let mut open_options = OpenOptions::new();
151 open_options
152 .read(true)
153 .write(true)
154 .create(true)
155 .truncate(false)
156 .mode(mode(Category::Owner, Op::Write) | mode(Category::Owner, Op::Read));
157
158 secure_open_impl(path.as_ref(), &mut open_options, true)
159 }
160
161 /// Return the system zoneinfo path after validating that it is safe
162 pub fn zoneinfo_path() -> Option<&'static str> {
163 let paths = [
164 "/usr/share/zoneinfo",
165 "/usr/share/lib/zoneinfo",
166 "/usr/lib/zoneinfo",
167 ];
168
169 paths.into_iter().find(|p| {
170 let path = Path::new(p);
171 path.metadata().and_then(|meta| checks(path, meta)).is_ok()
172 })
173 }
174
175 fn checks(path: &Path, meta: Metadata) -> io::Result<()> {
176 let error = |msg| Error::new(ErrorKind::PermissionDenied, msg);
177
178 let path_mode = meta.permissions().mode();
179 if meta.uid() != 0 {
180 Err(error(xlat!(
181 "{path} must be owned by root",
182 path = path.display()
183 )))
184 } else if meta.gid() != 0 && (path_mode & mode(Category::Group, Op::Write) != 0) {
185 Err(error(xlat!(
186 "{path} cannot be group-writable",
187 path = path.display()
188 )))
189 } else if path_mode & mode(Category::World, Op::Write) != 0 {
190 Err(error(xlat!(
191 "{path} cannot be world-writable",
192 path = path.display()
193 )))
194 } else {
195 Ok(())
196 }
197 }
198
199 // Open `path` with options `open_options`, provided that it is "secure".
200 // "Secure" means that it passes the `checks` function above.
201 // If `check_parent_dir` is set, also check that the parent directory is "secure" also.
202 // If `create_parent_dirs` is set, create the path to the file if it does not already exist.
203 fn secure_open_impl(
204 path: &Path,
205 open_options: &mut OpenOptions,
206 create_parent_dirs: bool,
207 ) -> io::Result<File> {
208 let error = |msg| Error::new(ErrorKind::PermissionDenied, msg);
209 if let Some(parent_dir) = path.parent() {
210 // if we should create parent dirs and it does not yet exist, create it
211 if create_parent_dirs && !parent_dir.exists() {
212 DirBuilder::new()
213 .recursive(true)
214 .mode(
215 mode(Category::Owner, Op::Write)
216 | mode(Category::Owner, Op::Read)
217 | mode(Category::Owner, Op::Exec)
218 | mode(Category::Group, Op::Exec)
219 | mode(Category::World, Op::Exec),
220 )
221 .create(parent_dir)?;
222 }
223
224 let parent_meta = std::fs::metadata(parent_dir)?;
225 checks(parent_dir, parent_meta)?;
226 } else {
227 return Err(error(xlat!(
228 "{path} has no valid parent directory",
229 path = path.display()
230 )));
231 }
232
233 let file = open_options.open(path)?;
234 let meta = file.metadata()?;
235 checks(path, meta)?;
236
237 Ok(file)
238 }
239
240 // Open the socket at path, provided that it is "secure".
241 // "Secure" means that it passes the `checks` function above.
242 #[cfg(feature = "unstable-remote-sudoers")]
243 fn secure_open_socket_impl(path: &Path) -> io::Result<BufReader<UnixStream>> {
244 let meta = fs::metadata(path)?;
245 checks(path, meta)?;
246 if let Some(parent_dir) = path.parent() {
247 let parent_meta = std::fs::metadata(parent_dir)?;
248 checks(parent_dir, parent_meta)?;
249 } else {
250 let error = |msg| Error::new(ErrorKind::PermissionDenied, msg);
251
252 return Err(error(xlat!(
253 "{path} has no valid parent directory",
254 path = path.display()
255 )));
256 }
257
258 let stream = UnixStream::connect(path)?;
259 stream.shutdown(Shutdown::Write)?;
260 let reader = BufReader::new(stream);
261
262 Ok(reader)
263 }
264
265 fn open_at(parent: BorrowedFd, file_name: &CStr, create: bool) -> io::Result<OwnedFd> {
266 let flags = if create {
267 libc::O_NOFOLLOW | libc::O_RDWR | libc::O_CREAT
268 } else {
269 libc::O_NOFOLLOW | libc::O_RDONLY
270 };
271
272 // the mode for files that are created is hardcoded, as it is in ogsudo
273 let mode = libc::S_IRUSR | libc::S_IWUSR | libc::S_IRGRP | libc::S_IROTH;
274
275 // SAFETY: by design, a correct CStr pointer is passed to openat; only if this call succeeds
276 // is the file descriptor it returns (which is then necessarily valid) passed to from_raw_fd
277 unsafe {
278 let fd = cerr(libc::openat(
279 parent.as_raw_fd(),
280 file_name.as_ptr(),
281 flags,
282 c_uint::from(mode),
283 ))?;
284
285 Ok(OwnedFd::from_raw_fd(fd))
286 }
287 }
288
289 fn faccess_at(parent: BorrowedFd, path: &CStr, mode: c_int, flags: c_int) -> io::Result<()> {
290 // SAFETY: by design, a correct CStr pointer is passed to faccessat
291 cerr(unsafe { libc::faccessat(parent.as_raw_fd(), path.as_ptr(), mode, flags) }).map(|_| ())
292 }
293
294 /// This opens a file for sudoedit, performing security checks (see below) and
295 /// opening with reduced privileges.
296 pub fn secure_open_for_sudoedit(
297 path: impl AsRef<Path>,
298 current_user: &CurrentUser,
299 target_user: &User,
300 target_group: &Group,
301 ) -> io::Result<File> {
302 if current_user.is_root() {
303 sudo_call(target_user, target_group, || {
304 OpenOptions::new()
305 .read(true)
306 .write(true)
307 .create(true)
308 .truncate(false)
309 .open(path)
310 })?
311 } else {
312 traversed_secure_open(path, current_user, target_user, target_group)
313 }
314 }
315
316 /// This opens a file making sure that
317 /// - no directory leading up to the file is editable by the user
318 /// - no components are a symbolic link
319 fn traversed_secure_open(
320 path: impl AsRef<Path>,
321 #[cfg(not(test))] forbidden_user: &CurrentUser,
322 #[cfg(test)] forbidden_user: &User,
323 target_user: &User,
324 target_group: &Group,
325 ) -> io::Result<File> {
326 let path = path.as_ref();
327
328 let Some(file_name) = path.file_name() else {
329 return Err(io::Error::new(
330 ErrorKind::InvalidInput,
331 xlat!("invalid path"),
332 ));
333 };
334
335 let mut components = path.parent().unwrap_or(Path::new("")).components();
336 if components.next() != Some(Component::RootDir) {
337 return Err(io::Error::new(
338 ErrorKind::InvalidInput,
339 xlat!("path must be absolute"),
340 ));
341 }
342
343 let user_cannot_write = |file: &File| -> io::Result<()> {
344 let meta = file.metadata()?;
345 let perms = meta.permissions().mode();
346
347 if meta.uid() == forbidden_user.uid.inner() {
348 // Owner can change file permissions
349 return Err(io::Error::new(
350 ErrorKind::PermissionDenied,
351 xlat!("cannot open a file in a path writable by the user"),
352 ));
353 }
354
355 let user_has_write_perms = if cfg!(test) {
356 // During testing we do a less comprehensive check as we don't have
357 // permission to set the real user id to arbitrary users, but faccessat
358 // looks at the real user id.
359 perms & mode(Category::World, Op::Write) != 0
360 || (perms & mode(Category::Group, Op::Write) != 0)
361 && forbidden_user.in_group_by_gid(GroupId::new(meta.gid()))
362 || (perms & mode(Category::Owner, Op::Write) != 0)
363 && forbidden_user.uid.inner() == meta.uid()
364 } else {
365 // Only works when forbidden_user is current user. This is enforced
366 // by accepting CurrentUser outside of test mode.
367 // We don't pass AT_EACCESS to faccessat to make it check using the
368 // real user id rather than the effective user id.
369 faccess_at(file.as_fd(), c"", libc::W_OK, libc::AT_EMPTY_PATH).is_ok()
370 };
371
372 if user_has_write_perms {
373 Err(io::Error::new(
374 ErrorKind::PermissionDenied,
375 xlat!("cannot open a file in a path writable by the user"),
376 ))
377 } else {
378 Ok(())
379 }
380 };
381
382 let mut cur = File::open("/")?;
383 user_cannot_write(&cur)?;
384
385 for component in components {
386 let dir: CString = match component {
387 Component::Normal(dir) => CString::new(dir.as_bytes())?,
388 Component::CurDir => c".".to_owned(),
389 Component::ParentDir => c"..".to_owned(),
390 _ => {
391 return Err(io::Error::new(
392 ErrorKind::InvalidInput,
393 xlat!("error in provided path"),
394 ));
395 }
396 };
397
398 sudo_call(target_user, target_group, || {
399 cur = open_at(cur.as_fd(), &dir, false)?.into();
400 io::Result::Ok(())
401 })??;
402 user_cannot_write(&cur)?;
403 }
404 sudo_call(target_user, target_group, || {
405 cur = open_at(cur.as_fd(), &CString::new(file_name.as_bytes())?, true)?.into();
406 io::Result::Ok(())
407 })??;
408 user_cannot_write(&cur)?;
409
410 Ok(cur)
411 }
412
413 #[cfg(test)]
414 mod test {
415 use super::*;
416
417 #[test]
418 fn secure_open_is_predictable() {
419 // /etc/hosts should be readable and "secure" (if this test fails, you have been compromised)
420 assert!(std::fs::File::open("/etc/hosts").is_ok());
421 assert!(secure_open_sudoers("/etc/hosts").is_ok());
422
423 // /tmp should be readable, but not secure (writable by group other than root)
424 assert!(std::fs::File::open("/tmp").is_ok());
425 assert!(secure_open_sudoers("/tmp").is_err());
426
427 #[cfg(target_os = "linux")]
428 {
429 // /var/log/wtmp should be readable, but not secure (writable by group other than root)
430 // It doesn't exist on many non-Linux systems however.
431 if std::fs::File::open("/var/log/wtmp").is_ok() {
432 assert!(secure_open_sudoers("/var/log/wtmp").is_err());
433 }
434 }
435
436 // /etc/shadow should not be readable
437 assert!(std::fs::File::open("/etc/shadow").is_err());
438 assert!(secure_open_sudoers("/etc/shadow").is_err());
439 }
440
441 #[test]
442 fn test_secure_open_cookie_file() {
443 assert!(secure_open_cookie_file("/etc/hosts").is_err());
444 }
445
446 #[test]
447 fn test_traverse_secure_open_negative() {
448 use crate::common::resolve::CurrentUser;
449
450 let root = User::from_name(c"root").unwrap().unwrap();
451 let user = CurrentUser::resolve().unwrap();
452
453 // not allowed -- invalid
454 assert!(traversed_secure_open("/", &root, &user, &user.group()).is_err());
455 // not allowed since the path is not absolute
456 assert!(traversed_secure_open("./hello.txt", &root, &user, &user.group()).is_err());
457 // not allowed since root can write to "/"
458 assert!(traversed_secure_open("/hello.txt", &root, &user, &user.group()).is_err());
459 // not allowed since "/tmp" is a directory
460 assert!(traversed_secure_open("/tmp", &user, &user, &user.group()).is_err());
461 // not allowed since anybody can write to "/tmp"
462 assert!(traversed_secure_open("/tmp/foo/hello.txt", &user, &user, &user.group()).is_err());
463 // not allowed since "/bin" is a symlink
464 assert!(traversed_secure_open("/bin/hello.txt", &user, &user, &user.group()).is_err());
465 }
466
467 #[test]
468 fn test_traverse_secure_open_positive() {
469 use crate::common::resolve::CurrentUser;
470 use crate::system::{GroupId, UserId};
471
472 let user = CurrentUser::resolve().unwrap();
473 let other_user = CurrentUser::fake(User {
474 uid: UserId::new(1042),
475 gid: GroupId::new(1042),
476
477 name: "test".into(),
478 home: "/home/test".into(),
479 shell: "/bin/sh".into(),
480 groups: vec![],
481 });
482
483 // allowed!
484 let path = std::env::current_dir()
485 .unwrap()
486 .join("sudo-rs-test-file.txt");
487 let file = traversed_secure_open(&path, &other_user, &user, &user.group()).unwrap();
488 if file.metadata().is_ok_and(|meta| meta.len() == 0) {
489 std::fs::remove_file(path).unwrap();
490 }
491 }
492 }