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