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