xref: /freebsd/sys/kern/sys_procdesc.c (revision 240c614d48cb0484bfe7876decdf6bbdcc99ba73)
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 		knlist_destroy(&pd->pd_selinfo.si_note);
278 		PROCDESC_LOCK_DESTROY(pd);
279 		free(pd, M_PROCDESC);
280 	}
281 }
282 
283 /*
284  * procdesc_exit() - notify a process descriptor that its process is exiting.
285  * We use the proctree_lock to ensure that process exit either happens
286  * strictly before or strictly after a concurrent call to procdesc_close().
287  */
288 int
289 procdesc_exit(struct proc *p)
290 {
291 	struct procdesc *pd;
292 
293 	sx_assert(&proctree_lock, SA_XLOCKED);
294 	PROC_LOCK_ASSERT(p, MA_OWNED);
295 	KASSERT(p->p_procdesc != NULL, ("procdesc_exit: p_procdesc NULL"));
296 
297 	pd = p->p_procdesc;
298 
299 	PROCDESC_LOCK(pd);
300 	KASSERT((pd->pd_flags & PDF_CLOSED) == 0 || p->p_pptr == p->p_reaper,
301 	    ("procdesc_exit: closed && parent not reaper"));
302 
303 	pd->pd_flags |= PDF_EXITED;
304 	pd->pd_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
305 
306 	/*
307 	 * If the process descriptor has been closed, then we have nothing
308 	 * to do; return 1 so that init will get SIGCHLD and do the reaping.
309 	 * Clean up the procdesc now rather than letting it happen during
310 	 * that reap.
311 	 */
312 	if (pd->pd_flags & PDF_CLOSED) {
313 		PROCDESC_UNLOCK(pd);
314 		pd->pd_proc = NULL;
315 		p->p_procdesc = NULL;
316 		procdesc_free(pd);
317 		return (1);
318 	}
319 	if (pd->pd_flags & PDF_SELECTED) {
320 		pd->pd_flags &= ~PDF_SELECTED;
321 		selwakeup(&pd->pd_selinfo);
322 	}
323 	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT);
324 	PROCDESC_UNLOCK(pd);
325 
326 	/* Wakeup all waiters for this procdesc' process exit. */
327 	wakeup(&p->p_procdesc);
328 	return (0);
329 }
330 
331 /*
332  * When a process descriptor is reaped, perhaps as a result of close(), release
333  * the process's reference on the process descriptor.
334  */
335 void
336 procdesc_reap(struct proc *p)
337 {
338 	struct procdesc *pd;
339 
340 	sx_assert(&proctree_lock, SA_XLOCKED);
341 	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
342 
343 	pd = p->p_procdesc;
344 	pd->pd_proc = NULL;
345 	p->p_procdesc = NULL;
346 	procdesc_free(pd);
347 }
348 
349 /*
350  * procdesc_close() - last close on a process descriptor.  If the process is
351  * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
352  * its reaper clean up the mess; if not, we have to clean up the zombie
353  * ourselves.
354  */
355 static int
356 procdesc_close(struct file *fp, struct thread *td)
357 {
358 	struct procdesc *pd;
359 	struct proc *p;
360 
361 	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
362 
363 	pd = fp->f_data;
364 	fp->f_ops = &badfileops;
365 	fp->f_data = NULL;
366 
367 	sx_xlock(&proctree_lock);
368 	PROCDESC_LOCK(pd);
369 	pd->pd_flags |= PDF_CLOSED;
370 	PROCDESC_UNLOCK(pd);
371 	p = pd->pd_proc;
372 	if (p == NULL) {
373 		/*
374 		 * This is the case where process' exit status was already
375 		 * collected and procdesc_reap() was already called.
376 		 */
377 		sx_xunlock(&proctree_lock);
378 	} else {
379 		PROC_LOCK(p);
380 		AUDIT_ARG_PROCESS(p);
381 		if (p->p_state == PRS_ZOMBIE) {
382 			/*
383 			 * If the process is already dead and just awaiting
384 			 * reaping, do that now.  This will release the
385 			 * process's reference to the process descriptor when it
386 			 * calls back into procdesc_reap().
387 			 */
388 			proc_reap(curthread, p, NULL, 0);
389 		} else {
390 			/*
391 			 * If the process is not yet dead, we need to kill it,
392 			 * but we can't wait around synchronously for it to go
393 			 * away, as that path leads to madness (and deadlocks).
394 			 * First, detach the process from its descriptor so that
395 			 * its exit status will be reported normally.
396 			 */
397 			pd->pd_proc = NULL;
398 			p->p_procdesc = NULL;
399 			pd->pd_pid = -1;
400 			procdesc_free(pd);
401 
402 			/*
403 			 * Next, reparent it to its reaper (usually init(8)) so
404 			 * that there's someone to pick up the pieces; finally,
405 			 * terminate with prejudice.
406 			 */
407 			p->p_sigparent = SIGCHLD;
408 			if ((p->p_flag & P_TRACED) == 0) {
409 				proc_reparent(p, p->p_reaper, true);
410 			} else {
411 				proc_clear_orphan(p);
412 				p->p_oppid = p->p_reaper->p_pid;
413 				proc_add_orphan(p, p->p_reaper);
414 			}
415 			if ((pd->pd_flags & PDF_DAEMON) == 0)
416 				kern_psignal(p, SIGKILL);
417 			PROC_UNLOCK(p);
418 			sx_xunlock(&proctree_lock);
419 		}
420 	}
421 
422 	/*
423 	 * Release the file descriptor's reference on the process descriptor.
424 	 */
425 	procdesc_free(pd);
426 	return (0);
427 }
428 
429 static int
430 procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
431     struct thread *td)
432 {
433 	struct procdesc *pd;
434 	int revents;
435 
436 	revents = 0;
437 	pd = fp->f_data;
438 	PROCDESC_LOCK(pd);
439 	if (pd->pd_flags & PDF_EXITED)
440 		revents |= POLLHUP;
441 	if (revents == 0) {
442 		selrecord(td, &pd->pd_selinfo);
443 		pd->pd_flags |= PDF_SELECTED;
444 	}
445 	PROCDESC_UNLOCK(pd);
446 	return (revents);
447 }
448 
449 static void
450 procdesc_kqops_detach(struct knote *kn)
451 {
452 	struct procdesc *pd;
453 
454 	pd = kn->kn_fp->f_data;
455 	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
456 }
457 
458 static int
459 procdesc_kqops_event(struct knote *kn, long hint)
460 {
461 	struct procdesc *pd;
462 	u_int event;
463 
464 	pd = kn->kn_fp->f_data;
465 	if (hint == 0) {
466 		/*
467 		 * Initial test after registration. Generate a NOTE_EXIT in
468 		 * case the process already terminated before registration.
469 		 */
470 		event = pd->pd_flags & PDF_EXITED ? NOTE_EXIT : 0;
471 	} else {
472 		/* Mask off extra data. */
473 		event = (u_int)hint & NOTE_PCTRLMASK;
474 	}
475 
476 	/* If the user is interested in this event, record it. */
477 	if (kn->kn_sfflags & event)
478 		kn->kn_fflags |= event;
479 
480 	/* Process is gone, so flag the event as finished. */
481 	if (event == NOTE_EXIT) {
482 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
483 		if (kn->kn_fflags & NOTE_EXIT)
484 			kn->kn_data = pd->pd_xstat;
485 		if (kn->kn_fflags == 0)
486 			kn->kn_flags |= EV_DROP;
487 		return (1);
488 	}
489 
490 	return (kn->kn_fflags != 0);
491 }
492 
493 static const struct filterops procdesc_kqops = {
494 	.f_isfd = 1,
495 	.f_detach = procdesc_kqops_detach,
496 	.f_event = procdesc_kqops_event,
497 	.f_copy = knote_triv_copy,
498 };
499 
500 static int
501 procdesc_kqfilter(struct file *fp, struct knote *kn)
502 {
503 	struct procdesc *pd;
504 
505 	pd = fp->f_data;
506 	switch (kn->kn_filter) {
507 	case EVFILT_PROCDESC:
508 		kn->kn_fop = &procdesc_kqops;
509 		kn->kn_flags |= EV_CLEAR;
510 		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
511 		return (0);
512 	default:
513 		return (EINVAL);
514 	}
515 }
516 
517 static int
518 procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
519 {
520 	struct procdesc *pd;
521 	struct timeval pstart, boottime;
522 
523 	/*
524 	 * XXXRW: Perhaps we should cache some more information from the
525 	 * process so that we can return it reliably here even after it has
526 	 * died.  For example, caching its credential data.
527 	 */
528 	bzero(sb, sizeof(*sb));
529 	pd = fp->f_data;
530 	sx_slock(&proctree_lock);
531 	if (pd->pd_proc != NULL) {
532 		PROC_LOCK(pd->pd_proc);
533 		AUDIT_ARG_PROCESS(pd->pd_proc);
534 
535 		/* Set birth and [acm] times to process start time. */
536 		pstart = pd->pd_proc->p_stats->p_start;
537 		getboottime(&boottime);
538 		timevaladd(&pstart, &boottime);
539 		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
540 		sb->st_atim = sb->st_birthtim;
541 		sb->st_ctim = sb->st_birthtim;
542 		sb->st_mtim = sb->st_birthtim;
543 		if (pd->pd_proc->p_state != PRS_ZOMBIE)
544 			sb->st_mode = S_IFREG | S_IRWXU;
545 		else
546 			sb->st_mode = S_IFREG;
547 		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
548 		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
549 		PROC_UNLOCK(pd->pd_proc);
550 	} else
551 		sb->st_mode = S_IFREG;
552 	sx_sunlock(&proctree_lock);
553 	return (0);
554 }
555 
556 static int
557 procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
558     struct filedesc *fdp)
559 {
560 	struct procdesc *pdp;
561 
562 	kif->kf_type = KF_TYPE_PROCDESC;
563 	pdp = fp->f_data;
564 	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
565 	return (0);
566 }
567 
568 static int
569 procdesc_cmp(struct file *fp1, struct file *fp2, struct thread *td)
570 {
571 	struct procdesc *pdp1, *pdp2;
572 
573 	if (fp2->f_type != DTYPE_PROCDESC)
574 		return (3);
575 	pdp1 = fp1->f_data;
576 	pdp2 = fp2->f_data;
577 	return (kcmp_cmp((uintptr_t)pdp1->pd_pid, (uintptr_t)pdp2->pd_pid));
578 }
579