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