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