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