kern_jail.c revision 298565
1/*-
2 * Copyright (c) 1999 Poul-Henning Kamp.
3 * Copyright (c) 2008 Bjoern A. Zeeb.
4 * Copyright (c) 2009 James Gritton.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/kern/kern_jail.c 298565 2016-04-25 04:24:00Z jamie $");
31
32#include "opt_compat.h"
33#include "opt_ddb.h"
34#include "opt_inet.h"
35#include "opt_inet6.h"
36
37#include <sys/param.h>
38#include <sys/types.h>
39#include <sys/kernel.h>
40#include <sys/systm.h>
41#include <sys/errno.h>
42#include <sys/sysproto.h>
43#include <sys/malloc.h>
44#include <sys/osd.h>
45#include <sys/priv.h>
46#include <sys/proc.h>
47#include <sys/taskqueue.h>
48#include <sys/fcntl.h>
49#include <sys/jail.h>
50#include <sys/lock.h>
51#include <sys/mutex.h>
52#include <sys/racct.h>
53#include <sys/refcount.h>
54#include <sys/sx.h>
55#include <sys/sysent.h>
56#include <sys/namei.h>
57#include <sys/mount.h>
58#include <sys/queue.h>
59#include <sys/socket.h>
60#include <sys/syscallsubr.h>
61#include <sys/sysctl.h>
62#include <sys/vnode.h>
63
64#include <net/if.h>
65#include <net/vnet.h>
66
67#include <netinet/in.h>
68
69#ifdef DDB
70#include <ddb/ddb.h>
71#endif /* DDB */
72
73#include <security/mac/mac_framework.h>
74
75#define	DEFAULT_HOSTUUID	"00000000-0000-0000-0000-000000000000"
76
77MALLOC_DEFINE(M_PRISON, "prison", "Prison structures");
78static MALLOC_DEFINE(M_PRISON_RACCT, "prison_racct", "Prison racct structures");
79
80/* Keep struct prison prison0 and some code in kern_jail_set() readable. */
81#ifdef INET
82#ifdef INET6
83#define	_PR_IP_SADDRSEL	PR_IP4_SADDRSEL|PR_IP6_SADDRSEL
84#else
85#define	_PR_IP_SADDRSEL	PR_IP4_SADDRSEL
86#endif
87#else /* !INET */
88#ifdef INET6
89#define	_PR_IP_SADDRSEL	PR_IP6_SADDRSEL
90#else
91#define	_PR_IP_SADDRSEL	0
92#endif
93#endif
94
95/* prison0 describes what is "real" about the system. */
96struct prison prison0 = {
97	.pr_id		= 0,
98	.pr_name	= "0",
99	.pr_ref		= 1,
100	.pr_uref	= 1,
101	.pr_path	= "/",
102	.pr_securelevel	= -1,
103	.pr_devfs_rsnum = 0,
104	.pr_childmax	= JAIL_MAX,
105	.pr_hostuuid	= DEFAULT_HOSTUUID,
106	.pr_children	= LIST_HEAD_INITIALIZER(prison0.pr_children),
107#ifdef VIMAGE
108	.pr_flags	= PR_HOST|PR_VNET|_PR_IP_SADDRSEL,
109#else
110	.pr_flags	= PR_HOST|_PR_IP_SADDRSEL,
111#endif
112	.pr_allow	= PR_ALLOW_ALL,
113};
114MTX_SYSINIT(prison0, &prison0.pr_mtx, "jail mutex", MTX_DEF);
115
116/* allprison, allprison_racct and lastprid are protected by allprison_lock. */
117struct	sx allprison_lock;
118SX_SYSINIT(allprison_lock, &allprison_lock, "allprison");
119struct	prisonlist allprison = TAILQ_HEAD_INITIALIZER(allprison);
120LIST_HEAD(, prison_racct) allprison_racct;
121int	lastprid = 0;
122
123static int do_jail_attach(struct thread *td, struct prison *pr);
124static void prison_complete(void *context, int pending);
125static void prison_deref(struct prison *pr, int flags);
126static char *prison_path(struct prison *pr1, struct prison *pr2);
127static void prison_remove_one(struct prison *pr);
128#ifdef RACCT
129static void prison_racct_attach(struct prison *pr);
130static void prison_racct_modify(struct prison *pr);
131static void prison_racct_detach(struct prison *pr);
132#endif
133#ifdef INET
134static int _prison_check_ip4(const struct prison *, const struct in_addr *);
135static int prison_restrict_ip4(struct prison *pr, struct in_addr *newip4);
136#endif
137#ifdef INET6
138static int _prison_check_ip6(struct prison *pr, struct in6_addr *ia6);
139static int prison_restrict_ip6(struct prison *pr, struct in6_addr *newip6);
140#endif
141
142/* Flags for prison_deref */
143#define	PD_DEREF	0x01
144#define	PD_DEUREF	0x02
145#define	PD_LOCKED	0x04
146#define	PD_LIST_SLOCKED	0x08
147#define	PD_LIST_XLOCKED	0x10
148
149/*
150 * Parameter names corresponding to PR_* flag values.  Size values are for kvm
151 * as we cannot figure out the size of a sparse array, or an array without a
152 * terminating entry.
153 */
154static char *pr_flag_names[] = {
155	[0] = "persist",
156#ifdef INET
157	[7] = "ip4.saddrsel",
158#endif
159#ifdef INET6
160	[8] = "ip6.saddrsel",
161#endif
162};
163const size_t pr_flag_names_size = sizeof(pr_flag_names);
164
165static char *pr_flag_nonames[] = {
166	[0] = "nopersist",
167#ifdef INET
168	[7] = "ip4.nosaddrsel",
169#endif
170#ifdef INET6
171	[8] = "ip6.nosaddrsel",
172#endif
173};
174const size_t pr_flag_nonames_size = sizeof(pr_flag_nonames);
175
176struct jailsys_flags {
177	const char	*name;
178	unsigned	 disable;
179	unsigned	 new;
180} pr_flag_jailsys[] = {
181	{ "host", 0, PR_HOST },
182#ifdef VIMAGE
183	{ "vnet", 0, PR_VNET },
184#endif
185#ifdef INET
186	{ "ip4", PR_IP4_USER, PR_IP4_USER },
187#endif
188#ifdef INET6
189	{ "ip6", PR_IP6_USER, PR_IP6_USER },
190#endif
191};
192const size_t pr_flag_jailsys_size = sizeof(pr_flag_jailsys);
193
194static char *pr_allow_names[] = {
195	"allow.set_hostname",
196	"allow.sysvipc",
197	"allow.raw_sockets",
198	"allow.chflags",
199	"allow.mount",
200	"allow.quotas",
201	"allow.socket_af",
202	"allow.mount.devfs",
203	"allow.mount.nullfs",
204	"allow.mount.zfs",
205	"allow.mount.procfs",
206	"allow.mount.tmpfs",
207	"allow.mount.fdescfs",
208	"allow.mount.linprocfs",
209	"allow.mount.linsysfs",
210};
211const size_t pr_allow_names_size = sizeof(pr_allow_names);
212
213static char *pr_allow_nonames[] = {
214	"allow.noset_hostname",
215	"allow.nosysvipc",
216	"allow.noraw_sockets",
217	"allow.nochflags",
218	"allow.nomount",
219	"allow.noquotas",
220	"allow.nosocket_af",
221	"allow.mount.nodevfs",
222	"allow.mount.nonullfs",
223	"allow.mount.nozfs",
224	"allow.mount.noprocfs",
225	"allow.mount.notmpfs",
226	"allow.mount.nofdescfs",
227	"allow.mount.nolinprocfs",
228	"allow.mount.nolinsysfs",
229};
230const size_t pr_allow_nonames_size = sizeof(pr_allow_nonames);
231
232#define	JAIL_DEFAULT_ALLOW		PR_ALLOW_SET_HOSTNAME
233#define	JAIL_DEFAULT_ENFORCE_STATFS	2
234#define	JAIL_DEFAULT_DEVFS_RSNUM	0
235static unsigned jail_default_allow = JAIL_DEFAULT_ALLOW;
236static int jail_default_enforce_statfs = JAIL_DEFAULT_ENFORCE_STATFS;
237static int jail_default_devfs_rsnum = JAIL_DEFAULT_DEVFS_RSNUM;
238#if defined(INET) || defined(INET6)
239static unsigned jail_max_af_ips = 255;
240#endif
241
242/*
243 * Initialize the parts of prison0 that can't be static-initialized with
244 * constants.  This is called from proc0_init() after creating thread0 cpuset.
245 */
246void
247prison0_init(void)
248{
249
250	prison0.pr_cpuset = cpuset_ref(thread0.td_cpuset);
251	prison0.pr_osreldate = osreldate;
252	strlcpy(prison0.pr_osrelease, osrelease, sizeof(prison0.pr_osrelease));
253}
254
255#ifdef INET
256static int
257qcmp_v4(const void *ip1, const void *ip2)
258{
259	in_addr_t iaa, iab;
260
261	/*
262	 * We need to compare in HBO here to get the list sorted as expected
263	 * by the result of the code.  Sorting NBO addresses gives you
264	 * interesting results.  If you do not understand, do not try.
265	 */
266	iaa = ntohl(((const struct in_addr *)ip1)->s_addr);
267	iab = ntohl(((const struct in_addr *)ip2)->s_addr);
268
269	/*
270	 * Do not simply return the difference of the two numbers, the int is
271	 * not wide enough.
272	 */
273	if (iaa > iab)
274		return (1);
275	else if (iaa < iab)
276		return (-1);
277	else
278		return (0);
279}
280#endif
281
282#ifdef INET6
283static int
284qcmp_v6(const void *ip1, const void *ip2)
285{
286	const struct in6_addr *ia6a, *ia6b;
287	int i, rc;
288
289	ia6a = (const struct in6_addr *)ip1;
290	ia6b = (const struct in6_addr *)ip2;
291
292	rc = 0;
293	for (i = 0; rc == 0 && i < sizeof(struct in6_addr); i++) {
294		if (ia6a->s6_addr[i] > ia6b->s6_addr[i])
295			rc = 1;
296		else if (ia6a->s6_addr[i] < ia6b->s6_addr[i])
297			rc = -1;
298	}
299	return (rc);
300}
301#endif
302
303/*
304 * struct jail_args {
305 *	struct jail *jail;
306 * };
307 */
308int
309sys_jail(struct thread *td, struct jail_args *uap)
310{
311	uint32_t version;
312	int error;
313	struct jail j;
314
315	error = copyin(uap->jail, &version, sizeof(uint32_t));
316	if (error)
317		return (error);
318
319	switch (version) {
320	case 0:
321	{
322		struct jail_v0 j0;
323
324		/* FreeBSD single IPv4 jails. */
325		bzero(&j, sizeof(struct jail));
326		error = copyin(uap->jail, &j0, sizeof(struct jail_v0));
327		if (error)
328			return (error);
329		j.version = j0.version;
330		j.path = j0.path;
331		j.hostname = j0.hostname;
332		j.ip4s = htonl(j0.ip_number);	/* jail_v0 is host order */
333		break;
334	}
335
336	case 1:
337		/*
338		 * Version 1 was used by multi-IPv4 jail implementations
339		 * that never made it into the official kernel.
340		 */
341		return (EINVAL);
342
343	case 2:	/* JAIL_API_VERSION */
344		/* FreeBSD multi-IPv4/IPv6,noIP jails. */
345		error = copyin(uap->jail, &j, sizeof(struct jail));
346		if (error)
347			return (error);
348		break;
349
350	default:
351		/* Sci-Fi jails are not supported, sorry. */
352		return (EINVAL);
353	}
354	return (kern_jail(td, &j));
355}
356
357int
358kern_jail(struct thread *td, struct jail *j)
359{
360	struct iovec optiov[2 * (4 + nitems(pr_allow_names)
361#ifdef INET
362			    + 1
363#endif
364#ifdef INET6
365			    + 1
366#endif
367			    )];
368	struct uio opt;
369	char *u_path, *u_hostname, *u_name;
370#ifdef INET
371	uint32_t ip4s;
372	struct in_addr *u_ip4;
373#endif
374#ifdef INET6
375	struct in6_addr *u_ip6;
376#endif
377	size_t tmplen;
378	int error, enforce_statfs, fi;
379
380	bzero(&optiov, sizeof(optiov));
381	opt.uio_iov = optiov;
382	opt.uio_iovcnt = 0;
383	opt.uio_offset = -1;
384	opt.uio_resid = -1;
385	opt.uio_segflg = UIO_SYSSPACE;
386	opt.uio_rw = UIO_READ;
387	opt.uio_td = td;
388
389	/* Set permissions for top-level jails from sysctls. */
390	if (!jailed(td->td_ucred)) {
391		for (fi = 0; fi < nitems(pr_allow_names); fi++) {
392			optiov[opt.uio_iovcnt].iov_base =
393			    (jail_default_allow & (1 << fi))
394			    ? pr_allow_names[fi] : pr_allow_nonames[fi];
395			optiov[opt.uio_iovcnt].iov_len =
396			    strlen(optiov[opt.uio_iovcnt].iov_base) + 1;
397			opt.uio_iovcnt += 2;
398		}
399		optiov[opt.uio_iovcnt].iov_base = "enforce_statfs";
400		optiov[opt.uio_iovcnt].iov_len = sizeof("enforce_statfs");
401		opt.uio_iovcnt++;
402		enforce_statfs = jail_default_enforce_statfs;
403		optiov[opt.uio_iovcnt].iov_base = &enforce_statfs;
404		optiov[opt.uio_iovcnt].iov_len = sizeof(enforce_statfs);
405		opt.uio_iovcnt++;
406	}
407
408	tmplen = MAXPATHLEN + MAXHOSTNAMELEN + MAXHOSTNAMELEN;
409#ifdef INET
410	ip4s = (j->version == 0) ? 1 : j->ip4s;
411	if (ip4s > jail_max_af_ips)
412		return (EINVAL);
413	tmplen += ip4s * sizeof(struct in_addr);
414#else
415	if (j->ip4s > 0)
416		return (EINVAL);
417#endif
418#ifdef INET6
419	if (j->ip6s > jail_max_af_ips)
420		return (EINVAL);
421	tmplen += j->ip6s * sizeof(struct in6_addr);
422#else
423	if (j->ip6s > 0)
424		return (EINVAL);
425#endif
426	u_path = malloc(tmplen, M_TEMP, M_WAITOK);
427	u_hostname = u_path + MAXPATHLEN;
428	u_name = u_hostname + MAXHOSTNAMELEN;
429#ifdef INET
430	u_ip4 = (struct in_addr *)(u_name + MAXHOSTNAMELEN);
431#endif
432#ifdef INET6
433#ifdef INET
434	u_ip6 = (struct in6_addr *)(u_ip4 + ip4s);
435#else
436	u_ip6 = (struct in6_addr *)(u_name + MAXHOSTNAMELEN);
437#endif
438#endif
439	optiov[opt.uio_iovcnt].iov_base = "path";
440	optiov[opt.uio_iovcnt].iov_len = sizeof("path");
441	opt.uio_iovcnt++;
442	optiov[opt.uio_iovcnt].iov_base = u_path;
443	error = copyinstr(j->path, u_path, MAXPATHLEN,
444	    &optiov[opt.uio_iovcnt].iov_len);
445	if (error) {
446		free(u_path, M_TEMP);
447		return (error);
448	}
449	opt.uio_iovcnt++;
450	optiov[opt.uio_iovcnt].iov_base = "host.hostname";
451	optiov[opt.uio_iovcnt].iov_len = sizeof("host.hostname");
452	opt.uio_iovcnt++;
453	optiov[opt.uio_iovcnt].iov_base = u_hostname;
454	error = copyinstr(j->hostname, u_hostname, MAXHOSTNAMELEN,
455	    &optiov[opt.uio_iovcnt].iov_len);
456	if (error) {
457		free(u_path, M_TEMP);
458		return (error);
459	}
460	opt.uio_iovcnt++;
461	if (j->jailname != NULL) {
462		optiov[opt.uio_iovcnt].iov_base = "name";
463		optiov[opt.uio_iovcnt].iov_len = sizeof("name");
464		opt.uio_iovcnt++;
465		optiov[opt.uio_iovcnt].iov_base = u_name;
466		error = copyinstr(j->jailname, u_name, MAXHOSTNAMELEN,
467		    &optiov[opt.uio_iovcnt].iov_len);
468		if (error) {
469			free(u_path, M_TEMP);
470			return (error);
471		}
472		opt.uio_iovcnt++;
473	}
474#ifdef INET
475	optiov[opt.uio_iovcnt].iov_base = "ip4.addr";
476	optiov[opt.uio_iovcnt].iov_len = sizeof("ip4.addr");
477	opt.uio_iovcnt++;
478	optiov[opt.uio_iovcnt].iov_base = u_ip4;
479	optiov[opt.uio_iovcnt].iov_len = ip4s * sizeof(struct in_addr);
480	if (j->version == 0)
481		u_ip4->s_addr = j->ip4s;
482	else {
483		error = copyin(j->ip4, u_ip4, optiov[opt.uio_iovcnt].iov_len);
484		if (error) {
485			free(u_path, M_TEMP);
486			return (error);
487		}
488	}
489	opt.uio_iovcnt++;
490#endif
491#ifdef INET6
492	optiov[opt.uio_iovcnt].iov_base = "ip6.addr";
493	optiov[opt.uio_iovcnt].iov_len = sizeof("ip6.addr");
494	opt.uio_iovcnt++;
495	optiov[opt.uio_iovcnt].iov_base = u_ip6;
496	optiov[opt.uio_iovcnt].iov_len = j->ip6s * sizeof(struct in6_addr);
497	error = copyin(j->ip6, u_ip6, optiov[opt.uio_iovcnt].iov_len);
498	if (error) {
499		free(u_path, M_TEMP);
500		return (error);
501	}
502	opt.uio_iovcnt++;
503#endif
504	KASSERT(opt.uio_iovcnt <= nitems(optiov),
505		("kern_jail: too many iovecs (%d)", opt.uio_iovcnt));
506	error = kern_jail_set(td, &opt, JAIL_CREATE | JAIL_ATTACH);
507	free(u_path, M_TEMP);
508	return (error);
509}
510
511
512/*
513 * struct jail_set_args {
514 *	struct iovec *iovp;
515 *	unsigned int iovcnt;
516 *	int flags;
517 * };
518 */
519int
520sys_jail_set(struct thread *td, struct jail_set_args *uap)
521{
522	struct uio *auio;
523	int error;
524
525	/* Check that we have an even number of iovecs. */
526	if (uap->iovcnt & 1)
527		return (EINVAL);
528
529	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
530	if (error)
531		return (error);
532	error = kern_jail_set(td, auio, uap->flags);
533	free(auio, M_IOV);
534	return (error);
535}
536
537int
538kern_jail_set(struct thread *td, struct uio *optuio, int flags)
539{
540	struct nameidata nd;
541#ifdef INET
542	struct in_addr *ip4;
543#endif
544#ifdef INET6
545	struct in6_addr *ip6;
546#endif
547	struct vfsopt *opt;
548	struct vfsoptlist *opts;
549	struct prison *pr, *deadpr, *mypr, *ppr, *tpr;
550	struct vnode *root;
551	char *domain, *errmsg, *host, *name, *namelc, *p, *path, *uuid;
552	char *g_path, *osrelstr;
553#if defined(INET) || defined(INET6)
554	struct prison *tppr;
555	void *op;
556#endif
557	unsigned long hid;
558	size_t namelen, onamelen;
559	int born, created, cuflags, descend, enforce;
560	int error, errmsg_len, errmsg_pos;
561	int gotchildmax, gotenforce, gothid, gotrsnum, gotslevel;
562	int fi, jid, jsys, len, level;
563	int childmax, osreldt, rsnum, slevel;
564	int fullpath_disabled;
565#if defined(INET) || defined(INET6)
566	int ii, ij;
567#endif
568#ifdef INET
569	int ip4s, redo_ip4;
570#endif
571#ifdef INET6
572	int ip6s, redo_ip6;
573#endif
574	uint64_t pr_allow, ch_allow, pr_flags, ch_flags;
575	unsigned tallow;
576	char numbuf[12];
577
578	error = priv_check(td, PRIV_JAIL_SET);
579	if (!error && (flags & JAIL_ATTACH))
580		error = priv_check(td, PRIV_JAIL_ATTACH);
581	if (error)
582		return (error);
583	mypr = ppr = td->td_ucred->cr_prison;
584	if ((flags & JAIL_CREATE) && mypr->pr_childmax == 0)
585		return (EPERM);
586	if (flags & ~JAIL_SET_MASK)
587		return (EINVAL);
588
589	/*
590	 * Check all the parameters before committing to anything.  Not all
591	 * errors can be caught early, but we may as well try.  Also, this
592	 * takes care of some expensive stuff (path lookup) before getting
593	 * the allprison lock.
594	 *
595	 * XXX Jails are not filesystems, and jail parameters are not mount
596	 *     options.  But it makes more sense to re-use the vfsopt code
597	 *     than duplicate it under a different name.
598	 */
599	error = vfs_buildopts(optuio, &opts);
600	if (error)
601		return (error);
602#ifdef INET
603	ip4 = NULL;
604#endif
605#ifdef INET6
606	ip6 = NULL;
607#endif
608	g_path = NULL;
609
610	error = vfs_copyopt(opts, "jid", &jid, sizeof(jid));
611	if (error == ENOENT)
612		jid = 0;
613	else if (error != 0)
614		goto done_free;
615
616	error = vfs_copyopt(opts, "securelevel", &slevel, sizeof(slevel));
617	if (error == ENOENT)
618		gotslevel = 0;
619	else if (error != 0)
620		goto done_free;
621	else
622		gotslevel = 1;
623
624	error =
625	    vfs_copyopt(opts, "children.max", &childmax, sizeof(childmax));
626	if (error == ENOENT)
627		gotchildmax = 0;
628	else if (error != 0)
629		goto done_free;
630	else
631		gotchildmax = 1;
632
633	error = vfs_copyopt(opts, "enforce_statfs", &enforce, sizeof(enforce));
634	if (error == ENOENT)
635		gotenforce = 0;
636	else if (error != 0)
637		goto done_free;
638	else if (enforce < 0 || enforce > 2) {
639		error = EINVAL;
640		goto done_free;
641	} else
642		gotenforce = 1;
643
644	error = vfs_copyopt(opts, "devfs_ruleset", &rsnum, sizeof(rsnum));
645	if (error == ENOENT)
646		gotrsnum = 0;
647	else if (error != 0)
648		goto done_free;
649	else
650		gotrsnum = 1;
651
652	pr_flags = ch_flags = 0;
653	for (fi = 0; fi < nitems(pr_flag_names); fi++) {
654		if (pr_flag_names[fi] == NULL)
655			continue;
656		vfs_flagopt(opts, pr_flag_names[fi], &pr_flags, 1 << fi);
657		vfs_flagopt(opts, pr_flag_nonames[fi], &ch_flags, 1 << fi);
658	}
659	ch_flags |= pr_flags;
660	for (fi = 0; fi < nitems(pr_flag_jailsys); fi++) {
661		error = vfs_copyopt(opts, pr_flag_jailsys[fi].name, &jsys,
662		    sizeof(jsys));
663		if (error == ENOENT)
664			continue;
665		if (error != 0)
666			goto done_free;
667		switch (jsys) {
668		case JAIL_SYS_DISABLE:
669			if (!pr_flag_jailsys[fi].disable) {
670				error = EINVAL;
671				goto done_free;
672			}
673			pr_flags |= pr_flag_jailsys[fi].disable;
674			break;
675		case JAIL_SYS_NEW:
676			pr_flags |= pr_flag_jailsys[fi].new;
677			break;
678		case JAIL_SYS_INHERIT:
679			break;
680		default:
681			error = EINVAL;
682			goto done_free;
683		}
684		ch_flags |=
685		    pr_flag_jailsys[fi].new | pr_flag_jailsys[fi].disable;
686	}
687	if ((flags & (JAIL_CREATE | JAIL_UPDATE | JAIL_ATTACH)) == JAIL_CREATE
688	    && !(pr_flags & PR_PERSIST)) {
689		error = EINVAL;
690		vfs_opterror(opts, "new jail must persist or attach");
691		goto done_errmsg;
692	}
693#ifdef VIMAGE
694	if ((flags & JAIL_UPDATE) && (ch_flags & PR_VNET)) {
695		error = EINVAL;
696		vfs_opterror(opts, "vnet cannot be changed after creation");
697		goto done_errmsg;
698	}
699#endif
700#ifdef INET
701	if ((flags & JAIL_UPDATE) && (ch_flags & PR_IP4_USER)) {
702		error = EINVAL;
703		vfs_opterror(opts, "ip4 cannot be changed after creation");
704		goto done_errmsg;
705	}
706#endif
707#ifdef INET6
708	if ((flags & JAIL_UPDATE) && (ch_flags & PR_IP6_USER)) {
709		error = EINVAL;
710		vfs_opterror(opts, "ip6 cannot be changed after creation");
711		goto done_errmsg;
712	}
713#endif
714
715	pr_allow = ch_allow = 0;
716	for (fi = 0; fi < nitems(pr_allow_names); fi++) {
717		vfs_flagopt(opts, pr_allow_names[fi], &pr_allow, 1 << fi);
718		vfs_flagopt(opts, pr_allow_nonames[fi], &ch_allow, 1 << fi);
719	}
720	ch_allow |= pr_allow;
721
722	error = vfs_getopt(opts, "name", (void **)&name, &len);
723	if (error == ENOENT)
724		name = NULL;
725	else if (error != 0)
726		goto done_free;
727	else {
728		if (len == 0 || name[len - 1] != '\0') {
729			error = EINVAL;
730			goto done_free;
731		}
732		if (len > MAXHOSTNAMELEN) {
733			error = ENAMETOOLONG;
734			goto done_free;
735		}
736	}
737
738	error = vfs_getopt(opts, "host.hostname", (void **)&host, &len);
739	if (error == ENOENT)
740		host = NULL;
741	else if (error != 0)
742		goto done_free;
743	else {
744		ch_flags |= PR_HOST;
745		pr_flags |= PR_HOST;
746		if (len == 0 || host[len - 1] != '\0') {
747			error = EINVAL;
748			goto done_free;
749		}
750		if (len > MAXHOSTNAMELEN) {
751			error = ENAMETOOLONG;
752			goto done_free;
753		}
754	}
755
756	error = vfs_getopt(opts, "host.domainname", (void **)&domain, &len);
757	if (error == ENOENT)
758		domain = NULL;
759	else if (error != 0)
760		goto done_free;
761	else {
762		ch_flags |= PR_HOST;
763		pr_flags |= PR_HOST;
764		if (len == 0 || domain[len - 1] != '\0') {
765			error = EINVAL;
766			goto done_free;
767		}
768		if (len > MAXHOSTNAMELEN) {
769			error = ENAMETOOLONG;
770			goto done_free;
771		}
772	}
773
774	error = vfs_getopt(opts, "host.hostuuid", (void **)&uuid, &len);
775	if (error == ENOENT)
776		uuid = NULL;
777	else if (error != 0)
778		goto done_free;
779	else {
780		ch_flags |= PR_HOST;
781		pr_flags |= PR_HOST;
782		if (len == 0 || uuid[len - 1] != '\0') {
783			error = EINVAL;
784			goto done_free;
785		}
786		if (len > HOSTUUIDLEN) {
787			error = ENAMETOOLONG;
788			goto done_free;
789		}
790	}
791
792#ifdef COMPAT_FREEBSD32
793	if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
794		uint32_t hid32;
795
796		error = vfs_copyopt(opts, "host.hostid", &hid32, sizeof(hid32));
797		hid = hid32;
798	} else
799#endif
800		error = vfs_copyopt(opts, "host.hostid", &hid, sizeof(hid));
801	if (error == ENOENT)
802		gothid = 0;
803	else if (error != 0)
804		goto done_free;
805	else {
806		gothid = 1;
807		ch_flags |= PR_HOST;
808		pr_flags |= PR_HOST;
809	}
810
811#ifdef INET
812	error = vfs_getopt(opts, "ip4.addr", &op, &ip4s);
813	if (error == ENOENT)
814		ip4s = 0;
815	else if (error != 0)
816		goto done_free;
817	else if (ip4s & (sizeof(*ip4) - 1)) {
818		error = EINVAL;
819		goto done_free;
820	} else {
821		ch_flags |= PR_IP4_USER;
822		pr_flags |= PR_IP4_USER;
823		if (ip4s > 0) {
824			ip4s /= sizeof(*ip4);
825			if (ip4s > jail_max_af_ips) {
826				error = EINVAL;
827				vfs_opterror(opts, "too many IPv4 addresses");
828				goto done_errmsg;
829			}
830			ip4 = malloc(ip4s * sizeof(*ip4), M_PRISON, M_WAITOK);
831			bcopy(op, ip4, ip4s * sizeof(*ip4));
832			/*
833			 * IP addresses are all sorted but ip[0] to preserve
834			 * the primary IP address as given from userland.
835			 * This special IP is used for unbound outgoing
836			 * connections as well for "loopback" traffic in case
837			 * source address selection cannot find any more fitting
838			 * address to connect from.
839			 */
840			if (ip4s > 1)
841				qsort(ip4 + 1, ip4s - 1, sizeof(*ip4), qcmp_v4);
842			/*
843			 * Check for duplicate addresses and do some simple
844			 * zero and broadcast checks. If users give other bogus
845			 * addresses it is their problem.
846			 *
847			 * We do not have to care about byte order for these
848			 * checks so we will do them in NBO.
849			 */
850			for (ii = 0; ii < ip4s; ii++) {
851				if (ip4[ii].s_addr == INADDR_ANY ||
852				    ip4[ii].s_addr == INADDR_BROADCAST) {
853					error = EINVAL;
854					goto done_free;
855				}
856				if ((ii+1) < ip4s &&
857				    (ip4[0].s_addr == ip4[ii+1].s_addr ||
858				     ip4[ii].s_addr == ip4[ii+1].s_addr)) {
859					error = EINVAL;
860					goto done_free;
861				}
862			}
863		}
864	}
865#endif
866
867#ifdef INET6
868	error = vfs_getopt(opts, "ip6.addr", &op, &ip6s);
869	if (error == ENOENT)
870		ip6s = 0;
871	else if (error != 0)
872		goto done_free;
873	else if (ip6s & (sizeof(*ip6) - 1)) {
874		error = EINVAL;
875		goto done_free;
876	} else {
877		ch_flags |= PR_IP6_USER;
878		pr_flags |= PR_IP6_USER;
879		if (ip6s > 0) {
880			ip6s /= sizeof(*ip6);
881			if (ip6s > jail_max_af_ips) {
882				error = EINVAL;
883				vfs_opterror(opts, "too many IPv6 addresses");
884				goto done_errmsg;
885			}
886			ip6 = malloc(ip6s * sizeof(*ip6), M_PRISON, M_WAITOK);
887			bcopy(op, ip6, ip6s * sizeof(*ip6));
888			if (ip6s > 1)
889				qsort(ip6 + 1, ip6s - 1, sizeof(*ip6), qcmp_v6);
890			for (ii = 0; ii < ip6s; ii++) {
891				if (IN6_IS_ADDR_UNSPECIFIED(&ip6[ii])) {
892					error = EINVAL;
893					goto done_free;
894				}
895				if ((ii+1) < ip6s &&
896				    (IN6_ARE_ADDR_EQUAL(&ip6[0], &ip6[ii+1]) ||
897				     IN6_ARE_ADDR_EQUAL(&ip6[ii], &ip6[ii+1])))
898				{
899					error = EINVAL;
900					goto done_free;
901				}
902			}
903		}
904	}
905#endif
906
907#if defined(VIMAGE) && (defined(INET) || defined(INET6))
908	if ((ch_flags & PR_VNET) && (ch_flags & (PR_IP4_USER | PR_IP6_USER))) {
909		error = EINVAL;
910		vfs_opterror(opts,
911		    "vnet jails cannot have IP address restrictions");
912		goto done_errmsg;
913	}
914#endif
915
916	fullpath_disabled = 0;
917	root = NULL;
918	error = vfs_getopt(opts, "path", (void **)&path, &len);
919	if (error == ENOENT)
920		path = NULL;
921	else if (error != 0)
922		goto done_free;
923	else {
924		if (flags & JAIL_UPDATE) {
925			error = EINVAL;
926			vfs_opterror(opts,
927			    "path cannot be changed after creation");
928			goto done_errmsg;
929		}
930		if (len == 0 || path[len - 1] != '\0') {
931			error = EINVAL;
932			goto done_free;
933		}
934		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
935		    path, td);
936		error = namei(&nd);
937		if (error)
938			goto done_free;
939		root = nd.ni_vp;
940		NDFREE(&nd, NDF_ONLY_PNBUF);
941		g_path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
942		strlcpy(g_path, path, MAXPATHLEN);
943		error = vn_path_to_global_path(td, root, g_path, MAXPATHLEN);
944		if (error == 0)
945			path = g_path;
946		else if (error == ENODEV) {
947			/* proceed if sysctl debug.disablefullpath == 1 */
948			fullpath_disabled = 1;
949			if (len < 2 || (len == 2 && path[0] == '/'))
950				path = NULL;
951		} else {
952			/* exit on other errors */
953			goto done_free;
954		}
955		if (root->v_type != VDIR) {
956			error = ENOTDIR;
957			vput(root);
958			goto done_free;
959		}
960		VOP_UNLOCK(root, 0);
961		if (fullpath_disabled) {
962			/* Leave room for a real-root full pathname. */
963			if (len + (path[0] == '/' && strcmp(mypr->pr_path, "/")
964			    ? strlen(mypr->pr_path) : 0) > MAXPATHLEN) {
965				error = ENAMETOOLONG;
966				goto done_free;
967			}
968		}
969	}
970
971	error = vfs_getopt(opts, "osrelease", (void **)&osrelstr, &len);
972	if (error == ENOENT)
973		osrelstr = NULL;
974	else if (error != 0)
975		goto done_free;
976	else {
977		if (flags & JAIL_UPDATE) {
978			error = EINVAL;
979			vfs_opterror(opts,
980			    "osrelease cannot be changed after creation");
981			goto done_errmsg;
982		}
983		if (len == 0 || len >= OSRELEASELEN) {
984			error = EINVAL;
985			vfs_opterror(opts,
986			    "osrelease string must be 1-%d bytes long",
987			    OSRELEASELEN - 1);
988			goto done_errmsg;
989		}
990	}
991
992	error = vfs_copyopt(opts, "osreldate", &osreldt, sizeof(osreldt));
993	if (error == ENOENT)
994		osreldt = 0;
995	else if (error != 0)
996		goto done_free;
997	else {
998		if (flags & JAIL_UPDATE) {
999			error = EINVAL;
1000			vfs_opterror(opts,
1001			    "osreldate cannot be changed after creation");
1002			goto done_errmsg;
1003		}
1004		if (osreldt == 0) {
1005			error = EINVAL;
1006			vfs_opterror(opts, "osreldate cannot be 0");
1007			goto done_errmsg;
1008		}
1009	}
1010
1011	/*
1012	 * Grab the allprison lock before letting modules check their
1013	 * parameters.  Once we have it, do not let go so we'll have a
1014	 * consistent view of the OSD list.
1015	 */
1016	sx_xlock(&allprison_lock);
1017	error = osd_jail_call(NULL, PR_METHOD_CHECK, opts);
1018	if (error)
1019		goto done_unlock_list;
1020
1021	/* By now, all parameters should have been noted. */
1022	TAILQ_FOREACH(opt, opts, link) {
1023		if (!opt->seen && strcmp(opt->name, "errmsg")) {
1024			error = EINVAL;
1025			vfs_opterror(opts, "unknown parameter: %s", opt->name);
1026			goto done_unlock_list;
1027		}
1028	}
1029
1030	/*
1031	 * See if we are creating a new record or updating an existing one.
1032	 * This abuses the file error codes ENOENT and EEXIST.
1033	 */
1034	cuflags = flags & (JAIL_CREATE | JAIL_UPDATE);
1035	if (!cuflags) {
1036		error = EINVAL;
1037		vfs_opterror(opts, "no valid operation (create or update)");
1038		goto done_unlock_list;
1039	}
1040	pr = NULL;
1041	namelc = NULL;
1042	if (cuflags == JAIL_CREATE && jid == 0 && name != NULL) {
1043		namelc = strrchr(name, '.');
1044		jid = strtoul(namelc != NULL ? namelc + 1 : name, &p, 10);
1045		if (*p != '\0')
1046			jid = 0;
1047	}
1048	if (jid != 0) {
1049		/*
1050		 * See if a requested jid already exists.  There is an
1051		 * information leak here if the jid exists but is not within
1052		 * the caller's jail hierarchy.  Jail creators will get EEXIST
1053		 * even though they cannot see the jail, and CREATE | UPDATE
1054		 * will return ENOENT which is not normally a valid error.
1055		 */
1056		if (jid < 0) {
1057			error = EINVAL;
1058			vfs_opterror(opts, "negative jid");
1059			goto done_unlock_list;
1060		}
1061		pr = prison_find(jid);
1062		if (pr != NULL) {
1063			ppr = pr->pr_parent;
1064			/* Create: jid must not exist. */
1065			if (cuflags == JAIL_CREATE) {
1066				mtx_unlock(&pr->pr_mtx);
1067				error = EEXIST;
1068				vfs_opterror(opts, "jail %d already exists",
1069				    jid);
1070				goto done_unlock_list;
1071			}
1072			if (!prison_ischild(mypr, pr)) {
1073				mtx_unlock(&pr->pr_mtx);
1074				pr = NULL;
1075			} else if (pr->pr_uref == 0) {
1076				if (!(flags & JAIL_DYING)) {
1077					mtx_unlock(&pr->pr_mtx);
1078					error = ENOENT;
1079					vfs_opterror(opts, "jail %d is dying",
1080					    jid);
1081					goto done_unlock_list;
1082				} else if ((flags & JAIL_ATTACH) ||
1083				    (pr_flags & PR_PERSIST)) {
1084					/*
1085					 * A dying jail might be resurrected
1086					 * (via attach or persist), but first
1087					 * it must determine if another jail
1088					 * has claimed its name.  Accomplish
1089					 * this by implicitly re-setting the
1090					 * name.
1091					 */
1092					if (name == NULL)
1093						name = prison_name(mypr, pr);
1094				}
1095			}
1096		}
1097		if (pr == NULL) {
1098			/* Update: jid must exist. */
1099			if (cuflags == JAIL_UPDATE) {
1100				error = ENOENT;
1101				vfs_opterror(opts, "jail %d not found", jid);
1102				goto done_unlock_list;
1103			}
1104		}
1105	}
1106	/*
1107	 * If the caller provided a name, look for a jail by that name.
1108	 * This has different semantics for creates and updates keyed by jid
1109	 * (where the name must not already exist in a different jail),
1110	 * and updates keyed by the name itself (where the name must exist
1111	 * because that is the jail being updated).
1112	 */
1113	if (name != NULL) {
1114		namelc = strrchr(name, '.');
1115		if (namelc == NULL)
1116			namelc = name;
1117		else {
1118			/*
1119			 * This is a hierarchical name.  Split it into the
1120			 * parent and child names, and make sure the parent
1121			 * exists or matches an already found jail.
1122			 */
1123			*namelc = '\0';
1124			if (pr != NULL) {
1125				if (strncmp(name, ppr->pr_name, namelc - name)
1126				    || ppr->pr_name[namelc - name] != '\0') {
1127					mtx_unlock(&pr->pr_mtx);
1128					error = EINVAL;
1129					vfs_opterror(opts,
1130					    "cannot change jail's parent");
1131					goto done_unlock_list;
1132				}
1133			} else {
1134				ppr = prison_find_name(mypr, name);
1135				if (ppr == NULL) {
1136					error = ENOENT;
1137					vfs_opterror(opts,
1138					    "jail \"%s\" not found", name);
1139					goto done_unlock_list;
1140				}
1141				mtx_unlock(&ppr->pr_mtx);
1142			}
1143			name = ++namelc;
1144		}
1145		if (name[0] != '\0') {
1146			namelen =
1147			    (ppr == &prison0) ? 0 : strlen(ppr->pr_name) + 1;
1148 name_again:
1149			deadpr = NULL;
1150			FOREACH_PRISON_CHILD(ppr, tpr) {
1151				if (tpr != pr && tpr->pr_ref > 0 &&
1152				    !strcmp(tpr->pr_name + namelen, name)) {
1153					if (pr == NULL &&
1154					    cuflags != JAIL_CREATE) {
1155						mtx_lock(&tpr->pr_mtx);
1156						if (tpr->pr_ref > 0) {
1157							/*
1158							 * Use this jail
1159							 * for updates.
1160							 */
1161							if (tpr->pr_uref > 0) {
1162								pr = tpr;
1163								break;
1164							}
1165							deadpr = tpr;
1166						}
1167						mtx_unlock(&tpr->pr_mtx);
1168					} else if (tpr->pr_uref > 0) {
1169						/*
1170						 * Create, or update(jid):
1171						 * name must not exist in an
1172						 * active sibling jail.
1173						 */
1174						error = EEXIST;
1175						if (pr != NULL)
1176							mtx_unlock(&pr->pr_mtx);
1177						vfs_opterror(opts,
1178						   "jail \"%s\" already exists",
1179						   name);
1180						goto done_unlock_list;
1181					}
1182				}
1183			}
1184			/* If no active jail is found, use a dying one. */
1185			if (deadpr != NULL && pr == NULL) {
1186				if (flags & JAIL_DYING) {
1187					mtx_lock(&deadpr->pr_mtx);
1188					if (deadpr->pr_ref == 0) {
1189						mtx_unlock(&deadpr->pr_mtx);
1190						goto name_again;
1191					}
1192					pr = deadpr;
1193				} else if (cuflags == JAIL_UPDATE) {
1194					error = ENOENT;
1195					vfs_opterror(opts,
1196					    "jail \"%s\" is dying", name);
1197					goto done_unlock_list;
1198				}
1199			}
1200			/* Update: name must exist if no jid. */
1201			else if (cuflags == JAIL_UPDATE && pr == NULL) {
1202				error = ENOENT;
1203				vfs_opterror(opts, "jail \"%s\" not found",
1204				    name);
1205				goto done_unlock_list;
1206			}
1207		}
1208	}
1209	/* Update: must provide a jid or name. */
1210	else if (cuflags == JAIL_UPDATE && pr == NULL) {
1211		error = ENOENT;
1212		vfs_opterror(opts, "update specified no jail");
1213		goto done_unlock_list;
1214	}
1215
1216	/* If there's no prison to update, create a new one and link it in. */
1217	if (pr == NULL) {
1218		for (tpr = mypr; tpr != NULL; tpr = tpr->pr_parent)
1219			if (tpr->pr_childcount >= tpr->pr_childmax) {
1220				error = EPERM;
1221				vfs_opterror(opts, "prison limit exceeded");
1222				goto done_unlock_list;
1223			}
1224		created = 1;
1225		mtx_lock(&ppr->pr_mtx);
1226		if (ppr->pr_ref == 0) {
1227			mtx_unlock(&ppr->pr_mtx);
1228			error = ENOENT;
1229			vfs_opterror(opts, "parent jail went away!");
1230			goto done_unlock_list;
1231		}
1232		ppr->pr_ref++;
1233		ppr->pr_uref++;
1234		mtx_unlock(&ppr->pr_mtx);
1235		pr = malloc(sizeof(*pr), M_PRISON, M_WAITOK | M_ZERO);
1236		if (jid == 0) {
1237			/* Find the next free jid. */
1238			jid = lastprid + 1;
1239 findnext:
1240			if (jid == JAIL_MAX)
1241				jid = 1;
1242			TAILQ_FOREACH(tpr, &allprison, pr_list) {
1243				if (tpr->pr_id < jid)
1244					continue;
1245				if (tpr->pr_id > jid || tpr->pr_ref == 0) {
1246					TAILQ_INSERT_BEFORE(tpr, pr, pr_list);
1247					break;
1248				}
1249				if (jid == lastprid) {
1250					error = EAGAIN;
1251					vfs_opterror(opts,
1252					    "no available jail IDs");
1253					free(pr, M_PRISON);
1254					prison_deref(ppr, PD_DEREF |
1255					    PD_DEUREF | PD_LIST_XLOCKED);
1256					goto done_releroot;
1257				}
1258				jid++;
1259				goto findnext;
1260			}
1261			lastprid = jid;
1262		} else {
1263			/*
1264			 * The jail already has a jid (that did not yet exist),
1265			 * so just find where to insert it.
1266			 */
1267			TAILQ_FOREACH(tpr, &allprison, pr_list)
1268				if (tpr->pr_id >= jid) {
1269					TAILQ_INSERT_BEFORE(tpr, pr, pr_list);
1270					break;
1271				}
1272		}
1273		if (tpr == NULL)
1274			TAILQ_INSERT_TAIL(&allprison, pr, pr_list);
1275		LIST_INSERT_HEAD(&ppr->pr_children, pr, pr_sibling);
1276		for (tpr = ppr; tpr != NULL; tpr = tpr->pr_parent)
1277			tpr->pr_childcount++;
1278
1279		pr->pr_parent = ppr;
1280		pr->pr_id = jid;
1281
1282		/* Set some default values, and inherit some from the parent. */
1283		if (name == NULL)
1284			name = "";
1285		if (path == NULL) {
1286			path = "/";
1287			root = mypr->pr_root;
1288			vref(root);
1289		}
1290		strlcpy(pr->pr_hostuuid, DEFAULT_HOSTUUID, HOSTUUIDLEN);
1291		pr->pr_flags |= PR_HOST;
1292#if defined(INET) || defined(INET6)
1293#ifdef VIMAGE
1294		if (!(pr_flags & PR_VNET))
1295#endif
1296		{
1297#ifdef INET
1298			if (!(ch_flags & PR_IP4_USER))
1299				pr->pr_flags |= PR_IP4 | PR_IP4_USER;
1300			else if (!(pr_flags & PR_IP4_USER)) {
1301				pr->pr_flags |= ppr->pr_flags & PR_IP4;
1302				if (ppr->pr_ip4 != NULL) {
1303					pr->pr_ip4s = ppr->pr_ip4s;
1304					pr->pr_ip4 = malloc(pr->pr_ip4s *
1305					    sizeof(struct in_addr), M_PRISON,
1306					    M_WAITOK);
1307					bcopy(ppr->pr_ip4, pr->pr_ip4,
1308					    pr->pr_ip4s * sizeof(*pr->pr_ip4));
1309				}
1310			}
1311#endif
1312#ifdef INET6
1313			if (!(ch_flags & PR_IP6_USER))
1314				pr->pr_flags |= PR_IP6 | PR_IP6_USER;
1315			else if (!(pr_flags & PR_IP6_USER)) {
1316				pr->pr_flags |= ppr->pr_flags & PR_IP6;
1317				if (ppr->pr_ip6 != NULL) {
1318					pr->pr_ip6s = ppr->pr_ip6s;
1319					pr->pr_ip6 = malloc(pr->pr_ip6s *
1320					    sizeof(struct in6_addr), M_PRISON,
1321					    M_WAITOK);
1322					bcopy(ppr->pr_ip6, pr->pr_ip6,
1323					    pr->pr_ip6s * sizeof(*pr->pr_ip6));
1324				}
1325			}
1326#endif
1327		}
1328#endif
1329		/* Source address selection is always on by default. */
1330		pr->pr_flags |= _PR_IP_SADDRSEL;
1331
1332		pr->pr_securelevel = ppr->pr_securelevel;
1333		pr->pr_allow = JAIL_DEFAULT_ALLOW & ppr->pr_allow;
1334		pr->pr_enforce_statfs = jail_default_enforce_statfs;
1335		pr->pr_devfs_rsnum = ppr->pr_devfs_rsnum;
1336
1337		pr->pr_osreldate = osreldt ? osreldt : ppr->pr_osreldate;
1338		if (osrelstr == NULL)
1339		    strcpy(pr->pr_osrelease, ppr->pr_osrelease);
1340		else
1341		    strcpy(pr->pr_osrelease, osrelstr);
1342
1343		LIST_INIT(&pr->pr_children);
1344		mtx_init(&pr->pr_mtx, "jail mutex", NULL, MTX_DEF | MTX_DUPOK);
1345
1346#ifdef VIMAGE
1347		/* Allocate a new vnet if specified. */
1348		pr->pr_vnet = (pr_flags & PR_VNET)
1349		    ? vnet_alloc() : ppr->pr_vnet;
1350#endif
1351		/*
1352		 * Allocate a dedicated cpuset for each jail.
1353		 * Unlike other initial settings, this may return an erorr.
1354		 */
1355		error = cpuset_create_root(ppr, &pr->pr_cpuset);
1356		if (error) {
1357			prison_deref(pr, PD_LIST_XLOCKED);
1358			goto done_releroot;
1359		}
1360
1361		mtx_lock(&pr->pr_mtx);
1362		/*
1363		 * New prisons do not yet have a reference, because we do not
1364		 * want other to see the incomplete prison once the
1365		 * allprison_lock is downgraded.
1366		 */
1367	} else {
1368		created = 0;
1369		/*
1370		 * Grab a reference for existing prisons, to ensure they
1371		 * continue to exist for the duration of the call.
1372		 */
1373		pr->pr_ref++;
1374#if defined(VIMAGE) && (defined(INET) || defined(INET6))
1375		if ((pr->pr_flags & PR_VNET) &&
1376		    (ch_flags & (PR_IP4_USER | PR_IP6_USER))) {
1377			error = EINVAL;
1378			vfs_opterror(opts,
1379			    "vnet jails cannot have IP address restrictions");
1380			goto done_deref_locked;
1381		}
1382#endif
1383#ifdef INET
1384		if (PR_IP4_USER & ch_flags & (pr_flags ^ pr->pr_flags)) {
1385			error = EINVAL;
1386			vfs_opterror(opts,
1387			    "ip4 cannot be changed after creation");
1388			goto done_deref_locked;
1389		}
1390#endif
1391#ifdef INET6
1392		if (PR_IP6_USER & ch_flags & (pr_flags ^ pr->pr_flags)) {
1393			error = EINVAL;
1394			vfs_opterror(opts,
1395			    "ip6 cannot be changed after creation");
1396			goto done_deref_locked;
1397		}
1398#endif
1399	}
1400
1401	/* Do final error checking before setting anything. */
1402	if (gotslevel) {
1403		if (slevel < ppr->pr_securelevel) {
1404			error = EPERM;
1405			goto done_deref_locked;
1406		}
1407	}
1408	if (gotchildmax) {
1409		if (childmax >= ppr->pr_childmax) {
1410			error = EPERM;
1411			goto done_deref_locked;
1412		}
1413	}
1414	if (gotenforce) {
1415		if (enforce < ppr->pr_enforce_statfs) {
1416			error = EPERM;
1417			goto done_deref_locked;
1418		}
1419	}
1420	if (gotrsnum) {
1421		/*
1422		 * devfs_rsnum is a uint16_t
1423		 */
1424		if (rsnum < 0 || rsnum > 65535) {
1425			error = EINVAL;
1426			goto done_deref_locked;
1427		}
1428		/*
1429		 * Nested jails always inherit parent's devfs ruleset
1430		 */
1431		if (jailed(td->td_ucred)) {
1432			if (rsnum > 0 && rsnum != ppr->pr_devfs_rsnum) {
1433				error = EPERM;
1434				goto done_deref_locked;
1435			} else
1436				rsnum = ppr->pr_devfs_rsnum;
1437		}
1438	}
1439#ifdef INET
1440	if (ip4s > 0) {
1441		if (ppr->pr_flags & PR_IP4) {
1442			/*
1443			 * Make sure the new set of IP addresses is a
1444			 * subset of the parent's list.  Don't worry
1445			 * about the parent being unlocked, as any
1446			 * setting is done with allprison_lock held.
1447			 */
1448			for (ij = 0; ij < ppr->pr_ip4s; ij++)
1449				if (ip4[0].s_addr == ppr->pr_ip4[ij].s_addr)
1450					break;
1451			if (ij == ppr->pr_ip4s) {
1452				error = EPERM;
1453				goto done_deref_locked;
1454			}
1455			if (ip4s > 1) {
1456				for (ii = ij = 1; ii < ip4s; ii++) {
1457					if (ip4[ii].s_addr ==
1458					    ppr->pr_ip4[0].s_addr)
1459						continue;
1460					for (; ij < ppr->pr_ip4s; ij++)
1461						if (ip4[ii].s_addr ==
1462						    ppr->pr_ip4[ij].s_addr)
1463							break;
1464					if (ij == ppr->pr_ip4s)
1465						break;
1466				}
1467				if (ij == ppr->pr_ip4s) {
1468					error = EPERM;
1469					goto done_deref_locked;
1470				}
1471			}
1472		}
1473		/*
1474		 * Check for conflicting IP addresses.  We permit them
1475		 * if there is no more than one IP on each jail.  If
1476		 * there is a duplicate on a jail with more than one
1477		 * IP stop checking and return error.
1478		 */
1479		tppr = ppr;
1480#ifdef VIMAGE
1481		for (; tppr != &prison0; tppr = tppr->pr_parent)
1482			if (tppr->pr_flags & PR_VNET)
1483				break;
1484#endif
1485		FOREACH_PRISON_DESCENDANT(tppr, tpr, descend) {
1486			if (tpr == pr ||
1487#ifdef VIMAGE
1488			    (tpr != tppr && (tpr->pr_flags & PR_VNET)) ||
1489#endif
1490			    tpr->pr_uref == 0) {
1491				descend = 0;
1492				continue;
1493			}
1494			if (!(tpr->pr_flags & PR_IP4_USER))
1495				continue;
1496			descend = 0;
1497			if (tpr->pr_ip4 == NULL ||
1498			    (ip4s == 1 && tpr->pr_ip4s == 1))
1499				continue;
1500			for (ii = 0; ii < ip4s; ii++) {
1501				if (_prison_check_ip4(tpr, &ip4[ii]) == 0) {
1502					error = EADDRINUSE;
1503					vfs_opterror(opts,
1504					    "IPv4 addresses clash");
1505					goto done_deref_locked;
1506				}
1507			}
1508		}
1509	}
1510#endif
1511#ifdef INET6
1512	if (ip6s > 0) {
1513		if (ppr->pr_flags & PR_IP6) {
1514			/*
1515			 * Make sure the new set of IP addresses is a
1516			 * subset of the parent's list.
1517			 */
1518			for (ij = 0; ij < ppr->pr_ip6s; ij++)
1519				if (IN6_ARE_ADDR_EQUAL(&ip6[0],
1520				    &ppr->pr_ip6[ij]))
1521					break;
1522			if (ij == ppr->pr_ip6s) {
1523				error = EPERM;
1524				goto done_deref_locked;
1525			}
1526			if (ip6s > 1) {
1527				for (ii = ij = 1; ii < ip6s; ii++) {
1528					if (IN6_ARE_ADDR_EQUAL(&ip6[ii],
1529					     &ppr->pr_ip6[0]))
1530						continue;
1531					for (; ij < ppr->pr_ip6s; ij++)
1532						if (IN6_ARE_ADDR_EQUAL(
1533						    &ip6[ii], &ppr->pr_ip6[ij]))
1534							break;
1535					if (ij == ppr->pr_ip6s)
1536						break;
1537				}
1538				if (ij == ppr->pr_ip6s) {
1539					error = EPERM;
1540					goto done_deref_locked;
1541				}
1542			}
1543		}
1544		/* Check for conflicting IP addresses. */
1545		tppr = ppr;
1546#ifdef VIMAGE
1547		for (; tppr != &prison0; tppr = tppr->pr_parent)
1548			if (tppr->pr_flags & PR_VNET)
1549				break;
1550#endif
1551		FOREACH_PRISON_DESCENDANT(tppr, tpr, descend) {
1552			if (tpr == pr ||
1553#ifdef VIMAGE
1554			    (tpr != tppr && (tpr->pr_flags & PR_VNET)) ||
1555#endif
1556			    tpr->pr_uref == 0) {
1557				descend = 0;
1558				continue;
1559			}
1560			if (!(tpr->pr_flags & PR_IP6_USER))
1561				continue;
1562			descend = 0;
1563			if (tpr->pr_ip6 == NULL ||
1564			    (ip6s == 1 && tpr->pr_ip6s == 1))
1565				continue;
1566			for (ii = 0; ii < ip6s; ii++) {
1567				if (_prison_check_ip6(tpr, &ip6[ii]) == 0) {
1568					error = EADDRINUSE;
1569					vfs_opterror(opts,
1570					    "IPv6 addresses clash");
1571					goto done_deref_locked;
1572				}
1573			}
1574		}
1575	}
1576#endif
1577	onamelen = namelen = 0;
1578	if (name != NULL) {
1579		/* Give a default name of the jid.  Also allow the name to be
1580		 * explicitly the jid - but not any other number, and only in
1581		 * normal form (no leading zero/etc).
1582		 */
1583		if (name[0] == '\0')
1584			snprintf(name = numbuf, sizeof(numbuf), "%d", jid);
1585		else if ((strtoul(namelc, &p, 10) != jid ||
1586			  namelc[0] < '1' || namelc[0] > '9') && *p == '\0') {
1587			error = EINVAL;
1588			vfs_opterror(opts,
1589			    "name cannot be numeric (unless it is the jid)");
1590			goto done_deref_locked;
1591		}
1592		/*
1593		 * Make sure the name isn't too long for the prison or its
1594		 * children.
1595		 */
1596		onamelen = strlen(pr->pr_name);
1597		namelen = strlen(name);
1598		if (strlen(ppr->pr_name) + namelen + 2 > sizeof(pr->pr_name)) {
1599			error = ENAMETOOLONG;
1600			goto done_deref_locked;
1601		}
1602		FOREACH_PRISON_DESCENDANT(pr, tpr, descend) {
1603			if (strlen(tpr->pr_name) + (namelen - onamelen) >=
1604			    sizeof(pr->pr_name)) {
1605				error = ENAMETOOLONG;
1606				goto done_deref_locked;
1607			}
1608		}
1609	}
1610	if (pr_allow & ~ppr->pr_allow) {
1611		error = EPERM;
1612		goto done_deref_locked;
1613	}
1614
1615	/* Set the parameters of the prison. */
1616#ifdef INET
1617	redo_ip4 = 0;
1618	if (pr_flags & PR_IP4_USER) {
1619		pr->pr_flags |= PR_IP4;
1620		free(pr->pr_ip4, M_PRISON);
1621		pr->pr_ip4s = ip4s;
1622		pr->pr_ip4 = ip4;
1623		ip4 = NULL;
1624		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1625#ifdef VIMAGE
1626			if (tpr->pr_flags & PR_VNET) {
1627				descend = 0;
1628				continue;
1629			}
1630#endif
1631			if (prison_restrict_ip4(tpr, NULL)) {
1632				redo_ip4 = 1;
1633				descend = 0;
1634			}
1635		}
1636	}
1637#endif
1638#ifdef INET6
1639	redo_ip6 = 0;
1640	if (pr_flags & PR_IP6_USER) {
1641		pr->pr_flags |= PR_IP6;
1642		free(pr->pr_ip6, M_PRISON);
1643		pr->pr_ip6s = ip6s;
1644		pr->pr_ip6 = ip6;
1645		ip6 = NULL;
1646		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1647#ifdef VIMAGE
1648			if (tpr->pr_flags & PR_VNET) {
1649				descend = 0;
1650				continue;
1651			}
1652#endif
1653			if (prison_restrict_ip6(tpr, NULL)) {
1654				redo_ip6 = 1;
1655				descend = 0;
1656			}
1657		}
1658	}
1659#endif
1660	if (gotslevel) {
1661		pr->pr_securelevel = slevel;
1662		/* Set all child jails to be at least this level. */
1663		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend)
1664			if (tpr->pr_securelevel < slevel)
1665				tpr->pr_securelevel = slevel;
1666	}
1667	if (gotchildmax) {
1668		pr->pr_childmax = childmax;
1669		/* Set all child jails to under this limit. */
1670		FOREACH_PRISON_DESCENDANT_LOCKED_LEVEL(pr, tpr, descend, level)
1671			if (tpr->pr_childmax > childmax - level)
1672				tpr->pr_childmax = childmax > level
1673				    ? childmax - level : 0;
1674	}
1675	if (gotenforce) {
1676		pr->pr_enforce_statfs = enforce;
1677		/* Pass this restriction on to the children. */
1678		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend)
1679			if (tpr->pr_enforce_statfs < enforce)
1680				tpr->pr_enforce_statfs = enforce;
1681	}
1682	if (gotrsnum) {
1683		pr->pr_devfs_rsnum = rsnum;
1684		/* Pass this restriction on to the children. */
1685		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend)
1686			tpr->pr_devfs_rsnum = rsnum;
1687	}
1688	if (name != NULL) {
1689		if (ppr == &prison0)
1690			strlcpy(pr->pr_name, name, sizeof(pr->pr_name));
1691		else
1692			snprintf(pr->pr_name, sizeof(pr->pr_name), "%s.%s",
1693			    ppr->pr_name, name);
1694		/* Change this component of child names. */
1695		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1696			bcopy(tpr->pr_name + onamelen, tpr->pr_name + namelen,
1697			    strlen(tpr->pr_name + onamelen) + 1);
1698			bcopy(pr->pr_name, tpr->pr_name, namelen);
1699		}
1700	}
1701	if (path != NULL) {
1702		/* Try to keep a real-rooted full pathname. */
1703		if (fullpath_disabled && path[0] == '/' &&
1704		    strcmp(mypr->pr_path, "/"))
1705			snprintf(pr->pr_path, sizeof(pr->pr_path), "%s%s",
1706			    mypr->pr_path, path);
1707		else
1708			strlcpy(pr->pr_path, path, sizeof(pr->pr_path));
1709		pr->pr_root = root;
1710	}
1711	if (PR_HOST & ch_flags & ~pr_flags) {
1712		if (pr->pr_flags & PR_HOST) {
1713			/*
1714			 * Copy the parent's host info.  As with pr_ip4 above,
1715			 * the lack of a lock on the parent is not a problem;
1716			 * it is always set with allprison_lock at least
1717			 * shared, and is held exclusively here.
1718			 */
1719			strlcpy(pr->pr_hostname, pr->pr_parent->pr_hostname,
1720			    sizeof(pr->pr_hostname));
1721			strlcpy(pr->pr_domainname, pr->pr_parent->pr_domainname,
1722			    sizeof(pr->pr_domainname));
1723			strlcpy(pr->pr_hostuuid, pr->pr_parent->pr_hostuuid,
1724			    sizeof(pr->pr_hostuuid));
1725			pr->pr_hostid = pr->pr_parent->pr_hostid;
1726		}
1727	} else if (host != NULL || domain != NULL || uuid != NULL || gothid) {
1728		/* Set this prison, and any descendants without PR_HOST. */
1729		if (host != NULL)
1730			strlcpy(pr->pr_hostname, host, sizeof(pr->pr_hostname));
1731		if (domain != NULL)
1732			strlcpy(pr->pr_domainname, domain,
1733			    sizeof(pr->pr_domainname));
1734		if (uuid != NULL)
1735			strlcpy(pr->pr_hostuuid, uuid, sizeof(pr->pr_hostuuid));
1736		if (gothid)
1737			pr->pr_hostid = hid;
1738		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1739			if (tpr->pr_flags & PR_HOST)
1740				descend = 0;
1741			else {
1742				if (host != NULL)
1743					strlcpy(tpr->pr_hostname,
1744					    pr->pr_hostname,
1745					    sizeof(tpr->pr_hostname));
1746				if (domain != NULL)
1747					strlcpy(tpr->pr_domainname,
1748					    pr->pr_domainname,
1749					    sizeof(tpr->pr_domainname));
1750				if (uuid != NULL)
1751					strlcpy(tpr->pr_hostuuid,
1752					    pr->pr_hostuuid,
1753					    sizeof(tpr->pr_hostuuid));
1754				if (gothid)
1755					tpr->pr_hostid = hid;
1756			}
1757		}
1758	}
1759	if ((tallow = ch_allow & ~pr_allow)) {
1760		/* Clear allow bits in all children. */
1761		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend)
1762			tpr->pr_allow &= ~tallow;
1763	}
1764	pr->pr_allow = (pr->pr_allow & ~ch_allow) | pr_allow;
1765	/*
1766	 * Persistent prisons get an extra reference, and prisons losing their
1767	 * persist flag lose that reference.  Only do this for existing prisons
1768	 * for now, so new ones will remain unseen until after the module
1769	 * handlers have completed.
1770	 */
1771	born = pr->pr_uref == 0;
1772	if (!created && (ch_flags & PR_PERSIST & (pr_flags ^ pr->pr_flags))) {
1773		if (pr_flags & PR_PERSIST) {
1774			pr->pr_ref++;
1775			pr->pr_uref++;
1776		} else {
1777			pr->pr_ref--;
1778			pr->pr_uref--;
1779		}
1780	}
1781	pr->pr_flags = (pr->pr_flags & ~ch_flags) | pr_flags;
1782	mtx_unlock(&pr->pr_mtx);
1783
1784#ifdef RACCT
1785	if (racct_enable && created)
1786		prison_racct_attach(pr);
1787#endif
1788
1789	/* Locks may have prevented a complete restriction of child IP
1790	 * addresses.  If so, allocate some more memory and try again.
1791	 */
1792#ifdef INET
1793	while (redo_ip4) {
1794		ip4s = pr->pr_ip4s;
1795		ip4 = malloc(ip4s * sizeof(*ip4), M_PRISON, M_WAITOK);
1796		mtx_lock(&pr->pr_mtx);
1797		redo_ip4 = 0;
1798		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1799#ifdef VIMAGE
1800			if (tpr->pr_flags & PR_VNET) {
1801				descend = 0;
1802				continue;
1803			}
1804#endif
1805			if (prison_restrict_ip4(tpr, ip4)) {
1806				if (ip4 != NULL)
1807					ip4 = NULL;
1808				else
1809					redo_ip4 = 1;
1810			}
1811		}
1812		mtx_unlock(&pr->pr_mtx);
1813	}
1814#endif
1815#ifdef INET6
1816	while (redo_ip6) {
1817		ip6s = pr->pr_ip6s;
1818		ip6 = malloc(ip6s * sizeof(*ip6), M_PRISON, M_WAITOK);
1819		mtx_lock(&pr->pr_mtx);
1820		redo_ip6 = 0;
1821		FOREACH_PRISON_DESCENDANT_LOCKED(pr, tpr, descend) {
1822#ifdef VIMAGE
1823			if (tpr->pr_flags & PR_VNET) {
1824				descend = 0;
1825				continue;
1826			}
1827#endif
1828			if (prison_restrict_ip6(tpr, ip6)) {
1829				if (ip6 != NULL)
1830					ip6 = NULL;
1831				else
1832					redo_ip6 = 1;
1833			}
1834		}
1835		mtx_unlock(&pr->pr_mtx);
1836	}
1837#endif
1838
1839	/* Let the modules do their work. */
1840	sx_downgrade(&allprison_lock);
1841	if (born) {
1842		error = osd_jail_call(pr, PR_METHOD_CREATE, opts);
1843		if (error) {
1844			(void)osd_jail_call(pr, PR_METHOD_REMOVE, NULL);
1845			prison_deref(pr, created
1846			    ? PD_LIST_SLOCKED
1847			    : PD_DEREF | PD_LIST_SLOCKED);
1848			goto done_errmsg;
1849		}
1850	}
1851	error = osd_jail_call(pr, PR_METHOD_SET, opts);
1852	if (error) {
1853		if (born)
1854			(void)osd_jail_call(pr, PR_METHOD_REMOVE, NULL);
1855		prison_deref(pr, created
1856		    ? PD_LIST_SLOCKED
1857		    : PD_DEREF | PD_LIST_SLOCKED);
1858		goto done_errmsg;
1859	}
1860
1861	/* Attach this process to the prison if requested. */
1862	if (flags & JAIL_ATTACH) {
1863		mtx_lock(&pr->pr_mtx);
1864		error = do_jail_attach(td, pr);
1865		if (error) {
1866			vfs_opterror(opts, "attach failed");
1867			if (!created)
1868				prison_deref(pr, PD_DEREF);
1869			goto done_errmsg;
1870		}
1871	}
1872
1873#ifdef RACCT
1874	if (racct_enable && !created) {
1875		if (!(flags & JAIL_ATTACH))
1876			sx_sunlock(&allprison_lock);
1877		prison_racct_modify(pr);
1878		if (!(flags & JAIL_ATTACH))
1879			sx_slock(&allprison_lock);
1880	}
1881#endif
1882
1883	td->td_retval[0] = pr->pr_id;
1884
1885	/*
1886	 * Now that it is all there, drop the temporary reference from existing
1887	 * prisons.  Or add a reference to newly created persistent prisons
1888	 * (which was not done earlier so that the prison would not be publicly
1889	 * visible).
1890	 */
1891	if (!created) {
1892		prison_deref(pr, (flags & JAIL_ATTACH)
1893		    ? PD_DEREF
1894		    : PD_DEREF | PD_LIST_SLOCKED);
1895	} else {
1896		if (pr_flags & PR_PERSIST) {
1897			mtx_lock(&pr->pr_mtx);
1898			pr->pr_ref++;
1899			pr->pr_uref++;
1900			mtx_unlock(&pr->pr_mtx);
1901		}
1902		if (!(flags & JAIL_ATTACH))
1903			sx_sunlock(&allprison_lock);
1904	}
1905
1906	goto done_free;
1907
1908 done_deref_locked:
1909	prison_deref(pr, created
1910	    ? PD_LOCKED | PD_LIST_XLOCKED
1911	    : PD_DEREF | PD_LOCKED | PD_LIST_XLOCKED);
1912	goto done_releroot;
1913 done_unlock_list:
1914	sx_xunlock(&allprison_lock);
1915 done_releroot:
1916	if (root != NULL)
1917		vrele(root);
1918 done_errmsg:
1919	if (error) {
1920		vfs_getopt(opts, "errmsg", (void **)&errmsg, &errmsg_len);
1921		if (errmsg_len > 0) {
1922			errmsg_pos = 2 * vfs_getopt_pos(opts, "errmsg") + 1;
1923			if (errmsg_pos > 0) {
1924				if (optuio->uio_segflg == UIO_SYSSPACE)
1925					bcopy(errmsg,
1926					   optuio->uio_iov[errmsg_pos].iov_base,
1927					   errmsg_len);
1928				else
1929					copyout(errmsg,
1930					   optuio->uio_iov[errmsg_pos].iov_base,
1931					   errmsg_len);
1932			}
1933		}
1934	}
1935 done_free:
1936#ifdef INET
1937	free(ip4, M_PRISON);
1938#endif
1939#ifdef INET6
1940	free(ip6, M_PRISON);
1941#endif
1942	if (g_path != NULL)
1943		free(g_path, M_TEMP);
1944	vfs_freeopts(opts);
1945	return (error);
1946}
1947
1948
1949/*
1950 * struct jail_get_args {
1951 *	struct iovec *iovp;
1952 *	unsigned int iovcnt;
1953 *	int flags;
1954 * };
1955 */
1956int
1957sys_jail_get(struct thread *td, struct jail_get_args *uap)
1958{
1959	struct uio *auio;
1960	int error;
1961
1962	/* Check that we have an even number of iovecs. */
1963	if (uap->iovcnt & 1)
1964		return (EINVAL);
1965
1966	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
1967	if (error)
1968		return (error);
1969	error = kern_jail_get(td, auio, uap->flags);
1970	if (error == 0)
1971		error = copyout(auio->uio_iov, uap->iovp,
1972		    uap->iovcnt * sizeof (struct iovec));
1973	free(auio, M_IOV);
1974	return (error);
1975}
1976
1977int
1978kern_jail_get(struct thread *td, struct uio *optuio, int flags)
1979{
1980	struct prison *pr, *mypr;
1981	struct vfsopt *opt;
1982	struct vfsoptlist *opts;
1983	char *errmsg, *name;
1984	int error, errmsg_len, errmsg_pos, fi, i, jid, len, locked, pos;
1985
1986	if (flags & ~JAIL_GET_MASK)
1987		return (EINVAL);
1988
1989	/* Get the parameter list. */
1990	error = vfs_buildopts(optuio, &opts);
1991	if (error)
1992		return (error);
1993	errmsg_pos = vfs_getopt_pos(opts, "errmsg");
1994	mypr = td->td_ucred->cr_prison;
1995
1996	/*
1997	 * Find the prison specified by one of: lastjid, jid, name.
1998	 */
1999	sx_slock(&allprison_lock);
2000	error = vfs_copyopt(opts, "lastjid", &jid, sizeof(jid));
2001	if (error == 0) {
2002		TAILQ_FOREACH(pr, &allprison, pr_list) {
2003			if (pr->pr_id > jid && prison_ischild(mypr, pr)) {
2004				mtx_lock(&pr->pr_mtx);
2005				if (pr->pr_ref > 0 &&
2006				    (pr->pr_uref > 0 || (flags & JAIL_DYING)))
2007					break;
2008				mtx_unlock(&pr->pr_mtx);
2009			}
2010		}
2011		if (pr != NULL)
2012			goto found_prison;
2013		error = ENOENT;
2014		vfs_opterror(opts, "no jail after %d", jid);
2015		goto done_unlock_list;
2016	} else if (error != ENOENT)
2017		goto done_unlock_list;
2018
2019	error = vfs_copyopt(opts, "jid", &jid, sizeof(jid));
2020	if (error == 0) {
2021		if (jid != 0) {
2022			pr = prison_find_child(mypr, jid);
2023			if (pr != NULL) {
2024				if (pr->pr_uref == 0 && !(flags & JAIL_DYING)) {
2025					mtx_unlock(&pr->pr_mtx);
2026					error = ENOENT;
2027					vfs_opterror(opts, "jail %d is dying",
2028					    jid);
2029					goto done_unlock_list;
2030				}
2031				goto found_prison;
2032			}
2033			error = ENOENT;
2034			vfs_opterror(opts, "jail %d not found", jid);
2035			goto done_unlock_list;
2036		}
2037	} else if (error != ENOENT)
2038		goto done_unlock_list;
2039
2040	error = vfs_getopt(opts, "name", (void **)&name, &len);
2041	if (error == 0) {
2042		if (len == 0 || name[len - 1] != '\0') {
2043			error = EINVAL;
2044			goto done_unlock_list;
2045		}
2046		pr = prison_find_name(mypr, name);
2047		if (pr != NULL) {
2048			if (pr->pr_uref == 0 && !(flags & JAIL_DYING)) {
2049				mtx_unlock(&pr->pr_mtx);
2050				error = ENOENT;
2051				vfs_opterror(opts, "jail \"%s\" is dying",
2052				    name);
2053				goto done_unlock_list;
2054			}
2055			goto found_prison;
2056		}
2057		error = ENOENT;
2058		vfs_opterror(opts, "jail \"%s\" not found", name);
2059		goto done_unlock_list;
2060	} else if (error != ENOENT)
2061		goto done_unlock_list;
2062
2063	vfs_opterror(opts, "no jail specified");
2064	error = ENOENT;
2065	goto done_unlock_list;
2066
2067 found_prison:
2068	/* Get the parameters of the prison. */
2069	pr->pr_ref++;
2070	locked = PD_LOCKED;
2071	td->td_retval[0] = pr->pr_id;
2072	error = vfs_setopt(opts, "jid", &pr->pr_id, sizeof(pr->pr_id));
2073	if (error != 0 && error != ENOENT)
2074		goto done_deref;
2075	i = (pr->pr_parent == mypr) ? 0 : pr->pr_parent->pr_id;
2076	error = vfs_setopt(opts, "parent", &i, sizeof(i));
2077	if (error != 0 && error != ENOENT)
2078		goto done_deref;
2079	error = vfs_setopts(opts, "name", prison_name(mypr, pr));
2080	if (error != 0 && error != ENOENT)
2081		goto done_deref;
2082	error = vfs_setopt(opts, "cpuset.id", &pr->pr_cpuset->cs_id,
2083	    sizeof(pr->pr_cpuset->cs_id));
2084	if (error != 0 && error != ENOENT)
2085		goto done_deref;
2086	error = vfs_setopts(opts, "path", prison_path(mypr, pr));
2087	if (error != 0 && error != ENOENT)
2088		goto done_deref;
2089#ifdef INET
2090	error = vfs_setopt_part(opts, "ip4.addr", pr->pr_ip4,
2091	    pr->pr_ip4s * sizeof(*pr->pr_ip4));
2092	if (error != 0 && error != ENOENT)
2093		goto done_deref;
2094#endif
2095#ifdef INET6
2096	error = vfs_setopt_part(opts, "ip6.addr", pr->pr_ip6,
2097	    pr->pr_ip6s * sizeof(*pr->pr_ip6));
2098	if (error != 0 && error != ENOENT)
2099		goto done_deref;
2100#endif
2101	error = vfs_setopt(opts, "securelevel", &pr->pr_securelevel,
2102	    sizeof(pr->pr_securelevel));
2103	if (error != 0 && error != ENOENT)
2104		goto done_deref;
2105	error = vfs_setopt(opts, "children.cur", &pr->pr_childcount,
2106	    sizeof(pr->pr_childcount));
2107	if (error != 0 && error != ENOENT)
2108		goto done_deref;
2109	error = vfs_setopt(opts, "children.max", &pr->pr_childmax,
2110	    sizeof(pr->pr_childmax));
2111	if (error != 0 && error != ENOENT)
2112		goto done_deref;
2113	error = vfs_setopts(opts, "host.hostname", pr->pr_hostname);
2114	if (error != 0 && error != ENOENT)
2115		goto done_deref;
2116	error = vfs_setopts(opts, "host.domainname", pr->pr_domainname);
2117	if (error != 0 && error != ENOENT)
2118		goto done_deref;
2119	error = vfs_setopts(opts, "host.hostuuid", pr->pr_hostuuid);
2120	if (error != 0 && error != ENOENT)
2121		goto done_deref;
2122#ifdef COMPAT_FREEBSD32
2123	if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
2124		uint32_t hid32 = pr->pr_hostid;
2125
2126		error = vfs_setopt(opts, "host.hostid", &hid32, sizeof(hid32));
2127	} else
2128#endif
2129	error = vfs_setopt(opts, "host.hostid", &pr->pr_hostid,
2130	    sizeof(pr->pr_hostid));
2131	if (error != 0 && error != ENOENT)
2132		goto done_deref;
2133	error = vfs_setopt(opts, "enforce_statfs", &pr->pr_enforce_statfs,
2134	    sizeof(pr->pr_enforce_statfs));
2135	if (error != 0 && error != ENOENT)
2136		goto done_deref;
2137	error = vfs_setopt(opts, "devfs_ruleset", &pr->pr_devfs_rsnum,
2138	    sizeof(pr->pr_devfs_rsnum));
2139	if (error != 0 && error != ENOENT)
2140		goto done_deref;
2141	for (fi = 0; fi < nitems(pr_flag_names); fi++) {
2142		if (pr_flag_names[fi] == NULL)
2143			continue;
2144		i = (pr->pr_flags & (1 << fi)) ? 1 : 0;
2145		error = vfs_setopt(opts, pr_flag_names[fi], &i, sizeof(i));
2146		if (error != 0 && error != ENOENT)
2147			goto done_deref;
2148		i = !i;
2149		error = vfs_setopt(opts, pr_flag_nonames[fi], &i, sizeof(i));
2150		if (error != 0 && error != ENOENT)
2151			goto done_deref;
2152	}
2153	for (fi = 0; fi < nitems(pr_flag_jailsys); fi++) {
2154		i = pr->pr_flags &
2155		    (pr_flag_jailsys[fi].disable | pr_flag_jailsys[fi].new);
2156		i = pr_flag_jailsys[fi].disable &&
2157		      (i == pr_flag_jailsys[fi].disable) ? JAIL_SYS_DISABLE
2158		    : (i == pr_flag_jailsys[fi].new) ? JAIL_SYS_NEW
2159		    : JAIL_SYS_INHERIT;
2160		error =
2161		    vfs_setopt(opts, pr_flag_jailsys[fi].name, &i, sizeof(i));
2162		if (error != 0 && error != ENOENT)
2163			goto done_deref;
2164	}
2165	for (fi = 0; fi < nitems(pr_allow_names); fi++) {
2166		if (pr_allow_names[fi] == NULL)
2167			continue;
2168		i = (pr->pr_allow & (1 << fi)) ? 1 : 0;
2169		error = vfs_setopt(opts, pr_allow_names[fi], &i, sizeof(i));
2170		if (error != 0 && error != ENOENT)
2171			goto done_deref;
2172		i = !i;
2173		error = vfs_setopt(opts, pr_allow_nonames[fi], &i, sizeof(i));
2174		if (error != 0 && error != ENOENT)
2175			goto done_deref;
2176	}
2177	i = (pr->pr_uref == 0);
2178	error = vfs_setopt(opts, "dying", &i, sizeof(i));
2179	if (error != 0 && error != ENOENT)
2180		goto done_deref;
2181	i = !i;
2182	error = vfs_setopt(opts, "nodying", &i, sizeof(i));
2183	if (error != 0 && error != ENOENT)
2184		goto done_deref;
2185	error = vfs_setopt(opts, "osreldate", &pr->pr_osreldate,
2186	    sizeof(pr->pr_osreldate));
2187	if (error != 0 && error != ENOENT)
2188		goto done_deref;
2189	error = vfs_setopts(opts, "osrelease", pr->pr_osrelease);
2190	if (error != 0 && error != ENOENT)
2191		goto done_deref;
2192
2193	/* Get the module parameters. */
2194	mtx_unlock(&pr->pr_mtx);
2195	locked = 0;
2196	error = osd_jail_call(pr, PR_METHOD_GET, opts);
2197	if (error)
2198		goto done_deref;
2199	prison_deref(pr, PD_DEREF | PD_LIST_SLOCKED);
2200
2201	/* By now, all parameters should have been noted. */
2202	TAILQ_FOREACH(opt, opts, link) {
2203		if (!opt->seen && strcmp(opt->name, "errmsg")) {
2204			error = EINVAL;
2205			vfs_opterror(opts, "unknown parameter: %s", opt->name);
2206			goto done_errmsg;
2207		}
2208	}
2209
2210	/* Write the fetched parameters back to userspace. */
2211	error = 0;
2212	TAILQ_FOREACH(opt, opts, link) {
2213		if (opt->pos >= 0 && opt->pos != errmsg_pos) {
2214			pos = 2 * opt->pos + 1;
2215			optuio->uio_iov[pos].iov_len = opt->len;
2216			if (opt->value != NULL) {
2217				if (optuio->uio_segflg == UIO_SYSSPACE) {
2218					bcopy(opt->value,
2219					    optuio->uio_iov[pos].iov_base,
2220					    opt->len);
2221				} else {
2222					error = copyout(opt->value,
2223					    optuio->uio_iov[pos].iov_base,
2224					    opt->len);
2225					if (error)
2226						break;
2227				}
2228			}
2229		}
2230	}
2231	goto done_errmsg;
2232
2233 done_deref:
2234	prison_deref(pr, locked | PD_DEREF | PD_LIST_SLOCKED);
2235	goto done_errmsg;
2236
2237 done_unlock_list:
2238	sx_sunlock(&allprison_lock);
2239 done_errmsg:
2240	if (error && errmsg_pos >= 0) {
2241		vfs_getopt(opts, "errmsg", (void **)&errmsg, &errmsg_len);
2242		errmsg_pos = 2 * errmsg_pos + 1;
2243		if (errmsg_len > 0) {
2244			if (optuio->uio_segflg == UIO_SYSSPACE)
2245				bcopy(errmsg,
2246				    optuio->uio_iov[errmsg_pos].iov_base,
2247				    errmsg_len);
2248			else
2249				copyout(errmsg,
2250				    optuio->uio_iov[errmsg_pos].iov_base,
2251				    errmsg_len);
2252		}
2253	}
2254	vfs_freeopts(opts);
2255	return (error);
2256}
2257
2258
2259/*
2260 * struct jail_remove_args {
2261 *	int jid;
2262 * };
2263 */
2264int
2265sys_jail_remove(struct thread *td, struct jail_remove_args *uap)
2266{
2267	struct prison *pr, *cpr, *lpr, *tpr;
2268	int descend, error;
2269
2270	error = priv_check(td, PRIV_JAIL_REMOVE);
2271	if (error)
2272		return (error);
2273
2274	sx_xlock(&allprison_lock);
2275	pr = prison_find_child(td->td_ucred->cr_prison, uap->jid);
2276	if (pr == NULL) {
2277		sx_xunlock(&allprison_lock);
2278		return (EINVAL);
2279	}
2280
2281	/* Remove all descendants of this prison, then remove this prison. */
2282	pr->pr_ref++;
2283	if (!LIST_EMPTY(&pr->pr_children)) {
2284		mtx_unlock(&pr->pr_mtx);
2285		lpr = NULL;
2286		FOREACH_PRISON_DESCENDANT(pr, cpr, descend) {
2287			mtx_lock(&cpr->pr_mtx);
2288			if (cpr->pr_ref > 0) {
2289				tpr = cpr;
2290				cpr->pr_ref++;
2291			} else {
2292				/* Already removed - do not do it again. */
2293				tpr = NULL;
2294			}
2295			mtx_unlock(&cpr->pr_mtx);
2296			if (lpr != NULL) {
2297				mtx_lock(&lpr->pr_mtx);
2298				prison_remove_one(lpr);
2299				sx_xlock(&allprison_lock);
2300			}
2301			lpr = tpr;
2302		}
2303		if (lpr != NULL) {
2304			mtx_lock(&lpr->pr_mtx);
2305			prison_remove_one(lpr);
2306			sx_xlock(&allprison_lock);
2307		}
2308		mtx_lock(&pr->pr_mtx);
2309	}
2310	prison_remove_one(pr);
2311	return (0);
2312}
2313
2314static void
2315prison_remove_one(struct prison *pr)
2316{
2317	struct proc *p;
2318	int deuref;
2319
2320	/* If the prison was persistent, it is not anymore. */
2321	deuref = 0;
2322	if (pr->pr_flags & PR_PERSIST) {
2323		pr->pr_ref--;
2324		deuref = PD_DEUREF;
2325		pr->pr_flags &= ~PR_PERSIST;
2326	}
2327
2328	/*
2329	 * jail_remove added a reference.  If that's the only one, remove
2330	 * the prison now.
2331	 */
2332	KASSERT(pr->pr_ref > 0,
2333	    ("prison_remove_one removing a dead prison (jid=%d)", pr->pr_id));
2334	if (pr->pr_ref == 1) {
2335		prison_deref(pr,
2336		    deuref | PD_DEREF | PD_LOCKED | PD_LIST_XLOCKED);
2337		return;
2338	}
2339
2340	mtx_unlock(&pr->pr_mtx);
2341	sx_xunlock(&allprison_lock);
2342	/*
2343	 * Kill all processes unfortunate enough to be attached to this prison.
2344	 */
2345	sx_slock(&allproc_lock);
2346	LIST_FOREACH(p, &allproc, p_list) {
2347		PROC_LOCK(p);
2348		if (p->p_state != PRS_NEW && p->p_ucred &&
2349		    p->p_ucred->cr_prison == pr)
2350			kern_psignal(p, SIGKILL);
2351		PROC_UNLOCK(p);
2352	}
2353	sx_sunlock(&allproc_lock);
2354	/* Remove the temporary reference added by jail_remove. */
2355	prison_deref(pr, deuref | PD_DEREF);
2356}
2357
2358
2359/*
2360 * struct jail_attach_args {
2361 *	int jid;
2362 * };
2363 */
2364int
2365sys_jail_attach(struct thread *td, struct jail_attach_args *uap)
2366{
2367	struct prison *pr;
2368	int error;
2369
2370	error = priv_check(td, PRIV_JAIL_ATTACH);
2371	if (error)
2372		return (error);
2373
2374	sx_slock(&allprison_lock);
2375	pr = prison_find_child(td->td_ucred->cr_prison, uap->jid);
2376	if (pr == NULL) {
2377		sx_sunlock(&allprison_lock);
2378		return (EINVAL);
2379	}
2380
2381	/*
2382	 * Do not allow a process to attach to a prison that is not
2383	 * considered to be "alive".
2384	 */
2385	if (pr->pr_uref == 0) {
2386		mtx_unlock(&pr->pr_mtx);
2387		sx_sunlock(&allprison_lock);
2388		return (EINVAL);
2389	}
2390
2391	return (do_jail_attach(td, pr));
2392}
2393
2394static int
2395do_jail_attach(struct thread *td, struct prison *pr)
2396{
2397	struct prison *ppr;
2398	struct proc *p;
2399	struct ucred *newcred, *oldcred;
2400	int error;
2401
2402	/*
2403	 * XXX: Note that there is a slight race here if two threads
2404	 * in the same privileged process attempt to attach to two
2405	 * different jails at the same time.  It is important for
2406	 * user processes not to do this, or they might end up with
2407	 * a process root from one prison, but attached to the jail
2408	 * of another.
2409	 */
2410	pr->pr_ref++;
2411	pr->pr_uref++;
2412	mtx_unlock(&pr->pr_mtx);
2413
2414	/* Let modules do whatever they need to prepare for attaching. */
2415	error = osd_jail_call(pr, PR_METHOD_ATTACH, td);
2416	if (error) {
2417		prison_deref(pr, PD_DEREF | PD_DEUREF | PD_LIST_SLOCKED);
2418		return (error);
2419	}
2420	sx_sunlock(&allprison_lock);
2421
2422	/*
2423	 * Reparent the newly attached process to this jail.
2424	 */
2425	ppr = td->td_ucred->cr_prison;
2426	p = td->td_proc;
2427	error = cpuset_setproc_update_set(p, pr->pr_cpuset);
2428	if (error)
2429		goto e_revert_osd;
2430
2431	vn_lock(pr->pr_root, LK_EXCLUSIVE | LK_RETRY);
2432	if ((error = change_dir(pr->pr_root, td)) != 0)
2433		goto e_unlock;
2434#ifdef MAC
2435	if ((error = mac_vnode_check_chroot(td->td_ucred, pr->pr_root)))
2436		goto e_unlock;
2437#endif
2438	VOP_UNLOCK(pr->pr_root, 0);
2439	if ((error = pwd_chroot(td, pr->pr_root)))
2440		goto e_revert_osd;
2441
2442	newcred = crget();
2443	PROC_LOCK(p);
2444	oldcred = p->p_ucred;
2445	setsugid(p);
2446	crcopy(newcred, oldcred);
2447	newcred->cr_prison = pr;
2448	proc_set_cred(p, newcred);
2449	PROC_UNLOCK(p);
2450#ifdef RACCT
2451	racct_proc_ucred_changed(p, oldcred, newcred);
2452#endif
2453	crfree(oldcred);
2454	prison_deref(ppr, PD_DEREF | PD_DEUREF);
2455	return (0);
2456 e_unlock:
2457	VOP_UNLOCK(pr->pr_root, 0);
2458 e_revert_osd:
2459	/* Tell modules this thread is still in its old jail after all. */
2460	(void)osd_jail_call(ppr, PR_METHOD_ATTACH, td);
2461	prison_deref(pr, PD_DEREF | PD_DEUREF);
2462	return (error);
2463}
2464
2465
2466/*
2467 * Returns a locked prison instance, or NULL on failure.
2468 */
2469struct prison *
2470prison_find(int prid)
2471{
2472	struct prison *pr;
2473
2474	sx_assert(&allprison_lock, SX_LOCKED);
2475	TAILQ_FOREACH(pr, &allprison, pr_list) {
2476		if (pr->pr_id == prid) {
2477			mtx_lock(&pr->pr_mtx);
2478			if (pr->pr_ref > 0)
2479				return (pr);
2480			mtx_unlock(&pr->pr_mtx);
2481		}
2482	}
2483	return (NULL);
2484}
2485
2486/*
2487 * Find a prison that is a descendant of mypr.  Returns a locked prison or NULL.
2488 */
2489struct prison *
2490prison_find_child(struct prison *mypr, int prid)
2491{
2492	struct prison *pr;
2493	int descend;
2494
2495	sx_assert(&allprison_lock, SX_LOCKED);
2496	FOREACH_PRISON_DESCENDANT(mypr, pr, descend) {
2497		if (pr->pr_id == prid) {
2498			mtx_lock(&pr->pr_mtx);
2499			if (pr->pr_ref > 0)
2500				return (pr);
2501			mtx_unlock(&pr->pr_mtx);
2502		}
2503	}
2504	return (NULL);
2505}
2506
2507/*
2508 * Look for the name relative to mypr.  Returns a locked prison or NULL.
2509 */
2510struct prison *
2511prison_find_name(struct prison *mypr, const char *name)
2512{
2513	struct prison *pr, *deadpr;
2514	size_t mylen;
2515	int descend;
2516
2517	sx_assert(&allprison_lock, SX_LOCKED);
2518	mylen = (mypr == &prison0) ? 0 : strlen(mypr->pr_name) + 1;
2519 again:
2520	deadpr = NULL;
2521	FOREACH_PRISON_DESCENDANT(mypr, pr, descend) {
2522		if (!strcmp(pr->pr_name + mylen, name)) {
2523			mtx_lock(&pr->pr_mtx);
2524			if (pr->pr_ref > 0) {
2525				if (pr->pr_uref > 0)
2526					return (pr);
2527				deadpr = pr;
2528			}
2529			mtx_unlock(&pr->pr_mtx);
2530		}
2531	}
2532	/* There was no valid prison - perhaps there was a dying one. */
2533	if (deadpr != NULL) {
2534		mtx_lock(&deadpr->pr_mtx);
2535		if (deadpr->pr_ref == 0) {
2536			mtx_unlock(&deadpr->pr_mtx);
2537			goto again;
2538		}
2539	}
2540	return (deadpr);
2541}
2542
2543/*
2544 * See if a prison has the specific flag set.
2545 */
2546int
2547prison_flag(struct ucred *cred, unsigned flag)
2548{
2549
2550	/* This is an atomic read, so no locking is necessary. */
2551	return (cred->cr_prison->pr_flags & flag);
2552}
2553
2554int
2555prison_allow(struct ucred *cred, unsigned flag)
2556{
2557
2558	/* This is an atomic read, so no locking is necessary. */
2559	return (cred->cr_prison->pr_allow & flag);
2560}
2561
2562/*
2563 * Remove a prison reference.  If that was the last reference, remove the
2564 * prison itself - but not in this context in case there are locks held.
2565 */
2566void
2567prison_free_locked(struct prison *pr)
2568{
2569
2570	mtx_assert(&pr->pr_mtx, MA_OWNED);
2571	pr->pr_ref--;
2572	if (pr->pr_ref == 0) {
2573		mtx_unlock(&pr->pr_mtx);
2574		TASK_INIT(&pr->pr_task, 0, prison_complete, pr);
2575		taskqueue_enqueue(taskqueue_thread, &pr->pr_task);
2576		return;
2577	}
2578	mtx_unlock(&pr->pr_mtx);
2579}
2580
2581void
2582prison_free(struct prison *pr)
2583{
2584
2585	mtx_lock(&pr->pr_mtx);
2586	prison_free_locked(pr);
2587}
2588
2589static void
2590prison_complete(void *context, int pending)
2591{
2592
2593	prison_deref((struct prison *)context, 0);
2594}
2595
2596/*
2597 * Remove a prison reference (usually).  This internal version assumes no
2598 * mutexes are held, except perhaps the prison itself.  If there are no more
2599 * references, release and delist the prison.  On completion, the prison lock
2600 * and the allprison lock are both unlocked.
2601 */
2602static void
2603prison_deref(struct prison *pr, int flags)
2604{
2605	struct prison *ppr, *tpr;
2606	int ref, lasturef;
2607
2608	if (!(flags & PD_LOCKED))
2609		mtx_lock(&pr->pr_mtx);
2610	for (;;) {
2611		if (flags & PD_DEUREF) {
2612			pr->pr_uref--;
2613			lasturef = pr->pr_uref == 0;
2614			if (lasturef)
2615				pr->pr_ref++;
2616			KASSERT(prison0.pr_uref != 0, ("prison0 pr_uref=0"));
2617		} else
2618			lasturef = 0;
2619		if (flags & PD_DEREF)
2620			pr->pr_ref--;
2621		ref = pr->pr_ref;
2622		mtx_unlock(&pr->pr_mtx);
2623
2624		/*
2625		 * Tell the modules if the last user reference was removed
2626		 * (even it sticks around in dying state).
2627		 */
2628		if (lasturef) {
2629			if (!(flags & (PD_LIST_SLOCKED | PD_LIST_XLOCKED))) {
2630				if (ref > 1) {
2631					sx_slock(&allprison_lock);
2632					flags |= PD_LIST_SLOCKED;
2633				} else {
2634					sx_xlock(&allprison_lock);
2635					flags |= PD_LIST_XLOCKED;
2636				}
2637			}
2638			(void)osd_jail_call(pr, PR_METHOD_REMOVE, NULL);
2639			mtx_lock(&pr->pr_mtx);
2640			ref = --pr->pr_ref;
2641			mtx_unlock(&pr->pr_mtx);
2642		}
2643
2644		/* If the prison still has references, nothing else to do. */
2645		if (ref > 0) {
2646			if (flags & PD_LIST_SLOCKED)
2647				sx_sunlock(&allprison_lock);
2648			else if (flags & PD_LIST_XLOCKED)
2649				sx_xunlock(&allprison_lock);
2650			return;
2651		}
2652
2653		if (flags & PD_LIST_SLOCKED) {
2654			if (!sx_try_upgrade(&allprison_lock)) {
2655				sx_sunlock(&allprison_lock);
2656				sx_xlock(&allprison_lock);
2657			}
2658		} else if (!(flags & PD_LIST_XLOCKED))
2659			sx_xlock(&allprison_lock);
2660
2661		TAILQ_REMOVE(&allprison, pr, pr_list);
2662		LIST_REMOVE(pr, pr_sibling);
2663		ppr = pr->pr_parent;
2664		for (tpr = ppr; tpr != NULL; tpr = tpr->pr_parent)
2665			tpr->pr_childcount--;
2666		sx_xunlock(&allprison_lock);
2667
2668#ifdef VIMAGE
2669		if (pr->pr_vnet != ppr->pr_vnet)
2670			vnet_destroy(pr->pr_vnet);
2671#endif
2672		if (pr->pr_root != NULL)
2673			vrele(pr->pr_root);
2674		mtx_destroy(&pr->pr_mtx);
2675#ifdef INET
2676		free(pr->pr_ip4, M_PRISON);
2677#endif
2678#ifdef INET6
2679		free(pr->pr_ip6, M_PRISON);
2680#endif
2681		if (pr->pr_cpuset != NULL)
2682			cpuset_rel(pr->pr_cpuset);
2683		osd_jail_exit(pr);
2684#ifdef RACCT
2685		if (racct_enable)
2686			prison_racct_detach(pr);
2687#endif
2688		free(pr, M_PRISON);
2689
2690		/* Removing a prison frees a reference on its parent. */
2691		pr = ppr;
2692		mtx_lock(&pr->pr_mtx);
2693		flags = PD_DEREF | PD_DEUREF;
2694	}
2695}
2696
2697void
2698prison_hold_locked(struct prison *pr)
2699{
2700
2701	mtx_assert(&pr->pr_mtx, MA_OWNED);
2702	KASSERT(pr->pr_ref > 0,
2703	    ("Trying to hold dead prison (jid=%d).", pr->pr_id));
2704	pr->pr_ref++;
2705}
2706
2707void
2708prison_hold(struct prison *pr)
2709{
2710
2711	mtx_lock(&pr->pr_mtx);
2712	prison_hold_locked(pr);
2713	mtx_unlock(&pr->pr_mtx);
2714}
2715
2716void
2717prison_proc_hold(struct prison *pr)
2718{
2719
2720	mtx_lock(&pr->pr_mtx);
2721	KASSERT(pr->pr_uref > 0,
2722	    ("Cannot add a process to a non-alive prison (jid=%d)", pr->pr_id));
2723	pr->pr_uref++;
2724	mtx_unlock(&pr->pr_mtx);
2725}
2726
2727void
2728prison_proc_free(struct prison *pr)
2729{
2730
2731	mtx_lock(&pr->pr_mtx);
2732	KASSERT(pr->pr_uref > 0,
2733	    ("Trying to kill a process in a dead prison (jid=%d)", pr->pr_id));
2734	prison_deref(pr, PD_DEUREF | PD_LOCKED);
2735}
2736
2737
2738#ifdef INET
2739/*
2740 * Restrict a prison's IP address list with its parent's, possibly replacing
2741 * it.  Return true if the replacement buffer was used (or would have been).
2742 */
2743static int
2744prison_restrict_ip4(struct prison *pr, struct in_addr *newip4)
2745{
2746	int ii, ij, used;
2747	struct prison *ppr;
2748
2749	ppr = pr->pr_parent;
2750	if (!(pr->pr_flags & PR_IP4_USER)) {
2751		/* This has no user settings, so just copy the parent's list. */
2752		if (pr->pr_ip4s < ppr->pr_ip4s) {
2753			/*
2754			 * There's no room for the parent's list.  Use the
2755			 * new list buffer, which is assumed to be big enough
2756			 * (if it was passed).  If there's no buffer, try to
2757			 * allocate one.
2758			 */
2759			used = 1;
2760			if (newip4 == NULL) {
2761				newip4 = malloc(ppr->pr_ip4s * sizeof(*newip4),
2762				    M_PRISON, M_NOWAIT);
2763				if (newip4 != NULL)
2764					used = 0;
2765			}
2766			if (newip4 != NULL) {
2767				bcopy(ppr->pr_ip4, newip4,
2768				    ppr->pr_ip4s * sizeof(*newip4));
2769				free(pr->pr_ip4, M_PRISON);
2770				pr->pr_ip4 = newip4;
2771				pr->pr_ip4s = ppr->pr_ip4s;
2772			}
2773			return (used);
2774		}
2775		pr->pr_ip4s = ppr->pr_ip4s;
2776		if (pr->pr_ip4s > 0)
2777			bcopy(ppr->pr_ip4, pr->pr_ip4,
2778			    pr->pr_ip4s * sizeof(*newip4));
2779		else if (pr->pr_ip4 != NULL) {
2780			free(pr->pr_ip4, M_PRISON);
2781			pr->pr_ip4 = NULL;
2782		}
2783	} else if (pr->pr_ip4s > 0) {
2784		/* Remove addresses that aren't in the parent. */
2785		for (ij = 0; ij < ppr->pr_ip4s; ij++)
2786			if (pr->pr_ip4[0].s_addr == ppr->pr_ip4[ij].s_addr)
2787				break;
2788		if (ij < ppr->pr_ip4s)
2789			ii = 1;
2790		else {
2791			bcopy(pr->pr_ip4 + 1, pr->pr_ip4,
2792			    --pr->pr_ip4s * sizeof(*pr->pr_ip4));
2793			ii = 0;
2794		}
2795		for (ij = 1; ii < pr->pr_ip4s; ) {
2796			if (pr->pr_ip4[ii].s_addr == ppr->pr_ip4[0].s_addr) {
2797				ii++;
2798				continue;
2799			}
2800			switch (ij >= ppr->pr_ip4s ? -1 :
2801				qcmp_v4(&pr->pr_ip4[ii], &ppr->pr_ip4[ij])) {
2802			case -1:
2803				bcopy(pr->pr_ip4 + ii + 1, pr->pr_ip4 + ii,
2804				    (--pr->pr_ip4s - ii) * sizeof(*pr->pr_ip4));
2805				break;
2806			case 0:
2807				ii++;
2808				ij++;
2809				break;
2810			case 1:
2811				ij++;
2812				break;
2813			}
2814		}
2815		if (pr->pr_ip4s == 0) {
2816			free(pr->pr_ip4, M_PRISON);
2817			pr->pr_ip4 = NULL;
2818		}
2819	}
2820	return (0);
2821}
2822
2823/*
2824 * Pass back primary IPv4 address of this jail.
2825 *
2826 * If not restricted return success but do not alter the address.  Caller has
2827 * to make sure to initialize it correctly (e.g. INADDR_ANY).
2828 *
2829 * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv4.
2830 * Address returned in NBO.
2831 */
2832int
2833prison_get_ip4(struct ucred *cred, struct in_addr *ia)
2834{
2835	struct prison *pr;
2836
2837	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2838	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
2839
2840	pr = cred->cr_prison;
2841	if (!(pr->pr_flags & PR_IP4))
2842		return (0);
2843	mtx_lock(&pr->pr_mtx);
2844	if (!(pr->pr_flags & PR_IP4)) {
2845		mtx_unlock(&pr->pr_mtx);
2846		return (0);
2847	}
2848	if (pr->pr_ip4 == NULL) {
2849		mtx_unlock(&pr->pr_mtx);
2850		return (EAFNOSUPPORT);
2851	}
2852
2853	ia->s_addr = pr->pr_ip4[0].s_addr;
2854	mtx_unlock(&pr->pr_mtx);
2855	return (0);
2856}
2857
2858/*
2859 * Return 1 if we should do proper source address selection or are not jailed.
2860 * We will return 0 if we should bypass source address selection in favour
2861 * of the primary jail IPv4 address. Only in this case *ia will be updated and
2862 * returned in NBO.
2863 * Return EAFNOSUPPORT, in case this jail does not allow IPv4.
2864 */
2865int
2866prison_saddrsel_ip4(struct ucred *cred, struct in_addr *ia)
2867{
2868	struct prison *pr;
2869	struct in_addr lia;
2870	int error;
2871
2872	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2873	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
2874
2875	if (!jailed(cred))
2876		return (1);
2877
2878	pr = cred->cr_prison;
2879	if (pr->pr_flags & PR_IP4_SADDRSEL)
2880		return (1);
2881
2882	lia.s_addr = INADDR_ANY;
2883	error = prison_get_ip4(cred, &lia);
2884	if (error)
2885		return (error);
2886	if (lia.s_addr == INADDR_ANY)
2887		return (1);
2888
2889	ia->s_addr = lia.s_addr;
2890	return (0);
2891}
2892
2893/*
2894 * Return true if pr1 and pr2 have the same IPv4 address restrictions.
2895 */
2896int
2897prison_equal_ip4(struct prison *pr1, struct prison *pr2)
2898{
2899
2900	if (pr1 == pr2)
2901		return (1);
2902
2903	/*
2904	 * No need to lock since the PR_IP4_USER flag can't be altered for
2905	 * existing prisons.
2906	 */
2907	while (pr1 != &prison0 &&
2908#ifdef VIMAGE
2909	       !(pr1->pr_flags & PR_VNET) &&
2910#endif
2911	       !(pr1->pr_flags & PR_IP4_USER))
2912		pr1 = pr1->pr_parent;
2913	while (pr2 != &prison0 &&
2914#ifdef VIMAGE
2915	       !(pr2->pr_flags & PR_VNET) &&
2916#endif
2917	       !(pr2->pr_flags & PR_IP4_USER))
2918		pr2 = pr2->pr_parent;
2919	return (pr1 == pr2);
2920}
2921
2922/*
2923 * Make sure our (source) address is set to something meaningful to this
2924 * jail.
2925 *
2926 * Returns 0 if jail doesn't restrict IPv4 or if address belongs to jail,
2927 * EADDRNOTAVAIL if the address doesn't belong, or EAFNOSUPPORT if the jail
2928 * doesn't allow IPv4.  Address passed in in NBO and returned in NBO.
2929 */
2930int
2931prison_local_ip4(struct ucred *cred, struct in_addr *ia)
2932{
2933	struct prison *pr;
2934	struct in_addr ia0;
2935	int error;
2936
2937	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2938	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
2939
2940	pr = cred->cr_prison;
2941	if (!(pr->pr_flags & PR_IP4))
2942		return (0);
2943	mtx_lock(&pr->pr_mtx);
2944	if (!(pr->pr_flags & PR_IP4)) {
2945		mtx_unlock(&pr->pr_mtx);
2946		return (0);
2947	}
2948	if (pr->pr_ip4 == NULL) {
2949		mtx_unlock(&pr->pr_mtx);
2950		return (EAFNOSUPPORT);
2951	}
2952
2953	ia0.s_addr = ntohl(ia->s_addr);
2954	if (ia0.s_addr == INADDR_LOOPBACK) {
2955		ia->s_addr = pr->pr_ip4[0].s_addr;
2956		mtx_unlock(&pr->pr_mtx);
2957		return (0);
2958	}
2959
2960	if (ia0.s_addr == INADDR_ANY) {
2961		/*
2962		 * In case there is only 1 IPv4 address, bind directly.
2963		 */
2964		if (pr->pr_ip4s == 1)
2965			ia->s_addr = pr->pr_ip4[0].s_addr;
2966		mtx_unlock(&pr->pr_mtx);
2967		return (0);
2968	}
2969
2970	error = _prison_check_ip4(pr, ia);
2971	mtx_unlock(&pr->pr_mtx);
2972	return (error);
2973}
2974
2975/*
2976 * Rewrite destination address in case we will connect to loopback address.
2977 *
2978 * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv4.
2979 * Address passed in in NBO and returned in NBO.
2980 */
2981int
2982prison_remote_ip4(struct ucred *cred, struct in_addr *ia)
2983{
2984	struct prison *pr;
2985
2986	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2987	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
2988
2989	pr = cred->cr_prison;
2990	if (!(pr->pr_flags & PR_IP4))
2991		return (0);
2992	mtx_lock(&pr->pr_mtx);
2993	if (!(pr->pr_flags & PR_IP4)) {
2994		mtx_unlock(&pr->pr_mtx);
2995		return (0);
2996	}
2997	if (pr->pr_ip4 == NULL) {
2998		mtx_unlock(&pr->pr_mtx);
2999		return (EAFNOSUPPORT);
3000	}
3001
3002	if (ntohl(ia->s_addr) == INADDR_LOOPBACK) {
3003		ia->s_addr = pr->pr_ip4[0].s_addr;
3004		mtx_unlock(&pr->pr_mtx);
3005		return (0);
3006	}
3007
3008	/*
3009	 * Return success because nothing had to be changed.
3010	 */
3011	mtx_unlock(&pr->pr_mtx);
3012	return (0);
3013}
3014
3015/*
3016 * Check if given address belongs to the jail referenced by cred/prison.
3017 *
3018 * Returns 0 if jail doesn't restrict IPv4 or if address belongs to jail,
3019 * EADDRNOTAVAIL if the address doesn't belong, or EAFNOSUPPORT if the jail
3020 * doesn't allow IPv4.  Address passed in in NBO.
3021 */
3022static int
3023_prison_check_ip4(const struct prison *pr, const struct in_addr *ia)
3024{
3025	int i, a, z, d;
3026
3027	/*
3028	 * Check the primary IP.
3029	 */
3030	if (pr->pr_ip4[0].s_addr == ia->s_addr)
3031		return (0);
3032
3033	/*
3034	 * All the other IPs are sorted so we can do a binary search.
3035	 */
3036	a = 0;
3037	z = pr->pr_ip4s - 2;
3038	while (a <= z) {
3039		i = (a + z) / 2;
3040		d = qcmp_v4(&pr->pr_ip4[i+1], ia);
3041		if (d > 0)
3042			z = i - 1;
3043		else if (d < 0)
3044			a = i + 1;
3045		else
3046			return (0);
3047	}
3048
3049	return (EADDRNOTAVAIL);
3050}
3051
3052int
3053prison_check_ip4(const struct ucred *cred, const struct in_addr *ia)
3054{
3055	struct prison *pr;
3056	int error;
3057
3058	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3059	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
3060
3061	pr = cred->cr_prison;
3062	if (!(pr->pr_flags & PR_IP4))
3063		return (0);
3064	mtx_lock(&pr->pr_mtx);
3065	if (!(pr->pr_flags & PR_IP4)) {
3066		mtx_unlock(&pr->pr_mtx);
3067		return (0);
3068	}
3069	if (pr->pr_ip4 == NULL) {
3070		mtx_unlock(&pr->pr_mtx);
3071		return (EAFNOSUPPORT);
3072	}
3073
3074	error = _prison_check_ip4(pr, ia);
3075	mtx_unlock(&pr->pr_mtx);
3076	return (error);
3077}
3078#endif
3079
3080#ifdef INET6
3081static int
3082prison_restrict_ip6(struct prison *pr, struct in6_addr *newip6)
3083{
3084	int ii, ij, used;
3085	struct prison *ppr;
3086
3087	ppr = pr->pr_parent;
3088	if (!(pr->pr_flags & PR_IP6_USER)) {
3089		/* This has no user settings, so just copy the parent's list. */
3090		if (pr->pr_ip6s < ppr->pr_ip6s) {
3091			/*
3092			 * There's no room for the parent's list.  Use the
3093			 * new list buffer, which is assumed to be big enough
3094			 * (if it was passed).  If there's no buffer, try to
3095			 * allocate one.
3096			 */
3097			used = 1;
3098			if (newip6 == NULL) {
3099				newip6 = malloc(ppr->pr_ip6s * sizeof(*newip6),
3100				    M_PRISON, M_NOWAIT);
3101				if (newip6 != NULL)
3102					used = 0;
3103			}
3104			if (newip6 != NULL) {
3105				bcopy(ppr->pr_ip6, newip6,
3106				    ppr->pr_ip6s * sizeof(*newip6));
3107				free(pr->pr_ip6, M_PRISON);
3108				pr->pr_ip6 = newip6;
3109				pr->pr_ip6s = ppr->pr_ip6s;
3110			}
3111			return (used);
3112		}
3113		pr->pr_ip6s = ppr->pr_ip6s;
3114		if (pr->pr_ip6s > 0)
3115			bcopy(ppr->pr_ip6, pr->pr_ip6,
3116			    pr->pr_ip6s * sizeof(*newip6));
3117		else if (pr->pr_ip6 != NULL) {
3118			free(pr->pr_ip6, M_PRISON);
3119			pr->pr_ip6 = NULL;
3120		}
3121	} else if (pr->pr_ip6s > 0) {
3122		/* Remove addresses that aren't in the parent. */
3123		for (ij = 0; ij < ppr->pr_ip6s; ij++)
3124			if (IN6_ARE_ADDR_EQUAL(&pr->pr_ip6[0],
3125			    &ppr->pr_ip6[ij]))
3126				break;
3127		if (ij < ppr->pr_ip6s)
3128			ii = 1;
3129		else {
3130			bcopy(pr->pr_ip6 + 1, pr->pr_ip6,
3131			    --pr->pr_ip6s * sizeof(*pr->pr_ip6));
3132			ii = 0;
3133		}
3134		for (ij = 1; ii < pr->pr_ip6s; ) {
3135			if (IN6_ARE_ADDR_EQUAL(&pr->pr_ip6[ii],
3136			    &ppr->pr_ip6[0])) {
3137				ii++;
3138				continue;
3139			}
3140			switch (ij >= ppr->pr_ip6s ? -1 :
3141				qcmp_v6(&pr->pr_ip6[ii], &ppr->pr_ip6[ij])) {
3142			case -1:
3143				bcopy(pr->pr_ip6 + ii + 1, pr->pr_ip6 + ii,
3144				    (--pr->pr_ip6s - ii) * sizeof(*pr->pr_ip6));
3145				break;
3146			case 0:
3147				ii++;
3148				ij++;
3149				break;
3150			case 1:
3151				ij++;
3152				break;
3153			}
3154		}
3155		if (pr->pr_ip6s == 0) {
3156			free(pr->pr_ip6, M_PRISON);
3157			pr->pr_ip6 = NULL;
3158		}
3159	}
3160	return 0;
3161}
3162
3163/*
3164 * Pass back primary IPv6 address for this jail.
3165 *
3166 * If not restricted return success but do not alter the address.  Caller has
3167 * to make sure to initialize it correctly (e.g. IN6ADDR_ANY_INIT).
3168 *
3169 * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv6.
3170 */
3171int
3172prison_get_ip6(struct ucred *cred, struct in6_addr *ia6)
3173{
3174	struct prison *pr;
3175
3176	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3177	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
3178
3179	pr = cred->cr_prison;
3180	if (!(pr->pr_flags & PR_IP6))
3181		return (0);
3182	mtx_lock(&pr->pr_mtx);
3183	if (!(pr->pr_flags & PR_IP6)) {
3184		mtx_unlock(&pr->pr_mtx);
3185		return (0);
3186	}
3187	if (pr->pr_ip6 == NULL) {
3188		mtx_unlock(&pr->pr_mtx);
3189		return (EAFNOSUPPORT);
3190	}
3191
3192	bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
3193	mtx_unlock(&pr->pr_mtx);
3194	return (0);
3195}
3196
3197/*
3198 * Return 1 if we should do proper source address selection or are not jailed.
3199 * We will return 0 if we should bypass source address selection in favour
3200 * of the primary jail IPv6 address. Only in this case *ia will be updated and
3201 * returned in NBO.
3202 * Return EAFNOSUPPORT, in case this jail does not allow IPv6.
3203 */
3204int
3205prison_saddrsel_ip6(struct ucred *cred, struct in6_addr *ia6)
3206{
3207	struct prison *pr;
3208	struct in6_addr lia6;
3209	int error;
3210
3211	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3212	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
3213
3214	if (!jailed(cred))
3215		return (1);
3216
3217	pr = cred->cr_prison;
3218	if (pr->pr_flags & PR_IP6_SADDRSEL)
3219		return (1);
3220
3221	lia6 = in6addr_any;
3222	error = prison_get_ip6(cred, &lia6);
3223	if (error)
3224		return (error);
3225	if (IN6_IS_ADDR_UNSPECIFIED(&lia6))
3226		return (1);
3227
3228	bcopy(&lia6, ia6, sizeof(struct in6_addr));
3229	return (0);
3230}
3231
3232/*
3233 * Return true if pr1 and pr2 have the same IPv6 address restrictions.
3234 */
3235int
3236prison_equal_ip6(struct prison *pr1, struct prison *pr2)
3237{
3238
3239	if (pr1 == pr2)
3240		return (1);
3241
3242	while (pr1 != &prison0 &&
3243#ifdef VIMAGE
3244	       !(pr1->pr_flags & PR_VNET) &&
3245#endif
3246	       !(pr1->pr_flags & PR_IP6_USER))
3247		pr1 = pr1->pr_parent;
3248	while (pr2 != &prison0 &&
3249#ifdef VIMAGE
3250	       !(pr2->pr_flags & PR_VNET) &&
3251#endif
3252	       !(pr2->pr_flags & PR_IP6_USER))
3253		pr2 = pr2->pr_parent;
3254	return (pr1 == pr2);
3255}
3256
3257/*
3258 * Make sure our (source) address is set to something meaningful to this jail.
3259 *
3260 * v6only should be set based on (inp->inp_flags & IN6P_IPV6_V6ONLY != 0)
3261 * when needed while binding.
3262 *
3263 * Returns 0 if jail doesn't restrict IPv6 or if address belongs to jail,
3264 * EADDRNOTAVAIL if the address doesn't belong, or EAFNOSUPPORT if the jail
3265 * doesn't allow IPv6.
3266 */
3267int
3268prison_local_ip6(struct ucred *cred, struct in6_addr *ia6, int v6only)
3269{
3270	struct prison *pr;
3271	int error;
3272
3273	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3274	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
3275
3276	pr = cred->cr_prison;
3277	if (!(pr->pr_flags & PR_IP6))
3278		return (0);
3279	mtx_lock(&pr->pr_mtx);
3280	if (!(pr->pr_flags & PR_IP6)) {
3281		mtx_unlock(&pr->pr_mtx);
3282		return (0);
3283	}
3284	if (pr->pr_ip6 == NULL) {
3285		mtx_unlock(&pr->pr_mtx);
3286		return (EAFNOSUPPORT);
3287	}
3288
3289	if (IN6_IS_ADDR_LOOPBACK(ia6)) {
3290		bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
3291		mtx_unlock(&pr->pr_mtx);
3292		return (0);
3293	}
3294
3295	if (IN6_IS_ADDR_UNSPECIFIED(ia6)) {
3296		/*
3297		 * In case there is only 1 IPv6 address, and v6only is true,
3298		 * then bind directly.
3299		 */
3300		if (v6only != 0 && pr->pr_ip6s == 1)
3301			bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
3302		mtx_unlock(&pr->pr_mtx);
3303		return (0);
3304	}
3305
3306	error = _prison_check_ip6(pr, ia6);
3307	mtx_unlock(&pr->pr_mtx);
3308	return (error);
3309}
3310
3311/*
3312 * Rewrite destination address in case we will connect to loopback address.
3313 *
3314 * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv6.
3315 */
3316int
3317prison_remote_ip6(struct ucred *cred, struct in6_addr *ia6)
3318{
3319	struct prison *pr;
3320
3321	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3322	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
3323
3324	pr = cred->cr_prison;
3325	if (!(pr->pr_flags & PR_IP6))
3326		return (0);
3327	mtx_lock(&pr->pr_mtx);
3328	if (!(pr->pr_flags & PR_IP6)) {
3329		mtx_unlock(&pr->pr_mtx);
3330		return (0);
3331	}
3332	if (pr->pr_ip6 == NULL) {
3333		mtx_unlock(&pr->pr_mtx);
3334		return (EAFNOSUPPORT);
3335	}
3336
3337	if (IN6_IS_ADDR_LOOPBACK(ia6)) {
3338		bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
3339		mtx_unlock(&pr->pr_mtx);
3340		return (0);
3341	}
3342
3343	/*
3344	 * Return success because nothing had to be changed.
3345	 */
3346	mtx_unlock(&pr->pr_mtx);
3347	return (0);
3348}
3349
3350/*
3351 * Check if given address belongs to the jail referenced by cred/prison.
3352 *
3353 * Returns 0 if jail doesn't restrict IPv6 or if address belongs to jail,
3354 * EADDRNOTAVAIL if the address doesn't belong, or EAFNOSUPPORT if the jail
3355 * doesn't allow IPv6.
3356 */
3357static int
3358_prison_check_ip6(struct prison *pr, struct in6_addr *ia6)
3359{
3360	int i, a, z, d;
3361
3362	/*
3363	 * Check the primary IP.
3364	 */
3365	if (IN6_ARE_ADDR_EQUAL(&pr->pr_ip6[0], ia6))
3366		return (0);
3367
3368	/*
3369	 * All the other IPs are sorted so we can do a binary search.
3370	 */
3371	a = 0;
3372	z = pr->pr_ip6s - 2;
3373	while (a <= z) {
3374		i = (a + z) / 2;
3375		d = qcmp_v6(&pr->pr_ip6[i+1], ia6);
3376		if (d > 0)
3377			z = i - 1;
3378		else if (d < 0)
3379			a = i + 1;
3380		else
3381			return (0);
3382	}
3383
3384	return (EADDRNOTAVAIL);
3385}
3386
3387int
3388prison_check_ip6(struct ucred *cred, struct in6_addr *ia6)
3389{
3390	struct prison *pr;
3391	int error;
3392
3393	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3394	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
3395
3396	pr = cred->cr_prison;
3397	if (!(pr->pr_flags & PR_IP6))
3398		return (0);
3399	mtx_lock(&pr->pr_mtx);
3400	if (!(pr->pr_flags & PR_IP6)) {
3401		mtx_unlock(&pr->pr_mtx);
3402		return (0);
3403	}
3404	if (pr->pr_ip6 == NULL) {
3405		mtx_unlock(&pr->pr_mtx);
3406		return (EAFNOSUPPORT);
3407	}
3408
3409	error = _prison_check_ip6(pr, ia6);
3410	mtx_unlock(&pr->pr_mtx);
3411	return (error);
3412}
3413#endif
3414
3415/*
3416 * Check if a jail supports the given address family.
3417 *
3418 * Returns 0 if not jailed or the address family is supported, EAFNOSUPPORT
3419 * if not.
3420 */
3421int
3422prison_check_af(struct ucred *cred, int af)
3423{
3424	struct prison *pr;
3425	int error;
3426
3427	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3428
3429	pr = cred->cr_prison;
3430#ifdef VIMAGE
3431	/* Prisons with their own network stack are not limited. */
3432	if (prison_owns_vnet(cred))
3433		return (0);
3434#endif
3435
3436	error = 0;
3437	switch (af)
3438	{
3439#ifdef INET
3440	case AF_INET:
3441		if (pr->pr_flags & PR_IP4)
3442		{
3443			mtx_lock(&pr->pr_mtx);
3444			if ((pr->pr_flags & PR_IP4) && pr->pr_ip4 == NULL)
3445				error = EAFNOSUPPORT;
3446			mtx_unlock(&pr->pr_mtx);
3447		}
3448		break;
3449#endif
3450#ifdef INET6
3451	case AF_INET6:
3452		if (pr->pr_flags & PR_IP6)
3453		{
3454			mtx_lock(&pr->pr_mtx);
3455			if ((pr->pr_flags & PR_IP6) && pr->pr_ip6 == NULL)
3456				error = EAFNOSUPPORT;
3457			mtx_unlock(&pr->pr_mtx);
3458		}
3459		break;
3460#endif
3461	case AF_LOCAL:
3462	case AF_ROUTE:
3463		break;
3464	default:
3465		if (!(pr->pr_allow & PR_ALLOW_SOCKET_AF))
3466			error = EAFNOSUPPORT;
3467	}
3468	return (error);
3469}
3470
3471/*
3472 * Check if given address belongs to the jail referenced by cred (wrapper to
3473 * prison_check_ip[46]).
3474 *
3475 * Returns 0 if jail doesn't restrict the address family or if address belongs
3476 * to jail, EADDRNOTAVAIL if the address doesn't belong, or EAFNOSUPPORT if
3477 * the jail doesn't allow the address family.  IPv4 Address passed in in NBO.
3478 */
3479int
3480prison_if(struct ucred *cred, struct sockaddr *sa)
3481{
3482#ifdef INET
3483	struct sockaddr_in *sai;
3484#endif
3485#ifdef INET6
3486	struct sockaddr_in6 *sai6;
3487#endif
3488	int error;
3489
3490	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
3491	KASSERT(sa != NULL, ("%s: sa is NULL", __func__));
3492
3493#ifdef VIMAGE
3494	if (prison_owns_vnet(cred))
3495		return (0);
3496#endif
3497
3498	error = 0;
3499	switch (sa->sa_family)
3500	{
3501#ifdef INET
3502	case AF_INET:
3503		sai = (struct sockaddr_in *)sa;
3504		error = prison_check_ip4(cred, &sai->sin_addr);
3505		break;
3506#endif
3507#ifdef INET6
3508	case AF_INET6:
3509		sai6 = (struct sockaddr_in6 *)sa;
3510		error = prison_check_ip6(cred, &sai6->sin6_addr);
3511		break;
3512#endif
3513	default:
3514		if (!(cred->cr_prison->pr_allow & PR_ALLOW_SOCKET_AF))
3515			error = EAFNOSUPPORT;
3516	}
3517	return (error);
3518}
3519
3520/*
3521 * Return 0 if jails permit p1 to frob p2, otherwise ESRCH.
3522 */
3523int
3524prison_check(struct ucred *cred1, struct ucred *cred2)
3525{
3526
3527	return ((cred1->cr_prison == cred2->cr_prison ||
3528	    prison_ischild(cred1->cr_prison, cred2->cr_prison)) ? 0 : ESRCH);
3529}
3530
3531/*
3532 * Return 1 if p2 is a child of p1, otherwise 0.
3533 */
3534int
3535prison_ischild(struct prison *pr1, struct prison *pr2)
3536{
3537
3538	for (pr2 = pr2->pr_parent; pr2 != NULL; pr2 = pr2->pr_parent)
3539		if (pr1 == pr2)
3540			return (1);
3541	return (0);
3542}
3543
3544/*
3545 * Return 1 if the passed credential is in a jail, otherwise 0.
3546 */
3547int
3548jailed(struct ucred *cred)
3549{
3550
3551	return (cred->cr_prison != &prison0);
3552}
3553
3554/*
3555 * Return 1 if the passed credential is in a jail and that jail does not
3556 * have its own virtual network stack, otherwise 0.
3557 */
3558int
3559jailed_without_vnet(struct ucred *cred)
3560{
3561
3562	if (!jailed(cred))
3563		return (0);
3564#ifdef VIMAGE
3565	if (prison_owns_vnet(cred))
3566		return (0);
3567#endif
3568
3569	return (1);
3570}
3571
3572/*
3573 * Return the correct hostname (domainname, et al) for the passed credential.
3574 */
3575void
3576getcredhostname(struct ucred *cred, char *buf, size_t size)
3577{
3578	struct prison *pr;
3579
3580	/*
3581	 * A NULL credential can be used to shortcut to the physical
3582	 * system's hostname.
3583	 */
3584	pr = (cred != NULL) ? cred->cr_prison : &prison0;
3585	mtx_lock(&pr->pr_mtx);
3586	strlcpy(buf, pr->pr_hostname, size);
3587	mtx_unlock(&pr->pr_mtx);
3588}
3589
3590void
3591getcreddomainname(struct ucred *cred, char *buf, size_t size)
3592{
3593
3594	mtx_lock(&cred->cr_prison->pr_mtx);
3595	strlcpy(buf, cred->cr_prison->pr_domainname, size);
3596	mtx_unlock(&cred->cr_prison->pr_mtx);
3597}
3598
3599void
3600getcredhostuuid(struct ucred *cred, char *buf, size_t size)
3601{
3602
3603	mtx_lock(&cred->cr_prison->pr_mtx);
3604	strlcpy(buf, cred->cr_prison->pr_hostuuid, size);
3605	mtx_unlock(&cred->cr_prison->pr_mtx);
3606}
3607
3608void
3609getcredhostid(struct ucred *cred, unsigned long *hostid)
3610{
3611
3612	mtx_lock(&cred->cr_prison->pr_mtx);
3613	*hostid = cred->cr_prison->pr_hostid;
3614	mtx_unlock(&cred->cr_prison->pr_mtx);
3615}
3616
3617#ifdef VIMAGE
3618/*
3619 * Determine whether the prison represented by cred owns
3620 * its vnet rather than having it inherited.
3621 *
3622 * Returns 1 in case the prison owns the vnet, 0 otherwise.
3623 */
3624int
3625prison_owns_vnet(struct ucred *cred)
3626{
3627
3628	/*
3629	 * vnets cannot be added/removed after jail creation,
3630	 * so no need to lock here.
3631	 */
3632	return (cred->cr_prison->pr_flags & PR_VNET ? 1 : 0);
3633}
3634#endif
3635
3636/*
3637 * Determine whether the subject represented by cred can "see"
3638 * status of a mount point.
3639 * Returns: 0 for permitted, ENOENT otherwise.
3640 * XXX: This function should be called cr_canseemount() and should be
3641 *      placed in kern_prot.c.
3642 */
3643int
3644prison_canseemount(struct ucred *cred, struct mount *mp)
3645{
3646	struct prison *pr;
3647	struct statfs *sp;
3648	size_t len;
3649
3650	pr = cred->cr_prison;
3651	if (pr->pr_enforce_statfs == 0)
3652		return (0);
3653	if (pr->pr_root->v_mount == mp)
3654		return (0);
3655	if (pr->pr_enforce_statfs == 2)
3656		return (ENOENT);
3657	/*
3658	 * If jail's chroot directory is set to "/" we should be able to see
3659	 * all mount-points from inside a jail.
3660	 * This is ugly check, but this is the only situation when jail's
3661	 * directory ends with '/'.
3662	 */
3663	if (strcmp(pr->pr_path, "/") == 0)
3664		return (0);
3665	len = strlen(pr->pr_path);
3666	sp = &mp->mnt_stat;
3667	if (strncmp(pr->pr_path, sp->f_mntonname, len) != 0)
3668		return (ENOENT);
3669	/*
3670	 * Be sure that we don't have situation where jail's root directory
3671	 * is "/some/path" and mount point is "/some/pathpath".
3672	 */
3673	if (sp->f_mntonname[len] != '\0' && sp->f_mntonname[len] != '/')
3674		return (ENOENT);
3675	return (0);
3676}
3677
3678void
3679prison_enforce_statfs(struct ucred *cred, struct mount *mp, struct statfs *sp)
3680{
3681	char jpath[MAXPATHLEN];
3682	struct prison *pr;
3683	size_t len;
3684
3685	pr = cred->cr_prison;
3686	if (pr->pr_enforce_statfs == 0)
3687		return;
3688	if (prison_canseemount(cred, mp) != 0) {
3689		bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
3690		strlcpy(sp->f_mntonname, "[restricted]",
3691		    sizeof(sp->f_mntonname));
3692		return;
3693	}
3694	if (pr->pr_root->v_mount == mp) {
3695		/*
3696		 * Clear current buffer data, so we are sure nothing from
3697		 * the valid path left there.
3698		 */
3699		bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
3700		*sp->f_mntonname = '/';
3701		return;
3702	}
3703	/*
3704	 * If jail's chroot directory is set to "/" we should be able to see
3705	 * all mount-points from inside a jail.
3706	 */
3707	if (strcmp(pr->pr_path, "/") == 0)
3708		return;
3709	len = strlen(pr->pr_path);
3710	strlcpy(jpath, sp->f_mntonname + len, sizeof(jpath));
3711	/*
3712	 * Clear current buffer data, so we are sure nothing from
3713	 * the valid path left there.
3714	 */
3715	bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
3716	if (*jpath == '\0') {
3717		/* Should never happen. */
3718		*sp->f_mntonname = '/';
3719	} else {
3720		strlcpy(sp->f_mntonname, jpath, sizeof(sp->f_mntonname));
3721	}
3722}
3723
3724/*
3725 * Check with permission for a specific privilege is granted within jail.  We
3726 * have a specific list of accepted privileges; the rest are denied.
3727 */
3728int
3729prison_priv_check(struct ucred *cred, int priv)
3730{
3731
3732	if (!jailed(cred))
3733		return (0);
3734
3735#ifdef VIMAGE
3736	/*
3737	 * Privileges specific to prisons with a virtual network stack.
3738	 * There might be a duplicate entry here in case the privilege
3739	 * is only granted conditionally in the legacy jail case.
3740	 */
3741	switch (priv) {
3742#ifdef notyet
3743		/*
3744		 * NFS-specific privileges.
3745		 */
3746	case PRIV_NFS_DAEMON:
3747	case PRIV_NFS_LOCKD:
3748#endif
3749		/*
3750		 * Network stack privileges.
3751		 */
3752	case PRIV_NET_BRIDGE:
3753	case PRIV_NET_GRE:
3754	case PRIV_NET_BPF:
3755	case PRIV_NET_RAW:		/* Dup, cond. in legacy jail case. */
3756	case PRIV_NET_ROUTE:
3757	case PRIV_NET_TAP:
3758	case PRIV_NET_SETIFMTU:
3759	case PRIV_NET_SETIFFLAGS:
3760	case PRIV_NET_SETIFCAP:
3761	case PRIV_NET_SETIFDESCR:
3762	case PRIV_NET_SETIFNAME	:
3763	case PRIV_NET_SETIFMETRIC:
3764	case PRIV_NET_SETIFPHYS:
3765	case PRIV_NET_SETIFMAC:
3766	case PRIV_NET_ADDMULTI:
3767	case PRIV_NET_DELMULTI:
3768	case PRIV_NET_HWIOCTL:
3769	case PRIV_NET_SETLLADDR:
3770	case PRIV_NET_ADDIFGROUP:
3771	case PRIV_NET_DELIFGROUP:
3772	case PRIV_NET_IFCREATE:
3773	case PRIV_NET_IFDESTROY:
3774	case PRIV_NET_ADDIFADDR:
3775	case PRIV_NET_DELIFADDR:
3776	case PRIV_NET_LAGG:
3777	case PRIV_NET_GIF:
3778	case PRIV_NET_SETIFVNET:
3779	case PRIV_NET_SETIFFIB:
3780
3781		/*
3782		 * 802.11-related privileges.
3783		 */
3784	case PRIV_NET80211_GETKEY:
3785#ifdef notyet
3786	case PRIV_NET80211_MANAGE:		/* XXX-BZ discuss with sam@ */
3787#endif
3788
3789#ifdef notyet
3790		/*
3791		 * ATM privileges.
3792		 */
3793	case PRIV_NETATM_CFG:
3794	case PRIV_NETATM_ADD:
3795	case PRIV_NETATM_DEL:
3796	case PRIV_NETATM_SET:
3797
3798		/*
3799		 * Bluetooth privileges.
3800		 */
3801	case PRIV_NETBLUETOOTH_RAW:
3802#endif
3803
3804		/*
3805		 * Netgraph and netgraph module privileges.
3806		 */
3807	case PRIV_NETGRAPH_CONTROL:
3808#ifdef notyet
3809	case PRIV_NETGRAPH_TTY:
3810#endif
3811
3812		/*
3813		 * IPv4 and IPv6 privileges.
3814		 */
3815	case PRIV_NETINET_IPFW:
3816	case PRIV_NETINET_DIVERT:
3817	case PRIV_NETINET_PF:
3818	case PRIV_NETINET_DUMMYNET:
3819	case PRIV_NETINET_CARP:
3820	case PRIV_NETINET_MROUTE:
3821	case PRIV_NETINET_RAW:
3822	case PRIV_NETINET_ADDRCTRL6:
3823	case PRIV_NETINET_ND6:
3824	case PRIV_NETINET_SCOPE6:
3825	case PRIV_NETINET_ALIFETIME6:
3826	case PRIV_NETINET_IPSEC:
3827	case PRIV_NETINET_BINDANY:
3828
3829#ifdef notyet
3830		/*
3831		 * NCP privileges.
3832		 */
3833	case PRIV_NETNCP:
3834
3835		/*
3836		 * SMB privileges.
3837		 */
3838	case PRIV_NETSMB:
3839#endif
3840
3841	/*
3842	 * No default: or deny here.
3843	 * In case of no permit fall through to next switch().
3844	 */
3845		if (cred->cr_prison->pr_flags & PR_VNET)
3846			return (0);
3847	}
3848#endif /* VIMAGE */
3849
3850	switch (priv) {
3851
3852		/*
3853		 * Allow ktrace privileges for root in jail.
3854		 */
3855	case PRIV_KTRACE:
3856
3857#if 0
3858		/*
3859		 * Allow jailed processes to configure audit identity and
3860		 * submit audit records (login, etc).  In the future we may
3861		 * want to further refine the relationship between audit and
3862		 * jail.
3863		 */
3864	case PRIV_AUDIT_GETAUDIT:
3865	case PRIV_AUDIT_SETAUDIT:
3866	case PRIV_AUDIT_SUBMIT:
3867#endif
3868
3869		/*
3870		 * Allow jailed processes to manipulate process UNIX
3871		 * credentials in any way they see fit.
3872		 */
3873	case PRIV_CRED_SETUID:
3874	case PRIV_CRED_SETEUID:
3875	case PRIV_CRED_SETGID:
3876	case PRIV_CRED_SETEGID:
3877	case PRIV_CRED_SETGROUPS:
3878	case PRIV_CRED_SETREUID:
3879	case PRIV_CRED_SETREGID:
3880	case PRIV_CRED_SETRESUID:
3881	case PRIV_CRED_SETRESGID:
3882
3883		/*
3884		 * Jail implements visibility constraints already, so allow
3885		 * jailed root to override uid/gid-based constraints.
3886		 */
3887	case PRIV_SEEOTHERGIDS:
3888	case PRIV_SEEOTHERUIDS:
3889
3890		/*
3891		 * Jail implements inter-process debugging limits already, so
3892		 * allow jailed root various debugging privileges.
3893		 */
3894	case PRIV_DEBUG_DIFFCRED:
3895	case PRIV_DEBUG_SUGID:
3896	case PRIV_DEBUG_UNPRIV:
3897
3898		/*
3899		 * Allow jail to set various resource limits and login
3900		 * properties, and for now, exceed process resource limits.
3901		 */
3902	case PRIV_PROC_LIMIT:
3903	case PRIV_PROC_SETLOGIN:
3904	case PRIV_PROC_SETRLIMIT:
3905
3906		/*
3907		 * System V and POSIX IPC privileges are granted in jail.
3908		 */
3909	case PRIV_IPC_READ:
3910	case PRIV_IPC_WRITE:
3911	case PRIV_IPC_ADMIN:
3912	case PRIV_IPC_MSGSIZE:
3913	case PRIV_MQ_ADMIN:
3914
3915		/*
3916		 * Jail operations within a jail work on child jails.
3917		 */
3918	case PRIV_JAIL_ATTACH:
3919	case PRIV_JAIL_SET:
3920	case PRIV_JAIL_REMOVE:
3921
3922		/*
3923		 * Jail implements its own inter-process limits, so allow
3924		 * root processes in jail to change scheduling on other
3925		 * processes in the same jail.  Likewise for signalling.
3926		 */
3927	case PRIV_SCHED_DIFFCRED:
3928	case PRIV_SCHED_CPUSET:
3929	case PRIV_SIGNAL_DIFFCRED:
3930	case PRIV_SIGNAL_SUGID:
3931
3932		/*
3933		 * Allow jailed processes to write to sysctls marked as jail
3934		 * writable.
3935		 */
3936	case PRIV_SYSCTL_WRITEJAIL:
3937
3938		/*
3939		 * Allow root in jail to manage a variety of quota
3940		 * properties.  These should likely be conditional on a
3941		 * configuration option.
3942		 */
3943	case PRIV_VFS_GETQUOTA:
3944	case PRIV_VFS_SETQUOTA:
3945
3946		/*
3947		 * Since Jail relies on chroot() to implement file system
3948		 * protections, grant many VFS privileges to root in jail.
3949		 * Be careful to exclude mount-related and NFS-related
3950		 * privileges.
3951		 */
3952	case PRIV_VFS_READ:
3953	case PRIV_VFS_WRITE:
3954	case PRIV_VFS_ADMIN:
3955	case PRIV_VFS_EXEC:
3956	case PRIV_VFS_LOOKUP:
3957	case PRIV_VFS_BLOCKRESERVE:	/* XXXRW: Slightly surprising. */
3958	case PRIV_VFS_CHFLAGS_DEV:
3959	case PRIV_VFS_CHOWN:
3960	case PRIV_VFS_CHROOT:
3961	case PRIV_VFS_RETAINSUGID:
3962	case PRIV_VFS_FCHROOT:
3963	case PRIV_VFS_LINK:
3964	case PRIV_VFS_SETGID:
3965	case PRIV_VFS_STAT:
3966	case PRIV_VFS_STICKYFILE:
3967
3968		/*
3969		 * As in the non-jail case, non-root users are expected to be
3970		 * able to read kernel/phyiscal memory (provided /dev/[k]mem
3971		 * exists in the jail and they have permission to access it).
3972		 */
3973	case PRIV_KMEM_READ:
3974		return (0);
3975
3976		/*
3977		 * Depending on the global setting, allow privilege of
3978		 * setting system flags.
3979		 */
3980	case PRIV_VFS_SYSFLAGS:
3981		if (cred->cr_prison->pr_allow & PR_ALLOW_CHFLAGS)
3982			return (0);
3983		else
3984			return (EPERM);
3985
3986		/*
3987		 * Depending on the global setting, allow privilege of
3988		 * mounting/unmounting file systems.
3989		 */
3990	case PRIV_VFS_MOUNT:
3991	case PRIV_VFS_UNMOUNT:
3992	case PRIV_VFS_MOUNT_NONUSER:
3993	case PRIV_VFS_MOUNT_OWNER:
3994		if (cred->cr_prison->pr_allow & PR_ALLOW_MOUNT &&
3995		    cred->cr_prison->pr_enforce_statfs < 2)
3996			return (0);
3997		else
3998			return (EPERM);
3999
4000		/*
4001		 * Allow jailed root to bind reserved ports and reuse in-use
4002		 * ports.
4003		 */
4004	case PRIV_NETINET_RESERVEDPORT:
4005	case PRIV_NETINET_REUSEPORT:
4006		return (0);
4007
4008		/*
4009		 * Allow jailed root to set certian IPv4/6 (option) headers.
4010		 */
4011	case PRIV_NETINET_SETHDROPTS:
4012		return (0);
4013
4014		/*
4015		 * Conditionally allow creating raw sockets in jail.
4016		 */
4017	case PRIV_NETINET_RAW:
4018		if (cred->cr_prison->pr_allow & PR_ALLOW_RAW_SOCKETS)
4019			return (0);
4020		else
4021			return (EPERM);
4022
4023		/*
4024		 * Since jail implements its own visibility limits on netstat
4025		 * sysctls, allow getcred.  This allows identd to work in
4026		 * jail.
4027		 */
4028	case PRIV_NETINET_GETCRED:
4029		return (0);
4030
4031		/*
4032		 * Allow jailed root to set loginclass.
4033		 */
4034	case PRIV_PROC_SETLOGINCLASS:
4035		return (0);
4036
4037	default:
4038		/*
4039		 * In all remaining cases, deny the privilege request.  This
4040		 * includes almost all network privileges, many system
4041		 * configuration privileges.
4042		 */
4043		return (EPERM);
4044	}
4045}
4046
4047/*
4048 * Return the part of pr2's name that is relative to pr1, or the whole name
4049 * if it does not directly follow.
4050 */
4051
4052char *
4053prison_name(struct prison *pr1, struct prison *pr2)
4054{
4055	char *name;
4056
4057	/* Jails see themselves as "0" (if they see themselves at all). */
4058	if (pr1 == pr2)
4059		return "0";
4060	name = pr2->pr_name;
4061	if (prison_ischild(pr1, pr2)) {
4062		/*
4063		 * pr1 isn't locked (and allprison_lock may not be either)
4064		 * so its length can't be counted on.  But the number of dots
4065		 * can be counted on - and counted.
4066		 */
4067		for (; pr1 != &prison0; pr1 = pr1->pr_parent)
4068			name = strchr(name, '.') + 1;
4069	}
4070	return (name);
4071}
4072
4073/*
4074 * Return the part of pr2's path that is relative to pr1, or the whole path
4075 * if it does not directly follow.
4076 */
4077static char *
4078prison_path(struct prison *pr1, struct prison *pr2)
4079{
4080	char *path1, *path2;
4081	int len1;
4082
4083	path1 = pr1->pr_path;
4084	path2 = pr2->pr_path;
4085	if (!strcmp(path1, "/"))
4086		return (path2);
4087	len1 = strlen(path1);
4088	if (strncmp(path1, path2, len1))
4089		return (path2);
4090	if (path2[len1] == '\0')
4091		return "/";
4092	if (path2[len1] == '/')
4093		return (path2 + len1);
4094	return (path2);
4095}
4096
4097
4098/*
4099 * Jail-related sysctls.
4100 */
4101static SYSCTL_NODE(_security, OID_AUTO, jail, CTLFLAG_RW, 0,
4102    "Jails");
4103
4104static int
4105sysctl_jail_list(SYSCTL_HANDLER_ARGS)
4106{
4107	struct xprison *xp;
4108	struct prison *pr, *cpr;
4109#ifdef INET
4110	struct in_addr *ip4 = NULL;
4111	int ip4s = 0;
4112#endif
4113#ifdef INET6
4114	struct in6_addr *ip6 = NULL;
4115	int ip6s = 0;
4116#endif
4117	int descend, error;
4118
4119	xp = malloc(sizeof(*xp), M_TEMP, M_WAITOK);
4120	pr = req->td->td_ucred->cr_prison;
4121	error = 0;
4122	sx_slock(&allprison_lock);
4123	FOREACH_PRISON_DESCENDANT(pr, cpr, descend) {
4124#if defined(INET) || defined(INET6)
4125 again:
4126#endif
4127		mtx_lock(&cpr->pr_mtx);
4128#ifdef INET
4129		if (cpr->pr_ip4s > 0) {
4130			if (ip4s < cpr->pr_ip4s) {
4131				ip4s = cpr->pr_ip4s;
4132				mtx_unlock(&cpr->pr_mtx);
4133				ip4 = realloc(ip4, ip4s *
4134				    sizeof(struct in_addr), M_TEMP, M_WAITOK);
4135				goto again;
4136			}
4137			bcopy(cpr->pr_ip4, ip4,
4138			    cpr->pr_ip4s * sizeof(struct in_addr));
4139		}
4140#endif
4141#ifdef INET6
4142		if (cpr->pr_ip6s > 0) {
4143			if (ip6s < cpr->pr_ip6s) {
4144				ip6s = cpr->pr_ip6s;
4145				mtx_unlock(&cpr->pr_mtx);
4146				ip6 = realloc(ip6, ip6s *
4147				    sizeof(struct in6_addr), M_TEMP, M_WAITOK);
4148				goto again;
4149			}
4150			bcopy(cpr->pr_ip6, ip6,
4151			    cpr->pr_ip6s * sizeof(struct in6_addr));
4152		}
4153#endif
4154		if (cpr->pr_ref == 0) {
4155			mtx_unlock(&cpr->pr_mtx);
4156			continue;
4157		}
4158		bzero(xp, sizeof(*xp));
4159		xp->pr_version = XPRISON_VERSION;
4160		xp->pr_id = cpr->pr_id;
4161		xp->pr_state = cpr->pr_uref > 0
4162		    ? PRISON_STATE_ALIVE : PRISON_STATE_DYING;
4163		strlcpy(xp->pr_path, prison_path(pr, cpr), sizeof(xp->pr_path));
4164		strlcpy(xp->pr_host, cpr->pr_hostname, sizeof(xp->pr_host));
4165		strlcpy(xp->pr_name, prison_name(pr, cpr), sizeof(xp->pr_name));
4166#ifdef INET
4167		xp->pr_ip4s = cpr->pr_ip4s;
4168#endif
4169#ifdef INET6
4170		xp->pr_ip6s = cpr->pr_ip6s;
4171#endif
4172		mtx_unlock(&cpr->pr_mtx);
4173		error = SYSCTL_OUT(req, xp, sizeof(*xp));
4174		if (error)
4175			break;
4176#ifdef INET
4177		if (xp->pr_ip4s > 0) {
4178			error = SYSCTL_OUT(req, ip4,
4179			    xp->pr_ip4s * sizeof(struct in_addr));
4180			if (error)
4181				break;
4182		}
4183#endif
4184#ifdef INET6
4185		if (xp->pr_ip6s > 0) {
4186			error = SYSCTL_OUT(req, ip6,
4187			    xp->pr_ip6s * sizeof(struct in6_addr));
4188			if (error)
4189				break;
4190		}
4191#endif
4192	}
4193	sx_sunlock(&allprison_lock);
4194	free(xp, M_TEMP);
4195#ifdef INET
4196	free(ip4, M_TEMP);
4197#endif
4198#ifdef INET6
4199	free(ip6, M_TEMP);
4200#endif
4201	return (error);
4202}
4203
4204SYSCTL_OID(_security_jail, OID_AUTO, list,
4205    CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
4206    sysctl_jail_list, "S", "List of active jails");
4207
4208static int
4209sysctl_jail_jailed(SYSCTL_HANDLER_ARGS)
4210{
4211	int error, injail;
4212
4213	injail = jailed(req->td->td_ucred);
4214	error = SYSCTL_OUT(req, &injail, sizeof(injail));
4215
4216	return (error);
4217}
4218
4219SYSCTL_PROC(_security_jail, OID_AUTO, jailed,
4220    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
4221    sysctl_jail_jailed, "I", "Process in jail?");
4222
4223static int
4224sysctl_jail_vnet(SYSCTL_HANDLER_ARGS)
4225{
4226	int error, havevnet;
4227#ifdef VIMAGE
4228	struct ucred *cred = req->td->td_ucred;
4229
4230	havevnet = jailed(cred) && prison_owns_vnet(cred);
4231#else
4232	havevnet = 0;
4233#endif
4234	error = SYSCTL_OUT(req, &havevnet, sizeof(havevnet));
4235
4236	return (error);
4237}
4238
4239SYSCTL_PROC(_security_jail, OID_AUTO, vnet,
4240    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
4241    sysctl_jail_vnet, "I", "Jail owns VNET?");
4242
4243#if defined(INET) || defined(INET6)
4244SYSCTL_UINT(_security_jail, OID_AUTO, jail_max_af_ips, CTLFLAG_RW,
4245    &jail_max_af_ips, 0,
4246    "Number of IP addresses a jail may have at most per address family");
4247#endif
4248
4249/*
4250 * Default parameters for jail(2) compatability.  For historical reasons,
4251 * the sysctl names have varying similarity to the parameter names.  Prisons
4252 * just see their own parameters, and can't change them.
4253 */
4254static int
4255sysctl_jail_default_allow(SYSCTL_HANDLER_ARGS)
4256{
4257	struct prison *pr;
4258	int allow, error, i;
4259
4260	pr = req->td->td_ucred->cr_prison;
4261	allow = (pr == &prison0) ? jail_default_allow : pr->pr_allow;
4262
4263	/* Get the current flag value, and convert it to a boolean. */
4264	i = (allow & arg2) ? 1 : 0;
4265	if (arg1 != NULL)
4266		i = !i;
4267	error = sysctl_handle_int(oidp, &i, 0, req);
4268	if (error || !req->newptr)
4269		return (error);
4270	i = i ? arg2 : 0;
4271	if (arg1 != NULL)
4272		i ^= arg2;
4273	/*
4274	 * The sysctls don't have CTLFLAGS_PRISON, so assume prison0
4275	 * for writing.
4276	 */
4277	mtx_lock(&prison0.pr_mtx);
4278	jail_default_allow = (jail_default_allow & ~arg2) | i;
4279	mtx_unlock(&prison0.pr_mtx);
4280	return (0);
4281}
4282
4283SYSCTL_PROC(_security_jail, OID_AUTO, set_hostname_allowed,
4284    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4285    NULL, PR_ALLOW_SET_HOSTNAME, sysctl_jail_default_allow, "I",
4286    "Processes in jail can set their hostnames");
4287SYSCTL_PROC(_security_jail, OID_AUTO, socket_unixiproute_only,
4288    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4289    (void *)1, PR_ALLOW_SOCKET_AF, sysctl_jail_default_allow, "I",
4290    "Processes in jail are limited to creating UNIX/IP/route sockets only");
4291SYSCTL_PROC(_security_jail, OID_AUTO, sysvipc_allowed,
4292    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4293    NULL, PR_ALLOW_SYSVIPC, sysctl_jail_default_allow, "I",
4294    "Processes in jail can use System V IPC primitives");
4295SYSCTL_PROC(_security_jail, OID_AUTO, allow_raw_sockets,
4296    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4297    NULL, PR_ALLOW_RAW_SOCKETS, sysctl_jail_default_allow, "I",
4298    "Prison root can create raw sockets");
4299SYSCTL_PROC(_security_jail, OID_AUTO, chflags_allowed,
4300    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4301    NULL, PR_ALLOW_CHFLAGS, sysctl_jail_default_allow, "I",
4302    "Processes in jail can alter system file flags");
4303SYSCTL_PROC(_security_jail, OID_AUTO, mount_allowed,
4304    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4305    NULL, PR_ALLOW_MOUNT, sysctl_jail_default_allow, "I",
4306    "Processes in jail can mount/unmount jail-friendly file systems");
4307SYSCTL_PROC(_security_jail, OID_AUTO, mount_devfs_allowed,
4308    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4309    NULL, PR_ALLOW_MOUNT_DEVFS, sysctl_jail_default_allow, "I",
4310    "Processes in jail can mount the devfs file system");
4311SYSCTL_PROC(_security_jail, OID_AUTO, mount_fdescfs_allowed,
4312    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4313    NULL, PR_ALLOW_MOUNT_FDESCFS, sysctl_jail_default_allow, "I",
4314    "Processes in jail can mount the fdescfs file system");
4315SYSCTL_PROC(_security_jail, OID_AUTO, mount_nullfs_allowed,
4316    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4317    NULL, PR_ALLOW_MOUNT_NULLFS, sysctl_jail_default_allow, "I",
4318    "Processes in jail can mount the nullfs file system");
4319SYSCTL_PROC(_security_jail, OID_AUTO, mount_procfs_allowed,
4320    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4321    NULL, PR_ALLOW_MOUNT_PROCFS, sysctl_jail_default_allow, "I",
4322    "Processes in jail can mount the procfs file system");
4323SYSCTL_PROC(_security_jail, OID_AUTO, mount_linprocfs_allowed,
4324    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4325    NULL, PR_ALLOW_MOUNT_LINPROCFS, sysctl_jail_default_allow, "I",
4326    "Processes in jail can mount the linprocfs file system");
4327SYSCTL_PROC(_security_jail, OID_AUTO, mount_linsysfs_allowed,
4328    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4329    NULL, PR_ALLOW_MOUNT_LINSYSFS, sysctl_jail_default_allow, "I",
4330    "Processes in jail can mount the linsysfs file system");
4331SYSCTL_PROC(_security_jail, OID_AUTO, mount_tmpfs_allowed,
4332    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4333    NULL, PR_ALLOW_MOUNT_TMPFS, sysctl_jail_default_allow, "I",
4334    "Processes in jail can mount the tmpfs file system");
4335SYSCTL_PROC(_security_jail, OID_AUTO, mount_zfs_allowed,
4336    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4337    NULL, PR_ALLOW_MOUNT_ZFS, sysctl_jail_default_allow, "I",
4338    "Processes in jail can mount the zfs file system");
4339
4340static int
4341sysctl_jail_default_level(SYSCTL_HANDLER_ARGS)
4342{
4343	struct prison *pr;
4344	int level, error;
4345
4346	pr = req->td->td_ucred->cr_prison;
4347	level = (pr == &prison0) ? *(int *)arg1 : *(int *)((char *)pr + arg2);
4348	error = sysctl_handle_int(oidp, &level, 0, req);
4349	if (error || !req->newptr)
4350		return (error);
4351	*(int *)arg1 = level;
4352	return (0);
4353}
4354
4355SYSCTL_PROC(_security_jail, OID_AUTO, enforce_statfs,
4356    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
4357    &jail_default_enforce_statfs, offsetof(struct prison, pr_enforce_statfs),
4358    sysctl_jail_default_level, "I",
4359    "Processes in jail cannot see all mounted file systems");
4360
4361SYSCTL_PROC(_security_jail, OID_AUTO, devfs_ruleset,
4362    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
4363    &jail_default_devfs_rsnum, offsetof(struct prison, pr_devfs_rsnum),
4364    sysctl_jail_default_level, "I",
4365    "Ruleset for the devfs filesystem in jail");
4366
4367/*
4368 * Nodes to describe jail parameters.  Maximum length of string parameters
4369 * is returned in the string itself, and the other parameters exist merely
4370 * to make themselves and their types known.
4371 */
4372SYSCTL_NODE(_security_jail, OID_AUTO, param, CTLFLAG_RW, 0,
4373    "Jail parameters");
4374
4375int
4376sysctl_jail_param(SYSCTL_HANDLER_ARGS)
4377{
4378	int i;
4379	long l;
4380	size_t s;
4381	char numbuf[12];
4382
4383	switch (oidp->oid_kind & CTLTYPE)
4384	{
4385	case CTLTYPE_LONG:
4386	case CTLTYPE_ULONG:
4387		l = 0;
4388#ifdef SCTL_MASK32
4389		if (!(req->flags & SCTL_MASK32))
4390#endif
4391			return (SYSCTL_OUT(req, &l, sizeof(l)));
4392	case CTLTYPE_INT:
4393	case CTLTYPE_UINT:
4394		i = 0;
4395		return (SYSCTL_OUT(req, &i, sizeof(i)));
4396	case CTLTYPE_STRING:
4397		snprintf(numbuf, sizeof(numbuf), "%jd", (intmax_t)arg2);
4398		return
4399		    (sysctl_handle_string(oidp, numbuf, sizeof(numbuf), req));
4400	case CTLTYPE_STRUCT:
4401		s = (size_t)arg2;
4402		return (SYSCTL_OUT(req, &s, sizeof(s)));
4403	}
4404	return (0);
4405}
4406
4407/*
4408 * CTLFLAG_RDTUN in the following indicates jail parameters that can be set at
4409 * jail creation time but cannot be changed in an existing jail.
4410 */
4411SYSCTL_JAIL_PARAM(, jid, CTLTYPE_INT | CTLFLAG_RDTUN, "I", "Jail ID");
4412SYSCTL_JAIL_PARAM(, parent, CTLTYPE_INT | CTLFLAG_RD, "I", "Jail parent ID");
4413SYSCTL_JAIL_PARAM_STRING(, name, CTLFLAG_RW, MAXHOSTNAMELEN, "Jail name");
4414SYSCTL_JAIL_PARAM_STRING(, path, CTLFLAG_RDTUN, MAXPATHLEN, "Jail root path");
4415SYSCTL_JAIL_PARAM(, securelevel, CTLTYPE_INT | CTLFLAG_RW,
4416    "I", "Jail secure level");
4417SYSCTL_JAIL_PARAM(, osreldate, CTLTYPE_INT | CTLFLAG_RDTUN, "I",
4418    "Jail value for kern.osreldate and uname -K");
4419SYSCTL_JAIL_PARAM_STRING(, osrelease, CTLFLAG_RDTUN, OSRELEASELEN,
4420    "Jail value for kern.osrelease and uname -r");
4421SYSCTL_JAIL_PARAM(, enforce_statfs, CTLTYPE_INT | CTLFLAG_RW,
4422    "I", "Jail cannot see all mounted file systems");
4423SYSCTL_JAIL_PARAM(, devfs_ruleset, CTLTYPE_INT | CTLFLAG_RW,
4424    "I", "Ruleset for in-jail devfs mounts");
4425SYSCTL_JAIL_PARAM(, persist, CTLTYPE_INT | CTLFLAG_RW,
4426    "B", "Jail persistence");
4427#ifdef VIMAGE
4428SYSCTL_JAIL_PARAM(, vnet, CTLTYPE_INT | CTLFLAG_RDTUN,
4429    "E,jailsys", "Virtual network stack");
4430#endif
4431SYSCTL_JAIL_PARAM(, dying, CTLTYPE_INT | CTLFLAG_RD,
4432    "B", "Jail is in the process of shutting down");
4433
4434SYSCTL_JAIL_PARAM_NODE(children, "Number of child jails");
4435SYSCTL_JAIL_PARAM(_children, cur, CTLTYPE_INT | CTLFLAG_RD,
4436    "I", "Current number of child jails");
4437SYSCTL_JAIL_PARAM(_children, max, CTLTYPE_INT | CTLFLAG_RW,
4438    "I", "Maximum number of child jails");
4439
4440SYSCTL_JAIL_PARAM_SYS_NODE(host, CTLFLAG_RW, "Jail host info");
4441SYSCTL_JAIL_PARAM_STRING(_host, hostname, CTLFLAG_RW, MAXHOSTNAMELEN,
4442    "Jail hostname");
4443SYSCTL_JAIL_PARAM_STRING(_host, domainname, CTLFLAG_RW, MAXHOSTNAMELEN,
4444    "Jail NIS domainname");
4445SYSCTL_JAIL_PARAM_STRING(_host, hostuuid, CTLFLAG_RW, HOSTUUIDLEN,
4446    "Jail host UUID");
4447SYSCTL_JAIL_PARAM(_host, hostid, CTLTYPE_ULONG | CTLFLAG_RW,
4448    "LU", "Jail host ID");
4449
4450SYSCTL_JAIL_PARAM_NODE(cpuset, "Jail cpuset");
4451SYSCTL_JAIL_PARAM(_cpuset, id, CTLTYPE_INT | CTLFLAG_RD, "I", "Jail cpuset ID");
4452
4453#ifdef INET
4454SYSCTL_JAIL_PARAM_SYS_NODE(ip4, CTLFLAG_RDTUN,
4455    "Jail IPv4 address virtualization");
4456SYSCTL_JAIL_PARAM_STRUCT(_ip4, addr, CTLFLAG_RW, sizeof(struct in_addr),
4457    "S,in_addr,a", "Jail IPv4 addresses");
4458SYSCTL_JAIL_PARAM(_ip4, saddrsel, CTLTYPE_INT | CTLFLAG_RW,
4459    "B", "Do (not) use IPv4 source address selection rather than the "
4460    "primary jail IPv4 address.");
4461#endif
4462#ifdef INET6
4463SYSCTL_JAIL_PARAM_SYS_NODE(ip6, CTLFLAG_RDTUN,
4464    "Jail IPv6 address virtualization");
4465SYSCTL_JAIL_PARAM_STRUCT(_ip6, addr, CTLFLAG_RW, sizeof(struct in6_addr),
4466    "S,in6_addr,a", "Jail IPv6 addresses");
4467SYSCTL_JAIL_PARAM(_ip6, saddrsel, CTLTYPE_INT | CTLFLAG_RW,
4468    "B", "Do (not) use IPv6 source address selection rather than the "
4469    "primary jail IPv6 address.");
4470#endif
4471
4472SYSCTL_JAIL_PARAM_NODE(allow, "Jail permission flags");
4473SYSCTL_JAIL_PARAM(_allow, set_hostname, CTLTYPE_INT | CTLFLAG_RW,
4474    "B", "Jail may set hostname");
4475SYSCTL_JAIL_PARAM(_allow, sysvipc, CTLTYPE_INT | CTLFLAG_RW,
4476    "B", "Jail may use SYSV IPC");
4477SYSCTL_JAIL_PARAM(_allow, raw_sockets, CTLTYPE_INT | CTLFLAG_RW,
4478    "B", "Jail may create raw sockets");
4479SYSCTL_JAIL_PARAM(_allow, chflags, CTLTYPE_INT | CTLFLAG_RW,
4480    "B", "Jail may alter system file flags");
4481SYSCTL_JAIL_PARAM(_allow, quotas, CTLTYPE_INT | CTLFLAG_RW,
4482    "B", "Jail may set file quotas");
4483SYSCTL_JAIL_PARAM(_allow, socket_af, CTLTYPE_INT | CTLFLAG_RW,
4484    "B", "Jail may create sockets other than just UNIX/IPv4/IPv6/route");
4485
4486SYSCTL_JAIL_PARAM_SUBNODE(allow, mount, "Jail mount/unmount permission flags");
4487SYSCTL_JAIL_PARAM(_allow_mount, , CTLTYPE_INT | CTLFLAG_RW,
4488    "B", "Jail may mount/unmount jail-friendly file systems in general");
4489SYSCTL_JAIL_PARAM(_allow_mount, devfs, CTLTYPE_INT | CTLFLAG_RW,
4490    "B", "Jail may mount the devfs file system");
4491SYSCTL_JAIL_PARAM(_allow_mount, fdescfs, CTLTYPE_INT | CTLFLAG_RW,
4492    "B", "Jail may mount the fdescfs file system");
4493SYSCTL_JAIL_PARAM(_allow_mount, nullfs, CTLTYPE_INT | CTLFLAG_RW,
4494    "B", "Jail may mount the nullfs file system");
4495SYSCTL_JAIL_PARAM(_allow_mount, procfs, CTLTYPE_INT | CTLFLAG_RW,
4496    "B", "Jail may mount the procfs file system");
4497SYSCTL_JAIL_PARAM(_allow_mount, linprocfs, CTLTYPE_INT | CTLFLAG_RW,
4498    "B", "Jail may mount the linprocfs file system");
4499SYSCTL_JAIL_PARAM(_allow_mount, linsysfs, CTLTYPE_INT | CTLFLAG_RW,
4500    "B", "Jail may mount the linsysfs file system");
4501SYSCTL_JAIL_PARAM(_allow_mount, tmpfs, CTLTYPE_INT | CTLFLAG_RW,
4502    "B", "Jail may mount the tmpfs file system");
4503SYSCTL_JAIL_PARAM(_allow_mount, zfs, CTLTYPE_INT | CTLFLAG_RW,
4504    "B", "Jail may mount the zfs file system");
4505
4506#ifdef RACCT
4507void
4508prison_racct_foreach(void (*callback)(struct racct *racct,
4509    void *arg2, void *arg3), void (*pre)(void), void (*post)(void),
4510    void *arg2, void *arg3)
4511{
4512	struct prison_racct *prr;
4513
4514	ASSERT_RACCT_ENABLED();
4515
4516	sx_slock(&allprison_lock);
4517	if (pre != NULL)
4518		(pre)();
4519	LIST_FOREACH(prr, &allprison_racct, prr_next)
4520		(callback)(prr->prr_racct, arg2, arg3);
4521	if (post != NULL)
4522		(post)();
4523	sx_sunlock(&allprison_lock);
4524}
4525
4526static struct prison_racct *
4527prison_racct_find_locked(const char *name)
4528{
4529	struct prison_racct *prr;
4530
4531	ASSERT_RACCT_ENABLED();
4532	sx_assert(&allprison_lock, SA_XLOCKED);
4533
4534	if (name[0] == '\0' || strlen(name) >= MAXHOSTNAMELEN)
4535		return (NULL);
4536
4537	LIST_FOREACH(prr, &allprison_racct, prr_next) {
4538		if (strcmp(name, prr->prr_name) != 0)
4539			continue;
4540
4541		/* Found prison_racct with a matching name? */
4542		prison_racct_hold(prr);
4543		return (prr);
4544	}
4545
4546	/* Add new prison_racct. */
4547	prr = malloc(sizeof(*prr), M_PRISON_RACCT, M_ZERO | M_WAITOK);
4548	racct_create(&prr->prr_racct);
4549
4550	strcpy(prr->prr_name, name);
4551	refcount_init(&prr->prr_refcount, 1);
4552	LIST_INSERT_HEAD(&allprison_racct, prr, prr_next);
4553
4554	return (prr);
4555}
4556
4557struct prison_racct *
4558prison_racct_find(const char *name)
4559{
4560	struct prison_racct *prr;
4561
4562	ASSERT_RACCT_ENABLED();
4563
4564	sx_xlock(&allprison_lock);
4565	prr = prison_racct_find_locked(name);
4566	sx_xunlock(&allprison_lock);
4567	return (prr);
4568}
4569
4570void
4571prison_racct_hold(struct prison_racct *prr)
4572{
4573
4574	ASSERT_RACCT_ENABLED();
4575
4576	refcount_acquire(&prr->prr_refcount);
4577}
4578
4579static void
4580prison_racct_free_locked(struct prison_racct *prr)
4581{
4582
4583	ASSERT_RACCT_ENABLED();
4584	sx_assert(&allprison_lock, SA_XLOCKED);
4585
4586	if (refcount_release(&prr->prr_refcount)) {
4587		racct_destroy(&prr->prr_racct);
4588		LIST_REMOVE(prr, prr_next);
4589		free(prr, M_PRISON_RACCT);
4590	}
4591}
4592
4593void
4594prison_racct_free(struct prison_racct *prr)
4595{
4596	int old;
4597
4598	ASSERT_RACCT_ENABLED();
4599	sx_assert(&allprison_lock, SA_UNLOCKED);
4600
4601	old = prr->prr_refcount;
4602	if (old > 1 && atomic_cmpset_int(&prr->prr_refcount, old, old - 1))
4603		return;
4604
4605	sx_xlock(&allprison_lock);
4606	prison_racct_free_locked(prr);
4607	sx_xunlock(&allprison_lock);
4608}
4609
4610static void
4611prison_racct_attach(struct prison *pr)
4612{
4613	struct prison_racct *prr;
4614
4615	ASSERT_RACCT_ENABLED();
4616	sx_assert(&allprison_lock, SA_XLOCKED);
4617
4618	prr = prison_racct_find_locked(pr->pr_name);
4619	KASSERT(prr != NULL, ("cannot find prison_racct"));
4620
4621	pr->pr_prison_racct = prr;
4622}
4623
4624/*
4625 * Handle jail renaming.  From the racct point of view, renaming means
4626 * moving from one prison_racct to another.
4627 */
4628static void
4629prison_racct_modify(struct prison *pr)
4630{
4631	struct proc *p;
4632	struct ucred *cred;
4633	struct prison_racct *oldprr;
4634
4635	ASSERT_RACCT_ENABLED();
4636
4637	sx_slock(&allproc_lock);
4638	sx_xlock(&allprison_lock);
4639
4640	if (strcmp(pr->pr_name, pr->pr_prison_racct->prr_name) == 0) {
4641		sx_xunlock(&allprison_lock);
4642		sx_sunlock(&allproc_lock);
4643		return;
4644	}
4645
4646	oldprr = pr->pr_prison_racct;
4647	pr->pr_prison_racct = NULL;
4648
4649	prison_racct_attach(pr);
4650
4651	/*
4652	 * Move resource utilisation records.
4653	 */
4654	racct_move(pr->pr_prison_racct->prr_racct, oldprr->prr_racct);
4655
4656	/*
4657	 * Force rctl to reattach rules to processes.
4658	 */
4659	FOREACH_PROC_IN_SYSTEM(p) {
4660		PROC_LOCK(p);
4661		cred = crhold(p->p_ucred);
4662		PROC_UNLOCK(p);
4663		racct_proc_ucred_changed(p, cred, cred);
4664		crfree(cred);
4665	}
4666
4667	sx_sunlock(&allproc_lock);
4668	prison_racct_free_locked(oldprr);
4669	sx_xunlock(&allprison_lock);
4670}
4671
4672static void
4673prison_racct_detach(struct prison *pr)
4674{
4675
4676	ASSERT_RACCT_ENABLED();
4677	sx_assert(&allprison_lock, SA_UNLOCKED);
4678
4679	if (pr->pr_prison_racct == NULL)
4680		return;
4681	prison_racct_free(pr->pr_prison_racct);
4682	pr->pr_prison_racct = NULL;
4683}
4684#endif /* RACCT */
4685
4686#ifdef DDB
4687
4688static void
4689db_show_prison(struct prison *pr)
4690{
4691	int fi;
4692#if defined(INET) || defined(INET6)
4693	int ii;
4694#endif
4695	unsigned jsf;
4696#ifdef INET6
4697	char ip6buf[INET6_ADDRSTRLEN];
4698#endif
4699
4700	db_printf("prison %p:\n", pr);
4701	db_printf(" jid             = %d\n", pr->pr_id);
4702	db_printf(" name            = %s\n", pr->pr_name);
4703	db_printf(" parent          = %p\n", pr->pr_parent);
4704	db_printf(" ref             = %d\n", pr->pr_ref);
4705	db_printf(" uref            = %d\n", pr->pr_uref);
4706	db_printf(" path            = %s\n", pr->pr_path);
4707	db_printf(" cpuset          = %d\n", pr->pr_cpuset
4708	    ? pr->pr_cpuset->cs_id : -1);
4709#ifdef VIMAGE
4710	db_printf(" vnet            = %p\n", pr->pr_vnet);
4711#endif
4712	db_printf(" root            = %p\n", pr->pr_root);
4713	db_printf(" securelevel     = %d\n", pr->pr_securelevel);
4714	db_printf(" devfs_rsnum     = %d\n", pr->pr_devfs_rsnum);
4715	db_printf(" children.max    = %d\n", pr->pr_childmax);
4716	db_printf(" children.cur    = %d\n", pr->pr_childcount);
4717	db_printf(" child           = %p\n", LIST_FIRST(&pr->pr_children));
4718	db_printf(" sibling         = %p\n", LIST_NEXT(pr, pr_sibling));
4719	db_printf(" flags           = 0x%x", pr->pr_flags);
4720	for (fi = 0; fi < nitems(pr_flag_names); fi++)
4721		if (pr_flag_names[fi] != NULL && (pr->pr_flags & (1 << fi)))
4722			db_printf(" %s", pr_flag_names[fi]);
4723	for (fi = 0; fi < nitems(pr_flag_jailsys); fi++) {
4724		jsf = pr->pr_flags &
4725		    (pr_flag_jailsys[fi].disable | pr_flag_jailsys[fi].new);
4726		db_printf(" %-16s= %s\n", pr_flag_jailsys[fi].name,
4727		    pr_flag_jailsys[fi].disable &&
4728		      (jsf == pr_flag_jailsys[fi].disable) ? "disable"
4729		    : (jsf == pr_flag_jailsys[fi].new) ? "new"
4730		    : "inherit");
4731	}
4732	db_printf(" allow           = 0x%x", pr->pr_allow);
4733	for (fi = 0; fi < nitems(pr_allow_names); fi++)
4734		if (pr_allow_names[fi] != NULL && (pr->pr_allow & (1 << fi)))
4735			db_printf(" %s", pr_allow_names[fi]);
4736	db_printf("\n");
4737	db_printf(" enforce_statfs  = %d\n", pr->pr_enforce_statfs);
4738	db_printf(" host.hostname   = %s\n", pr->pr_hostname);
4739	db_printf(" host.domainname = %s\n", pr->pr_domainname);
4740	db_printf(" host.hostuuid   = %s\n", pr->pr_hostuuid);
4741	db_printf(" host.hostid     = %lu\n", pr->pr_hostid);
4742#ifdef INET
4743	db_printf(" ip4s            = %d\n", pr->pr_ip4s);
4744	for (ii = 0; ii < pr->pr_ip4s; ii++)
4745		db_printf(" %s %s\n",
4746		    ii == 0 ? "ip4.addr        =" : "                 ",
4747		    inet_ntoa(pr->pr_ip4[ii]));
4748#endif
4749#ifdef INET6
4750	db_printf(" ip6s            = %d\n", pr->pr_ip6s);
4751	for (ii = 0; ii < pr->pr_ip6s; ii++)
4752		db_printf(" %s %s\n",
4753		    ii == 0 ? "ip6.addr        =" : "                 ",
4754		    ip6_sprintf(ip6buf, &pr->pr_ip6[ii]));
4755#endif
4756}
4757
4758DB_SHOW_COMMAND(prison, db_show_prison_command)
4759{
4760	struct prison *pr;
4761
4762	if (!have_addr) {
4763		/*
4764		 * Show all prisons in the list, and prison0 which is not
4765		 * listed.
4766		 */
4767		db_show_prison(&prison0);
4768		if (!db_pager_quit) {
4769			TAILQ_FOREACH(pr, &allprison, pr_list) {
4770				db_show_prison(pr);
4771				if (db_pager_quit)
4772					break;
4773			}
4774		}
4775		return;
4776	}
4777
4778	if (addr == 0)
4779		pr = &prison0;
4780	else {
4781		/* Look for a prison with the ID and with references. */
4782		TAILQ_FOREACH(pr, &allprison, pr_list)
4783			if (pr->pr_id == addr && pr->pr_ref > 0)
4784				break;
4785		if (pr == NULL)
4786			/* Look again, without requiring a reference. */
4787			TAILQ_FOREACH(pr, &allprison, pr_list)
4788				if (pr->pr_id == addr)
4789					break;
4790		if (pr == NULL)
4791			/* Assume address points to a valid prison. */
4792			pr = (struct prison *)addr;
4793	}
4794	db_show_prison(pr);
4795}
4796
4797#endif /* DDB */
4798