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