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