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