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