Debian Codegraph @

third_party/rust/rustix/src/procfs.rs

raw
1 //! Utilities for working with `/proc`, where Linux's `procfs` is typically
2 //! mounted.
3 //!
4 //! `/proc` serves as an adjunct to Linux's main syscall surface area,
5 //! providing additional features with an awkward interface.
6 //!
7 //! This module does a considerable amount of work to determine whether `/proc`
8 //! is mounted, with actual `procfs`, and without any additional mount points
9 //! on top of the paths we open.
10 //!
11 //! Why all the effort to detect bind mount points? People are doing all kinds
12 //! of things with Linux containers these days, with many different privilege
13 //! schemes, and we want to avoid making any unnecessary assumptions. Rustix
14 //! and its users will sometimes use procfs *implicitly* (when Linux gives them
15 //! no better options), in ways that aren't obvious from their public APIs.
16 //! These filesystem accesses might not be visible to someone auditing the main
17 //! code of an application for places which may be influenced by the filesystem
18 //! namespace. So with the checking here, they may fail, but they won't be able
19 //! to succeed with bogus results.
20
21 use crate::fd::{AsFd, BorrowedFd, OwnedFd};
22 use crate::ffi::CStr;
23 use crate::fs::{
24 fstat, fstatfs, major, openat, renameat, seek, FileType, FsWord, Mode, OFlags, RawDir,
25 SeekFrom, Stat, CWD, PROC_SUPER_MAGIC,
26 };
27 use crate::io;
28 use crate::path::DecInt;
29 #[cfg(feature = "rustc-dep-of-std")]
30 use core::lazy::OnceCell;
31 use core::mem::MaybeUninit;
32 #[cfg(not(feature = "rustc-dep-of-std"))]
33 use once_cell::sync::OnceCell;
34
35 /// Linux's procfs always uses inode 1 for its root directory.
36 const PROC_ROOT_INO: u64 = 1;
37
38 // Identify an entry within "/proc", to determine which anomalies to check for.
39 #[derive(Copy, Clone, Debug)]
40 enum Kind {
41 Proc,
42 Pid,
43 Fd,
44 File,
45 Symlink,
46 }
47
48 /// Check a subdirectory of "/proc" for anomalies.
49 fn check_proc_entry(
50 kind: Kind,
51 entry: BorrowedFd<'_>,
52 proc_stat: Option<&Stat>,
53 ) -> io::Result<Stat> {
54 let entry_stat = fstat(entry)?;
55 check_proc_entry_with_stat(kind, entry, entry_stat, proc_stat)
56 }
57
58 /// Check a subdirectory of "/proc" for anomalies, using the provided `Stat`.
59 fn check_proc_entry_with_stat(
60 kind: Kind,
61 entry: BorrowedFd<'_>,
62 entry_stat: Stat,
63 proc_stat: Option<&Stat>,
64 ) -> io::Result<Stat> {
65 // Check the filesystem magic.
66 check_procfs(entry)?;
67
68 match kind {
69 Kind::Proc => check_proc_root(entry, &entry_stat)?,
70 Kind::Pid | Kind::Fd => check_proc_subdir(entry, &entry_stat, proc_stat)?,
71 Kind::File => check_proc_file(&entry_stat, proc_stat)?,
72 Kind::Symlink => check_proc_symlink(&entry_stat, proc_stat)?,
73 }
74
75 // "/proc" directories are typically mounted r-xr-xr-x.
76 // "/proc/self/fd" is r-x------. Allow them to have fewer permissions, but
77 // not more.
78 match kind {
79 Kind::Symlink => {
80 // On Linux, symlinks don't have their own permissions.
81 }
82 _ => {
83 let expected_mode = if let Kind::Fd = kind { 0o500 } else { 0o555 };
84 if entry_stat.st_mode & 0o777 & !expected_mode != 0 {
85 return Err(io::Errno::NOTSUP);
86 }
87 }
88 }
89
90 match kind {
91 Kind::Fd => {
92 // Check that the "/proc/self/fd" directory doesn't have any
93 // extraneous links into it (which might include unexpected
94 // subdirectories).
95 if entry_stat.st_nlink != 2 {
96 return Err(io::Errno::NOTSUP);
97 }
98 }
99 Kind::Pid | Kind::Proc => {
100 // Check that the "/proc" and "/proc/self" directories aren't
101 // empty.
102 if entry_stat.st_nlink <= 2 {
103 return Err(io::Errno::NOTSUP);
104 }
105 }
106 Kind::File => {
107 // Check that files in procfs don't have extraneous hard links to
108 // them (which might indicate hard links to other things).
109 if entry_stat.st_nlink != 1 {
110 return Err(io::Errno::NOTSUP);
111 }
112 }
113 Kind::Symlink => {
114 // Check that symlinks in procfs don't have extraneous hard links
115 // to them (which might indicate hard links to other things).
116 if entry_stat.st_nlink != 1 {
117 return Err(io::Errno::NOTSUP);
118 }
119 }
120 }
121
122 Ok(entry_stat)
123 }
124
125 fn check_proc_root(entry: BorrowedFd<'_>, stat: &Stat) -> io::Result<()> {
126 // We use `O_DIRECTORY` for proc directories, so open should fail if we
127 // don't get a directory when we expect one.
128 assert_eq!(FileType::from_raw_mode(stat.st_mode), FileType::Directory);
129
130 // Check the root inode number.
131 if stat.st_ino != PROC_ROOT_INO {
132 return Err(io::Errno::NOTSUP);
133 }
134
135 // Proc is a non-device filesystem, so check for major number 0.
136 // <https://www.kernel.org/doc/Documentation/admin-guide/devices.txt>
137 if major(stat.st_dev) != 0 {
138 return Err(io::Errno::NOTSUP);
139 }
140
141 // Check that "/proc" is a mountpoint.
142 if !is_mountpoint(entry) {
143 return Err(io::Errno::NOTSUP);
144 }
145
146 Ok(())
147 }
148
149 fn check_proc_subdir(
150 entry: BorrowedFd<'_>,
151 stat: &Stat,
152 proc_stat: Option<&Stat>,
153 ) -> io::Result<()> {
154 // We use `O_DIRECTORY` for proc directories, so open should fail if we
155 // don't get a directory when we expect one.
156 assert_eq!(FileType::from_raw_mode(stat.st_mode), FileType::Directory);
157
158 check_proc_nonroot(stat, proc_stat)?;
159
160 // Check that subdirectories of "/proc" are not mount points.
161 if is_mountpoint(entry) {
162 return Err(io::Errno::NOTSUP);
163 }
164
165 Ok(())
166 }
167
168 fn check_proc_file(stat: &Stat, proc_stat: Option<&Stat>) -> io::Result<()> {
169 // Check that we have a regular file.
170 if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
171 return Err(io::Errno::NOTSUP);
172 }
173
174 check_proc_nonroot(stat, proc_stat)?;
175
176 Ok(())
177 }
178
179 fn check_proc_symlink(stat: &Stat, proc_stat: Option<&Stat>) -> io::Result<()> {
180 // Check that we have a symbolic link.
181 if FileType::from_raw_mode(stat.st_mode) != FileType::Symlink {
182 return Err(io::Errno::NOTSUP);
183 }
184
185 check_proc_nonroot(stat, proc_stat)?;
186
187 Ok(())
188 }
189
190 fn check_proc_nonroot(stat: &Stat, proc_stat: Option<&Stat>) -> io::Result<()> {
191 // Check that we haven't been linked back to the root of "/proc".
192 if stat.st_ino == PROC_ROOT_INO {
193 return Err(io::Errno::NOTSUP);
194 }
195
196 // Check that we're still in procfs.
197 if stat.st_dev != proc_stat.unwrap().st_dev {
198 return Err(io::Errno::NOTSUP);
199 }
200
201 Ok(())
202 }
203
204 /// Check that `file` is opened on a `procfs` filesystem.
205 fn check_procfs(file: BorrowedFd<'_>) -> io::Result<()> {
206 let statfs = fstatfs(file)?;
207 let f_type = statfs.f_type;
208 if f_type != FsWord::from(PROC_SUPER_MAGIC) {
209 return Err(io::Errno::NOTSUP);
210 }
211
212 Ok(())
213 }
214
215 /// Check whether the given directory handle is a mount point.
216 fn is_mountpoint(file: BorrowedFd<'_>) -> bool {
217 // We use a `renameat` call that would otherwise fail, but which fails with
218 // `XDEV` first if it would cross a mount point.
219 let err = renameat(file, cstr!("../."), file, cstr!(".")).unwrap_err();
220 match err {
221 io::Errno::XDEV => true, // the rename failed due to crossing a mount point
222 io::Errno::BUSY => false, // the rename failed normally
223 _ => panic!("Unexpected error from `renameat`: {:?}", err),
224 }
225 }
226
227 /// Open a directory in `/proc`, mapping all errors to `io::Errno::NOTSUP`.
228 fn proc_opendirat<P: crate::path::Arg, Fd: AsFd>(dirfd: Fd, path: P) -> io::Result<OwnedFd> {
229 // We don't add `PATH` here because that disables `DIRECTORY`. And we don't
230 // add `NOATIME` for the same reason as the comment in `open_and_check_file`.
231 let oflags =
232 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOCTTY;
233 openat(dirfd, path, oflags, Mode::empty()).map_err(|_err| io::Errno::NOTSUP)
234 }
235
236 /// Returns a handle to Linux's `/proc` directory.
237 ///
238 /// This ensures that `/proc` is procfs, that nothing is mounted on top of it,
239 /// and that it looks normal. It also returns the `Stat` of `/proc`.
240 ///
241 /// # References
242 /// - [Linux]
243 ///
244 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
245 fn proc() -> io::Result<(BorrowedFd<'static>, &'static Stat)> {
246 static PROC: StaticFd = StaticFd::new();
247
248 // `OnceBox` is “racy” in that the initialization function may run
249 // multiple times. We're ok with that, since the initialization function
250 // has no side effects.
251 PROC.get_or_try_init(|| {
252 // Open "/proc".
253 let proc = proc_opendirat(CWD, cstr!("/proc"))?;
254 let proc_stat =
255 check_proc_entry(Kind::Proc, proc.as_fd(), None).map_err(|_err| io::Errno::NOTSUP)?;
256
257 Ok(new_static_fd(proc, proc_stat))
258 })
259 .map(|(fd, stat)| (fd.as_fd(), stat))
260 }
261
262 /// Returns a handle to Linux's `/proc/self` directory.
263 ///
264 /// This ensures that `/proc/self` is procfs, that nothing is mounted on top of
265 /// it, and that it looks normal. It also returns the `Stat` of `/proc/self`.
266 ///
267 /// # References
268 /// - [Linux]
269 ///
270 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
271 #[allow(unsafe_code)]
272 fn proc_self() -> io::Result<(BorrowedFd<'static>, &'static Stat)> {
273 static PROC_SELF: StaticFd = StaticFd::new();
274
275 // The init function here may run multiple times; see above.
276 PROC_SELF
277 .get_or_try_init(|| {
278 let (proc, proc_stat) = proc()?;
279
280 // `getpid` would return our pid in our own pid namespace, so
281 // instead use `readlink` on the `self` symlink to learn our pid in
282 // the procfs namespace.
283 let self_symlink = open_and_check_file(proc, proc_stat, cstr!("self"), Kind::Symlink)?;
284 let mut buf = [MaybeUninit::<u8>::uninit(); 20];
285 let len = crate::backend::fs::syscalls::readlinkat(
286 self_symlink.as_fd(),
287 cstr!(""),
288 &mut buf,
289 )?;
290 let pid: &[u8] = unsafe { core::mem::transmute(&buf[..len]) };
291
292 // Open "/proc/self". Use our pid to compute the name rather than
293 // literally using "self", as "self" is a symlink.
294 let proc_self = proc_opendirat(proc, pid)?;
295 let proc_self_stat = check_proc_entry(Kind::Pid, proc_self.as_fd(), Some(proc_stat))
296 .map_err(|_err| io::Errno::NOTSUP)?;
297
298 Ok(new_static_fd(proc_self, proc_self_stat))
299 })
300 .map(|(owned, stat)| (owned.as_fd(), stat))
301 }
302
303 /// Returns a handle to Linux's `/proc/self/fd` directory.
304 ///
305 /// This ensures that `/proc/self/fd` is `procfs`, that nothing is mounted on
306 /// top of it, and that it looks normal.
307 ///
308 /// # References
309 /// - [Linux]
310 ///
311 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
312 #[cfg_attr(docsrs, doc(cfg(feature = "procfs")))]
313 pub fn proc_self_fd() -> io::Result<BorrowedFd<'static>> {
314 static PROC_SELF_FD: StaticFd = StaticFd::new();
315
316 // The init function here may run multiple times; see above.
317 PROC_SELF_FD
318 .get_or_try_init(|| {
319 let (_, proc_stat) = proc()?;
320
321 let (proc_self, _proc_self_stat) = proc_self()?;
322
323 // Open "/proc/self/fd".
324 let proc_self_fd = proc_opendirat(proc_self, cstr!("fd"))?;
325 let proc_self_fd_stat =
326 check_proc_entry(Kind::Fd, proc_self_fd.as_fd(), Some(proc_stat))
327 .map_err(|_err| io::Errno::NOTSUP)?;
328
329 Ok(new_static_fd(proc_self_fd, proc_self_fd_stat))
330 })
331 .map(|(owned, _stat)| owned.as_fd())
332 }
333
334 type StaticFd = OnceCell<(OwnedFd, Stat)>;
335
336 #[inline]
337 fn new_static_fd(fd: OwnedFd, stat: Stat) -> (OwnedFd, Stat) {
338 (fd, stat)
339 }
340
341 /// Returns a handle to Linux's `/proc/self/fdinfo` directory.
342 ///
343 /// This ensures that `/proc/self/fdinfo` is `procfs`, that nothing is mounted
344 /// on top of it, and that it looks normal. It also returns the `Stat` of
345 /// `/proc/self/fd`.
346 ///
347 /// # References
348 /// - [Linux]
349 ///
350 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
351 fn proc_self_fdinfo() -> io::Result<(BorrowedFd<'static>, &'static Stat)> {
352 static PROC_SELF_FDINFO: StaticFd = StaticFd::new();
353
354 PROC_SELF_FDINFO
355 .get_or_try_init(|| {
356 let (_, proc_stat) = proc()?;
357
358 let (proc_self, _proc_self_stat) = proc_self()?;
359
360 // Open "/proc/self/fdinfo".
361 let proc_self_fdinfo = proc_opendirat(proc_self, cstr!("fdinfo"))?;
362 let proc_self_fdinfo_stat =
363 check_proc_entry(Kind::Fd, proc_self_fdinfo.as_fd(), Some(proc_stat))
364 .map_err(|_err| io::Errno::NOTSUP)?;
365
366 Ok((proc_self_fdinfo, proc_self_fdinfo_stat))
367 })
368 .map(|(owned, stat)| (owned.as_fd(), stat))
369 }
370
371 /// Returns a handle to a Linux `/proc/self/fdinfo/<fd>` file.
372 ///
373 /// This ensures that `/proc/self/fdinfo/<fd>` is `procfs`, that nothing is
374 /// mounted on top of it, and that it looks normal.
375 ///
376 /// # References
377 /// - [Linux]
378 ///
379 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
380 #[inline]
381 #[cfg_attr(docsrs, doc(cfg(feature = "procfs")))]
382 pub fn proc_self_fdinfo_fd<Fd: AsFd>(fd: Fd) -> io::Result<OwnedFd> {
383 _proc_self_fdinfo(fd.as_fd())
384 }
385
386 fn _proc_self_fdinfo(fd: BorrowedFd<'_>) -> io::Result<OwnedFd> {
387 let (proc_self_fdinfo, proc_self_fdinfo_stat) = proc_self_fdinfo()?;
388 let fd_str = DecInt::from_fd(fd);
389 open_and_check_file(
390 proc_self_fdinfo,
391 proc_self_fdinfo_stat,
392 fd_str.as_c_str(),
393 Kind::File,
394 )
395 }
396
397 /// Returns a handle to a Linux `/proc/self/pagemap` file.
398 ///
399 /// This ensures that `/proc/self/pagemap` is `procfs`, that nothing is
400 /// mounted on top of it, and that it looks normal.
401 ///
402 /// # References
403 /// - [Linux]
404 /// - [Linux pagemap]
405 ///
406 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
407 /// [Linux pagemap]: https://www.kernel.org/doc/Documentation/vm/pagemap.txt
408 #[inline]
409 #[cfg_attr(docsrs, doc(cfg(feature = "procfs")))]
410 pub fn proc_self_pagemap() -> io::Result<OwnedFd> {
411 proc_self_file(cstr!("pagemap"))
412 }
413
414 /// Returns a handle to a Linux `/proc/self/maps` file.
415 ///
416 /// This ensures that `/proc/self/maps` is `procfs`, that nothing is
417 /// mounted on top of it, and that it looks normal.
418 ///
419 /// # References
420 /// - [Linux]
421 ///
422 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
423 #[inline]
424 #[cfg_attr(docsrs, doc(cfg(feature = "procfs")))]
425 pub fn proc_self_maps() -> io::Result<OwnedFd> {
426 proc_self_file(cstr!("maps"))
427 }
428
429 /// Returns a handle to a Linux `/proc/self/status` file.
430 ///
431 /// This ensures that `/proc/self/status` is `procfs`, that nothing is
432 /// mounted on top of it, and that it looks normal.
433 ///
434 /// # References
435 /// - [Linux]
436 ///
437 /// [Linux]: https://man7.org/linux/man-pages/man5/proc.5.html
438 #[inline]
439 #[cfg_attr(docsrs, doc(cfg(feature = "procfs")))]
440 pub fn proc_self_status() -> io::Result<OwnedFd> {
441 proc_self_file(cstr!("status"))
442 }
443
444 /// Open a file under `/proc/self`.
445 fn proc_self_file(name: &CStr) -> io::Result<OwnedFd> {
446 let (proc_self, proc_self_stat) = proc_self()?;
447 open_and_check_file(proc_self, proc_self_stat, name, Kind::File)
448 }
449
450 /// Open a procfs file within in `dir` and check it for bind mounts.
451 fn open_and_check_file(
452 dir: BorrowedFd<'_>,
453 dir_stat: &Stat,
454 name: &CStr,
455 kind: Kind,
456 ) -> io::Result<OwnedFd> {
457 let (_, proc_stat) = proc()?;
458
459 // Don't use `NOATIME`, because it [requires us to own the file], and when
460 // a process sets itself non-dumpable Linux changes the user:group of its
461 // `/proc/<pid>` files [to root:root].
462 //
463 // [requires us to own the file]: https://man7.org/linux/man-pages/man2/openat.2.html
464 // [to root:root]: https://man7.org/linux/man-pages/man5/proc.5.html
465 let mut oflags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NOCTTY;
466 if let Kind::Symlink = kind {
467 // Open symlinks with `O_PATH`.
468 oflags |= OFlags::PATH;
469 }
470 let file = openat(dir, name, oflags, Mode::empty()).map_err(|_err| io::Errno::NOTSUP)?;
471 let file_stat = fstat(&file)?;
472
473 // `is_mountpoint` only works on directory mount points, not file mount
474 // points. To detect file mount points, scan the parent directory to see if
475 // we can find a regular file with an inode and name that matches the file
476 // we just opened. If we can't find it, there could be a file bind mount on
477 // top of the file we want.
478 //
479 // TODO: With Linux 5.8 we might be able to use `statx` and
480 // `STATX_ATTR_MOUNT_ROOT` to detect mountpoints directly instead of doing
481 // this scanning.
482
483 let expected_type = match kind {
484 Kind::File => FileType::RegularFile,
485 Kind::Symlink => FileType::Symlink,
486 _ => unreachable!(),
487 };
488
489 let mut found_file = false;
490 let mut found_dot = false;
491
492 // Open a new fd, so that if we're called on multiple threads, they don't
493 // share a seek position.
494 let oflags =
495 OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NOCTTY | OFlags::DIRECTORY;
496 let dir = openat(dir, cstr!("."), oflags, Mode::empty()).map_err(|_err| io::Errno::NOTSUP)?;
497 let check_dir_stat = fstat(&dir)?;
498 if check_dir_stat.st_dev != dir_stat.st_dev || check_dir_stat.st_ino != dir_stat.st_ino {
499 return Err(io::Errno::NOTSUP);
500 }
501
502 // Position the directory iteration at the start.
503 seek(&dir, SeekFrom::Start(0))?;
504
505 let mut buf = [MaybeUninit::uninit(); 2048];
506 let mut iter = RawDir::new(dir, &mut buf);
507 while let Some(entry) = iter.next() {
508 let entry = entry.map_err(|_err| io::Errno::NOTSUP)?;
509 if entry.ino() == file_stat.st_ino
510 && entry.file_type() == expected_type
511 && entry.file_name() == name
512 {
513 // We found the file. Proceed to check the file handle.
514 let _ = check_proc_entry_with_stat(kind, file.as_fd(), file_stat, Some(proc_stat))?;
515
516 found_file = true;
517 } else if entry.ino() == dir_stat.st_ino
518 && entry.file_type() == FileType::Directory
519 && entry.file_name() == cstr!(".")
520 {
521 // We found ".", and it's the right ".".
522 found_dot = true;
523 }
524 }
525
526 if found_file && found_dot {
527 Ok(file)
528 } else {
529 Err(io::Errno::NOTSUP)
530 }
531 }