1/*-
2 * Copyright (c) 2009, 2016 Robert N. M. Watson
3 * All rights reserved.
4 *
5 * This software was developed at the University of Cambridge Computer
6 * Laboratory with support from a grant from Google, Inc.
7 *
8 * Portions of this software were developed by BAE Systems, the University of
9 * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
10 * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
11 * Computing (TC) research program.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 *    notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 *    notice, this list of conditions and the following disclaimer in the
20 *    documentation and/or other materials provided with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35/*-
36 * FreeBSD process descriptor facility.
37 *
38 * Some processes are represented by a file descriptor, which will be used in
39 * preference to signaling and pids for the purposes of process management,
40 * and is, in effect, a form of capability.  When a process descriptor is
41 * used with a process, it ceases to be visible to certain traditional UNIX
42 * process facilities, such as waitpid(2).
43 *
44 * Some semantics:
45 *
46 * - At most one process descriptor will exist for any process, although
47 *   references to that descriptor may be held from many processes (or even
48 *   be in flight between processes over a local domain socket).
49 * - Last close on the process descriptor will terminate the process using
50 *   SIGKILL and reparent it to init so that there's a process to reap it
51 *   when it's done exiting.
52 * - If the process exits before the descriptor is closed, it will not
53 *   generate SIGCHLD on termination, or be picked up by waitpid().
54 * - The pdkill(2) system call may be used to deliver a signal to the process
55 *   using its process descriptor.
56 * - The pdwait4(2) system call may be used to block (or not) on a process
57 *   descriptor to collect termination information.
58 *
59 * Open questions:
60 *
61 * - How to handle ptrace(2)?
62 * - Will we want to add a pidtoprocdesc(2) system call to allow process
63 *   descriptors to be created for processes without pdfork(2)?
64 */
65
66#include <sys/cdefs.h>
67__FBSDID("$FreeBSD: stable/11/sys/kern/sys_procdesc.c 330964 2018-03-15 02:20:06Z eadler $");
68
69#include <sys/param.h>
70#include <sys/capsicum.h>
71#include <sys/fcntl.h>
72#include <sys/file.h>
73#include <sys/filedesc.h>
74#include <sys/kernel.h>
75#include <sys/lock.h>
76#include <sys/mutex.h>
77#include <sys/poll.h>
78#include <sys/proc.h>
79#include <sys/procdesc.h>
80#include <sys/resourcevar.h>
81#include <sys/stat.h>
82#include <sys/sysproto.h>
83#include <sys/sysctl.h>
84#include <sys/systm.h>
85#include <sys/ucred.h>
86#include <sys/user.h>
87
88#include <security/audit/audit.h>
89
90#include <vm/uma.h>
91
92FEATURE(process_descriptors, "Process Descriptors");
93
94static uma_zone_t procdesc_zone;
95
96static fo_poll_t	procdesc_poll;
97static fo_kqfilter_t	procdesc_kqfilter;
98static fo_stat_t	procdesc_stat;
99static fo_close_t	procdesc_close;
100static fo_fill_kinfo_t	procdesc_fill_kinfo;
101
102static struct fileops procdesc_ops = {
103	.fo_read = invfo_rdwr,
104	.fo_write = invfo_rdwr,
105	.fo_truncate = invfo_truncate,
106	.fo_ioctl = invfo_ioctl,
107	.fo_poll = procdesc_poll,
108	.fo_kqfilter = procdesc_kqfilter,
109	.fo_stat = procdesc_stat,
110	.fo_close = procdesc_close,
111	.fo_chmod = invfo_chmod,
112	.fo_chown = invfo_chown,
113	.fo_sendfile = invfo_sendfile,
114	.fo_fill_kinfo = procdesc_fill_kinfo,
115	.fo_flags = DFLAG_PASSABLE,
116};
117
118/*
119 * Initialize with VFS so that process descriptors are available along with
120 * other file descriptor types.  As long as it runs before init(8) starts,
121 * there shouldn't be a problem.
122 */
123static void
124procdesc_init(void *dummy __unused)
125{
126
127	procdesc_zone = uma_zcreate("procdesc", sizeof(struct procdesc),
128	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
129	if (procdesc_zone == NULL)
130		panic("procdesc_init: procdesc_zone not initialized");
131}
132SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_ANY, procdesc_init, NULL);
133
134/*
135 * Return a locked process given a process descriptor, or ESRCH if it has
136 * died.
137 */
138int
139procdesc_find(struct thread *td, int fd, cap_rights_t *rightsp,
140    struct proc **p)
141{
142	struct procdesc *pd;
143	struct file *fp;
144	int error;
145
146	error = fget(td, fd, rightsp, &fp);
147	if (error)
148		return (error);
149	if (fp->f_type != DTYPE_PROCDESC) {
150		error = EBADF;
151		goto out;
152	}
153	pd = fp->f_data;
154	sx_slock(&proctree_lock);
155	if (pd->pd_proc != NULL) {
156		*p = pd->pd_proc;
157		PROC_LOCK(*p);
158	} else
159		error = ESRCH;
160	sx_sunlock(&proctree_lock);
161out:
162	fdrop(fp, td);
163	return (error);
164}
165
166/*
167 * Function to be used by procstat(1) sysctls when returning procdesc
168 * information.
169 */
170pid_t
171procdesc_pid(struct file *fp_procdesc)
172{
173	struct procdesc *pd;
174
175	KASSERT(fp_procdesc->f_type == DTYPE_PROCDESC,
176	   ("procdesc_pid: !procdesc"));
177
178	pd = fp_procdesc->f_data;
179	return (pd->pd_pid);
180}
181
182/*
183 * Retrieve the PID associated with a process descriptor.
184 */
185int
186kern_pdgetpid(struct thread *td, int fd, cap_rights_t *rightsp, pid_t *pidp)
187{
188	struct file *fp;
189	int error;
190
191	error = fget(td, fd, rightsp, &fp);
192	if (error)
193		return (error);
194	if (fp->f_type != DTYPE_PROCDESC) {
195		error = EBADF;
196		goto out;
197	}
198	*pidp = procdesc_pid(fp);
199out:
200	fdrop(fp, td);
201	return (error);
202}
203
204/*
205 * System call to return the pid of a process given its process descriptor.
206 */
207int
208sys_pdgetpid(struct thread *td, struct pdgetpid_args *uap)
209{
210	cap_rights_t rights;
211	pid_t pid;
212	int error;
213
214	AUDIT_ARG_FD(uap->fd);
215	error = kern_pdgetpid(td, uap->fd,
216	    cap_rights_init(&rights, CAP_PDGETPID), &pid);
217	if (error == 0)
218		error = copyout(&pid, uap->pidp, sizeof(pid));
219	return (error);
220}
221
222/*
223 * When a new process is forked by pdfork(), a file descriptor is allocated
224 * by the fork code first, then the process is forked, and then we get a
225 * chance to set up the process descriptor.  Failure is not permitted at this
226 * point, so procdesc_new() must succeed.
227 */
228void
229procdesc_new(struct proc *p, int flags)
230{
231	struct procdesc *pd;
232
233	pd = uma_zalloc(procdesc_zone, M_WAITOK | M_ZERO);
234	pd->pd_proc = p;
235	pd->pd_pid = p->p_pid;
236	p->p_procdesc = pd;
237	pd->pd_flags = 0;
238	if (flags & PD_DAEMON)
239		pd->pd_flags |= PDF_DAEMON;
240	PROCDESC_LOCK_INIT(pd);
241	knlist_init_mtx(&pd->pd_selinfo.si_note, &pd->pd_lock);
242
243	/*
244	 * Process descriptors start out with two references: one from their
245	 * struct file, and the other from their struct proc.
246	 */
247	refcount_init(&pd->pd_refcount, 2);
248}
249
250/*
251 * Create a new process decriptor for the process that refers to it.
252 */
253int
254procdesc_falloc(struct thread *td, struct file **resultfp, int *resultfd,
255    int flags, struct filecaps *fcaps)
256{
257	int fflags;
258
259	fflags = 0;
260	if (flags & PD_CLOEXEC)
261		fflags = O_CLOEXEC;
262
263	return (falloc_caps(td, resultfp, resultfd, fflags, fcaps));
264}
265
266/*
267 * Initialize a file with a process descriptor.
268 */
269void
270procdesc_finit(struct procdesc *pdp, struct file *fp)
271{
272
273	finit(fp, FREAD | FWRITE, DTYPE_PROCDESC, pdp, &procdesc_ops);
274}
275
276static void
277procdesc_free(struct procdesc *pd)
278{
279
280	/*
281	 * When the last reference is released, we assert that the descriptor
282	 * has been closed, but not that the process has exited, as we will
283	 * detach the descriptor before the process dies if the descript is
284	 * closed, as we can't wait synchronously.
285	 */
286	if (refcount_release(&pd->pd_refcount)) {
287		KASSERT(pd->pd_proc == NULL,
288		    ("procdesc_free: pd_proc != NULL"));
289		KASSERT((pd->pd_flags & PDF_CLOSED),
290		    ("procdesc_free: !PDF_CLOSED"));
291
292		knlist_destroy(&pd->pd_selinfo.si_note);
293		PROCDESC_LOCK_DESTROY(pd);
294		uma_zfree(procdesc_zone, pd);
295	}
296}
297
298/*
299 * procdesc_exit() - notify a process descriptor that its process is exiting.
300 * We use the proctree_lock to ensure that process exit either happens
301 * strictly before or strictly after a concurrent call to procdesc_close().
302 */
303int
304procdesc_exit(struct proc *p)
305{
306	struct procdesc *pd;
307
308	sx_assert(&proctree_lock, SA_XLOCKED);
309	PROC_LOCK_ASSERT(p, MA_OWNED);
310	KASSERT(p->p_procdesc != NULL, ("procdesc_exit: p_procdesc NULL"));
311
312	pd = p->p_procdesc;
313
314	PROCDESC_LOCK(pd);
315	KASSERT((pd->pd_flags & PDF_CLOSED) == 0 || p->p_pptr == initproc,
316	    ("procdesc_exit: closed && parent not init"));
317
318	pd->pd_flags |= PDF_EXITED;
319	pd->pd_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
320
321	/*
322	 * If the process descriptor has been closed, then we have nothing
323	 * to do; return 1 so that init will get SIGCHLD and do the reaping.
324	 * Clean up the procdesc now rather than letting it happen during
325	 * that reap.
326	 */
327	if (pd->pd_flags & PDF_CLOSED) {
328		PROCDESC_UNLOCK(pd);
329		pd->pd_proc = NULL;
330		p->p_procdesc = NULL;
331		procdesc_free(pd);
332		return (1);
333	}
334	if (pd->pd_flags & PDF_SELECTED) {
335		pd->pd_flags &= ~PDF_SELECTED;
336		selwakeup(&pd->pd_selinfo);
337	}
338	KNOTE_LOCKED(&pd->pd_selinfo.si_note, NOTE_EXIT);
339	PROCDESC_UNLOCK(pd);
340	return (0);
341}
342
343/*
344 * When a process descriptor is reaped, perhaps as a result of close() or
345 * pdwait4(), release the process's reference on the process descriptor.
346 */
347void
348procdesc_reap(struct proc *p)
349{
350	struct procdesc *pd;
351
352	sx_assert(&proctree_lock, SA_XLOCKED);
353	KASSERT(p->p_procdesc != NULL, ("procdesc_reap: p_procdesc == NULL"));
354
355	pd = p->p_procdesc;
356	pd->pd_proc = NULL;
357	p->p_procdesc = NULL;
358	procdesc_free(pd);
359}
360
361/*
362 * procdesc_close() - last close on a process descriptor.  If the process is
363 * still running, terminate with SIGKILL (unless PDF_DAEMON is set) and let
364 * init(8) clean up the mess; if not, we have to clean up the zombie ourselves.
365 */
366static int
367procdesc_close(struct file *fp, struct thread *td)
368{
369	struct procdesc *pd;
370	struct proc *p;
371
372	KASSERT(fp->f_type == DTYPE_PROCDESC, ("procdesc_close: !procdesc"));
373
374	pd = fp->f_data;
375	fp->f_ops = &badfileops;
376	fp->f_data = NULL;
377
378	sx_xlock(&proctree_lock);
379	PROCDESC_LOCK(pd);
380	pd->pd_flags |= PDF_CLOSED;
381	PROCDESC_UNLOCK(pd);
382	p = pd->pd_proc;
383	if (p == NULL) {
384		/*
385		 * This is the case where process' exit status was already
386		 * collected and procdesc_reap() was already called.
387		 */
388		sx_xunlock(&proctree_lock);
389	} else {
390		PROC_LOCK(p);
391		AUDIT_ARG_PROCESS(p);
392		if (p->p_state == PRS_ZOMBIE) {
393			/*
394			 * If the process is already dead and just awaiting
395			 * reaping, do that now.  This will release the
396			 * process's reference to the process descriptor when it
397			 * calls back into procdesc_reap().
398			 */
399			PROC_SLOCK(p);
400			proc_reap(curthread, p, NULL, 0);
401		} else {
402			/*
403			 * If the process is not yet dead, we need to kill it,
404			 * but we can't wait around synchronously for it to go
405			 * away, as that path leads to madness (and deadlocks).
406			 * First, detach the process from its descriptor so that
407			 * its exit status will be reported normally.
408			 */
409			pd->pd_proc = NULL;
410			p->p_procdesc = NULL;
411			procdesc_free(pd);
412
413			/*
414			 * Next, reparent it to init(8) so that there's someone
415			 * to pick up the pieces; finally, terminate with
416			 * prejudice.
417			 */
418			p->p_sigparent = SIGCHLD;
419			proc_reparent(p, initproc);
420			if ((pd->pd_flags & PDF_DAEMON) == 0)
421				kern_psignal(p, SIGKILL);
422			PROC_UNLOCK(p);
423			sx_xunlock(&proctree_lock);
424		}
425	}
426
427	/*
428	 * Release the file descriptor's reference on the process descriptor.
429	 */
430	procdesc_free(pd);
431	return (0);
432}
433
434static int
435procdesc_poll(struct file *fp, int events, struct ucred *active_cred,
436    struct thread *td)
437{
438	struct procdesc *pd;
439	int revents;
440
441	revents = 0;
442	pd = fp->f_data;
443	PROCDESC_LOCK(pd);
444	if (pd->pd_flags & PDF_EXITED)
445		revents |= POLLHUP;
446	if (revents == 0) {
447		selrecord(td, &pd->pd_selinfo);
448		pd->pd_flags |= PDF_SELECTED;
449	}
450	PROCDESC_UNLOCK(pd);
451	return (revents);
452}
453
454static void
455procdesc_kqops_detach(struct knote *kn)
456{
457	struct procdesc *pd;
458
459	pd = kn->kn_fp->f_data;
460	knlist_remove(&pd->pd_selinfo.si_note, kn, 0);
461}
462
463static int
464procdesc_kqops_event(struct knote *kn, long hint)
465{
466	struct procdesc *pd;
467	u_int event;
468
469	pd = kn->kn_fp->f_data;
470	if (hint == 0) {
471		/*
472		 * Initial test after registration. Generate a NOTE_EXIT in
473		 * case the process already terminated before registration.
474		 */
475		event = pd->pd_flags & PDF_EXITED ? NOTE_EXIT : 0;
476	} else {
477		/* Mask off extra data. */
478		event = (u_int)hint & NOTE_PCTRLMASK;
479	}
480
481	/* If the user is interested in this event, record it. */
482	if (kn->kn_sfflags & event)
483		kn->kn_fflags |= event;
484
485	/* Process is gone, so flag the event as finished. */
486	if (event == NOTE_EXIT) {
487		kn->kn_flags |= EV_EOF | EV_ONESHOT;
488		if (kn->kn_fflags & NOTE_EXIT)
489			kn->kn_data = pd->pd_xstat;
490		if (kn->kn_fflags == 0)
491			kn->kn_flags |= EV_DROP;
492		return (1);
493	}
494
495	return (kn->kn_fflags != 0);
496}
497
498static struct filterops procdesc_kqops = {
499	.f_isfd = 1,
500	.f_detach = procdesc_kqops_detach,
501	.f_event = procdesc_kqops_event,
502};
503
504static int
505procdesc_kqfilter(struct file *fp, struct knote *kn)
506{
507	struct procdesc *pd;
508
509	pd = fp->f_data;
510	switch (kn->kn_filter) {
511	case EVFILT_PROCDESC:
512		kn->kn_fop = &procdesc_kqops;
513		kn->kn_flags |= EV_CLEAR;
514		knlist_add(&pd->pd_selinfo.si_note, kn, 0);
515		return (0);
516	default:
517		return (EINVAL);
518	}
519}
520
521static int
522procdesc_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
523    struct thread *td)
524{
525	struct procdesc *pd;
526	struct timeval pstart, boottime;
527
528	/*
529	 * XXXRW: Perhaps we should cache some more information from the
530	 * process so that we can return it reliably here even after it has
531	 * died.  For example, caching its credential data.
532	 */
533	bzero(sb, sizeof(*sb));
534	pd = fp->f_data;
535	sx_slock(&proctree_lock);
536	if (pd->pd_proc != NULL) {
537		PROC_LOCK(pd->pd_proc);
538		AUDIT_ARG_PROCESS(pd->pd_proc);
539
540		/* Set birth and [acm] times to process start time. */
541		pstart = pd->pd_proc->p_stats->p_start;
542		getboottime(&boottime);
543		timevaladd(&pstart, &boottime);
544		TIMEVAL_TO_TIMESPEC(&pstart, &sb->st_birthtim);
545		sb->st_atim = sb->st_birthtim;
546		sb->st_ctim = sb->st_birthtim;
547		sb->st_mtim = sb->st_birthtim;
548		if (pd->pd_proc->p_state != PRS_ZOMBIE)
549			sb->st_mode = S_IFREG | S_IRWXU;
550		else
551			sb->st_mode = S_IFREG;
552		sb->st_uid = pd->pd_proc->p_ucred->cr_ruid;
553		sb->st_gid = pd->pd_proc->p_ucred->cr_rgid;
554		PROC_UNLOCK(pd->pd_proc);
555	} else
556		sb->st_mode = S_IFREG;
557	sx_sunlock(&proctree_lock);
558	return (0);
559}
560
561static int
562procdesc_fill_kinfo(struct file *fp, struct kinfo_file *kif,
563    struct filedesc *fdp)
564{
565	struct procdesc *pdp;
566
567	kif->kf_type = KF_TYPE_PROCDESC;
568	pdp = fp->f_data;
569	kif->kf_un.kf_proc.kf_pid = pdp->pd_pid;
570	return (0);
571}
572