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