xref: /freebsd/sys/kern/sys_procdesc.c (revision 3f0efe05432b1633991114ca4ca330102a561959)
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/fcntl.h>
68 #include <sys/file.h>
69 #include <sys/filedesc.h>
70 #include <sys/kernel.h>
71 #include <sys/lock.h>
72 #include <sys/mutex.h>
73 #include <sys/poll.h>
74 #include <sys/proc.h>
75 #include <sys/procdesc.h>
76 #include <sys/resourcevar.h>
77 #include <sys/stat.h>
78 #include <sys/sysproto.h>
79 #include <sys/sysctl.h>
80 #include <sys/systm.h>
81 #include <sys/ucred.h>
82 #include <sys/user.h>
83 
84 #include <security/audit/audit.h>
85 
86 #include <vm/uma.h>
87 
88 FEATURE(process_descriptors, "Process Descriptors");
89 
90 MALLOC_DEFINE(M_PROCDESC, "procdesc", "process descriptors");
91 
92 static fo_poll_t	procdesc_poll;
93 static fo_kqfilter_t	procdesc_kqfilter;
94 static fo_stat_t	procdesc_stat;
95 static fo_close_t	procdesc_close;
96 static fo_fill_kinfo_t	procdesc_fill_kinfo;
97 static fo_cmp_t		procdesc_cmp;
98 
99 static struct fileops procdesc_ops = {
100 	.fo_read = invfo_rdwr,
101 	.fo_write = invfo_rdwr,
102 	.fo_truncate = invfo_truncate,
103 	.fo_ioctl = invfo_ioctl,
104 	.fo_poll = procdesc_poll,
105 	.fo_kqfilter = procdesc_kqfilter,
106 	.fo_stat = procdesc_stat,
107 	.fo_close = procdesc_close,
108 	.fo_chmod = invfo_chmod,
109 	.fo_chown = invfo_chown,
110 	.fo_sendfile = invfo_sendfile,
111 	.fo_fill_kinfo = procdesc_fill_kinfo,
112 	.fo_cmp = procdesc_cmp,
113 	.fo_flags = DFLAG_PASSABLE,
114 };
115 
116 /*
117  * Return a locked process given a process descriptor, or ESRCH if it has
118  * died.
119  */
120 int
121 procdesc_find(struct thread *td, int fd, cap_rights_t *rightsp,
122     struct proc **p)
123 {
124 	struct procdesc *pd;
125 	struct file *fp;
126 	int error;
127 
128 	error = fget(td, fd, rightsp, &fp);
129 	if (error)
130 		return (error);
131 	if (fp->f_type != DTYPE_PROCDESC) {
132 		error = EBADF;
133 		goto out;
134 	}
135 	pd = fp->f_data;
136 	sx_slock(&proctree_lock);
137 	if (pd->pd_proc != NULL) {
138 		*p = pd->pd_proc;
139 		PROC_LOCK(*p);
140 	} else
141 		error = ESRCH;
142 	sx_sunlock(&proctree_lock);
143 out:
144 	fdrop(fp, td);
145 	return (error);
146 }
147 
148 /*
149  * Function to be used by procstat(1) sysctls when returning procdesc
150  * information.
151  */
152 pid_t
153 procdesc_pid(struct file *fp_procdesc)
154 {
155 	struct procdesc *pd;
156 
157 	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
158 	   ("procdesc_pid: !procdesc"));
159 
160 	pd = fp_procdesc->f_data;
161 	return (pd->pd_pid);
162 }
163 
164 /*
165  * Retrieve the PID associated with a process descriptor.
166  */
167 int
168 kern_pdgetpid(struct thread *td, int fd, cap_rights_t *rightsp, pid_t *pidp)
169 {
170 	struct file *fp;
171 	int error;
172 
173 	error = fget(td, fd, rightsp, &fp);
174 	if (error)
175 		return (error);
176 	if (fp->f_type != DTYPE_PROCDESC) {
177 		error = EBADF;
178 		goto out;
179 	}
180 	*pidp = procdesc_pid(fp);
181 out:
182 	fdrop(fp, td);
183 	return (error);
184 }
185 
186 /*
187  * System call to return the pid of a process given its process descriptor.
188  */
189 int
190 sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
191 {
192 	pid_t pid;
193 	int error;
194 
195 	AUDIT_ARG_FD(uap->fd);
196 	error = kern_pdgetpid(td, uap->fd, &cap_pdgetpid_rights, &pid);
197 	if (error == 0)
198 		error = copyout(&pid, uap->pidp, sizeof(pid));
199 	return (error);
200 }
201 
202 /*
203  * When a new process is forked by pdfork(), a file descriptor is allocated
204  * by the fork code first, then the process is forked, and then we get a
205  * chance to set up the process descriptor.  Failure is not permitted at this
206  * point, so procdesc_new() must succeed.
207  */
208 void
209 procdesc_new(struct proc *p, int flags)
210 {
211 	struct procdesc *pd;
212 
213 	pd = malloc(sizeof(*pd), M_PROCDESC, M_WAITOK | M_ZERO);
214 	pd->pd_proc = p;
215 	pd->pd_pid = p->p_pid;
216 	p->p_procdesc = pd;
217 	pd->pd_flags = 0;
218 	if (flags & PD_DAEMON)
219 		pd->pd_flags |= PDF_DAEMON;
220 	PROCDESC_LOCK_INIT(pd);
221 	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
222 
223 	/*
224 	 * Process descriptors start out with two references: one from their
225 	 * struct file, and the other from their struct proc.
226 	 */
227 	refcount_init(&pd->pd_refcount, 2);
228 }
229 
230 /*
231  * Create a new process decriptor for the process that refers to it.
232  */
233 int
234 procdesc_falloc(struct thread *td, struct file **resultfp, int *resultfd,
235     int flags, struct filecaps *fcaps)
236 {
237 	int fflags;
238 
239 	fflags = 0;
240 	if (flags & PD_CLOEXEC)
241 		fflags = O_CLOEXEC;
242 
243 	return (falloc_caps(td, resultfp, resultfd, fflags, fcaps));
244 }
245 
246 /*
247  * Initialize a file with a process descriptor.
248  */
249 void
250 procdesc_finit(struct procdesc *pdp, struct file *fp)
251 {
252 
253 	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
254 }
255 
256 static void
257 procdesc_free(struct procdesc *pd)
258 {
259 
260 	/*
261 	 * When the last reference is released, we assert that the descriptor
262 	 * has been closed, but not that the process has exited, as we will
263 	 * detach the descriptor before the process dies if the descript is
264 	 * closed, as we can't wait synchronously.
265 	 */
266 	if (refcount_release(&pd->pd_refcount)) {
267 		KASSERT(pd->pd_proc == NULL,
268 		    ("procdesc_free: pd_proc != NULL"));
269 		KASSERT((pd->pd_flags & PDF_CLOSED),
270 		    ("procdesc_free: !PDF_CLOSED"));
271 
272 		knlist_destroy(&pd->pd_selinfo.si_note);
273 		PROCDESC_LOCK_DESTROY(pd);
274 		free(pd, M_PROCDESC);
275 	}
276 }
277 
278 /*
279  * procdesc_exit() - notify a process descriptor that its process is exiting.
280  * We use the proctree_lock to ensure that process exit either happens
281  * strictly before or strictly after a concurrent call to procdesc_close().
282  */
283 int
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 	KASSERT(p->p_procdesc != NULL, ("procdesc_exit: p_procdesc NULL"));
291 
292 	pd = p->p_procdesc;
293 
294 	PROCDESC_LOCK(pd);
295 	KASSERT((pd->pd_flags & PDF_CLOSED) == 0 || p->p_pptr == p->p_reaper,
296 	    ("procdesc_exit: closed && parent not reaper"));
297 
298 	pd->pd_flags |= PDF_EXITED;
299 	pd->pd_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
300 
301 	/*
302 	 * If the process descriptor has been closed, then we have nothing
303 	 * to do; return 1 so that init will get SIGCHLD and do the reaping.
304 	 * Clean up the procdesc now rather than letting it happen during
305 	 * that reap.
306 	 */
307 	if (pd->pd_flags & PDF_CLOSED) {
308 		PROCDESC_UNLOCK(pd);
309 		pd->pd_proc = NULL;
310 		p->p_procdesc = NULL;
311 		procdesc_free(pd);
312 		return (1);
313 	}
314 	if (pd->pd_flags & PDF_SELECTED) {
315 		pd->pd_flags &= ~PDF_SELECTED;
316 		selwakeup(&pd->pd_selinfo);
317 	}
318 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT);
319 	PROCDESC_UNLOCK(pd);
320 	return (0);
321 }
322 
323 /*
324  * When a process descriptor is reaped, perhaps as a result of close(), release
325  * the process's reference on the process descriptor.
326  */
327 void
328 procdesc_reap(struct proc *p)
329 {
330 	struct procdesc *pd;
331 
332 	sx_assert(&proctree_lock, SA_XLOCKED);
333 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
334 
335 	pd = p->p_procdesc;
336 	pd->pd_proc = NULL;
337 	p->p_procdesc = NULL;
338 	procdesc_free(pd);
339 }
340 
341 /*
342  * procdesc_close() - last close on a process descriptor.  If the process is
343  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
344  * its reaper clean up the mess; if not, we have to clean up the zombie
345  * ourselves.
346  */
347 static int
348 procdesc_close(struct file *fp, struct thread *td)
349 {
350 	struct procdesc *pd;
351 	struct proc *p;
352 
353 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
354 
355 	pd = fp->f_data;
356 	fp->f_ops = &badfileops;
357 	fp->f_data = NULL;
358 
359 	sx_xlock(&proctree_lock);
360 	PROCDESC_LOCK(pd);
361 	pd->pd_flags |= PDF_CLOSED;
362 	PROCDESC_UNLOCK(pd);
363 	p = pd->pd_proc;
364 	if (p == NULL) {
365 		/*
366 		 * This is the case where process' exit status was already
367 		 * collected and procdesc_reap() was already called.
368 		 */
369 		sx_xunlock(&proctree_lock);
370 	} else {
371 		PROC_LOCK(p);
372 		AUDIT_ARG_PROCESS(p);
373 		if (p->p_state == PRS_ZOMBIE) {
374 			/*
375 			 * If the process is already dead and just awaiting
376 			 * reaping, do that now.  This will release the
377 			 * process's reference to the process descriptor when it
378 			 * calls back into procdesc_reap().
379 			 */
380 			proc_reap(curthread, p, NULL, 0);
381 		} else {
382 			/*
383 			 * If the process is not yet dead, we need to kill it,
384 			 * but we can't wait around synchronously for it to go
385 			 * away, as that path leads to madness (and deadlocks).
386 			 * First, detach the process from its descriptor so that
387 			 * its exit status will be reported normally.
388 			 */
389 			pd->pd_proc = NULL;
390 			p->p_procdesc = NULL;
391 			procdesc_free(pd);
392 
393 			/*
394 			 * Next, reparent it to its reaper (usually init(8)) so
395 			 * that there's someone to pick up the pieces; finally,
396 			 * terminate with prejudice.
397 			 */
398 			p->p_sigparent = SIGCHLD;
399 			if ((p->p_flag & P_TRACED) == 0) {
400 				proc_reparent(p, p->p_reaper, true);
401 			} else {
402 				proc_clear_orphan(p);
403 				p->p_oppid = p->p_reaper->p_pid;
404 				proc_add_orphan(p, p->p_reaper);
405 			}
406 			if ((pd->pd_flags & PDF_DAEMON) == 0)
407 				kern_psignal(p, SIGKILL);
408 			PROC_UNLOCK(p);
409 			sx_xunlock(&proctree_lock);
410 		}
411 	}
412 
413 	/*
414 	 * Release the file descriptor's reference on the process descriptor.
415 	 */
416 	procdesc_free(pd);
417 	return (0);
418 }
419 
420 static int
421 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
422     struct thread *td)
423 {
424 	struct procdesc *pd;
425 	int revents;
426 
427 	revents = 0;
428 	pd = fp->f_data;
429 	PROCDESC_LOCK(pd);
430 	if (pd->pd_flags & PDF_EXITED)
431 		revents |= POLLHUP;
432 	if (revents == 0) {
433 		selrecord(td, &pd->pd_selinfo);
434 		pd->pd_flags |= PDF_SELECTED;
435 	}
436 	PROCDESC_UNLOCK(pd);
437 	return (revents);
438 }
439 
440 static void
441 procdesc_kqops_detach(struct knote *kn)
442 {
443 	struct procdesc *pd;
444 
445 	pd = kn->kn_fp->f_data;
446 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
447 }
448 
449 static int
450 procdesc_kqops_event(struct knote *kn, long hint)
451 {
452 	struct procdesc *pd;
453 	u_int event;
454 
455 	pd = kn->kn_fp->f_data;
456 	if (hint == 0) {
457 		/*
458 		 * Initial test after registration. Generate a NOTE_EXIT in
459 		 * case the process already terminated before registration.
460 		 */
461 		event = pd->pd_flags & PDF_EXITED ? NOTE_EXIT : 0;
462 	} else {
463 		/* Mask off extra data. */
464 		event = (u_int)hint & NOTE_PCTRLMASK;
465 	}
466 
467 	/* If the user is interested in this event, record it. */
468 	if (kn->kn_sfflags & event)
469 		kn->kn_fflags |= event;
470 
471 	/* Process is gone, so flag the event as finished. */
472 	if (event == NOTE_EXIT) {
473 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
474 		if (kn->kn_fflags & NOTE_EXIT)
475 			kn->kn_data = pd->pd_xstat;
476 		if (kn->kn_fflags == 0)
477 			kn->kn_flags |= EV_DROP;
478 		return (1);
479 	}
480 
481 	return (kn->kn_fflags != 0);
482 }
483 
484 static struct filterops procdesc_kqops = {
485 	.f_isfd = 1,
486 	.f_detach = procdesc_kqops_detach,
487 	.f_event = procdesc_kqops_event,
488 };
489 
490 static int
491 procdesc_kqfilter(struct file *fp, struct knote *kn)
492 {
493 	struct procdesc *pd;
494 
495 	pd = fp->f_data;
496 	switch (kn->kn_filter) {
497 	case EVFILT_PROCDESC:
498 		kn->kn_fop = &procdesc_kqops;
499 		kn->kn_flags |= EV_CLEAR;
500 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
501 		return (0);
502 	default:
503 		return (EINVAL);
504 	}
505 }
506 
507 static int
508 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
509 {
510 	struct procdesc *pd;
511 	struct timeval pstart, boottime;
512 
513 	/*
514 	 * XXXRW: Perhaps we should cache some more information from the
515 	 * process so that we can return it reliably here even after it has
516 	 * died.  For example, caching its credential data.
517 	 */
518 	bzero(sb, sizeof(*sb));
519 	pd = fp->f_data;
520 	sx_slock(&proctree_lock);
521 	if (pd->pd_proc != NULL) {
522 		PROC_LOCK(pd->pd_proc);
523 		AUDIT_ARG_PROCESS(pd->pd_proc);
524 
525 		/* Set birth and [acm] times to process start time. */
526 		pstart = pd->pd_proc->p_stats->p_start;
527 		getboottime(&boottime);
528 		timevaladd(&pstart, &boottime);
529 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
530 		sb->st_atim = sb->st_birthtim;
531 		sb->st_ctim = sb->st_birthtim;
532 		sb->st_mtim = sb->st_birthtim;
533 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
534 			sb->st_mode = S_IFREG | S_IRWXU;
535 		else
536 			sb->st_mode = S_IFREG;
537 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
538 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
539 		PROC_UNLOCK(pd->pd_proc);
540 	} else
541 		sb->st_mode = S_IFREG;
542 	sx_sunlock(&proctree_lock);
543 	return (0);
544 }
545 
546 static int
547 procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
548     struct filedesc *fdp)
549 {
550 	struct procdesc *pdp;
551 
552 	kif->kf_type = KF_TYPE_PROCDESC;
553 	pdp = fp->f_data;
554 	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
555 	return (0);
556 }
557 
558 static int
559 procdesc_cmp(struct file *fp1, struct file *fp2, struct thread *td)
560 {
561 	struct procdesc *pdp1, *pdp2;
562 
563 	if (fp2->f_type != DTYPE_PROCDESC)
564 		return (3);
565 	pdp1 = fp1->f_data;
566 	pdp2 = fp2->f_data;
567 	return (kcmp_cmp((uintptr_t)pdp1->pd_pid, (uintptr_t)pdp2->pd_pid));
568 }
569