Debian Codegraph @

tests/linux_kernel/tools/test_fsrefs.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 import array
5 import contextlib
6 import ctypes
7 import errno
8 import io
9 import mmap
10 import os
11 from pathlib import Path
12 import re
13 import socket
14 import subprocess
15 import sys
16 import tempfile
17 import unittest
18
19 from drgn import container_of
20 from drgn.helpers.linux.fs import fget
21 from drgn.helpers.linux.pid import find_task
22 from tests.linux_kernel import (
23 CLONE_NEWNS,
24 CLONE_NEWUSER,
25 MS_NODEV,
26 MS_NOEXEC,
27 MS_NOSUID,
28 LinuxKernelTestCase,
29 fallocate,
30 fork_and_stop,
31 iter_mounts,
32 losetup,
33 mkswap,
34 mount,
35 perf_event_attr,
36 perf_event_open,
37 skip_unless_have_test_disk,
38 swapoff,
39 swapon,
40 umount,
41 unshare,
42 )
43 from tools.fsrefs import main
44
45 UPROBE_TYPE_PATH = Path("/sys/bus/event_source/devices/uprobe/type")
46
47
48 class TestFsRefs(LinuxKernelTestCase):
49 def setUp(self):
50 super().setUp()
51 self._tmp = Path(self.enterContext(tempfile.TemporaryDirectory()))
52
53 def run_and_capture(self, *args):
54 f = io.StringIO()
55 with contextlib.redirect_stdout(f):
56 main(self.prog, args)
57 return f.getvalue()
58
59 def test_fd(self):
60 path = self._tmp / "file"
61 fd = os.open(path, os.O_CREAT | os.O_WRONLY, 0o600)
62 try:
63 self.assertRegex(
64 self.run_and_capture("--check", "tasks", "--inode", str(path)),
65 rf"pid {os.getpid()} \(.*\) fd {fd} ",
66 )
67 finally:
68 os.close(fd)
69
70 def test_dereference(self):
71 file = self._tmp / "file"
72 link = self._tmp / "link"
73 file.touch()
74 link.symlink_to("file")
75
76 file_fd = os.open(file, os.O_CREAT | os.O_WRONLY, 0o600)
77 try:
78 link_fd = os.open(link, os.O_PATH | os.O_NOFOLLOW)
79 try:
80 output = self.run_and_capture("--check", "tasks", "--inode", str(link))
81 self.assertNotRegex(
82 output,
83 rf"pid {os.getpid()} \(.*\) fd {file_fd} ",
84 )
85 self.assertRegex(
86 output,
87 rf"pid {os.getpid()} \(.*\) fd {link_fd} ",
88 )
89
90 output = self.run_and_capture(
91 "--check", "tasks", "--inode", str(link), "--dereference"
92 )
93 self.assertRegex(
94 output,
95 rf"pid {os.getpid()} \(.*\) fd {file_fd} ",
96 )
97 self.assertNotRegex(
98 output,
99 rf"pid {os.getpid()} \(.*\) fd {link_fd} ",
100 )
101 finally:
102 os.close(link_fd)
103 finally:
104 os.close(file_fd)
105
106 def test_cwd(self):
107 def mkdir_and_chdir(path, mode):
108 os.mkdir(path, mode)
109 os.chdir(path)
110
111 path = self._tmp / "dir"
112 with fork_and_stop(mkdir_and_chdir, path, 0o600) as (pid, _):
113 self.assertRegex(
114 self.run_and_capture("--check", "tasks", "--inode", str(path)),
115 rf"pid {pid} \(.*\) cwd ",
116 )
117
118 def test_root(self):
119 def mkdir_and_chroot(path, mode):
120 os.mkdir(path, mode)
121 os.chroot(path)
122
123 path = self._tmp / "dir"
124 with fork_and_stop(mkdir_and_chroot, path, 0o600) as (pid, _):
125 self.assertRegex(
126 self.run_and_capture("--check", "tasks", "--inode", str(path)),
127 rf"pid {pid} \(.*\) root ",
128 )
129
130 def test_exe(self):
131 self.assertRegex(
132 self.run_and_capture(
133 "--check", "tasks", "--inode", sys.executable, "--dereference"
134 ),
135 rf"pid {os.getpid()} \(.*\) exe ",
136 )
137
138 def test_vma(self):
139 path = self._tmp / "file"
140 with open(path, "w+b") as f:
141 os.ftruncate(f.fileno(), mmap.PAGESIZE)
142 # Note: this dups the file descriptor internally.
143 with mmap.mmap(f.fileno(), mmap.PAGESIZE) as map:
144 f.close()
145 start = ctypes.addressof(ctypes.c_char.from_buffer(map))
146 end = start + mmap.PAGESIZE
147 self.assertRegex(
148 self.run_and_capture("--check", "tasks", "--inode", str(path)),
149 rf"pid {os.getpid()} \(.*\) vma {hex(start)}-{hex(end)} ",
150 )
151
152 def test_inode_pointer(self):
153 self.assertRegex(
154 self.run_and_capture(
155 "--check",
156 "tasks",
157 "--inode-pointer",
158 hex(find_task(self.prog, os.getpid()).mm.exe_file.f_inode),
159 "--dereference",
160 ),
161 rf"pid {os.getpid()} \(.*\) exe ",
162 )
163
164 def test_super_block(self):
165 with contextlib.ExitStack() as exit_stack:
166 mount("tmpfs", self._tmp, "tmpfs")
167 exit_stack.callback(umount, self._tmp)
168
169 pid, _ = exit_stack.enter_context(fork_and_stop(unshare, CLONE_NEWNS))
170
171 path1 = self._tmp / "file1"
172 fd1 = os.open(path1, os.O_CREAT | os.O_WRONLY, 0o600)
173 exit_stack.callback(os.close, fd1)
174
175 path2 = self._tmp / "file2"
176 fd2 = os.open(path2, os.O_CREAT | os.O_WRONLY, 0o600)
177 exit_stack.callback(os.close, fd2)
178
179 output = self.run_and_capture(
180 "--check", "mounts", "--check", "tasks", "--super-block", str(self._tmp)
181 )
182
183 with self.subTest("mount"):
184 self.assertIn(f"mount {self._tmp} (struct mount", output)
185
186 with self.subTest("mount in namespace"):
187 ino = Path(f"/proc/{pid}/ns/mnt").stat().st_ino
188 self.assertIn(f"mount {self._tmp} (mount namespace {ino}) ", output)
189
190 with self.subTest("fd"):
191 self.assertRegex(
192 output,
193 rf"pid {os.getpid()} \(.*\) fd {fd1} \(struct file \*\)0x[0-9a-f]+ {re.escape(str(path1))}",
194 )
195 self.assertRegex(
196 output,
197 rf"pid {os.getpid()} \(.*\) fd {fd2} \(struct file \*\)0x[0-9a-f]+ {re.escape(str(path2))}",
198 )
199
200 with self.subTest("super_block_pointer"):
201 self.assertIn(
202 f"mount {self._tmp} ",
203 self.run_and_capture(
204 "--check",
205 "mounts",
206 "--super-block-pointer",
207 hex(fget(find_task(self.prog, os.getpid()), fd1).f_inode.i_sb),
208 ),
209 )
210
211 @skip_unless_have_test_disk
212 def test_super_block_on_block_device(self):
213 disk = os.environ["DRGN_TEST_DISK"]
214 for fstype, mkfs in (
215 ("ext2", ("mke2fs", "-qF")),
216 ("btrfs", ("mkfs.btrfs", "-qf", "-s", str(mmap.PAGESIZE))),
217 ):
218 with self.subTest(fstype=fstype):
219 subprocess.check_call([*mkfs, disk])
220
221 with contextlib.ExitStack() as exit_stack:
222 mount(disk, self._tmp, fstype)
223 exit_stack.callback(umount, self._tmp)
224
225 self.assertIn(
226 f"mount {self._tmp} ",
227 self.run_and_capture(
228 "--check",
229 "mounts",
230 "--dereference",
231 "--super-block-on-block-device",
232 str(disk),
233 ),
234 )
235
236 @skip_unless_have_test_disk
237 def test_btrfs_subvolume(self):
238 disk = os.environ["DRGN_TEST_DISK"]
239 with contextlib.ExitStack() as exit_stack:
240 subprocess.check_call(["mkfs.btrfs", "-qf", "-s", str(mmap.PAGESIZE), disk])
241
242 mount(disk, self._tmp, "btrfs")
243 exit_stack.callback(umount, self._tmp)
244
245 subvol = self._tmp / "subvol"
246 subprocess.check_call(["btrfs", "-q", "subvolume", "create", subvol])
247
248 top_file = self._tmp / "file"
249 top_fd = os.open(top_file, os.O_CREAT | os.O_WRONLY, 0o600)
250 exit_stack.callback(os.close, top_fd)
251 top_regex = rf"pid {os.getpid()} \(.*\) fd {top_fd} \(struct file \*\)0x[0-9a-f]+ {re.escape(str(top_file))}"
252
253 subvol_file = subvol / "file"
254 subvol_fd = os.open(subvol_file, os.O_CREAT | os.O_WRONLY, 0o600)
255 exit_stack.callback(os.close, subvol_fd)
256 subvol_regex = rf"pid {os.getpid()} \(.*\) fd {subvol_fd} \(struct file \*\)0x[0-9a-f]+ {re.escape(str(subvol_file))}"
257
258 subvol_output = self.run_and_capture(
259 "--check", "tasks", "--btrfs-subvolume", str(subvol)
260 )
261 self.assertRegex(subvol_output, subvol_regex)
262 self.assertNotRegex(subvol_output, top_regex)
263
264 top_root = container_of(
265 fget(find_task(self.prog, os.getpid()), top_fd).f_inode,
266 "struct btrfs_inode",
267 "vfs_inode",
268 ).root
269 top_output = self.run_and_capture(
270 "--check", "tasks", "--btrfs-subvolume-pointer", hex(top_root)
271 )
272 self.assertRegex(top_output, top_regex)
273 self.assertNotRegex(top_output, subvol_regex)
274
275 def test_not_btrfs(self):
276 with self.assertRaises(SystemExit) as cm:
277 main(self.prog, ["--check", "tasks", "--btrfs-subvolume", "/proc"])
278 self.assertIn("not on Btrfs", cm.exception.code)
279
280 def test_binfmt_misc(self):
281 for mnt in iter_mounts():
282 if mnt.fstype == "binfmt_misc":
283 break
284 else:
285 self.skipTest("binfmt_misc not mounted")
286
287 path = self._tmp / "file"
288 path.touch()
289 path.chmod(0o700)
290 try:
291 id = os.urandom(20)
292 name = f"drgntest_{id.hex()}"
293 encoded_id = "".join([f"\\x{byte:02x}" for byte in id])
294 (mnt.mount_point / "register").write_text(
295 f":{name}:M::{encoded_id}::{path}:F"
296 )
297
298 self.assertIn(
299 f"binfmt_misc {name} ",
300 self.run_and_capture("--check", "binfmt_misc", "--inode", str(path)),
301 )
302 finally:
303 try:
304 with open(mnt.mount_point / name, "r+") as f:
305 f.write("-1")
306 except FileNotFoundError:
307 pass
308
309 def test_binfmt_misc_in_user_ns(self):
310 id = os.urandom(20)
311 name = f"drgntest_{id.hex()}"
312
313 def setup_binfmt_misc_in_userns(path):
314 try:
315 unshare(CLONE_NEWUSER | CLONE_NEWNS)
316 except OSError as e:
317 if e.errno == errno.EINVAL:
318 return "kernel does not support user namespaces (CONFIG_USER_NS)"
319 else:
320 raise
321 Path("/proc/self/uid_map").write_text("0 0 1")
322 Path("/proc/self/setgroups").write_text("deny")
323 Path("/proc/self/gid_map").write_text("0 0 1")
324
325 mount_point = path.parent / "binfmt_misc"
326 mount_point.mkdir()
327 try:
328 mount(
329 "binfmt_misc",
330 mount_point,
331 "binfmt_misc",
332 MS_NOSUID | MS_NODEV | MS_NOEXEC,
333 )
334 except OSError as e:
335 if e.errno == errno.ENODEV:
336 return "kernel does not support binfmt_misc (CONFIG_BINFMT_MISC)"
337 elif e.errno == errno.EPERM:
338 return "kernel does not support sandboxed binfmt_misc mounts"
339 else:
340 raise
341
342 path.touch()
343 path.chmod(0o700)
344 encoded_id = "".join([f"\\x{byte:02x}" for byte in id])
345 (mount_point / "register").write_text(f":{name}:M::{encoded_id}::{path}:F")
346
347 path = self._tmp / "file"
348 with fork_and_stop(setup_binfmt_misc_in_userns, path) as (pid, skip):
349 if skip:
350 self.skipTest(skip)
351 ino = Path(f"/proc/{pid}/ns/user").stat().st_ino
352 self.assertIn(
353 f"binfmt_misc (user namespace {ino}) {name} ",
354 self.run_and_capture("--check", "binfmt_misc", "--inode", str(path)),
355 )
356
357 def test_loop_device(self):
358 path = self._tmp / "file"
359 with open(path, "wb") as f:
360 os.ftruncate(f.fileno(), 1024 * 1024)
361 with losetup(f.fileno()) as loop_file:
362 f.close()
363 number = int(loop_file.name.replace("/dev/loop", ""))
364 self.assertIn(
365 f"loop device {number} ",
366 self.run_and_capture("--check", "loop", "--inode", str(path)),
367 )
368
369 @skip_unless_have_test_disk
370 def test_swap_file(self):
371 disk = os.environ["DRGN_TEST_DISK"]
372 subprocess.check_call(["mke2fs", "-qF", disk])
373
374 with contextlib.ExitStack() as exit_stack:
375 mount(disk, self._tmp, "ext2")
376 exit_stack.callback(umount, self._tmp)
377
378 path = self._tmp / "swap_file"
379 fallocate(path, 0, 1024 * 1024)
380 mkswap(path)
381 swapon(path)
382 exit_stack.callback(swapoff, path)
383
384 self.assertIn(
385 "swap file (struct swap_info_struct *)",
386 self.run_and_capture("--check", "swap", "--inode", str(path)),
387 )
388
389 def test_uprobe_event(self):
390 for mnt in iter_mounts():
391 if mnt.fstype == "tracefs":
392 break
393 else:
394 self.skipTest("tracefs not mounted")
395 uprobe_events = mnt.mount_point / "uprobe_events"
396 if not uprobe_events.exists():
397 self.skipTest(
398 "kernel does not support uprobe events (CONFIG_UPROBE_EVENTS)"
399 )
400
401 def uprobe_events_append(s):
402 # open(..., "a") tries lseek(..., SEEK_END), which fails with
403 # EINVAL.
404 with open(os.open(uprobe_events, os.O_WRONLY | os.O_APPEND), "w") as f:
405 f.write(s)
406
407 path = self._tmp / "file"
408 path.touch()
409
410 probe_name = f"drgntest_{os.urandom(20).hex()}"
411 retprobe_name = f"drgntest_{os.urandom(20).hex()}"
412 with contextlib.ExitStack() as exit_stack:
413 uprobe_events_append(f"p:{probe_name} {path}:0\n")
414 exit_stack.callback(uprobe_events_append, f"-:{probe_name}\n")
415 uprobe_events_append(f"r:{retprobe_name} {path}:0\n")
416 exit_stack.callback(uprobe_events_append, f"-:{retprobe_name}\n")
417
418 instance = Path(tempfile.mkdtemp(dir=mnt.mount_point / "instances"))
419 exit_stack.callback(instance.rmdir)
420
421 (instance / "events/uprobes" / probe_name / "enable").write_text("1")
422 (instance / "events/uprobes" / retprobe_name / "enable").write_text("1")
423
424 output = self.run_and_capture("--check", "uprobes", "--inode", str(path))
425 self.assertIn(f"uprobe event p:uprobes/{probe_name} ", output)
426 self.assertIn(f"uprobe event r:uprobes/{retprobe_name} ", output)
427
428 @unittest.skipUnless(
429 UPROBE_TYPE_PATH.exists(), "kernel does not support perf_uprobe"
430 )
431 def test_perf_uprobe(self):
432 path = self._tmp / "file"
433 path.touch()
434
435 attr = perf_event_attr()
436 attr.type = int(UPROBE_TYPE_PATH.read_text())
437 ctypes_path = ctypes.c_char_p(os.fsencode(path))
438 attr.uprobe_path = ctypes.cast(ctypes_path, ctypes.c_void_p).value
439 fd = perf_event_open(attr, -1, min(os.sched_getaffinity(0)))
440 try:
441 self.assertIn(
442 f"perf uprobe (owned by pid {os.getpid()}",
443 self.run_and_capture("--check", "uprobes", "--inode", str(path)),
444 )
445 finally:
446 os.close(fd)
447
448 @unittest.skipUnless(
449 UPROBE_TYPE_PATH.exists(), "kernel does not support perf_uprobe"
450 )
451 def test_perf_uprobe_no_owner(self):
452 path = self._tmp / "file"
453 path.touch()
454
455 sock1, sock2 = socket.socketpair()
456 try:
457 # Create a perf event in a process, send it over a Unix socket to
458 # keep it alive, then die.
459 pid = os.fork()
460 if pid == 0:
461 try:
462 attr = perf_event_attr()
463 attr.type = int(UPROBE_TYPE_PATH.read_text())
464 ctypes_path = ctypes.c_char_p(os.fsencode(path))
465 attr.uprobe_path = ctypes.cast(ctypes_path, ctypes.c_void_p).value
466 fd = perf_event_open(attr, -1, min(os.sched_getaffinity(0)))
467 sock2.sendmsg(
468 [b"\0"],
469 [
470 (
471 socket.SOL_SOCKET,
472 socket.SCM_RIGHTS,
473 array.array("i", [fd]),
474 )
475 ],
476 )
477 finally:
478 os._exit(0)
479
480 os.waitpid(pid, 0)
481 self.assertIn(
482 "perf uprobe (no owner)",
483 self.run_and_capture("--check", "uprobes", "--inode", str(path)),
484 )
485 finally:
486 sock1.close()
487 sock2.close()