xref: /linux/fs/pidfs.c (revision 055f213075fbfa8e950bed8f2c50d01ac71bbf37)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/anon_inodes.h>
3 #include <linux/exportfs.h>
4 #include <linux/file.h>
5 #include <linux/fs.h>
6 #include <linux/cgroup.h>
7 #include <linux/magic.h>
8 #include <linux/mount.h>
9 #include <linux/pid.h>
10 #include <linux/pidfs.h>
11 #include <linux/pid_namespace.h>
12 #include <linux/poll.h>
13 #include <linux/proc_fs.h>
14 #include <linux/proc_ns.h>
15 #include <linux/pseudo_fs.h>
16 #include <linux/ptrace.h>
17 #include <linux/seq_file.h>
18 #include <uapi/linux/pidfd.h>
19 #include <linux/ipc_namespace.h>
20 #include <linux/time_namespace.h>
21 #include <linux/utsname.h>
22 #include <net/net_namespace.h>
23 #include <linux/coredump.h>
24 #include <linux/xattr.h>
25 
26 #include "internal.h"
27 #include "mount.h"
28 
29 #define PIDFS_PID_DEAD ERR_PTR(-ESRCH)
30 
31 static struct kmem_cache *pidfs_attr_cachep __ro_after_init;
32 static struct kmem_cache *pidfs_xattr_cachep __ro_after_init;
33 
34 static struct path pidfs_root_path = {};
35 
pidfs_get_root(struct path * path)36 void pidfs_get_root(struct path *path)
37 {
38 	*path = pidfs_root_path;
39 	path_get(path);
40 }
41 
42 /*
43  * Stashes information that userspace needs to access even after the
44  * process has been reaped.
45  */
46 struct pidfs_exit_info {
47 	__u64 cgroupid;
48 	__s32 exit_code;
49 	__u32 coredump_mask;
50 };
51 
52 struct pidfs_attr {
53 	struct simple_xattrs *xattrs;
54 	struct pidfs_exit_info __pei;
55 	struct pidfs_exit_info *exit_info;
56 };
57 
58 static struct rb_root pidfs_ino_tree = RB_ROOT;
59 
60 #if BITS_PER_LONG == 32
pidfs_ino(u64 ino)61 static inline unsigned long pidfs_ino(u64 ino)
62 {
63 	return lower_32_bits(ino);
64 }
65 
66 /* On 32 bit the generation number are the upper 32 bits. */
pidfs_gen(u64 ino)67 static inline u32 pidfs_gen(u64 ino)
68 {
69 	return upper_32_bits(ino);
70 }
71 
72 #else
73 
74 /* On 64 bit simply return ino. */
pidfs_ino(u64 ino)75 static inline unsigned long pidfs_ino(u64 ino)
76 {
77 	return ino;
78 }
79 
80 /* On 64 bit the generation number is 0. */
pidfs_gen(u64 ino)81 static inline u32 pidfs_gen(u64 ino)
82 {
83 	return 0;
84 }
85 #endif
86 
pidfs_ino_cmp(struct rb_node * a,const struct rb_node * b)87 static int pidfs_ino_cmp(struct rb_node *a, const struct rb_node *b)
88 {
89 	struct pid *pid_a = rb_entry(a, struct pid, pidfs_node);
90 	struct pid *pid_b = rb_entry(b, struct pid, pidfs_node);
91 	u64 pid_ino_a = pid_a->ino;
92 	u64 pid_ino_b = pid_b->ino;
93 
94 	if (pid_ino_a < pid_ino_b)
95 		return -1;
96 	if (pid_ino_a > pid_ino_b)
97 		return 1;
98 	return 0;
99 }
100 
pidfs_add_pid(struct pid * pid)101 void pidfs_add_pid(struct pid *pid)
102 {
103 	static u64 pidfs_ino_nr = 2;
104 
105 	/*
106 	 * On 64 bit nothing special happens. The 64bit number assigned
107 	 * to struct pid is the inode number.
108 	 *
109 	 * On 32 bit the 64 bit number assigned to struct pid is split
110 	 * into two 32 bit numbers. The lower 32 bits are used as the
111 	 * inode number and the upper 32 bits are used as the inode
112 	 * generation number.
113 	 *
114 	 * On 32 bit pidfs_ino() will return the lower 32 bit. When
115 	 * pidfs_ino() returns zero a wrap around happened. When a
116 	 * wraparound happens the 64 bit number will be incremented by 2
117 	 * so inode numbering starts at 2 again.
118 	 *
119 	 * On 64 bit comparing two pidfds is as simple as comparing
120 	 * inode numbers.
121 	 *
122 	 * When a wraparound happens on 32 bit multiple pidfds with the
123 	 * same inode number are likely to exist (This isn't a problem
124 	 * since before pidfs pidfds used the anonymous inode meaning
125 	 * all pidfds had the same inode number.). Userspace can
126 	 * reconstruct the 64 bit identifier by retrieving both the
127 	 * inode number and the inode generation number to compare or
128 	 * use file handles.
129 	 */
130 	if (pidfs_ino(pidfs_ino_nr) == 0)
131 		pidfs_ino_nr += 2;
132 
133 	pid->ino = pidfs_ino_nr;
134 	pid->stashed = NULL;
135 	pid->attr = NULL;
136 	pidfs_ino_nr++;
137 
138 	write_seqcount_begin(&pidmap_lock_seq);
139 	rb_find_add_rcu(&pid->pidfs_node, &pidfs_ino_tree, pidfs_ino_cmp);
140 	write_seqcount_end(&pidmap_lock_seq);
141 }
142 
pidfs_remove_pid(struct pid * pid)143 void pidfs_remove_pid(struct pid *pid)
144 {
145 	write_seqcount_begin(&pidmap_lock_seq);
146 	rb_erase(&pid->pidfs_node, &pidfs_ino_tree);
147 	write_seqcount_end(&pidmap_lock_seq);
148 }
149 
pidfs_free_pid(struct pid * pid)150 void pidfs_free_pid(struct pid *pid)
151 {
152 	struct pidfs_attr *attr __free(kfree) = no_free_ptr(pid->attr);
153 	struct simple_xattrs *xattrs __free(kfree) = NULL;
154 
155 	/*
156 	 * Any dentry must've been wiped from the pid by now.
157 	 * Otherwise there's a reference count bug.
158 	 */
159 	VFS_WARN_ON_ONCE(pid->stashed);
160 
161 	/*
162 	 * This if an error occurred during e.g., task creation that
163 	 * causes us to never go through the exit path.
164 	 */
165 	if (unlikely(!attr))
166 		return;
167 
168 	/* This never had a pidfd created. */
169 	if (IS_ERR(attr))
170 		return;
171 
172 	xattrs = no_free_ptr(attr->xattrs);
173 	if (xattrs)
174 		simple_xattrs_free(xattrs, NULL);
175 }
176 
177 #ifdef CONFIG_PROC_FS
178 /**
179  * pidfd_show_fdinfo - print information about a pidfd
180  * @m: proc fdinfo file
181  * @f: file referencing a pidfd
182  *
183  * Pid:
184  * This function will print the pid that a given pidfd refers to in the
185  * pid namespace of the procfs instance.
186  * If the pid namespace of the process is not a descendant of the pid
187  * namespace of the procfs instance 0 will be shown as its pid. This is
188  * similar to calling getppid() on a process whose parent is outside of
189  * its pid namespace.
190  *
191  * NSpid:
192  * If pid namespaces are supported then this function will also print
193  * the pid of a given pidfd refers to for all descendant pid namespaces
194  * starting from the current pid namespace of the instance, i.e. the
195  * Pid field and the first entry in the NSpid field will be identical.
196  * If the pid namespace of the process is not a descendant of the pid
197  * namespace of the procfs instance 0 will be shown as its first NSpid
198  * entry and no others will be shown.
199  * Note that this differs from the Pid and NSpid fields in
200  * /proc/<pid>/status where Pid and NSpid are always shown relative to
201  * the  pid namespace of the procfs instance. The difference becomes
202  * obvious when sending around a pidfd between pid namespaces from a
203  * different branch of the tree, i.e. where no ancestral relation is
204  * present between the pid namespaces:
205  * - create two new pid namespaces ns1 and ns2 in the initial pid
206  *   namespace (also take care to create new mount namespaces in the
207  *   new pid namespace and mount procfs)
208  * - create a process with a pidfd in ns1
209  * - send pidfd from ns1 to ns2
210  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
211  *   have exactly one entry, which is 0
212  */
pidfd_show_fdinfo(struct seq_file * m,struct file * f)213 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
214 {
215 	struct pid *pid = pidfd_pid(f);
216 	struct pid_namespace *ns;
217 	pid_t nr = -1;
218 
219 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
220 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
221 		nr = pid_nr_ns(pid, ns);
222 	}
223 
224 	seq_put_decimal_ll(m, "Pid:\t", nr);
225 
226 #ifdef CONFIG_PID_NS
227 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
228 	if (nr > 0) {
229 		int i;
230 
231 		/* If nr is non-zero it means that 'pid' is valid and that
232 		 * ns, i.e. the pid namespace associated with the procfs
233 		 * instance, is in the pid namespace hierarchy of pid.
234 		 * Start at one below the already printed level.
235 		 */
236 		for (i = ns->level + 1; i <= pid->level; i++)
237 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
238 	}
239 #endif
240 	seq_putc(m, '\n');
241 }
242 #endif
243 
244 /*
245  * Poll support for process exit notification.
246  */
pidfd_poll(struct file * file,struct poll_table_struct * pts)247 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
248 {
249 	struct pid *pid = pidfd_pid(file);
250 	struct task_struct *task;
251 	__poll_t poll_flags = 0;
252 
253 	poll_wait(file, &pid->wait_pidfd, pts);
254 	/*
255 	 * Don't wake waiters if the thread-group leader exited
256 	 * prematurely. They either get notified when the last subthread
257 	 * exits or not at all if one of the remaining subthreads execs
258 	 * and assumes the struct pid of the old thread-group leader.
259 	 */
260 	guard(rcu)();
261 	task = pid_task(pid, PIDTYPE_PID);
262 	if (!task)
263 		poll_flags = EPOLLIN | EPOLLRDNORM | EPOLLHUP;
264 	else if (task->exit_state && !delay_group_leader(task))
265 		poll_flags = EPOLLIN | EPOLLRDNORM;
266 
267 	return poll_flags;
268 }
269 
pid_in_current_pidns(const struct pid * pid)270 static inline bool pid_in_current_pidns(const struct pid *pid)
271 {
272 	const struct pid_namespace *ns = task_active_pid_ns(current);
273 
274 	if (ns->level <= pid->level)
275 		return pid->numbers[ns->level].ns == ns;
276 
277 	return false;
278 }
279 
pidfs_coredump_mask(unsigned long mm_flags)280 static __u32 pidfs_coredump_mask(unsigned long mm_flags)
281 {
282 	switch (__get_dumpable(mm_flags)) {
283 	case SUID_DUMP_USER:
284 		return PIDFD_COREDUMP_USER;
285 	case SUID_DUMP_ROOT:
286 		return PIDFD_COREDUMP_ROOT;
287 	case SUID_DUMP_DISABLE:
288 		return PIDFD_COREDUMP_SKIP;
289 	default:
290 		WARN_ON_ONCE(true);
291 	}
292 
293 	return 0;
294 }
295 
pidfd_info(struct file * file,unsigned int cmd,unsigned long arg)296 static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg)
297 {
298 	struct pidfd_info __user *uinfo = (struct pidfd_info __user *)arg;
299 	struct task_struct *task __free(put_task) = NULL;
300 	struct pid *pid = pidfd_pid(file);
301 	size_t usize = _IOC_SIZE(cmd);
302 	struct pidfd_info kinfo = {};
303 	struct pidfs_exit_info *exit_info;
304 	struct user_namespace *user_ns;
305 	struct pidfs_attr *attr;
306 	const struct cred *c;
307 	__u64 mask;
308 
309 	if (!uinfo)
310 		return -EINVAL;
311 	if (usize < PIDFD_INFO_SIZE_VER0)
312 		return -EINVAL; /* First version, no smaller struct possible */
313 
314 	if (copy_from_user(&mask, &uinfo->mask, sizeof(mask)))
315 		return -EFAULT;
316 
317 	/*
318 	 * Restrict information retrieval to tasks within the caller's pid
319 	 * namespace hierarchy.
320 	 */
321 	if (!pid_in_current_pidns(pid))
322 		return -ESRCH;
323 
324 	attr = READ_ONCE(pid->attr);
325 	if (mask & PIDFD_INFO_EXIT) {
326 		exit_info = READ_ONCE(attr->exit_info);
327 		if (exit_info) {
328 			kinfo.mask |= PIDFD_INFO_EXIT;
329 #ifdef CONFIG_CGROUPS
330 			kinfo.cgroupid = exit_info->cgroupid;
331 			kinfo.mask |= PIDFD_INFO_CGROUPID;
332 #endif
333 			kinfo.exit_code = exit_info->exit_code;
334 		}
335 	}
336 
337 	if (mask & PIDFD_INFO_COREDUMP) {
338 		kinfo.mask |= PIDFD_INFO_COREDUMP;
339 		kinfo.coredump_mask = READ_ONCE(attr->__pei.coredump_mask);
340 	}
341 
342 	task = get_pid_task(pid, PIDTYPE_PID);
343 	if (!task) {
344 		/*
345 		 * If the task has already been reaped, only exit
346 		 * information is available
347 		 */
348 		if (!(mask & PIDFD_INFO_EXIT))
349 			return -ESRCH;
350 
351 		goto copy_out;
352 	}
353 
354 	c = get_task_cred(task);
355 	if (!c)
356 		return -ESRCH;
357 
358 	if ((kinfo.mask & PIDFD_INFO_COREDUMP) && !(kinfo.coredump_mask)) {
359 		task_lock(task);
360 		if (task->mm)
361 			kinfo.coredump_mask = pidfs_coredump_mask(task->mm->flags);
362 		task_unlock(task);
363 	}
364 
365 	/* Unconditionally return identifiers and credentials, the rest only on request */
366 
367 	user_ns = current_user_ns();
368 	kinfo.ruid = from_kuid_munged(user_ns, c->uid);
369 	kinfo.rgid = from_kgid_munged(user_ns, c->gid);
370 	kinfo.euid = from_kuid_munged(user_ns, c->euid);
371 	kinfo.egid = from_kgid_munged(user_ns, c->egid);
372 	kinfo.suid = from_kuid_munged(user_ns, c->suid);
373 	kinfo.sgid = from_kgid_munged(user_ns, c->sgid);
374 	kinfo.fsuid = from_kuid_munged(user_ns, c->fsuid);
375 	kinfo.fsgid = from_kgid_munged(user_ns, c->fsgid);
376 	kinfo.mask |= PIDFD_INFO_CREDS;
377 	put_cred(c);
378 
379 #ifdef CONFIG_CGROUPS
380 	if (!kinfo.cgroupid) {
381 		struct cgroup *cgrp;
382 
383 		rcu_read_lock();
384 		cgrp = task_dfl_cgroup(task);
385 		kinfo.cgroupid = cgroup_id(cgrp);
386 		kinfo.mask |= PIDFD_INFO_CGROUPID;
387 		rcu_read_unlock();
388 	}
389 #endif
390 
391 	/*
392 	 * Copy pid/tgid last, to reduce the chances the information might be
393 	 * stale. Note that it is not possible to ensure it will be valid as the
394 	 * task might return as soon as the copy_to_user finishes, but that's ok
395 	 * and userspace expects that might happen and can act accordingly, so
396 	 * this is just best-effort. What we can do however is checking that all
397 	 * the fields are set correctly, or return ESRCH to avoid providing
398 	 * incomplete information. */
399 
400 	kinfo.ppid = task_ppid_nr_ns(task, NULL);
401 	kinfo.tgid = task_tgid_vnr(task);
402 	kinfo.pid = task_pid_vnr(task);
403 	kinfo.mask |= PIDFD_INFO_PID;
404 
405 	if (kinfo.pid == 0 || kinfo.tgid == 0)
406 		return -ESRCH;
407 
408 copy_out:
409 	/*
410 	 * If userspace and the kernel have the same struct size it can just
411 	 * be copied. If userspace provides an older struct, only the bits that
412 	 * userspace knows about will be copied. If userspace provides a new
413 	 * struct, only the bits that the kernel knows about will be copied.
414 	 */
415 	return copy_struct_to_user(uinfo, usize, &kinfo, sizeof(kinfo), NULL);
416 }
417 
pidfs_ioctl_valid(unsigned int cmd)418 static bool pidfs_ioctl_valid(unsigned int cmd)
419 {
420 	switch (cmd) {
421 	case FS_IOC_GETVERSION:
422 	case PIDFD_GET_CGROUP_NAMESPACE:
423 	case PIDFD_GET_IPC_NAMESPACE:
424 	case PIDFD_GET_MNT_NAMESPACE:
425 	case PIDFD_GET_NET_NAMESPACE:
426 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
427 	case PIDFD_GET_TIME_NAMESPACE:
428 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
429 	case PIDFD_GET_UTS_NAMESPACE:
430 	case PIDFD_GET_USER_NAMESPACE:
431 	case PIDFD_GET_PID_NAMESPACE:
432 		return true;
433 	}
434 
435 	/* Extensible ioctls require some more careful checks. */
436 	switch (_IOC_NR(cmd)) {
437 	case _IOC_NR(PIDFD_GET_INFO):
438 		/*
439 		 * Try to prevent performing a pidfd ioctl when someone
440 		 * erronously mistook the file descriptor for a pidfd.
441 		 * This is not perfect but will catch most cases.
442 		 */
443 		return (_IOC_TYPE(cmd) == _IOC_TYPE(PIDFD_GET_INFO));
444 	}
445 
446 	return false;
447 }
448 
pidfd_ioctl(struct file * file,unsigned int cmd,unsigned long arg)449 static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
450 {
451 	struct task_struct *task __free(put_task) = NULL;
452 	struct nsproxy *nsp __free(put_nsproxy) = NULL;
453 	struct ns_common *ns_common = NULL;
454 	struct pid_namespace *pid_ns;
455 
456 	if (!pidfs_ioctl_valid(cmd))
457 		return -ENOIOCTLCMD;
458 
459 	if (cmd == FS_IOC_GETVERSION) {
460 		if (!arg)
461 			return -EINVAL;
462 
463 		__u32 __user *argp = (__u32 __user *)arg;
464 		return put_user(file_inode(file)->i_generation, argp);
465 	}
466 
467 	/* Extensible IOCTL that does not open namespace FDs, take a shortcut */
468 	if (_IOC_NR(cmd) == _IOC_NR(PIDFD_GET_INFO))
469 		return pidfd_info(file, cmd, arg);
470 
471 	task = get_pid_task(pidfd_pid(file), PIDTYPE_PID);
472 	if (!task)
473 		return -ESRCH;
474 
475 	if (arg)
476 		return -EINVAL;
477 
478 	scoped_guard(task_lock, task) {
479 		nsp = task->nsproxy;
480 		if (nsp)
481 			get_nsproxy(nsp);
482 	}
483 	if (!nsp)
484 		return -ESRCH; /* just pretend it didn't exist */
485 
486 	/*
487 	 * We're trying to open a file descriptor to the namespace so perform a
488 	 * filesystem cred ptrace check. Also, we mirror nsfs behavior.
489 	 */
490 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
491 		return -EACCES;
492 
493 	switch (cmd) {
494 	/* Namespaces that hang of nsproxy. */
495 	case PIDFD_GET_CGROUP_NAMESPACE:
496 		if (IS_ENABLED(CONFIG_CGROUPS)) {
497 			get_cgroup_ns(nsp->cgroup_ns);
498 			ns_common = to_ns_common(nsp->cgroup_ns);
499 		}
500 		break;
501 	case PIDFD_GET_IPC_NAMESPACE:
502 		if (IS_ENABLED(CONFIG_IPC_NS)) {
503 			get_ipc_ns(nsp->ipc_ns);
504 			ns_common = to_ns_common(nsp->ipc_ns);
505 		}
506 		break;
507 	case PIDFD_GET_MNT_NAMESPACE:
508 		get_mnt_ns(nsp->mnt_ns);
509 		ns_common = to_ns_common(nsp->mnt_ns);
510 		break;
511 	case PIDFD_GET_NET_NAMESPACE:
512 		if (IS_ENABLED(CONFIG_NET_NS)) {
513 			ns_common = to_ns_common(nsp->net_ns);
514 			get_net_ns(ns_common);
515 		}
516 		break;
517 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
518 		if (IS_ENABLED(CONFIG_PID_NS)) {
519 			get_pid_ns(nsp->pid_ns_for_children);
520 			ns_common = to_ns_common(nsp->pid_ns_for_children);
521 		}
522 		break;
523 	case PIDFD_GET_TIME_NAMESPACE:
524 		if (IS_ENABLED(CONFIG_TIME_NS)) {
525 			get_time_ns(nsp->time_ns);
526 			ns_common = to_ns_common(nsp->time_ns);
527 		}
528 		break;
529 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
530 		if (IS_ENABLED(CONFIG_TIME_NS)) {
531 			get_time_ns(nsp->time_ns_for_children);
532 			ns_common = to_ns_common(nsp->time_ns_for_children);
533 		}
534 		break;
535 	case PIDFD_GET_UTS_NAMESPACE:
536 		if (IS_ENABLED(CONFIG_UTS_NS)) {
537 			get_uts_ns(nsp->uts_ns);
538 			ns_common = to_ns_common(nsp->uts_ns);
539 		}
540 		break;
541 	/* Namespaces that don't hang of nsproxy. */
542 	case PIDFD_GET_USER_NAMESPACE:
543 		if (IS_ENABLED(CONFIG_USER_NS)) {
544 			rcu_read_lock();
545 			ns_common = to_ns_common(get_user_ns(task_cred_xxx(task, user_ns)));
546 			rcu_read_unlock();
547 		}
548 		break;
549 	case PIDFD_GET_PID_NAMESPACE:
550 		if (IS_ENABLED(CONFIG_PID_NS)) {
551 			rcu_read_lock();
552 			pid_ns = task_active_pid_ns(task);
553 			if (pid_ns)
554 				ns_common = to_ns_common(get_pid_ns(pid_ns));
555 			rcu_read_unlock();
556 		}
557 		break;
558 	default:
559 		return -ENOIOCTLCMD;
560 	}
561 
562 	if (!ns_common)
563 		return -EOPNOTSUPP;
564 
565 	/* open_namespace() unconditionally consumes the reference */
566 	return open_namespace(ns_common);
567 }
568 
569 static const struct file_operations pidfs_file_operations = {
570 	.poll		= pidfd_poll,
571 #ifdef CONFIG_PROC_FS
572 	.show_fdinfo	= pidfd_show_fdinfo,
573 #endif
574 	.unlocked_ioctl	= pidfd_ioctl,
575 	.compat_ioctl   = compat_ptr_ioctl,
576 };
577 
pidfd_pid(const struct file * file)578 struct pid *pidfd_pid(const struct file *file)
579 {
580 	if (file->f_op != &pidfs_file_operations)
581 		return ERR_PTR(-EBADF);
582 	return file_inode(file)->i_private;
583 }
584 
585 /*
586  * We're called from release_task(). We know there's at least one
587  * reference to struct pid being held that won't be released until the
588  * task has been reaped which cannot happen until we're out of
589  * release_task().
590  *
591  * If this struct pid has at least once been referred to by a pidfd then
592  * pid->attr will be allocated. If not we mark the struct pid as dead so
593  * anyone who is trying to register it with pidfs will fail to do so.
594  * Otherwise we would hand out pidfs for reaped tasks without having
595  * exit information available.
596  *
597  * Worst case is that we've filled in the info and the pid gets freed
598  * right away in free_pid() when no one holds a pidfd anymore. Since
599  * pidfs_exit() currently is placed after exit_task_work() we know that
600  * it cannot be us aka the exiting task holding a pidfd to itself.
601  */
pidfs_exit(struct task_struct * tsk)602 void pidfs_exit(struct task_struct *tsk)
603 {
604 	struct pid *pid = task_pid(tsk);
605 	struct pidfs_attr *attr;
606 	struct pidfs_exit_info *exit_info;
607 #ifdef CONFIG_CGROUPS
608 	struct cgroup *cgrp;
609 #endif
610 
611 	might_sleep();
612 
613 	guard(spinlock_irq)(&pid->wait_pidfd.lock);
614 	attr = pid->attr;
615 	if (!attr) {
616 		/*
617 		 * No one ever held a pidfd for this struct pid.
618 		 * Mark it as dead so no one can add a pidfs
619 		 * entry anymore. We're about to be reaped and
620 		 * so no exit information would be available.
621 		 */
622 		pid->attr = PIDFS_PID_DEAD;
623 		return;
624 	}
625 
626 	/*
627 	 * If @pid->attr is set someone might still legitimately hold a
628 	 * pidfd to @pid or someone might concurrently still be getting
629 	 * a reference to an already stashed dentry from @pid->stashed.
630 	 * So defer cleaning @pid->attr until the last reference to @pid
631 	 * is put
632 	 */
633 
634 	exit_info = &attr->__pei;
635 
636 #ifdef CONFIG_CGROUPS
637 	rcu_read_lock();
638 	cgrp = task_dfl_cgroup(tsk);
639 	exit_info->cgroupid = cgroup_id(cgrp);
640 	rcu_read_unlock();
641 #endif
642 	exit_info->exit_code = tsk->exit_code;
643 
644 	/* Ensure that PIDFD_GET_INFO sees either all or nothing. */
645 	smp_store_release(&attr->exit_info, &attr->__pei);
646 }
647 
648 #ifdef CONFIG_COREDUMP
pidfs_coredump(const struct coredump_params * cprm)649 void pidfs_coredump(const struct coredump_params *cprm)
650 {
651 	struct pid *pid = cprm->pid;
652 	struct pidfs_exit_info *exit_info;
653 	struct pidfs_attr *attr;
654 	__u32 coredump_mask = 0;
655 
656 	attr = READ_ONCE(pid->attr);
657 
658 	VFS_WARN_ON_ONCE(!attr);
659 	VFS_WARN_ON_ONCE(attr == PIDFS_PID_DEAD);
660 
661 	exit_info = &attr->__pei;
662 	/* Note how we were coredumped. */
663 	coredump_mask = pidfs_coredump_mask(cprm->mm_flags);
664 	/* Note that we actually did coredump. */
665 	coredump_mask |= PIDFD_COREDUMPED;
666 	/* If coredumping is set to skip we should never end up here. */
667 	VFS_WARN_ON_ONCE(coredump_mask & PIDFD_COREDUMP_SKIP);
668 	smp_store_release(&exit_info->coredump_mask, coredump_mask);
669 }
670 #endif
671 
672 static struct vfsmount *pidfs_mnt __ro_after_init;
673 
674 /*
675  * The vfs falls back to simple_setattr() if i_op->setattr() isn't
676  * implemented. Let's reject it completely until we have a clean
677  * permission concept for pidfds.
678  */
pidfs_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * attr)679 static int pidfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
680 			 struct iattr *attr)
681 {
682 	return anon_inode_setattr(idmap, dentry, attr);
683 }
684 
pidfs_getattr(struct mnt_idmap * idmap,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)685 static int pidfs_getattr(struct mnt_idmap *idmap, const struct path *path,
686 			 struct kstat *stat, u32 request_mask,
687 			 unsigned int query_flags)
688 {
689 	return anon_inode_getattr(idmap, path, stat, request_mask, query_flags);
690 }
691 
pidfs_listxattr(struct dentry * dentry,char * buf,size_t size)692 static ssize_t pidfs_listxattr(struct dentry *dentry, char *buf, size_t size)
693 {
694 	struct inode *inode = d_inode(dentry);
695 	struct pid *pid = inode->i_private;
696 	struct pidfs_attr *attr = pid->attr;
697 	struct simple_xattrs *xattrs;
698 
699 	xattrs = READ_ONCE(attr->xattrs);
700 	if (!xattrs)
701 		return 0;
702 
703 	return simple_xattr_list(inode, xattrs, buf, size);
704 }
705 
706 static const struct inode_operations pidfs_inode_operations = {
707 	.getattr	= pidfs_getattr,
708 	.setattr	= pidfs_setattr,
709 	.listxattr	= pidfs_listxattr,
710 };
711 
pidfs_evict_inode(struct inode * inode)712 static void pidfs_evict_inode(struct inode *inode)
713 {
714 	struct pid *pid = inode->i_private;
715 
716 	clear_inode(inode);
717 	put_pid(pid);
718 }
719 
720 static const struct super_operations pidfs_sops = {
721 	.drop_inode	= generic_delete_inode,
722 	.evict_inode	= pidfs_evict_inode,
723 	.statfs		= simple_statfs,
724 };
725 
726 /*
727  * 'lsof' has knowledge of out historical anon_inode use, and expects
728  * the pidfs dentry name to start with 'anon_inode'.
729  */
pidfs_dname(struct dentry * dentry,char * buffer,int buflen)730 static char *pidfs_dname(struct dentry *dentry, char *buffer, int buflen)
731 {
732 	return dynamic_dname(buffer, buflen, "anon_inode:[pidfd]");
733 }
734 
735 const struct dentry_operations pidfs_dentry_operations = {
736 	.d_dname	= pidfs_dname,
737 	.d_prune	= stashed_dentry_prune,
738 };
739 
pidfs_encode_fh(struct inode * inode,u32 * fh,int * max_len,struct inode * parent)740 static int pidfs_encode_fh(struct inode *inode, u32 *fh, int *max_len,
741 			   struct inode *parent)
742 {
743 	const struct pid *pid = inode->i_private;
744 
745 	if (*max_len < 2) {
746 		*max_len = 2;
747 		return FILEID_INVALID;
748 	}
749 
750 	*max_len = 2;
751 	*(u64 *)fh = pid->ino;
752 	return FILEID_KERNFS;
753 }
754 
pidfs_ino_find(const void * key,const struct rb_node * node)755 static int pidfs_ino_find(const void *key, const struct rb_node *node)
756 {
757 	const u64 pid_ino = *(u64 *)key;
758 	const struct pid *pid = rb_entry(node, struct pid, pidfs_node);
759 
760 	if (pid_ino < pid->ino)
761 		return -1;
762 	if (pid_ino > pid->ino)
763 		return 1;
764 	return 0;
765 }
766 
767 /* Find a struct pid based on the inode number. */
pidfs_ino_get_pid(u64 ino)768 static struct pid *pidfs_ino_get_pid(u64 ino)
769 {
770 	struct pid *pid;
771 	struct rb_node *node;
772 	unsigned int seq;
773 
774 	guard(rcu)();
775 	do {
776 		seq = read_seqcount_begin(&pidmap_lock_seq);
777 		node = rb_find_rcu(&ino, &pidfs_ino_tree, pidfs_ino_find);
778 		if (node)
779 			break;
780 	} while (read_seqcount_retry(&pidmap_lock_seq, seq));
781 
782 	if (!node)
783 		return NULL;
784 
785 	pid = rb_entry(node, struct pid, pidfs_node);
786 
787 	/* Within our pid namespace hierarchy? */
788 	if (pid_vnr(pid) == 0)
789 		return NULL;
790 
791 	return get_pid(pid);
792 }
793 
pidfs_fh_to_dentry(struct super_block * sb,struct fid * fid,int fh_len,int fh_type)794 static struct dentry *pidfs_fh_to_dentry(struct super_block *sb,
795 					 struct fid *fid, int fh_len,
796 					 int fh_type)
797 {
798 	int ret;
799 	u64 pid_ino;
800 	struct path path;
801 	struct pid *pid;
802 
803 	if (fh_len < 2)
804 		return NULL;
805 
806 	switch (fh_type) {
807 	case FILEID_KERNFS:
808 		pid_ino = *(u64 *)fid;
809 		break;
810 	default:
811 		return NULL;
812 	}
813 
814 	pid = pidfs_ino_get_pid(pid_ino);
815 	if (!pid)
816 		return NULL;
817 
818 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, pid, &path);
819 	if (ret < 0)
820 		return ERR_PTR(ret);
821 
822 	VFS_WARN_ON_ONCE(!pid->attr);
823 
824 	mntput(path.mnt);
825 	return path.dentry;
826 }
827 
828 /*
829  * Make sure that we reject any nonsensical flags that users pass via
830  * open_by_handle_at(). Note that PIDFD_THREAD is defined as O_EXCL, and
831  * PIDFD_NONBLOCK as O_NONBLOCK.
832  */
833 #define VALID_FILE_HANDLE_OPEN_FLAGS \
834 	(O_RDONLY | O_WRONLY | O_RDWR | O_NONBLOCK | O_CLOEXEC | O_EXCL)
835 
pidfs_export_permission(struct handle_to_path_ctx * ctx,unsigned int oflags)836 static int pidfs_export_permission(struct handle_to_path_ctx *ctx,
837 				   unsigned int oflags)
838 {
839 	if (oflags & ~(VALID_FILE_HANDLE_OPEN_FLAGS | O_LARGEFILE))
840 		return -EINVAL;
841 
842 	/*
843 	 * pidfd_ino_get_pid() will verify that the struct pid is part
844 	 * of the caller's pid namespace hierarchy. No further
845 	 * permission checks are needed.
846 	 */
847 	return 0;
848 }
849 
pidfs_export_open(struct path * path,unsigned int oflags)850 static struct file *pidfs_export_open(struct path *path, unsigned int oflags)
851 {
852 	/*
853 	 * Clear O_LARGEFILE as open_by_handle_at() forces it and raise
854 	 * O_RDWR as pidfds always are.
855 	 */
856 	oflags &= ~O_LARGEFILE;
857 	return dentry_open(path, oflags | O_RDWR, current_cred());
858 }
859 
860 static const struct export_operations pidfs_export_operations = {
861 	.encode_fh	= pidfs_encode_fh,
862 	.fh_to_dentry	= pidfs_fh_to_dentry,
863 	.open		= pidfs_export_open,
864 	.permission	= pidfs_export_permission,
865 };
866 
pidfs_init_inode(struct inode * inode,void * data)867 static int pidfs_init_inode(struct inode *inode, void *data)
868 {
869 	const struct pid *pid = data;
870 
871 	inode->i_private = data;
872 	inode->i_flags |= S_PRIVATE | S_ANON_INODE;
873 	/* We allow to set xattrs. */
874 	inode->i_flags &= ~S_IMMUTABLE;
875 	inode->i_mode |= S_IRWXU;
876 	inode->i_op = &pidfs_inode_operations;
877 	inode->i_fop = &pidfs_file_operations;
878 	inode->i_ino = pidfs_ino(pid->ino);
879 	inode->i_generation = pidfs_gen(pid->ino);
880 	return 0;
881 }
882 
pidfs_put_data(void * data)883 static void pidfs_put_data(void *data)
884 {
885 	struct pid *pid = data;
886 	put_pid(pid);
887 }
888 
889 /**
890  * pidfs_register_pid - register a struct pid in pidfs
891  * @pid: pid to pin
892  *
893  * Register a struct pid in pidfs.
894  *
895  * Return: On success zero, on error a negative error code is returned.
896  */
pidfs_register_pid(struct pid * pid)897 int pidfs_register_pid(struct pid *pid)
898 {
899 	struct pidfs_attr *new_attr __free(kfree) = NULL;
900 	struct pidfs_attr *attr;
901 
902 	might_sleep();
903 
904 	if (!pid)
905 		return 0;
906 
907 	attr = READ_ONCE(pid->attr);
908 	if (unlikely(attr == PIDFS_PID_DEAD))
909 		return PTR_ERR(PIDFS_PID_DEAD);
910 	if (attr)
911 		return 0;
912 
913 	new_attr = kmem_cache_zalloc(pidfs_attr_cachep, GFP_KERNEL);
914 	if (!new_attr)
915 		return -ENOMEM;
916 
917 	/* Synchronize with pidfs_exit(). */
918 	guard(spinlock_irq)(&pid->wait_pidfd.lock);
919 
920 	attr = pid->attr;
921 	if (unlikely(attr == PIDFS_PID_DEAD))
922 		return PTR_ERR(PIDFS_PID_DEAD);
923 	if (unlikely(attr))
924 		return 0;
925 
926 	pid->attr = no_free_ptr(new_attr);
927 	return 0;
928 }
929 
pidfs_stash_dentry(struct dentry ** stashed,struct dentry * dentry)930 static struct dentry *pidfs_stash_dentry(struct dentry **stashed,
931 					 struct dentry *dentry)
932 {
933 	int ret;
934 	struct pid *pid = d_inode(dentry)->i_private;
935 
936 	VFS_WARN_ON_ONCE(stashed != &pid->stashed);
937 
938 	ret = pidfs_register_pid(pid);
939 	if (ret)
940 		return ERR_PTR(ret);
941 
942 	return stash_dentry(stashed, dentry);
943 }
944 
945 static const struct stashed_operations pidfs_stashed_ops = {
946 	.stash_dentry	= pidfs_stash_dentry,
947 	.init_inode	= pidfs_init_inode,
948 	.put_data	= pidfs_put_data,
949 };
950 
pidfs_xattr_get(const struct xattr_handler * handler,struct dentry * unused,struct inode * inode,const char * suffix,void * value,size_t size)951 static int pidfs_xattr_get(const struct xattr_handler *handler,
952 			   struct dentry *unused, struct inode *inode,
953 			   const char *suffix, void *value, size_t size)
954 {
955 	struct pid *pid = inode->i_private;
956 	struct pidfs_attr *attr = pid->attr;
957 	const char *name;
958 	struct simple_xattrs *xattrs;
959 
960 	xattrs = READ_ONCE(attr->xattrs);
961 	if (!xattrs)
962 		return 0;
963 
964 	name = xattr_full_name(handler, suffix);
965 	return simple_xattr_get(xattrs, name, value, size);
966 }
967 
pidfs_xattr_set(const struct xattr_handler * handler,struct mnt_idmap * idmap,struct dentry * unused,struct inode * inode,const char * suffix,const void * value,size_t size,int flags)968 static int pidfs_xattr_set(const struct xattr_handler *handler,
969 			   struct mnt_idmap *idmap, struct dentry *unused,
970 			   struct inode *inode, const char *suffix,
971 			   const void *value, size_t size, int flags)
972 {
973 	struct pid *pid = inode->i_private;
974 	struct pidfs_attr *attr = pid->attr;
975 	const char *name;
976 	struct simple_xattrs *xattrs;
977 	struct simple_xattr *old_xattr;
978 
979 	/* Ensure we're the only one to set @attr->xattrs. */
980 	WARN_ON_ONCE(!inode_is_locked(inode));
981 
982 	xattrs = READ_ONCE(attr->xattrs);
983 	if (!xattrs) {
984 		xattrs = kmem_cache_zalloc(pidfs_xattr_cachep, GFP_KERNEL);
985 		if (!xattrs)
986 			return -ENOMEM;
987 
988 		simple_xattrs_init(xattrs);
989 		smp_store_release(&pid->attr->xattrs, xattrs);
990 	}
991 
992 	name = xattr_full_name(handler, suffix);
993 	old_xattr = simple_xattr_set(xattrs, name, value, size, flags);
994 	if (IS_ERR(old_xattr))
995 		return PTR_ERR(old_xattr);
996 
997 	simple_xattr_free(old_xattr);
998 	return 0;
999 }
1000 
1001 static const struct xattr_handler pidfs_trusted_xattr_handler = {
1002 	.prefix = XATTR_TRUSTED_PREFIX,
1003 	.get	= pidfs_xattr_get,
1004 	.set	= pidfs_xattr_set,
1005 };
1006 
1007 static const struct xattr_handler *const pidfs_xattr_handlers[] = {
1008 	&pidfs_trusted_xattr_handler,
1009 	NULL
1010 };
1011 
pidfs_init_fs_context(struct fs_context * fc)1012 static int pidfs_init_fs_context(struct fs_context *fc)
1013 {
1014 	struct pseudo_fs_context *ctx;
1015 
1016 	ctx = init_pseudo(fc, PID_FS_MAGIC);
1017 	if (!ctx)
1018 		return -ENOMEM;
1019 
1020 	fc->s_iflags |= SB_I_NOEXEC;
1021 	fc->s_iflags |= SB_I_NODEV;
1022 	ctx->ops = &pidfs_sops;
1023 	ctx->eops = &pidfs_export_operations;
1024 	ctx->dops = &pidfs_dentry_operations;
1025 	ctx->xattr = pidfs_xattr_handlers;
1026 	fc->s_fs_info = (void *)&pidfs_stashed_ops;
1027 	return 0;
1028 }
1029 
1030 static struct file_system_type pidfs_type = {
1031 	.name			= "pidfs",
1032 	.init_fs_context	= pidfs_init_fs_context,
1033 	.kill_sb		= kill_anon_super,
1034 };
1035 
pidfs_alloc_file(struct pid * pid,unsigned int flags)1036 struct file *pidfs_alloc_file(struct pid *pid, unsigned int flags)
1037 {
1038 	struct file *pidfd_file;
1039 	struct path path __free(path_put) = {};
1040 	int ret;
1041 
1042 	/*
1043 	 * Ensure that PIDFD_STALE can be passed as a flag without
1044 	 * overloading other uapi pidfd flags.
1045 	 */
1046 	BUILD_BUG_ON(PIDFD_STALE == PIDFD_THREAD);
1047 	BUILD_BUG_ON(PIDFD_STALE == PIDFD_NONBLOCK);
1048 
1049 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, get_pid(pid), &path);
1050 	if (ret < 0)
1051 		return ERR_PTR(ret);
1052 
1053 	VFS_WARN_ON_ONCE(!pid->attr);
1054 
1055 	flags &= ~PIDFD_STALE;
1056 	flags |= O_RDWR;
1057 	pidfd_file = dentry_open(&path, flags, current_cred());
1058 	/* Raise PIDFD_THREAD explicitly as do_dentry_open() strips it. */
1059 	if (!IS_ERR(pidfd_file))
1060 		pidfd_file->f_flags |= (flags & PIDFD_THREAD);
1061 
1062 	return pidfd_file;
1063 }
1064 
pidfs_init(void)1065 void __init pidfs_init(void)
1066 {
1067 	pidfs_attr_cachep = kmem_cache_create("pidfs_attr_cache", sizeof(struct pidfs_attr), 0,
1068 					 (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT |
1069 					  SLAB_ACCOUNT | SLAB_PANIC), NULL);
1070 
1071 	pidfs_xattr_cachep = kmem_cache_create("pidfs_xattr_cache",
1072 					       sizeof(struct simple_xattrs), 0,
1073 					       (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT |
1074 						SLAB_ACCOUNT | SLAB_PANIC), NULL);
1075 
1076 	pidfs_mnt = kern_mount(&pidfs_type);
1077 	if (IS_ERR(pidfs_mnt))
1078 		panic("Failed to mount pidfs pseudo filesystem");
1079 
1080 	pidfs_root_path.mnt = pidfs_mnt;
1081 	pidfs_root_path.dentry = pidfs_mnt->mnt_root;
1082 }
1083