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