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