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