xref: /freebsd/sys/kern/sys_procdesc.c (revision e8b9b6b9f31c463137b4104550bfb3286a43703a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009, 2016 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * This software was developed at the University of Cambridge Computer
8  * Laboratory with support from a grant from Google, Inc.
9  *
10  * Portions of this software were developed by BAE Systems, the University of
11  * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
12  * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
13  * Computing (TC) research program.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 /*-
38  * FreeBSD process descriptor facility.
39  *
40  * Some processes are represented by a file descriptor, which will be used in
41  * preference to signaling and pids for the purposes of process management,
42  * and is, in effect, a form of capability.  When a process descriptor is
43  * used with a process, it ceases to be visible to certain traditional UNIX
44  * process facilities, such as waitpid(2).
45  *
46  * Some semantics:
47  *
48  * - At most one process descriptor will exist for any process, although
49  *   references to that descriptor may be held from many processes (or even
50  *   be in flight between processes over a local domain socket).
51  * - Last close on the process descriptor will terminate the process using
52  *   SIGKILL and reparent it to init so that there's a process to reap it
53  *   when it's done exiting.
54  * - If the process exits before the descriptor is closed, it will not
55  *   generate SIGCHLD on termination, or be picked up by waitpid().
56  * - The pdkill(2) system call may be used to deliver a signal to the process
57  *   using its process descriptor.
58  *
59  * Open questions:
60  *
61  * - Will we want to add a pidtoprocdesc(2) system call to allow process
62  *   descriptors to be created for processes without pdfork(2)?
63  */
64 
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/event.h>
68 #include <sys/fcntl.h>
69 #include <sys/file.h>
70 #include <sys/filedesc.h>
71 #include <sys/imgact.h>
72 #include <sys/kernel.h>
73 #include <sys/lock.h>
74 #include <sys/mutex.h>
75 #include <sys/poll.h>
76 #include <sys/proc.h>
77 #include <sys/procdesc.h>
78 #include <sys/resourcevar.h>
79 #include <sys/stat.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysproto.h>
82 #include <sys/sysctl.h>
83 #include <sys/systm.h>
84 #include <sys/ucred.h>
85 #include <sys/user.h>
86 
87 #include <security/audit/audit.h>
88 
89 #include <vm/uma.h>
90 
91 FEATURE(process_descriptors, "Process Descriptors");
92 
93 MALLOC_DEFINE(M_PROCDESC, "procdesc", "process descriptors");
94 
95 static fo_poll_t	procdesc_poll;
96 static fo_kqfilter_t	procdesc_kqfilter;
97 static fo_stat_t	procdesc_stat;
98 static fo_close_t	procdesc_close;
99 static fo_fill_kinfo_t	procdesc_fill_kinfo;
100 static fo_cmp_t		procdesc_cmp;
101 
102 static const struct fileops procdesc_ops = {
103 	.fo_read = invfo_rdwr,
104 	.fo_write = invfo_rdwr,
105 	.fo_truncate = invfo_truncate,
106 	.fo_ioctl = invfo_ioctl,
107 	.fo_poll = procdesc_poll,
108 	.fo_kqfilter = procdesc_kqfilter,
109 	.fo_stat = procdesc_stat,
110 	.fo_close = procdesc_close,
111 	.fo_chmod = invfo_chmod,
112 	.fo_chown = invfo_chown,
113 	.fo_sendfile = invfo_sendfile,
114 	.fo_fill_kinfo = procdesc_fill_kinfo,
115 	.fo_cmp = procdesc_cmp,
116 	.fo_flags = DFLAG_PASSABLE,
117 };
118 
119 /*
120  * Function to be used by procstat(1) sysctls when returning procdesc
121  * information.
122  */
123 pid_t
procdesc_pid(struct file * fp_procdesc)124 procdesc_pid(struct file *fp_procdesc)
125 {
126 	struct procdesc *pd;
127 
128 	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
129 	   ("procdesc_pid: !procdesc"));
130 
131 	pd = fp_procdesc->f_data;
132 	return (pd->pd_pid);
133 }
134 
135 /*
136  * Retrieve the PID associated with a process descriptor.
137  */
138 int
kern_pdgetpid(struct thread * td,int fd,const cap_rights_t * rightsp,pid_t * pidp)139 kern_pdgetpid(struct thread *td, int fd, const cap_rights_t *rightsp,
140     pid_t *pidp)
141 {
142 	struct file *fp;
143 	int error;
144 
145 	error = fget_procdesc(td, fd, rightsp, EBADF, &fp, NULL, NULL);
146 	if (error == 0)
147 		*pidp = procdesc_pid(fp);
148 	if (fp != NULL)
149 		fdrop(fp, td);
150 	return (error);
151 }
152 
153 /*
154  * System call to return the pid of a process given its process descriptor.
155  */
156 int
sys_pdgetpid(struct thread * td,struct pdgetpid_args * uap)157 sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
158 {
159 	pid_t pid;
160 	int error;
161 
162 	AUDIT_ARG_FD(uap->fd);
163 	error = kern_pdgetpid(td, uap->fd, &cap_pdgetpid_rights, &pid);
164 	if (error == 0)
165 		error = copyout(&pid, uap->pidp, sizeof(pid));
166 	return (error);
167 }
168 
169 static struct procdesc *
procdesc_alloc(int flags)170 procdesc_alloc(int flags)
171 {
172 	struct procdesc *pd;
173 
174 	pd = malloc(sizeof(*pd), M_PROCDESC, M_WAITOK | M_ZERO);
175 	pd->pd_flags = 0;
176 	pd->pd_pid = -1;
177 	PROCDESC_LOCK_INIT(pd);
178 	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
179 
180 	/*
181 	 * Process descriptors start out with two references: one from their
182 	 * struct file, and the other from their struct proc.
183 	 */
184 	refcount_init(&pd->pd_refcount, 2);
185 	pd->pd_fpcount = 1;
186 
187 	return (pd);
188 }
189 
190 /*
191  * When a new process is forked by pdfork(), a file descriptor is allocated
192  * by the fork code first, then the process is forked, and then we get a
193  * chance to set up the process descriptor.  Failure is not permitted at this
194  * point, so procdesc_new() must succeed.
195  */
196 void
procdesc_new(struct proc * p,int flags)197 procdesc_new(struct proc *p, int flags)
198 {
199 	struct procdesc *pd;
200 
201 	pd = procdesc_alloc(flags);
202 	pd->pd_proc = p;
203 	pd->pd_pid = p->p_pid;
204 	MPASS(p->p_procdesc == NULL);
205 	p->p_procdesc = pd;
206 }
207 
208 static int
pdtofdflags(int flags)209 pdtofdflags(int flags)
210 {
211 	int fflags;
212 
213 	fflags = 0;
214 	if (flags & PD_CLOEXEC)
215 		fflags |= O_CLOEXEC;
216 	return (fflags);
217 }
218 
219 /*
220  * Create a new process decriptor for the process that refers to it.
221  */
222 int
procdesc_falloc(struct thread * td,struct file ** resultfp,int * resultfd,int flags,struct filecaps * fcaps)223 procdesc_falloc(struct thread *td, struct file **resultfp, int *resultfd,
224     int flags, struct filecaps *fcaps)
225 {
226 	int error;
227 
228 	error = falloc_caps(td, resultfp, resultfd, pdtofdflags(flags), fcaps);
229 	if (error == 0 && (flags & PD_DAEMON) != 0)
230 		(*resultfp)->f_pdflags |= F_PD_NOKILL;
231 	return (error);
232 }
233 
234 /*
235  * Initialize a file with a process descriptor.
236  */
237 void
procdesc_finit(struct procdesc * pdp,struct file * fp)238 procdesc_finit(struct procdesc *pdp, struct file *fp)
239 {
240 
241 	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
242 }
243 
244 static void
procdesc_destroy(struct procdesc * pd)245 procdesc_destroy(struct procdesc *pd)
246 {
247 	knlist_destroy(&pd->pd_selinfo.si_note);
248 	PROCDESC_LOCK_DESTROY(pd);
249 	free(pd, M_PROCDESC);
250 }
251 
252 static void
procdesc_free(struct procdesc * pd)253 procdesc_free(struct procdesc *pd)
254 {
255 
256 	/*
257 	 * When the last reference is released, we assert that the descriptor
258 	 * has been closed, but not that the process has exited, as we will
259 	 * detach the descriptor before the process dies if the descript is
260 	 * closed, as we can't wait synchronously.
261 	 */
262 	if (refcount_release(&pd->pd_refcount)) {
263 		KASSERT(pd->pd_proc == NULL,
264 		    ("procdesc_free: pd_proc != NULL"));
265 		KASSERT(pd->pd_fpcount == 0,
266 		    ("procdesc_free: not closed %p %d", pd, pd->pd_fpcount));
267 
268 		if (pd->pd_pid != -1)
269 			proc_id_clear(PROC_ID_PID, pd->pd_pid);
270 
271 		seldrain(&pd->pd_selinfo);
272 		procdesc_destroy(pd);
273 	}
274 }
275 
276 /*
277  * procdesc_exit() - notify a process descriptor that its process is exiting.
278  * We use the proctree_lock to ensure that process exit either happens
279  * strictly before or strictly after a concurrent call to procdesc_close().
280  * Return true if the process' parent is responsible for reaping the child,
281  * false otherwise.
282  */
283 bool
procdesc_exit(struct proc * p)284 procdesc_exit(struct proc *p)
285 {
286 	struct procdesc *pd;
287 
288 	sx_assert(&proctree_lock, SA_XLOCKED);
289 	PROC_LOCK_ASSERT(p, MA_OWNED);
290 	MPASS((p->p_flag & P_WEXIT) != 0);
291 
292 	pd = p->p_procdesc;
293 	if (pd == NULL)
294 		goto out;
295 
296 	PROCDESC_LOCK(pd);
297 	KASSERT(pd->pd_fpcount > 0, ("%s: closed procdesc %p", __func__, pd));
298 
299 	pd->pd_flags |= PDF_EXITED;
300 	pd->pd_xexit = p->p_xexit;
301 	pd->pd_xsig = p->p_xsig;
302 
303 	selwakeup(&pd->pd_selinfo);
304 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT | NOTE_PDSIGCHLD);
305 	PROCDESC_UNLOCK(pd);
306 
307 	/* Wakeup all waiters for this procdesc' process exit. */
308 	wakeup(&p->p_procdesc);
309 out:
310 	return ((p->p_zombieref & PZOMBIEREF_PARENT) != 0);
311 }
312 
313 void
procdesc_jobstate(struct proc * p)314 procdesc_jobstate(struct proc *p)
315 {
316 	struct procdesc *pd;
317 
318 	PROC_LOCK_ASSERT(p, MA_OWNED);
319 	pd = p->p_procdesc;
320 	if (pd == NULL)
321 		return;
322 
323 	PROCDESC_LOCK(pd);
324 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_PDSIGCHLD);
325 	PROCDESC_UNLOCK(pd);
326 	wakeup(&p->p_procdesc);
327 }
328 
329 void
procdesc_fork(struct proc * p,pid_t child_pid)330 procdesc_fork(struct proc *p, pid_t child_pid)
331 {
332 	struct procdesc *pd;
333 
334 	PROC_LOCK(p);
335 	pd = p->p_procdesc;
336 	if (pd != NULL) {
337 		PROCDESC_LOCK(pd);
338 		pd->pd_last_child = child_pid;
339 		KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_FORK);
340 		PROCDESC_UNLOCK(pd);
341 	}
342 	PROC_UNLOCK(p);
343 }
344 
345 void
procdesc_fill_winfo(struct procdesc * pd,bool proc_locked)346 procdesc_fill_winfo(struct procdesc *pd, bool proc_locked)
347 {
348 	struct proc *p;
349 
350 	sx_assert(&proctree_lock, SA_XLOCKED);
351 
352 	if ((pd->pd_flags & (PDF_EXITED | PDF_EXIT_INFO)) == PDF_EXITED) {
353 		pd->pd_flags |= PDF_EXIT_INFO;
354 		p = pd->pd_proc;
355 		if (!proc_locked)
356 			PROC_LOCK(p);
357 		wait_fill_siginfo(p, &pd->pd_siginfo);
358 		wait_fill_wrusage(p, &pd->pd_wrusage);
359 		if (!proc_locked)
360 			PROC_UNLOCK(p);
361 	}
362 }
363 
364 /*
365  * When a process descriptor is reaped, perhaps as a result of close(), release
366  * the process's reference on the process descriptor.
367  */
368 void
procdesc_reap(struct proc * p)369 procdesc_reap(struct proc *p)
370 {
371 	struct procdesc *pd;
372 
373 	sx_assert(&proctree_lock, SA_XLOCKED);
374 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
375 
376 	pd = p->p_procdesc;
377 	procdesc_fill_winfo(pd, false);
378 	pd->pd_proc = NULL;
379 	p->p_procdesc = NULL;
380 	procdesc_free(pd);
381 }
382 
383 static void
procdesc_close_tail(struct file * fp,struct proc * p)384 procdesc_close_tail(struct file *fp, struct proc *p)
385 {
386 	if ((fp->f_pdflags & F_PD_NOKILL) == 0)
387 		kern_psignal(p, SIGKILL);
388 	PROC_UNLOCK(p);
389 	sx_xunlock(&proctree_lock);
390 }
391 
392 /*
393  * procdesc_close() - last close on a process descriptor.  If the process is
394  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
395  * its reaper clean up the mess; if not, we have to clean up the zombie
396  * ourselves.
397  */
398 static int
procdesc_close(struct file * fp,struct thread * td)399 procdesc_close(struct file *fp, struct thread *td)
400 {
401 	struct procdesc *pd;
402 	struct proc *p;
403 
404 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
405 
406 	pd = fp->f_data;
407 	fp->f_ops = &badfileops;
408 	fp->f_data = NULL;
409 
410 	sx_xlock(&proctree_lock);
411 	PROCDESC_LOCK(pd);
412 	MPASS(pd->pd_fpcount > 0);
413 	pd->pd_fpcount--;
414 	PROCDESC_UNLOCK(pd);
415 	p = pd->pd_proc;
416 	if (p == NULL) {
417 		/*
418 		 * This is the case where process' exit status was already
419 		 * collected and procdesc_reap() was already called.
420 		 */
421 		sx_xunlock(&proctree_lock);
422 	} else {
423 		PROC_LOCK(p);
424 		AUDIT_ARG_PROCESS(p);
425 		if (pd->pd_fpcount == 0) /* last procdesc */ {
426 			/*
427 			 * If the process is not yet dead, we need to kill it,
428 			 * but we can't wait around synchronously for it to go
429 			 * away, as that path leads to madness (and deadlocks).
430 			 * First, detach the process from its descriptor so that
431 			 * its exit status will be reported normally.
432 			 */
433 			pd->pd_proc = NULL;
434 			p->p_procdesc = NULL;
435 			pd->pd_pid = -1;
436 			procdesc_free(pd);
437 			if (p->p_state == PRS_ZOMBIE) {
438 				proc_reap(curthread, p, NULL, 0,
439 				    PZOMBIEREF_PROCDESC);
440 				goto out;
441 			}
442 
443 			/*
444 			 * Not a zombie, and no more opened process
445 			 * descriptors. Clear PZOMBIEREF_PROCDESC
446 			 * since right now nobody would call
447 			 * proc_reap(p, PZOMBIEREF_PROCDESC).  The
448 			 * flag is re-added if pdopenpid() is called.
449 			 */
450 			p->p_zombieref &= ~PZOMBIEREF_PROCDESC;
451 
452 			/*
453 			 * A reference for waitpid() or failed
454 			 * finstall() should not cause reaping.
455 			 */
456 			if ((fp->f_pdflags & F_PD_NOFINSTALL) == 0 &&
457 			    (p->p_zombieref & PZOMBIEREF_PARENT) == 0) {
458 				/*
459 				 * Next, reparent it to its reaper
460 				 * (usually init(8)) so that there's
461 				 * someone to pick up the pieces;
462 				 * finally, terminate with prejudice.
463 				 */
464 				p->p_sigparent = SIGCHLD;
465 				if ((p->p_flag & P_TRACED) == 0) {
466 					proc_reparent(p, p->p_reaper, true);
467 				} else {
468 					proc_clear_orphan(p);
469 					p->p_oppid = p->p_reaper->p_pid;
470 					proc_add_orphan(p, p->p_reaper);
471 				}
472 			}
473 
474 			procdesc_close_tail(fp, p);
475 		} else {
476 			procdesc_close_tail(fp, p);
477 		}
478 	}
479 out:
480 	/*
481 	 * Release the file descriptor's reference on the process descriptor.
482 	 */
483 	procdesc_free(pd);
484 	return (0);
485 }
486 
487 static int
procdesc_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)488 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
489     struct thread *td)
490 {
491 	struct procdesc *pd;
492 	int revents;
493 
494 	revents = 0;
495 	pd = fp->f_data;
496 	PROCDESC_LOCK(pd);
497 	if ((atomic_load_int(&pd->pd_flags) & PDF_EXITED) != 0)
498 		revents |= POLLHUP;
499 	else
500 		selrecord(td, &pd->pd_selinfo);
501 	PROCDESC_UNLOCK(pd);
502 	return (revents);
503 }
504 
505 static void
procdesc_kqops_detach(struct knote * kn)506 procdesc_kqops_detach(struct knote *kn)
507 {
508 	struct procdesc *pd;
509 
510 	pd = kn->kn_fp->f_data;
511 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
512 }
513 
514 static int
procdesc_kqops_event(struct knote * kn,long hint)515 procdesc_kqops_event(struct knote *kn, long hint)
516 {
517 	struct procdesc *pd;
518 	struct proc *p;
519 	u_int event;
520 
521 	pd = kn->kn_fp->f_data;
522 	if (hint == 0) {
523 		/*
524 		 * Initial test after registration.  Generate notes in
525 		 * case the process already terminated before
526 		 * registration, or is stopped, or traced, with an event
527 		 * pending.
528 		 */
529 		p = pd->pd_proc;
530 		if ((atomic_load_int(&pd->pd_flags) & PDF_EXITED) != 0)
531 			event = NOTE_EXIT | NOTE_PDSIGCHLD;
532 		else if ((atomic_load_int(&p->p_flag) & (P_STOPPED_SIG |
533 		    P_STOPPED_TRACE)) != 0)
534 			event = NOTE_PDSIGCHLD;
535 		else
536 			event = 0;
537 	} else {
538 		/* Mask off extra data. */
539 		event = (u_int)hint & NOTE_PCTRLMASK;
540 	}
541 
542 	/* If the user is interested in this event, record it. */
543 	if ((kn->kn_sfflags & event) != 0)
544 		kn->kn_fflags |= kn->kn_sfflags & event;
545 
546 	/* Report exit status */
547 	if ((kn->kn_fflags & NOTE_EXIT) != 0)
548 		kn->kn_data = KW_EXITCODE(pd->pd_xexit, pd->pd_xsig);
549 
550 	/* Process is gone, so flag the event as finished. */
551 	if ((event & NOTE_REAP) != 0 ||
552 	    ((event & NOTE_EXIT) != 0 && (kn->kn_sfflags & NOTE_REAP) == 0)) {
553 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
554 		if (kn->kn_fflags == 0)
555 			kn->kn_flags |= EV_DROP;
556 		return (1);
557 	}
558 
559 	if ((kn->kn_fflags & NOTE_FORK) != 0)
560 		kn->kn_data = pd->pd_last_child;
561 
562 	return (kn->kn_fflags != 0);
563 }
564 
565 static const struct filterops procdesc_kqops = {
566 	.f_isfd = 1,
567 	.f_detach = procdesc_kqops_detach,
568 	.f_event = procdesc_kqops_event,
569 	.f_copy = knote_triv_copy,
570 };
571 
572 static int
procdesc_kqfilter(struct file * fp,struct knote * kn)573 procdesc_kqfilter(struct file *fp, struct knote *kn)
574 {
575 	struct procdesc *pd;
576 
577 	pd = fp->f_data;
578 	switch (kn->kn_filter) {
579 	case EVFILT_PROCDESC:
580 		kn->kn_fop = &procdesc_kqops;
581 		kn->kn_flags |= EV_CLEAR;
582 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
583 		return (0);
584 	default:
585 		return (EINVAL);
586 	}
587 }
588 
589 static int
procdesc_stat(struct file * fp,struct stat * sb,struct ucred * active_cred)590 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
591 {
592 	struct procdesc *pd;
593 	struct timeval pstart, boottime;
594 
595 	/*
596 	 * XXXRW: Perhaps we should cache some more information from the
597 	 * process so that we can return it reliably here even after it has
598 	 * died.  For example, caching its credential data.
599 	 */
600 	bzero(sb, sizeof(*sb));
601 	pd = fp->f_data;
602 	sx_slock(&proctree_lock);
603 	if (pd->pd_proc != NULL) {
604 		PROC_LOCK(pd->pd_proc);
605 		AUDIT_ARG_PROCESS(pd->pd_proc);
606 
607 		/* Set birth and [acm] times to process start time. */
608 		pstart = pd->pd_proc->p_stats->p_start;
609 		getboottime(&boottime);
610 		timevaladd(&pstart, &boottime);
611 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
612 		sb->st_atim = sb->st_birthtim;
613 		sb->st_ctim = sb->st_birthtim;
614 		sb->st_mtim = sb->st_birthtim;
615 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
616 			sb->st_mode = S_IFREG | S_IRWXU;
617 		else
618 			sb->st_mode = S_IFREG;
619 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
620 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
621 		PROC_UNLOCK(pd->pd_proc);
622 	} else
623 		sb->st_mode = S_IFREG;
624 	sx_sunlock(&proctree_lock);
625 	return (0);
626 }
627 
628 static int
procdesc_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)629 procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
630     struct filedesc *fdp)
631 {
632 	struct procdesc *pdp;
633 
634 	kif->kf_type = KF_TYPE_PROCDESC;
635 	pdp = fp->f_data;
636 	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
637 	return (0);
638 }
639 
640 static int
procdesc_cmp(struct file * fp1,struct file * fp2,struct thread * td)641 procdesc_cmp(struct file *fp1, struct file *fp2, struct thread *td)
642 {
643 	struct procdesc *pdp1, *pdp2;
644 
645 	if (fp2->f_type != DTYPE_PROCDESC)
646 		return (3);
647 	pdp1 = fp1->f_data;
648 	pdp2 = fp2->f_data;
649 	return (kcmp_cmp((uintptr_t)pdp1->pd_pid, (uintptr_t)pdp2->pd_pid));
650 }
651 
652 static int
pdopenpid1(struct thread * td,pid_t pid,struct procdesc ** pdf,struct file * fp)653 pdopenpid1(struct thread *td, pid_t pid, struct procdesc **pdf, struct file *fp)
654 {
655 	struct proc *p;
656 	struct procdesc *pd;
657 	int error;
658 
659 	sx_assert(&proctree_lock, SX_XLOCKED);
660 
661 	error = pget(pid, PGET_NOTID | PGET_CANDEBUG, &p);
662 	if (error != 0)
663 		return (error);
664 	if ((p->p_flag & (P_SYSTEM | P_WEXIT)) != 0) {
665 		PROC_UNLOCK(p);
666 		return (EBUSY);
667 	}
668 	pd = p->p_procdesc;
669 	if (pd != NULL) {
670 		MPASS((p->p_zombieref & PZOMBIEREF_PROCDESC) != 0);
671 		refcount_acquire(&pd->pd_refcount);
672 		PROCDESC_LOCK(pd);
673 		MPASS(pd->pd_fpcount > 0);
674 		pd->pd_fpcount++;
675 		PROCDESC_UNLOCK(pd);
676 	} else {
677 		pd = *pdf;
678 		*pdf = NULL;
679 		pd->pd_proc = p;
680 		pd->pd_pid = p->p_pid;
681 		p->p_procdesc = pd;
682 		MPASS((p->p_zombieref & PZOMBIEREF_PROCDESC) == 0);
683 		p->p_zombieref |= PZOMBIEREF_PROCDESC;
684 	}
685 	procdesc_finit(pd, fp);
686 	PROC_UNLOCK(p);
687 	return (0);
688 }
689 
690 static int
kern_pdopenpid(struct thread * td,pid_t pid,int flags)691 kern_pdopenpid(struct thread *td, pid_t pid, int flags)
692 {
693 	struct file *fp;
694 	struct procdesc *pdf;
695 	int error, fd, fflags;
696 
697 	error = falloc_noinstall(td, &fp);
698 	if (error != 0)
699 		return (error);
700 	fflags = pdtofdflags(flags);
701 	pdf = procdesc_alloc(flags);
702 	if ((flags & PD_DAEMON) != 0)
703 		fp->f_pdflags |= F_PD_NOKILL;
704 
705 	sx_xlock(&proctree_lock);
706 	error = pdopenpid1(td, pid, &pdf, fp);
707 	sx_xunlock(&proctree_lock);
708 
709 	if (error == 0) {
710 		error = finstall(td, fp, &fd, fflags, NULL);
711 		if (error == 0) {
712 			td->td_retval[0] = fd;
713 		} else {
714 			/*
715 			 * Not killing the target process if cannot
716 			 * return file descriptor to userspace.
717 			 */
718 			fp->f_pdflags |= F_PD_NOKILL | F_PD_NOFINSTALL;
719 		}
720 	}
721 	fdrop(fp, td);
722 
723 	if (pdf != NULL) {
724 		MPASS(pdf->pd_refcount == 2);
725 		MPASS(pdf->pd_fpcount == 1);
726 		MPASS(pdf->pd_proc == NULL);
727 		MPASS(pdf->pd_pid == -1);
728 		procdesc_destroy(pdf);
729 	}
730 	return (error);
731 }
732 
733 int
sys_pdopenpid(struct thread * td,struct pdopenpid_args * args)734 sys_pdopenpid(struct thread *td, struct pdopenpid_args *args)
735 {
736 	AUDIT_ARG_PID(args->pid);
737 	AUDIT_ARG_FFLAGS(args->flags);
738 
739 	if ((args->flags & ~(PD_ALLOWED_AT_OPENPID)) != 0)
740 		return (EINVAL);
741 	return (kern_pdopenpid(td, args->pid, args->flags));
742 }
743 
744 /*
745  * Get the file/process descriptor/process from the procdesc file
746  * descriptor.  The process descriptor and process returns are
747  * optional.  If requested to return the process, the proctree lock
748  * must be held, and the process will be returned locked.
749  *
750  * The caller must fdrop(*pfp) if *pfp != NULL, regardless of the
751  * error returned, after the proctree_lock is unlocked.
752  * procdesc_close() takes the proctree_lock.
753  */
754 int
fget_procdesc(struct thread * td,int pdfd,const cap_rights_t * cap_rights,int wrong_type_error,struct file ** pfp,struct procdesc ** pdp,struct proc ** pp)755 fget_procdesc(struct thread *td, int pdfd, const cap_rights_t *cap_rights,
756     int wrong_type_error, struct file **pfp, struct procdesc **pdp,
757     struct proc **pp)
758 {
759 	struct file *fp;
760 	struct procdesc *pd;
761 	struct proc *p;
762 	int error;
763 
764 	if (pp != NULL)
765 		sx_assert(&proctree_lock, SX_LOCKED);
766 
767 	*pfp = NULL;
768 	error = fget(td, pdfd, cap_rights, &fp);
769 	if (error != 0)
770 		return (error);
771 	*pfp = fp;
772 	if (fp->f_type != DTYPE_PROCDESC)
773 		return (wrong_type_error);
774 	pd = fp->f_data;
775 	if (pp != NULL) {
776 		p = pd->pd_proc;
777 		if (p == NULL) {
778 			return (ESRCH);
779 		} else {
780 			*pp = p;
781 			PROC_LOCK(p);
782 		}
783 	}
784 	if (pdp != NULL)
785 		*pdp = pd;
786 	return (0);
787 }
788 
789 static int
kern_pddupfd(struct thread * td,int pdfd,int fd,int flags)790 kern_pddupfd(struct thread *td, int pdfd, int fd, int flags)
791 {
792 	struct proc *p;
793 	struct file *fp, *pfp;
794 	struct filecaps fcaps;
795 	uint8_t fd_flags;
796 	int error, fdr;
797 
798 	sx_slock(&proctree_lock);
799 	error = fget_procdesc(td, pdfd, &cap_pddupfd_rights, EINVAL, &pfp,
800 	    NULL, &p);
801 	if (error == 0) {
802 		if ((p->p_flag & P_WEXIT) != 0) {
803 			error = ESRCH;
804 			PROC_UNLOCK(p);
805 		} else {
806 			_PHOLD(p);
807 		}
808 	}
809 	sx_sunlock(&proctree_lock);
810 	if (error != 0)
811 		goto out;
812 	AUDIT_ARG_PROCESS(p);
813 	PROC_LOCK_ASSERT(p, MA_OWNED);
814 
815 	/*
816 	 * Block the target process from entering execve().
817 	 * We need to ensure that the p_candebug() predicate
818 	 * is stable until the fget_remote() call ends even
819 	 * after the process lock is dropped.  For that, the
820 	 * process must not change uid/suid.
821 	 */
822 	execve_block_wait(td, p);
823 	error = p_candebug(td, p);
824 
825 	if (error == 0) {
826 		PROC_UNLOCK(p);
827 		error = fget_remote(td, p, fd, &fcaps, &fd_flags, &fp);
828 		if (error == 0) {
829 			if ((fp->f_ops->fo_flags & DFLAG_PASSABLE) == 0) {
830 				error = EOPNOTSUPP;
831 			} else {
832 				error = finstall_refed(td, fp, &fdr, O_CLOEXEC |
833 				    ((fd_flags & FD_RESOLVE_BENEATH) != 0 ?
834 				    O_RESOLVE_BENEATH : 0), &fcaps);
835 			}
836 			if (error != 0) {
837 				fdrop(fp, td);
838 				filecaps_free(&fcaps);
839 			} else {
840 				td->td_retval[0] = fdr;
841 			}
842 		}
843 		PROC_LOCK(p);
844 	}
845 	execve_unblock(td, p);
846 	_PRELE(p);
847 	PROC_UNLOCK(p);
848 out:
849 	if (pfp != NULL)
850 		fdrop(pfp, td);
851 	return (error);
852 }
853 
854 int
sys_pddupfd(struct thread * td,struct pddupfd_args * args)855 sys_pddupfd(struct thread *td, struct pddupfd_args *args)
856 {
857 	if (args->flags != 0)
858 		return (EINVAL);
859 	return (kern_pddupfd(td, args->pd, args->fd, args->flags));
860 }
861