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