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