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