xref: /freebsd/sys/kern/kern_jail.c (revision 00a5db46de56179184c0f000eaacad695e2b0859)
1 /*-
2  * Copyright (c) 1999 Poul-Henning Kamp.
3  * Copyright (c) 2008 Bjoern A. Zeeb.
4  * Copyright (c) 2009 James Gritton.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_ddb.h"
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_mac.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/priv.h>
45 #include <sys/proc.h>
46 #include <sys/taskqueue.h>
47 #include <sys/fcntl.h>
48 #include <sys/jail.h>
49 #include <sys/lock.h>
50 #include <sys/mutex.h>
51 #include <sys/osd.h>
52 #include <sys/sx.h>
53 #include <sys/namei.h>
54 #include <sys/mount.h>
55 #include <sys/queue.h>
56 #include <sys/socket.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/sysctl.h>
59 #include <sys/vnode.h>
60 #include <sys/vimage.h>
61 #include <net/if.h>
62 #include <netinet/in.h>
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #ifdef INET6
66 #include <netinet6/in6_var.h>
67 #endif /* INET6 */
68 #endif /* DDB */
69 
70 #include <security/mac/mac_framework.h>
71 
72 MALLOC_DEFINE(M_PRISON, "prison", "Prison structures");
73 
74 SYSCTL_NODE(_security, OID_AUTO, jail, CTLFLAG_RW, 0,
75     "Jail rules");
76 
77 int	jail_set_hostname_allowed = 1;
78 SYSCTL_INT(_security_jail, OID_AUTO, set_hostname_allowed, CTLFLAG_RW,
79     &jail_set_hostname_allowed, 0,
80     "Processes in jail can set their hostnames");
81 
82 int	jail_socket_unixiproute_only = 1;
83 SYSCTL_INT(_security_jail, OID_AUTO, socket_unixiproute_only, CTLFLAG_RW,
84     &jail_socket_unixiproute_only, 0,
85     "Processes in jail are limited to creating UNIX/IP/route sockets only");
86 
87 int	jail_sysvipc_allowed = 0;
88 SYSCTL_INT(_security_jail, OID_AUTO, sysvipc_allowed, CTLFLAG_RW,
89     &jail_sysvipc_allowed, 0,
90     "Processes in jail can use System V IPC primitives");
91 
92 static int jail_enforce_statfs = 2;
93 SYSCTL_INT(_security_jail, OID_AUTO, enforce_statfs, CTLFLAG_RW,
94     &jail_enforce_statfs, 0,
95     "Processes in jail cannot see all mounted file systems");
96 
97 int	jail_allow_raw_sockets = 0;
98 SYSCTL_INT(_security_jail, OID_AUTO, allow_raw_sockets, CTLFLAG_RW,
99     &jail_allow_raw_sockets, 0,
100     "Prison root can create raw sockets");
101 
102 int	jail_chflags_allowed = 0;
103 SYSCTL_INT(_security_jail, OID_AUTO, chflags_allowed, CTLFLAG_RW,
104     &jail_chflags_allowed, 0,
105     "Processes in jail can alter system file flags");
106 
107 int	jail_mount_allowed = 0;
108 SYSCTL_INT(_security_jail, OID_AUTO, mount_allowed, CTLFLAG_RW,
109     &jail_mount_allowed, 0,
110     "Processes in jail can mount/unmount jail-friendly file systems");
111 
112 int	jail_max_af_ips = 255;
113 SYSCTL_INT(_security_jail, OID_AUTO, jail_max_af_ips, CTLFLAG_RW,
114     &jail_max_af_ips, 0,
115     "Number of IP addresses a jail may have at most per address family");
116 
117 /* allprison, lastprid, and prisoncount are protected by allprison_lock. */
118 struct	sx allprison_lock;
119 SX_SYSINIT(allprison_lock, &allprison_lock, "allprison");
120 struct	prisonlist allprison = TAILQ_HEAD_INITIALIZER(allprison);
121 int	lastprid = 0;
122 int	prisoncount = 0;
123 
124 static int do_jail_attach(struct thread *td, struct prison *pr);
125 static void prison_complete(void *context, int pending);
126 static void prison_deref(struct prison *pr, int flags);
127 #ifdef INET
128 static int _prison_check_ip4(struct prison *pr, struct in_addr *ia);
129 #endif
130 #ifdef INET6
131 static int _prison_check_ip6(struct prison *pr, struct in6_addr *ia6);
132 #endif
133 static int sysctl_jail_list(SYSCTL_HANDLER_ARGS);
134 
135 /* Flags for prison_deref */
136 #define	PD_DEREF	0x01
137 #define	PD_DEUREF	0x02
138 #define	PD_LOCKED	0x04
139 #define	PD_LIST_SLOCKED	0x08
140 #define	PD_LIST_XLOCKED	0x10
141 
142 #ifdef INET
143 static int
144 qcmp_v4(const void *ip1, const void *ip2)
145 {
146 	in_addr_t iaa, iab;
147 
148 	/*
149 	 * We need to compare in HBO here to get the list sorted as expected
150 	 * by the result of the code.  Sorting NBO addresses gives you
151 	 * interesting results.  If you do not understand, do not try.
152 	 */
153 	iaa = ntohl(((const struct in_addr *)ip1)->s_addr);
154 	iab = ntohl(((const struct in_addr *)ip2)->s_addr);
155 
156 	/*
157 	 * Do not simply return the difference of the two numbers, the int is
158 	 * not wide enough.
159 	 */
160 	if (iaa > iab)
161 		return (1);
162 	else if (iaa < iab)
163 		return (-1);
164 	else
165 		return (0);
166 }
167 #endif
168 
169 #ifdef INET6
170 static int
171 qcmp_v6(const void *ip1, const void *ip2)
172 {
173 	const struct in6_addr *ia6a, *ia6b;
174 	int i, rc;
175 
176 	ia6a = (const struct in6_addr *)ip1;
177 	ia6b = (const struct in6_addr *)ip2;
178 
179 	rc = 0;
180 	for (i = 0; rc == 0 && i < sizeof(struct in6_addr); i++) {
181 		if (ia6a->s6_addr[i] > ia6b->s6_addr[i])
182 			rc = 1;
183 		else if (ia6a->s6_addr[i] < ia6b->s6_addr[i])
184 			rc = -1;
185 	}
186 	return (rc);
187 }
188 #endif
189 
190 /*
191  * struct jail_args {
192  *	struct jail *jail;
193  * };
194  */
195 int
196 jail(struct thread *td, struct jail_args *uap)
197 {
198 	struct iovec optiov[10];
199 	struct uio opt;
200 	char *u_path, *u_hostname, *u_name;
201 #ifdef INET
202 	struct in_addr *u_ip4;
203 #endif
204 #ifdef INET6
205 	struct in6_addr *u_ip6;
206 #endif
207 	uint32_t version;
208 	int error;
209 
210 	error = copyin(uap->jail, &version, sizeof(uint32_t));
211 	if (error)
212 		return (error);
213 
214 	switch (version) {
215 	case 0:
216 	{
217 		/* FreeBSD single IPv4 jails. */
218 		struct jail_v0 j0;
219 
220 		error = copyin(uap->jail, &j0, sizeof(struct jail_v0));
221 		if (error)
222 			return (error);
223 		u_path = malloc(MAXPATHLEN + MAXHOSTNAMELEN, M_TEMP, M_WAITOK);
224 		u_hostname = u_path + MAXPATHLEN;
225 		opt.uio_iov = optiov;
226 		opt.uio_iovcnt = 4;
227 		opt.uio_offset = -1;
228 		opt.uio_resid = -1;
229 		opt.uio_segflg = UIO_SYSSPACE;
230 		opt.uio_rw = UIO_READ;
231 		opt.uio_td = td;
232 		optiov[0].iov_base = "path";
233 		optiov[0].iov_len = sizeof("path");
234 		optiov[1].iov_base = u_path;
235 		error =
236 		    copyinstr(j0.path, u_path, MAXPATHLEN, &optiov[1].iov_len);
237 		if (error) {
238 			free(u_path, M_TEMP);
239 			return (error);
240 		}
241 		optiov[2].iov_base = "host.hostname";
242 		optiov[2].iov_len = sizeof("host.hostname");
243 		optiov[3].iov_base = u_hostname;
244 		error = copyinstr(j0.hostname, u_hostname, MAXHOSTNAMELEN,
245 		    &optiov[3].iov_len);
246 		if (error) {
247 			free(u_path, M_TEMP);
248 			return (error);
249 		}
250 #ifdef INET
251 		optiov[opt.uio_iovcnt].iov_base = "ip4.addr";
252 		optiov[opt.uio_iovcnt].iov_len = sizeof("ip4.addr");
253 		opt.uio_iovcnt++;
254 		optiov[opt.uio_iovcnt].iov_base = &j0.ip_number;
255 		j0.ip_number = htonl(j0.ip_number);
256 		optiov[opt.uio_iovcnt].iov_len = sizeof(j0.ip_number);
257 		opt.uio_iovcnt++;
258 #endif
259 		break;
260 	}
261 
262 	case 1:
263 		/*
264 		 * Version 1 was used by multi-IPv4 jail implementations
265 		 * that never made it into the official kernel.
266 		 */
267 		return (EINVAL);
268 
269 	case 2:	/* JAIL_API_VERSION */
270 	{
271 		/* FreeBSD multi-IPv4/IPv6,noIP jails. */
272 		struct jail j;
273 		size_t tmplen;
274 
275 		error = copyin(uap->jail, &j, sizeof(struct jail));
276 		if (error)
277 			return (error);
278 		tmplen = MAXPATHLEN + MAXHOSTNAMELEN + MAXHOSTNAMELEN;
279 #ifdef INET
280 		if (j.ip4s > jail_max_af_ips)
281 			return (EINVAL);
282 		tmplen += j.ip4s * sizeof(struct in_addr);
283 #else
284 		if (j.ip4s > 0)
285 			return (EINVAL);
286 #endif
287 #ifdef INET6
288 		if (j.ip6s > jail_max_af_ips)
289 			return (EINVAL);
290 		tmplen += j.ip6s * sizeof(struct in6_addr);
291 #else
292 		if (j.ip6s > 0)
293 			return (EINVAL);
294 #endif
295 		u_path = malloc(tmplen, M_TEMP, M_WAITOK);
296 		u_hostname = u_path + MAXPATHLEN;
297 		u_name = u_hostname + MAXHOSTNAMELEN;
298 #ifdef INET
299 		u_ip4 = (struct in_addr *)(u_name + MAXHOSTNAMELEN);
300 #endif
301 #ifdef INET6
302 #ifdef INET
303 		u_ip6 = (struct in6_addr *)(u_ip4 + j.ip4s);
304 #else
305 		u_ip6 = (struct in6_addr *)(u_name + MAXHOSTNAMELEN);
306 #endif
307 #endif
308 		opt.uio_iov = optiov;
309 		opt.uio_iovcnt = 4;
310 		opt.uio_offset = -1;
311 		opt.uio_resid = -1;
312 		opt.uio_segflg = UIO_SYSSPACE;
313 		opt.uio_rw = UIO_READ;
314 		opt.uio_td = td;
315 		optiov[0].iov_base = "path";
316 		optiov[0].iov_len = sizeof("path");
317 		optiov[1].iov_base = u_path;
318 		error =
319 		    copyinstr(j.path, u_path, MAXPATHLEN, &optiov[1].iov_len);
320 		if (error) {
321 			free(u_path, M_TEMP);
322 			return (error);
323 		}
324 		optiov[2].iov_base = "host.hostname";
325 		optiov[2].iov_len = sizeof("host.hostname");
326 		optiov[3].iov_base = u_hostname;
327 		error = copyinstr(j.hostname, u_hostname, MAXHOSTNAMELEN,
328 		    &optiov[3].iov_len);
329 		if (error) {
330 			free(u_path, M_TEMP);
331 			return (error);
332 		}
333 		if (j.jailname != NULL) {
334 			optiov[opt.uio_iovcnt].iov_base = "name";
335 			optiov[opt.uio_iovcnt].iov_len = sizeof("name");
336 			opt.uio_iovcnt++;
337 			optiov[opt.uio_iovcnt].iov_base = u_name;
338 			error = copyinstr(j.jailname, u_name, MAXHOSTNAMELEN,
339 			    &optiov[opt.uio_iovcnt].iov_len);
340 			if (error) {
341 				free(u_path, M_TEMP);
342 				return (error);
343 			}
344 			opt.uio_iovcnt++;
345 		}
346 #ifdef INET
347 		optiov[opt.uio_iovcnt].iov_base = "ip4.addr";
348 		optiov[opt.uio_iovcnt].iov_len = sizeof("ip4.addr");
349 		opt.uio_iovcnt++;
350 		optiov[opt.uio_iovcnt].iov_base = u_ip4;
351 		optiov[opt.uio_iovcnt].iov_len =
352 		    j.ip4s * sizeof(struct in_addr);
353 		error = copyin(j.ip4, u_ip4, optiov[opt.uio_iovcnt].iov_len);
354 		if (error) {
355 			free(u_path, M_TEMP);
356 			return (error);
357 		}
358 		opt.uio_iovcnt++;
359 #endif
360 #ifdef INET6
361 		optiov[opt.uio_iovcnt].iov_base = "ip6.addr";
362 		optiov[opt.uio_iovcnt].iov_len = sizeof("ip6.addr");
363 		opt.uio_iovcnt++;
364 		optiov[opt.uio_iovcnt].iov_base = u_ip6;
365 		optiov[opt.uio_iovcnt].iov_len =
366 		    j.ip6s * sizeof(struct in6_addr);
367 		error = copyin(j.ip6, u_ip6, optiov[opt.uio_iovcnt].iov_len);
368 		if (error) {
369 			free(u_path, M_TEMP);
370 			return (error);
371 		}
372 		opt.uio_iovcnt++;
373 #endif
374 		break;
375 	}
376 
377 	default:
378 		/* Sci-Fi jails are not supported, sorry. */
379 		return (EINVAL);
380 	}
381 	error = kern_jail_set(td, &opt, JAIL_CREATE | JAIL_ATTACH);
382 	free(u_path, M_TEMP);
383 	return (error);
384 }
385 
386 /*
387  * struct jail_set_args {
388  *	struct iovec *iovp;
389  *	unsigned int iovcnt;
390  *	int flags;
391  * };
392  */
393 int
394 jail_set(struct thread *td, struct jail_set_args *uap)
395 {
396 	struct uio *auio;
397 	int error;
398 
399 	/* Check that we have an even number of iovecs. */
400 	if (uap->iovcnt & 1)
401 		return (EINVAL);
402 
403 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
404 	if (error)
405 		return (error);
406 	error = kern_jail_set(td, auio, uap->flags);
407 	free(auio, M_IOV);
408 	return (error);
409 }
410 
411 int
412 kern_jail_set(struct thread *td, struct uio *optuio, int flags)
413 {
414 	struct nameidata nd;
415 #ifdef INET
416 	struct in_addr *ip4;
417 #endif
418 #ifdef INET6
419 	struct in6_addr *ip6;
420 #endif
421 	struct vfsopt *opt;
422 	struct vfsoptlist *opts;
423 	struct prison *pr, *deadpr, *tpr;
424 	struct vnode *root;
425 	char *errmsg, *host, *name, *p, *path;
426 	void *op;
427 	int created, cuflags, error, errmsg_len, errmsg_pos;
428 	int gotslevel, jid, len;
429 	int slevel, vfslocked;
430 #if defined(INET) || defined(INET6)
431 	int ii;
432 #endif
433 #ifdef INET
434 	int ip4s;
435 #endif
436 #ifdef INET6
437 	int ip6s;
438 #endif
439 	unsigned pr_flags, ch_flags;
440 	char numbuf[12];
441 
442 	error = priv_check(td, PRIV_JAIL_SET);
443 	if (!error && (flags & JAIL_ATTACH))
444 		error = priv_check(td, PRIV_JAIL_ATTACH);
445 	if (error)
446 		return (error);
447 	if (flags & ~JAIL_SET_MASK)
448 		return (EINVAL);
449 
450 	/*
451 	 * Check all the parameters before committing to anything.  Not all
452 	 * errors can be caught early, but we may as well try.  Also, this
453 	 * takes care of some expensive stuff (path lookup) before getting
454 	 * the allprison lock.
455 	 *
456 	 * XXX Jails are not filesystems, and jail parameters are not mount
457 	 *     options.  But it makes more sense to re-use the vfsopt code
458 	 *     than duplicate it under a different name.
459 	 */
460 	error = vfs_buildopts(optuio, &opts);
461 	if (error)
462 		return (error);
463 #ifdef INET
464 	ip4 = NULL;
465 #endif
466 #ifdef INET6
467 	ip6 = NULL;
468 #endif
469 
470 	error = vfs_copyopt(opts, "jid", &jid, sizeof(jid));
471 	if (error == ENOENT)
472 		jid = 0;
473 	else if (error != 0)
474 		goto done_free;
475 
476 	error = vfs_copyopt(opts, "securelevel", &slevel, sizeof(slevel));
477 	if (error == ENOENT)
478 		gotslevel = 0;
479 	else if (error != 0)
480 		goto done_free;
481 	else
482 		gotslevel = 1;
483 
484 	pr_flags = ch_flags = 0;
485 	vfs_flagopt(opts, "persist", &pr_flags, PR_PERSIST);
486 	vfs_flagopt(opts, "nopersist", &ch_flags, PR_PERSIST);
487 	ch_flags |= pr_flags;
488 	if ((flags & (JAIL_CREATE | JAIL_UPDATE | JAIL_ATTACH)) == JAIL_CREATE
489 	    && !(pr_flags & PR_PERSIST)) {
490 		error = EINVAL;
491 		vfs_opterror(opts, "new jail must persist or attach");
492 		goto done_errmsg;
493 	}
494 
495 	error = vfs_getopt(opts, "name", (void **)&name, &len);
496 	if (error == ENOENT)
497 		name = NULL;
498 	else if (error != 0)
499 		goto done_free;
500 	else {
501 		if (len == 0 || name[len - 1] != '\0') {
502 			error = EINVAL;
503 			goto done_free;
504 		}
505 		if (len > MAXHOSTNAMELEN) {
506 			error = ENAMETOOLONG;
507 			goto done_free;
508 		}
509 	}
510 
511 	error = vfs_getopt(opts, "host.hostname", (void **)&host, &len);
512 	if (error == ENOENT)
513 		host = NULL;
514 	else if (error != 0)
515 		goto done_free;
516 	else {
517 		if (len == 0 || host[len - 1] != '\0') {
518 			error = EINVAL;
519 			goto done_free;
520 		}
521 		if (len > MAXHOSTNAMELEN) {
522 			error = ENAMETOOLONG;
523 			goto done_free;
524 		}
525 	}
526 
527 #ifdef INET
528 	error = vfs_getopt(opts, "ip4.addr", &op, &ip4s);
529 	if (error == ENOENT)
530 		ip4s = -1;
531 	else if (error != 0)
532 		goto done_free;
533 	else if (ip4s & (sizeof(*ip4) - 1)) {
534 		error = EINVAL;
535 		goto done_free;
536 	} else if (ip4s > 0) {
537 		ip4s /= sizeof(*ip4);
538 		if (ip4s > jail_max_af_ips) {
539 			error = EINVAL;
540 			vfs_opterror(opts, "too many IPv4 addresses");
541 			goto done_errmsg;
542 		}
543 		ip4 = malloc(ip4s * sizeof(*ip4), M_PRISON, M_WAITOK);
544 		bcopy(op, ip4, ip4s * sizeof(*ip4));
545 		/*
546 		 * IP addresses are all sorted but ip[0] to preserve the
547 		 * primary IP address as given from userland.  This special IP
548 		 * is used for unbound outgoing connections as well for
549 		 * "loopback" traffic.
550 		 */
551 		if (ip4s > 1)
552 			qsort(ip4 + 1, ip4s - 1, sizeof(*ip4), qcmp_v4);
553 		/*
554 		 * Check for duplicate addresses and do some simple zero and
555 		 * broadcast checks. If users give other bogus addresses it is
556 		 * their problem.
557 		 *
558 		 * We do not have to care about byte order for these checks so
559 		 * we will do them in NBO.
560 		 */
561 		for (ii = 0; ii < ip4s; ii++) {
562 			if (ip4[ii].s_addr == INADDR_ANY ||
563 			    ip4[ii].s_addr == INADDR_BROADCAST) {
564 				error = EINVAL;
565 				goto done_free;
566 			}
567 			if ((ii+1) < ip4s &&
568 			    (ip4[0].s_addr == ip4[ii+1].s_addr ||
569 			     ip4[ii].s_addr == ip4[ii+1].s_addr)) {
570 				error = EINVAL;
571 				goto done_free;
572 			}
573 		}
574 	}
575 #endif
576 
577 #ifdef INET6
578 	error = vfs_getopt(opts, "ip6.addr", &op, &ip6s);
579 	if (error == ENOENT)
580 		ip6s = -1;
581 	else if (error != 0)
582 		goto done_free;
583 	else if (ip6s & (sizeof(*ip6) - 1)) {
584 		error = EINVAL;
585 		goto done_free;
586 	} else if (ip6s > 0) {
587 		ip6s /= sizeof(*ip6);
588 		if (ip6s > jail_max_af_ips) {
589 			error = EINVAL;
590 			vfs_opterror(opts, "too many IPv6 addresses");
591 			goto done_errmsg;
592 		}
593 		ip6 = malloc(ip6s * sizeof(*ip6), M_PRISON, M_WAITOK);
594 		bcopy(op, ip6, ip6s * sizeof(*ip6));
595 		if (ip6s > 1)
596 			qsort(ip6 + 1, ip6s - 1, sizeof(*ip6), qcmp_v6);
597 		for (ii = 0; ii < ip6s; ii++) {
598 			if (IN6_IS_ADDR_UNSPECIFIED(&ip6[0])) {
599 				error = EINVAL;
600 				goto done_free;
601 			}
602 			if ((ii+1) < ip6s &&
603 			    (IN6_ARE_ADDR_EQUAL(&ip6[0], &ip6[ii+1]) ||
604 			     IN6_ARE_ADDR_EQUAL(&ip6[ii], &ip6[ii+1])))
605 			{
606 				error = EINVAL;
607 				goto done_free;
608 			}
609 		}
610 	}
611 #endif
612 
613 	root = NULL;
614 	error = vfs_getopt(opts, "path", (void **)&path, &len);
615 	if (error == ENOENT)
616 		path = NULL;
617 	else if (error != 0)
618 		goto done_free;
619 	else {
620 		if (flags & JAIL_UPDATE) {
621 			error = EINVAL;
622 			vfs_opterror(opts,
623 			    "path cannot be changed after creation");
624 			goto done_errmsg;
625 		}
626 		if (len == 0 || path[len - 1] != '\0') {
627 			error = EINVAL;
628 			goto done_free;
629 		}
630 		if (len > MAXPATHLEN) {
631 			error = ENAMETOOLONG;
632 			goto done_free;
633 		}
634 		if (len < 2 || (len == 2 && path[0] == '/'))
635 			path = NULL;
636 		else {
637 			NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW, UIO_SYSSPACE,
638 			    path, td);
639 			error = namei(&nd);
640 			if (error)
641 				goto done_free;
642 			vfslocked = NDHASGIANT(&nd);
643 			root = nd.ni_vp;
644 			NDFREE(&nd, NDF_ONLY_PNBUF);
645 			if (root->v_type != VDIR) {
646 				error = ENOTDIR;
647 				vrele(root);
648 				VFS_UNLOCK_GIANT(vfslocked);
649 				goto done_free;
650 			}
651 			VFS_UNLOCK_GIANT(vfslocked);
652 		}
653 	}
654 
655 	/*
656 	 * Grab the allprison lock before letting modules check their
657 	 * parameters.  Once we have it, do not let go so we'll have a
658 	 * consistent view of the OSD list.
659 	 */
660 	sx_xlock(&allprison_lock);
661 	error = osd_jail_call(NULL, PR_METHOD_CHECK, opts);
662 	if (error)
663 		goto done_unlock_list;
664 
665 	/* By now, all parameters should have been noted. */
666 	TAILQ_FOREACH(opt, opts, link) {
667 		if (!opt->seen && strcmp(opt->name, "errmsg")) {
668 			error = EINVAL;
669 			vfs_opterror(opts, "unknown parameter: %s", opt->name);
670 			goto done_unlock_list;
671 		}
672 	}
673 
674 	/*
675 	 * See if we are creating a new record or updating an existing one.
676 	 * This abuses the file error codes ENOENT and EEXIST.
677 	 */
678 	cuflags = flags & (JAIL_CREATE | JAIL_UPDATE);
679 	if (!cuflags) {
680 		error = EINVAL;
681 		vfs_opterror(opts, "no valid operation (create or update)");
682 		goto done_unlock_list;
683 	}
684 	pr = NULL;
685 	if (jid != 0) {
686 		/* See if a requested jid already exists. */
687 		if (jid < 0) {
688 			error = EINVAL;
689 			vfs_opterror(opts, "negative jid");
690 			goto done_unlock_list;
691 		}
692 		pr = prison_find(jid);
693 		if (pr != NULL) {
694 			/* Create: jid must not exist. */
695 			if (cuflags == JAIL_CREATE) {
696 				mtx_unlock(&pr->pr_mtx);
697 				error = EEXIST;
698 				vfs_opterror(opts, "jail %d already exists",
699 				    jid);
700 				goto done_unlock_list;
701 			}
702 			if (pr->pr_uref == 0) {
703 				if (!(flags & JAIL_DYING)) {
704 					mtx_unlock(&pr->pr_mtx);
705 					error = ENOENT;
706 					vfs_opterror(opts, "jail %d is dying",
707 					    jid);
708 					goto done_unlock_list;
709 				} else if ((flags & JAIL_ATTACH) ||
710 				    (pr_flags & PR_PERSIST)) {
711 					/*
712 					 * A dying jail might be resurrected
713 					 * (via attach or persist), but first
714 					 * it must determine if another jail
715 					 * has claimed its name.  Accomplish
716 					 * this by implicitly re-setting the
717 					 * name.
718 					 */
719 					if (name == NULL)
720 						name = pr->pr_name;
721 				}
722 			}
723 		}
724 		if (pr == NULL) {
725 			/* Update: jid must exist. */
726 			if (cuflags == JAIL_UPDATE) {
727 				error = ENOENT;
728 				vfs_opterror(opts, "jail %d not found", jid);
729 				goto done_unlock_list;
730 			}
731 		}
732 	}
733 	/*
734 	 * If the caller provided a name, look for a jail by that name.
735 	 * This has different semantics for creates and updates keyed by jid
736 	 * (where the name must not already exist in a different jail),
737 	 * and updates keyed by the name itself (where the name must exist
738 	 * because that is the jail being updated).
739 	 */
740 	if (name != NULL) {
741 		if (name[0] != '\0') {
742 			deadpr = NULL;
743  name_again:
744 			TAILQ_FOREACH(tpr, &allprison, pr_list) {
745 				if (tpr != pr && tpr->pr_ref > 0 &&
746 				    !strcmp(tpr->pr_name, name)) {
747 					if (pr == NULL &&
748 					    cuflags != JAIL_CREATE) {
749 						mtx_lock(&tpr->pr_mtx);
750 						if (tpr->pr_ref > 0) {
751 							/*
752 							 * Use this jail
753 							 * for updates.
754 							 */
755 							if (tpr->pr_uref > 0) {
756 								pr = tpr;
757 								break;
758 							}
759 							deadpr = tpr;
760 						}
761 						mtx_unlock(&tpr->pr_mtx);
762 					} else if (tpr->pr_uref > 0) {
763 						/*
764 						 * Create, or update(jid):
765 						 * name must not exist in an
766 						 * active jail.
767 						 */
768 						error = EEXIST;
769 						if (pr != NULL)
770 							mtx_unlock(&pr->pr_mtx);
771 						vfs_opterror(opts,
772 						   "jail \"%s\" already exists",
773 						   name);
774 						goto done_unlock_list;
775 					}
776 				}
777 			}
778 			/* If no active jail is found, use a dying one. */
779 			if (deadpr != NULL && pr == NULL) {
780 				if (flags & JAIL_DYING) {
781 					mtx_lock(&deadpr->pr_mtx);
782 					if (deadpr->pr_ref == 0) {
783 						mtx_unlock(&deadpr->pr_mtx);
784 						goto name_again;
785 					}
786 					pr = deadpr;
787 				} else if (cuflags == JAIL_UPDATE) {
788 					error = ENOENT;
789 					vfs_opterror(opts,
790 					    "jail \"%s\" is dying", name);
791 					goto done_unlock_list;
792 				}
793 			}
794 			/* Update: name must exist if no jid. */
795 			else if (cuflags == JAIL_UPDATE && pr == NULL) {
796 				error = ENOENT;
797 				vfs_opterror(opts, "jail \"%s\" not found",
798 				    name);
799 				goto done_unlock_list;
800 			}
801 		}
802 	}
803 	/* Update: must provide a jid or name. */
804 	else if (cuflags == JAIL_UPDATE && pr == NULL) {
805 		error = ENOENT;
806 		vfs_opterror(opts, "update specified no jail");
807 		goto done_unlock_list;
808 	}
809 
810 	/* If there's no prison to update, create a new one and link it in. */
811 	if (pr == NULL) {
812 		created = 1;
813 		pr = malloc(sizeof(*pr), M_PRISON, M_WAITOK | M_ZERO);
814 		if (jid == 0) {
815 			/* Find the next free jid. */
816 			jid = lastprid + 1;
817  findnext:
818 			if (jid == JAIL_MAX)
819 				jid = 1;
820 			TAILQ_FOREACH(tpr, &allprison, pr_list) {
821 				if (tpr->pr_id < jid)
822 					continue;
823 				if (tpr->pr_id > jid || tpr->pr_ref == 0) {
824 					TAILQ_INSERT_BEFORE(tpr, pr, pr_list);
825 					break;
826 				}
827 				if (jid == lastprid) {
828 					error = EAGAIN;
829 					vfs_opterror(opts,
830 					    "no available jail IDs");
831 					free(pr, M_PRISON);
832 					goto done_unlock_list;
833 				}
834 				jid++;
835 				goto findnext;
836 			}
837 			lastprid = jid;
838 		} else {
839 			/*
840 			 * The jail already has a jid (that did not yet exist),
841 			 * so just find where to insert it.
842 			 */
843 			TAILQ_FOREACH(tpr, &allprison, pr_list)
844 				if (tpr->pr_id >= jid) {
845 					TAILQ_INSERT_BEFORE(tpr, pr, pr_list);
846 					break;
847 				}
848 		}
849 		if (tpr == NULL)
850 			TAILQ_INSERT_TAIL(&allprison, pr, pr_list);
851 		prisoncount++;
852 
853 		pr->pr_id = jid;
854 		if (name == NULL)
855 			name = "";
856 		if (path == NULL) {
857 			path = "/";
858 			root = rootvnode;
859 			vref(root);
860 		}
861 
862 		mtx_init(&pr->pr_mtx, "jail mutex", NULL, MTX_DEF);
863 
864 		/*
865 		 * Allocate a dedicated cpuset for each jail.
866 		 * Unlike other initial settings, this may return an erorr.
867 		 */
868 		error = cpuset_create_root(td, &pr->pr_cpuset);
869 		if (error) {
870 			prison_deref(pr, PD_LIST_XLOCKED);
871 			goto done_releroot;
872 		}
873 
874 		mtx_lock(&pr->pr_mtx);
875 		/*
876 		 * New prisons do not yet have a reference, because we do not
877 		 * want other to see the incomplete prison once the
878 		 * allprison_lock is downgraded.
879 		 */
880 	} else {
881 		created = 0;
882 		/*
883 		 * Grab a reference for existing prisons, to ensure they
884 		 * continue to exist for the duration of the call.
885 		 */
886 		pr->pr_ref++;
887 	}
888 
889 	/* Do final error checking before setting anything. */
890 	error = 0;
891 #if defined(INET) || defined(INET6)
892 	if (
893 #ifdef INET
894 	    ip4s > 0
895 #ifdef INET6
896 	    ||
897 #endif
898 #endif
899 #ifdef INET6
900 	    ip6s > 0
901 #endif
902 	    )
903 		/*
904 		 * Check for conflicting IP addresses.  We permit them if there
905 		 * is no more than 1 IP on each jail.  If there is a duplicate
906 		 * on a jail with more than one IP stop checking and return
907 		 * error.
908 		 */
909 		TAILQ_FOREACH(tpr, &allprison, pr_list) {
910 			if (tpr == pr || tpr->pr_uref == 0)
911 				continue;
912 #ifdef INET
913 			if ((ip4s > 0 && tpr->pr_ip4s > 1) ||
914 			    (ip4s > 1 && tpr->pr_ip4s > 0))
915 				for (ii = 0; ii < ip4s; ii++)
916 					if (_prison_check_ip4(tpr,
917 					    &ip4[ii]) == 0) {
918 						error = EINVAL;
919 						vfs_opterror(opts,
920 						    "IPv4 addresses clash");
921 						goto done_deref_locked;
922 					}
923 #endif
924 #ifdef INET6
925 			if ((ip6s > 0 && tpr->pr_ip6s > 1) ||
926 			    (ip6s > 1 && tpr->pr_ip6s > 0))
927 				for (ii = 0; ii < ip6s; ii++)
928 					if (_prison_check_ip6(tpr,
929 					    &ip6[ii]) == 0) {
930 						error = EINVAL;
931 						vfs_opterror(opts,
932 						    "IPv6 addresses clash");
933 						goto done_deref_locked;
934 					}
935 #endif
936 		}
937 #endif
938 	if (error == 0 && name != NULL) {
939 		/* Give a default name of the jid. */
940 		if (name[0] == '\0')
941 			snprintf(name = numbuf, sizeof(numbuf), "%d", jid);
942 		else if (strtoul(name, &p, 10) != jid && *p == '\0') {
943 			error = EINVAL;
944 			vfs_opterror(opts, "name cannot be numeric");
945 		}
946 	}
947 	if (error) {
948  done_deref_locked:
949 		/*
950 		 * Some parameter had an error so do not set anything.
951 		 * If this is a new jail, it will go away without ever
952 		 * having been seen.
953 		 */
954 		prison_deref(pr, created
955 		    ? PD_LOCKED | PD_LIST_XLOCKED
956 		    : PD_DEREF | PD_LOCKED | PD_LIST_XLOCKED);
957 		goto done_releroot;
958 	}
959 
960 	/* Set the parameters of the prison. */
961 #ifdef INET
962 	if (ip4s >= 0) {
963 		pr->pr_ip4s = ip4s;
964 		free(pr->pr_ip4, M_PRISON);
965 		pr->pr_ip4 = ip4;
966 		ip4 = NULL;
967 	}
968 #endif
969 #ifdef INET6
970 	if (ip6s >= 0) {
971 		pr->pr_ip6s = ip6s;
972 		free(pr->pr_ip6, M_PRISON);
973 		pr->pr_ip6 = ip6;
974 		ip6 = NULL;
975 	}
976 #endif
977 	if (gotslevel)
978 		pr->pr_securelevel = slevel;
979 	if (name != NULL)
980 		strlcpy(pr->pr_name, name, sizeof(pr->pr_name));
981 	if (path != NULL) {
982 		strlcpy(pr->pr_path, path, sizeof(pr->pr_path));
983 		pr->pr_root = root;
984 	}
985 	if (host != NULL)
986 		strlcpy(pr->pr_host, host, sizeof(pr->pr_host));
987 	/*
988 	 * Persistent prisons get an extra reference, and prisons losing their
989 	 * persist flag lose that reference.  Only do this for existing prisons
990 	 * for now, so new ones will remain unseen until after the module
991 	 * handlers have completed.
992 	 */
993 	if (!created && (ch_flags & PR_PERSIST & (pr_flags ^ pr->pr_flags))) {
994 		if (pr_flags & PR_PERSIST) {
995 			pr->pr_ref++;
996 			pr->pr_uref++;
997 		} else {
998 			pr->pr_ref--;
999 			pr->pr_uref--;
1000 		}
1001 	}
1002 	pr->pr_flags = (pr->pr_flags & ~ch_flags) | pr_flags;
1003 	mtx_unlock(&pr->pr_mtx);
1004 
1005 	/* Let the modules do their work. */
1006 	sx_downgrade(&allprison_lock);
1007 	if (created) {
1008 		error = osd_jail_call(pr, PR_METHOD_CREATE, opts);
1009 		if (error) {
1010 			prison_deref(pr, PD_LIST_SLOCKED);
1011 			goto done_errmsg;
1012 		}
1013 	}
1014 	error = osd_jail_call(pr, PR_METHOD_SET, opts);
1015 	if (error) {
1016 		prison_deref(pr, created
1017 		    ? PD_LIST_SLOCKED
1018 		    : PD_DEREF | PD_LIST_SLOCKED);
1019 		goto done_errmsg;
1020 	}
1021 
1022 	/* Attach this process to the prison if requested. */
1023 	if (flags & JAIL_ATTACH) {
1024 		mtx_lock(&pr->pr_mtx);
1025 		error = do_jail_attach(td, pr);
1026 		if (error) {
1027 			vfs_opterror(opts, "attach failed");
1028 			if (!created)
1029 				prison_deref(pr, PD_DEREF);
1030 			goto done_errmsg;
1031 		}
1032 	}
1033 
1034 	/*
1035 	 * Now that it is all there, drop the temporary reference from existing
1036 	 * prisons.  Or add a reference to newly created persistent prisons
1037 	 * (which was not done earlier so that the prison would not be publicly
1038 	 * visible).
1039 	 */
1040 	if (!created) {
1041 		prison_deref(pr, (flags & JAIL_ATTACH)
1042 		    ? PD_DEREF
1043 		    : PD_DEREF | PD_LIST_SLOCKED);
1044 	} else {
1045 		if (pr_flags & PR_PERSIST) {
1046 			mtx_lock(&pr->pr_mtx);
1047 			pr->pr_ref++;
1048 			pr->pr_uref++;
1049 			mtx_unlock(&pr->pr_mtx);
1050 		}
1051 		if (!(flags & JAIL_ATTACH))
1052 			sx_sunlock(&allprison_lock);
1053 	}
1054 	td->td_retval[0] = pr->pr_id;
1055 	goto done_errmsg;
1056 
1057  done_unlock_list:
1058 	sx_xunlock(&allprison_lock);
1059  done_releroot:
1060 	if (root != NULL) {
1061 		vfslocked = VFS_LOCK_GIANT(root->v_mount);
1062 		vrele(root);
1063 		VFS_UNLOCK_GIANT(vfslocked);
1064 	}
1065  done_errmsg:
1066 	if (error) {
1067 		vfs_getopt(opts, "errmsg", (void **)&errmsg, &errmsg_len);
1068 		if (errmsg_len > 0) {
1069 			errmsg_pos = 2 * vfs_getopt_pos(opts, "errmsg") + 1;
1070 			if (errmsg_pos > 0) {
1071 				if (optuio->uio_segflg == UIO_SYSSPACE)
1072 					bcopy(errmsg,
1073 					   optuio->uio_iov[errmsg_pos].iov_base,
1074 					   errmsg_len);
1075 				else
1076 					copyout(errmsg,
1077 					   optuio->uio_iov[errmsg_pos].iov_base,
1078 					   errmsg_len);
1079 			}
1080 		}
1081 	}
1082  done_free:
1083 #ifdef INET
1084 	free(ip4, M_PRISON);
1085 #endif
1086 #ifdef INET6
1087 	free(ip6, M_PRISON);
1088 #endif
1089 	vfs_freeopts(opts);
1090 	return (error);
1091 }
1092 
1093 /*
1094  * Sysctl nodes to describe jail parameters.  Maximum length of string
1095  * parameters is returned in the string itself, and the other parameters
1096  * exist merely to make themselves and their types known.
1097  */
1098 SYSCTL_NODE(_security_jail, OID_AUTO, param, CTLFLAG_RW, 0,
1099     "Jail parameters");
1100 
1101 int
1102 sysctl_jail_param(SYSCTL_HANDLER_ARGS)
1103 {
1104 	int i;
1105 	long l;
1106 	size_t s;
1107 	char numbuf[12];
1108 
1109 	switch (oidp->oid_kind & CTLTYPE)
1110 	{
1111 	case CTLTYPE_LONG:
1112 	case CTLTYPE_ULONG:
1113 		l = 0;
1114 #ifdef SCTL_MASK32
1115 		if (!(req->flags & SCTL_MASK32))
1116 #endif
1117 			return (SYSCTL_OUT(req, &l, sizeof(l)));
1118 	case CTLTYPE_INT:
1119 	case CTLTYPE_UINT:
1120 		i = 0;
1121 		return (SYSCTL_OUT(req, &i, sizeof(i)));
1122 	case CTLTYPE_STRING:
1123 		snprintf(numbuf, sizeof(numbuf), "%d", arg2);
1124 		return
1125 		    (sysctl_handle_string(oidp, numbuf, sizeof(numbuf), req));
1126 	case CTLTYPE_STRUCT:
1127 		s = (size_t)arg2;
1128 		return (SYSCTL_OUT(req, &s, sizeof(s)));
1129 	}
1130 	return (0);
1131 }
1132 
1133 SYSCTL_JAIL_PARAM(, jid, CTLTYPE_INT | CTLFLAG_RD, "I", "Jail ID");
1134 SYSCTL_JAIL_PARAM_STRING(, name, CTLFLAG_RW, MAXHOSTNAMELEN, "Jail name");
1135 SYSCTL_JAIL_PARAM(, cpuset, CTLTYPE_INT | CTLFLAG_RD, "I", "Jail cpuset ID");
1136 SYSCTL_JAIL_PARAM_STRING(, path, CTLFLAG_RD, MAXPATHLEN, "Jail root path");
1137 SYSCTL_JAIL_PARAM(, securelevel, CTLTYPE_INT | CTLFLAG_RW,
1138     "I", "Jail secure level");
1139 SYSCTL_JAIL_PARAM(, persist, CTLTYPE_INT | CTLFLAG_RW,
1140     "B", "Jail persistence");
1141 SYSCTL_JAIL_PARAM(, dying, CTLTYPE_INT | CTLFLAG_RD,
1142     "B", "Jail is in the process of shutting down");
1143 
1144 SYSCTL_JAIL_PARAM_NODE(host, "Jail host info");
1145 SYSCTL_JAIL_PARAM_STRING(_host, hostname, CTLFLAG_RW, MAXHOSTNAMELEN,
1146     "Jail hostname");
1147 
1148 #ifdef INET
1149 SYSCTL_JAIL_PARAM_NODE(ip4, "Jail IPv4 address virtualization");
1150 SYSCTL_JAIL_PARAM_STRUCT(_ip4, addr, CTLFLAG_RW, sizeof(struct in_addr),
1151     "S,in_addr,a", "Jail IPv4 addresses");
1152 #endif
1153 #ifdef INET6
1154 SYSCTL_JAIL_PARAM_NODE(ip6, "Jail IPv6 address virtualization");
1155 SYSCTL_JAIL_PARAM_STRUCT(_ip6, addr, CTLFLAG_RW, sizeof(struct in6_addr),
1156     "S,in6_addr,a", "Jail IPv6 addresses");
1157 #endif
1158 
1159 
1160 /*
1161  * struct jail_get_args {
1162  *	struct iovec *iovp;
1163  *	unsigned int iovcnt;
1164  *	int flags;
1165  * };
1166  */
1167 int
1168 jail_get(struct thread *td, struct jail_get_args *uap)
1169 {
1170 	struct uio *auio;
1171 	int error;
1172 
1173 	/* Check that we have an even number of iovecs. */
1174 	if (uap->iovcnt & 1)
1175 		return (EINVAL);
1176 
1177 	error = copyinuio(uap->iovp, uap->iovcnt, &auio);
1178 	if (error)
1179 		return (error);
1180 	error = kern_jail_get(td, auio, uap->flags);
1181 	if (error == 0)
1182 		error = copyout(auio->uio_iov, uap->iovp,
1183 		    uap->iovcnt * sizeof (struct iovec));
1184 	free(auio, M_IOV);
1185 	return (error);
1186 }
1187 
1188 int
1189 kern_jail_get(struct thread *td, struct uio *optuio, int flags)
1190 {
1191 	struct prison *pr;
1192 	struct vfsopt *opt;
1193 	struct vfsoptlist *opts;
1194 	char *errmsg, *name;
1195 	int error, errmsg_len, errmsg_pos, i, jid, len, locked, pos;
1196 
1197 	if (flags & ~JAIL_GET_MASK)
1198 		return (EINVAL);
1199 
1200 	/* Get the parameter list. */
1201 	error = vfs_buildopts(optuio, &opts);
1202 	if (error)
1203 		return (error);
1204 	errmsg_pos = vfs_getopt_pos(opts, "errmsg");
1205 
1206 	/* Don't allow a jailed process to see any jails, not even its own. */
1207 	if (jailed(td->td_ucred)) {
1208 		vfs_opterror(opts, "jail not found");
1209 		return (ENOENT);
1210 	}
1211 
1212 	/*
1213 	 * Find the prison specified by one of: lastjid, jid, name.
1214 	 */
1215 	sx_slock(&allprison_lock);
1216 	error = vfs_copyopt(opts, "lastjid", &jid, sizeof(jid));
1217 	if (error == 0) {
1218 		TAILQ_FOREACH(pr, &allprison, pr_list) {
1219 			if (pr->pr_id > jid) {
1220 				mtx_lock(&pr->pr_mtx);
1221 				if (pr->pr_ref > 0 &&
1222 				    (pr->pr_uref > 0 || (flags & JAIL_DYING)))
1223 					break;
1224 				mtx_unlock(&pr->pr_mtx);
1225 			}
1226 		}
1227 		if (pr != NULL)
1228 			goto found_prison;
1229 		error = ENOENT;
1230 		vfs_opterror(opts, "no jail after %d", jid);
1231 		goto done_unlock_list;
1232 	} else if (error != ENOENT)
1233 		goto done_unlock_list;
1234 
1235 	error = vfs_copyopt(opts, "jid", &jid, sizeof(jid));
1236 	if (error == 0) {
1237 		if (jid != 0) {
1238 			pr = prison_find(jid);
1239 			if (pr != NULL) {
1240 				if (pr->pr_uref == 0 && !(flags & JAIL_DYING)) {
1241 					mtx_unlock(&pr->pr_mtx);
1242 					error = ENOENT;
1243 					vfs_opterror(opts, "jail %d is dying",
1244 					    jid);
1245 					goto done_unlock_list;
1246 				}
1247 				goto found_prison;
1248 			}
1249 			error = ENOENT;
1250 			vfs_opterror(opts, "jail %d not found", jid);
1251 			goto done_unlock_list;
1252 		}
1253 	} else if (error != ENOENT)
1254 		goto done_unlock_list;
1255 
1256 	error = vfs_getopt(opts, "name", (void **)&name, &len);
1257 	if (error == 0) {
1258 		if (len == 0 || name[len - 1] != '\0') {
1259 			error = EINVAL;
1260 			goto done_unlock_list;
1261 		}
1262 		pr = prison_find_name(name);
1263 		if (pr != NULL) {
1264 			if (pr->pr_uref == 0 && !(flags & JAIL_DYING)) {
1265 				mtx_unlock(&pr->pr_mtx);
1266 				error = ENOENT;
1267 				vfs_opterror(opts, "jail \"%s\" is dying",
1268 				    name);
1269 				goto done_unlock_list;
1270 			}
1271 			goto found_prison;
1272 		}
1273 		error = ENOENT;
1274 		vfs_opterror(opts, "jail \"%s\" not found", name);
1275 		goto done_unlock_list;
1276 	} else if (error != ENOENT)
1277 		goto done_unlock_list;
1278 
1279 	vfs_opterror(opts, "no jail specified");
1280 	error = ENOENT;
1281 	goto done_unlock_list;
1282 
1283  found_prison:
1284 	/* Get the parameters of the prison. */
1285 	pr->pr_ref++;
1286 	locked = PD_LOCKED;
1287 	td->td_retval[0] = pr->pr_id;
1288 	error = vfs_setopt(opts, "jid", &pr->pr_id, sizeof(pr->pr_id));
1289 	if (error != 0 && error != ENOENT)
1290 		goto done_deref;
1291 	error = vfs_setopts(opts, "name", pr->pr_name);
1292 	if (error != 0 && error != ENOENT)
1293 		goto done_deref;
1294 	error = vfs_setopt(opts, "cpuset", &pr->pr_cpuset->cs_id,
1295 	    sizeof(pr->pr_cpuset->cs_id));
1296 	if (error != 0 && error != ENOENT)
1297 		goto done_deref;
1298 	error = vfs_setopts(opts, "path", pr->pr_path);
1299 	if (error != 0 && error != ENOENT)
1300 		goto done_deref;
1301 #ifdef INET
1302 	error = vfs_setopt_part(opts, "ip4.addr", pr->pr_ip4,
1303 	    pr->pr_ip4s * sizeof(*pr->pr_ip4));
1304 	if (error != 0 && error != ENOENT)
1305 		goto done_deref;
1306 #endif
1307 #ifdef INET6
1308 	error = vfs_setopt_part(opts, "ip6.addr", pr->pr_ip6,
1309 	    pr->pr_ip6s * sizeof(*pr->pr_ip6));
1310 	if (error != 0 && error != ENOENT)
1311 		goto done_deref;
1312 #endif
1313 	error = vfs_setopt(opts, "securelevel", &pr->pr_securelevel,
1314 	    sizeof(pr->pr_securelevel));
1315 	if (error != 0 && error != ENOENT)
1316 		goto done_deref;
1317 	error = vfs_setopts(opts, "host.hostname", pr->pr_host);
1318 	if (error != 0 && error != ENOENT)
1319 		goto done_deref;
1320 	i = pr->pr_flags & PR_PERSIST ? 1 : 0;
1321 	error = vfs_setopt(opts, "persist", &i, sizeof(i));
1322 	if (error != 0 && error != ENOENT)
1323 		goto done_deref;
1324 	i = !i;
1325 	error = vfs_setopt(opts, "nopersist", &i, sizeof(i));
1326 	if (error != 0 && error != ENOENT)
1327 		goto done_deref;
1328 	i = (pr->pr_uref == 0);
1329 	error = vfs_setopt(opts, "dying", &i, sizeof(i));
1330 	if (error != 0 && error != ENOENT)
1331 		goto done_deref;
1332 	i = !i;
1333 	error = vfs_setopt(opts, "nodying", &i, sizeof(i));
1334 	if (error != 0 && error != ENOENT)
1335 		goto done_deref;
1336 
1337 	/* Get the module parameters. */
1338 	mtx_unlock(&pr->pr_mtx);
1339 	locked = 0;
1340 	error = osd_jail_call(pr, PR_METHOD_GET, opts);
1341 	if (error)
1342 		goto done_deref;
1343 	prison_deref(pr, PD_DEREF | PD_LIST_SLOCKED);
1344 
1345 	/* By now, all parameters should have been noted. */
1346 	TAILQ_FOREACH(opt, opts, link) {
1347 		if (!opt->seen && strcmp(opt->name, "errmsg")) {
1348 			error = EINVAL;
1349 			vfs_opterror(opts, "unknown parameter: %s", opt->name);
1350 			goto done_errmsg;
1351 		}
1352 	}
1353 
1354 	/* Write the fetched parameters back to userspace. */
1355 	error = 0;
1356 	TAILQ_FOREACH(opt, opts, link) {
1357 		if (opt->pos >= 0 && opt->pos != errmsg_pos) {
1358 			pos = 2 * opt->pos + 1;
1359 			optuio->uio_iov[pos].iov_len = opt->len;
1360 			if (opt->value != NULL) {
1361 				if (optuio->uio_segflg == UIO_SYSSPACE) {
1362 					bcopy(opt->value,
1363 					    optuio->uio_iov[pos].iov_base,
1364 					    opt->len);
1365 				} else {
1366 					error = copyout(opt->value,
1367 					    optuio->uio_iov[pos].iov_base,
1368 					    opt->len);
1369 					if (error)
1370 						break;
1371 				}
1372 			}
1373 		}
1374 	}
1375 	goto done_errmsg;
1376 
1377  done_deref:
1378 	prison_deref(pr, locked | PD_DEREF | PD_LIST_SLOCKED);
1379 	goto done_errmsg;
1380 
1381  done_unlock_list:
1382 	sx_sunlock(&allprison_lock);
1383  done_errmsg:
1384 	if (error && errmsg_pos >= 0) {
1385 		vfs_getopt(opts, "errmsg", (void **)&errmsg, &errmsg_len);
1386 		errmsg_pos = 2 * errmsg_pos + 1;
1387 		if (errmsg_len > 0) {
1388 			if (optuio->uio_segflg == UIO_SYSSPACE)
1389 				bcopy(errmsg,
1390 				    optuio->uio_iov[errmsg_pos].iov_base,
1391 				    errmsg_len);
1392 			else
1393 				copyout(errmsg,
1394 				    optuio->uio_iov[errmsg_pos].iov_base,
1395 				    errmsg_len);
1396 		}
1397 	}
1398 	vfs_freeopts(opts);
1399 	return (error);
1400 }
1401 
1402 /*
1403  * struct jail_remove_args {
1404  *	int jid;
1405  * };
1406  */
1407 int
1408 jail_remove(struct thread *td, struct jail_remove_args *uap)
1409 {
1410 	struct prison *pr;
1411 	struct proc *p;
1412 	int deuref, error;
1413 
1414 	error = priv_check(td, PRIV_JAIL_REMOVE);
1415 	if (error)
1416 		return (error);
1417 
1418 	sx_xlock(&allprison_lock);
1419 	pr = prison_find(uap->jid);
1420 	if (pr == NULL) {
1421 		sx_xunlock(&allprison_lock);
1422 		return (EINVAL);
1423 	}
1424 
1425 	/* If the prison was persistent, it is not anymore. */
1426 	deuref = 0;
1427 	if (pr->pr_flags & PR_PERSIST) {
1428 		pr->pr_ref--;
1429 		deuref = PD_DEUREF;
1430 		pr->pr_flags &= ~PR_PERSIST;
1431 	}
1432 
1433 	/* If there are no references left, remove the prison now. */
1434 	if (pr->pr_ref == 0) {
1435 		prison_deref(pr,
1436 		    deuref | PD_DEREF | PD_LOCKED | PD_LIST_XLOCKED);
1437 		return (0);
1438 	}
1439 
1440 	/*
1441 	 * Keep a temporary reference to make sure this prison sticks around.
1442 	 */
1443 	pr->pr_ref++;
1444 	mtx_unlock(&pr->pr_mtx);
1445 	sx_xunlock(&allprison_lock);
1446 	/*
1447 	 * Kill all processes unfortunate enough to be attached to this prison.
1448 	 */
1449 	sx_slock(&allproc_lock);
1450 	LIST_FOREACH(p, &allproc, p_list) {
1451 		PROC_LOCK(p);
1452 		if (p->p_state != PRS_NEW && p->p_ucred &&
1453 		    p->p_ucred->cr_prison == pr)
1454 			psignal(p, SIGKILL);
1455 		PROC_UNLOCK(p);
1456 	}
1457 	sx_sunlock(&allproc_lock);
1458 	/* Remove the temporary reference. */
1459 	prison_deref(pr, deuref | PD_DEREF);
1460 	return (0);
1461 }
1462 
1463 
1464 /*
1465  * struct jail_attach_args {
1466  *	int jid;
1467  * };
1468  */
1469 int
1470 jail_attach(struct thread *td, struct jail_attach_args *uap)
1471 {
1472 	struct prison *pr;
1473 	int error;
1474 
1475 	error = priv_check(td, PRIV_JAIL_ATTACH);
1476 	if (error)
1477 		return (error);
1478 
1479 	sx_slock(&allprison_lock);
1480 	pr = prison_find(uap->jid);
1481 	if (pr == NULL) {
1482 		sx_sunlock(&allprison_lock);
1483 		return (EINVAL);
1484 	}
1485 
1486 	/*
1487 	 * Do not allow a process to attach to a prison that is not
1488 	 * considered to be "alive".
1489 	 */
1490 	if (pr->pr_uref == 0) {
1491 		mtx_unlock(&pr->pr_mtx);
1492 		sx_sunlock(&allprison_lock);
1493 		return (EINVAL);
1494 	}
1495 
1496 	return (do_jail_attach(td, pr));
1497 }
1498 
1499 static int
1500 do_jail_attach(struct thread *td, struct prison *pr)
1501 {
1502 	struct proc *p;
1503 	struct ucred *newcred, *oldcred;
1504 	int vfslocked, error;
1505 
1506 	/*
1507 	 * XXX: Note that there is a slight race here if two threads
1508 	 * in the same privileged process attempt to attach to two
1509 	 * different jails at the same time.  It is important for
1510 	 * user processes not to do this, or they might end up with
1511 	 * a process root from one prison, but attached to the jail
1512 	 * of another.
1513 	 */
1514 	pr->pr_ref++;
1515 	pr->pr_uref++;
1516 	mtx_unlock(&pr->pr_mtx);
1517 
1518 	/* Let modules do whatever they need to prepare for attaching. */
1519 	error = osd_jail_call(pr, PR_METHOD_ATTACH, td);
1520 	if (error) {
1521 		prison_deref(pr, PD_DEREF | PD_DEUREF | PD_LIST_SLOCKED);
1522 		return (error);
1523 	}
1524 	sx_sunlock(&allprison_lock);
1525 
1526 	/*
1527 	 * Reparent the newly attached process to this jail.
1528 	 */
1529 	p = td->td_proc;
1530 	error = cpuset_setproc_update_set(p, pr->pr_cpuset);
1531 	if (error)
1532 		goto e_revert_osd;
1533 
1534 	vfslocked = VFS_LOCK_GIANT(pr->pr_root->v_mount);
1535 	vn_lock(pr->pr_root, LK_EXCLUSIVE | LK_RETRY);
1536 	if ((error = change_dir(pr->pr_root, td)) != 0)
1537 		goto e_unlock;
1538 #ifdef MAC
1539 	if ((error = mac_vnode_check_chroot(td->td_ucred, pr->pr_root)))
1540 		goto e_unlock;
1541 #endif
1542 	VOP_UNLOCK(pr->pr_root, 0);
1543 	if ((error = change_root(pr->pr_root, td)))
1544 		goto e_unlock_giant;
1545 	VFS_UNLOCK_GIANT(vfslocked);
1546 
1547 	newcred = crget();
1548 	PROC_LOCK(p);
1549 	oldcred = p->p_ucred;
1550 	setsugid(p);
1551 	crcopy(newcred, oldcred);
1552 	newcred->cr_prison = pr;
1553 	p->p_ucred = newcred;
1554 	PROC_UNLOCK(p);
1555 	crfree(oldcred);
1556 	return (0);
1557  e_unlock:
1558 	VOP_UNLOCK(pr->pr_root, 0);
1559  e_unlock_giant:
1560 	VFS_UNLOCK_GIANT(vfslocked);
1561  e_revert_osd:
1562 	/* Tell modules this thread is still in its old jail after all. */
1563 	(void)osd_jail_call(td->td_ucred->cr_prison, PR_METHOD_ATTACH, td);
1564 	prison_deref(pr, PD_DEREF | PD_DEUREF);
1565 	return (error);
1566 }
1567 
1568 /*
1569  * Returns a locked prison instance, or NULL on failure.
1570  */
1571 struct prison *
1572 prison_find(int prid)
1573 {
1574 	struct prison *pr;
1575 
1576 	sx_assert(&allprison_lock, SX_LOCKED);
1577 	TAILQ_FOREACH(pr, &allprison, pr_list) {
1578 		if (pr->pr_id == prid) {
1579 			mtx_lock(&pr->pr_mtx);
1580 			if (pr->pr_ref > 0)
1581 				return (pr);
1582 			mtx_unlock(&pr->pr_mtx);
1583 		}
1584 	}
1585 	return (NULL);
1586 }
1587 
1588 /*
1589  * Look for the named prison.  Returns a locked prison or NULL.
1590  */
1591 struct prison *
1592 prison_find_name(const char *name)
1593 {
1594 	struct prison *pr, *deadpr;
1595 
1596 	sx_assert(&allprison_lock, SX_LOCKED);
1597  again:
1598 	deadpr = NULL;
1599 	TAILQ_FOREACH(pr, &allprison, pr_list) {
1600 		if (!strcmp(pr->pr_name, name)) {
1601 			mtx_lock(&pr->pr_mtx);
1602 			if (pr->pr_ref > 0) {
1603 				if (pr->pr_uref > 0)
1604 					return (pr);
1605 				deadpr = pr;
1606 			}
1607 			mtx_unlock(&pr->pr_mtx);
1608 		}
1609 	}
1610 	/* There was no valid prison - perhaps there was a dying one */
1611 	if (deadpr != NULL) {
1612 		mtx_lock(&deadpr->pr_mtx);
1613 		if (deadpr->pr_ref == 0) {
1614 			mtx_unlock(&deadpr->pr_mtx);
1615 			goto again;
1616 		}
1617 	}
1618 	return (deadpr);
1619 }
1620 
1621 /*
1622  * Remove a prison reference.  If that was the last reference, remove the
1623  * prison itself - but not in this context in case there are locks held.
1624  */
1625 void
1626 prison_free_locked(struct prison *pr)
1627 {
1628 
1629 	mtx_assert(&pr->pr_mtx, MA_OWNED);
1630 	pr->pr_ref--;
1631 	if (pr->pr_ref == 0) {
1632 		mtx_unlock(&pr->pr_mtx);
1633 		TASK_INIT(&pr->pr_task, 0, prison_complete, pr);
1634 		taskqueue_enqueue(taskqueue_thread, &pr->pr_task);
1635 		return;
1636 	}
1637 	mtx_unlock(&pr->pr_mtx);
1638 }
1639 
1640 void
1641 prison_free(struct prison *pr)
1642 {
1643 
1644 	mtx_lock(&pr->pr_mtx);
1645 	prison_free_locked(pr);
1646 }
1647 
1648 static void
1649 prison_complete(void *context, int pending)
1650 {
1651 
1652 	prison_deref((struct prison *)context, 0);
1653 }
1654 
1655 /*
1656  * Remove a prison reference (usually).  This internal version assumes no
1657  * mutexes are held, except perhaps the prison itself.  If there are no more
1658  * references, release and delist the prison.  On completion, the prison lock
1659  * and the allprison lock are both unlocked.
1660  */
1661 static void
1662 prison_deref(struct prison *pr, int flags)
1663 {
1664 	int vfslocked;
1665 
1666 	if (!(flags & PD_LOCKED))
1667 		mtx_lock(&pr->pr_mtx);
1668 	if (flags & PD_DEUREF) {
1669 		pr->pr_uref--;
1670 		/* Done if there were only user references to remove. */
1671 		if (!(flags & PD_DEREF)) {
1672 			mtx_unlock(&pr->pr_mtx);
1673 			if (flags & PD_LIST_SLOCKED)
1674 				sx_sunlock(&allprison_lock);
1675 			else if (flags & PD_LIST_XLOCKED)
1676 				sx_xunlock(&allprison_lock);
1677 			return;
1678 		}
1679 	}
1680 	if (flags & PD_DEREF)
1681 		pr->pr_ref--;
1682 	/* If the prison still has references, nothing else to do. */
1683 	if (pr->pr_ref > 0) {
1684 		mtx_unlock(&pr->pr_mtx);
1685 		if (flags & PD_LIST_SLOCKED)
1686 			sx_sunlock(&allprison_lock);
1687 		else if (flags & PD_LIST_XLOCKED)
1688 			sx_xunlock(&allprison_lock);
1689 		return;
1690 	}
1691 
1692 	KASSERT(pr->pr_uref == 0,
1693 	    ("%s: Trying to remove an active prison (jid=%d).", __func__,
1694 	    pr->pr_id));
1695 	mtx_unlock(&pr->pr_mtx);
1696 	if (flags & PD_LIST_SLOCKED) {
1697 		if (!sx_try_upgrade(&allprison_lock)) {
1698 			sx_sunlock(&allprison_lock);
1699 			sx_xlock(&allprison_lock);
1700 		}
1701 	} else if (!(flags & PD_LIST_XLOCKED))
1702 		sx_xlock(&allprison_lock);
1703 
1704 	TAILQ_REMOVE(&allprison, pr, pr_list);
1705 	prisoncount--;
1706 	sx_xunlock(&allprison_lock);
1707 
1708 	if (pr->pr_root != NULL) {
1709 		vfslocked = VFS_LOCK_GIANT(pr->pr_root->v_mount);
1710 		vrele(pr->pr_root);
1711 		VFS_UNLOCK_GIANT(vfslocked);
1712 	}
1713 	mtx_destroy(&pr->pr_mtx);
1714 #ifdef INET
1715 	free(pr->pr_ip4, M_PRISON);
1716 #endif
1717 #ifdef INET6
1718 	free(pr->pr_ip6, M_PRISON);
1719 #endif
1720 	if (pr->pr_cpuset != NULL)
1721 		cpuset_rel(pr->pr_cpuset);
1722 	osd_jail_exit(pr);
1723 	free(pr, M_PRISON);
1724 }
1725 
1726 void
1727 prison_hold_locked(struct prison *pr)
1728 {
1729 
1730 	mtx_assert(&pr->pr_mtx, MA_OWNED);
1731 	KASSERT(pr->pr_ref > 0,
1732 	    ("Trying to hold dead prison (jid=%d).", pr->pr_id));
1733 	pr->pr_ref++;
1734 }
1735 
1736 void
1737 prison_hold(struct prison *pr)
1738 {
1739 
1740 	mtx_lock(&pr->pr_mtx);
1741 	prison_hold_locked(pr);
1742 	mtx_unlock(&pr->pr_mtx);
1743 }
1744 
1745 void
1746 prison_proc_hold(struct prison *pr)
1747 {
1748 
1749 	mtx_lock(&pr->pr_mtx);
1750 	KASSERT(pr->pr_uref > 0,
1751 	    ("Cannot add a process to a non-alive prison (jid=%d)", pr->pr_id));
1752 	pr->pr_uref++;
1753 	mtx_unlock(&pr->pr_mtx);
1754 }
1755 
1756 void
1757 prison_proc_free(struct prison *pr)
1758 {
1759 
1760 	mtx_lock(&pr->pr_mtx);
1761 	KASSERT(pr->pr_uref > 0,
1762 	    ("Trying to kill a process in a dead prison (jid=%d)", pr->pr_id));
1763 	prison_deref(pr, PD_DEUREF | PD_LOCKED);
1764 }
1765 
1766 
1767 #ifdef INET
1768 /*
1769  * Pass back primary IPv4 address of this jail.
1770  *
1771  * If not jailed return success but do not alter the address.  Caller has to
1772  * make sure to initialize it correctly (e.g. INADDR_ANY).
1773  *
1774  * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv4.
1775  * Address returned in NBO.
1776  */
1777 int
1778 prison_get_ip4(struct ucred *cred, struct in_addr *ia)
1779 {
1780 	struct prison *pr;
1781 
1782 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1783 	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
1784 
1785 	if (!jailed(cred))
1786 		return (0);
1787 	pr = cred->cr_prison;
1788 	mtx_lock(&pr->pr_mtx);
1789 	if (pr->pr_ip4 == NULL) {
1790 		mtx_unlock(&pr->pr_mtx);
1791 		return (EAFNOSUPPORT);
1792 	}
1793 
1794 	ia->s_addr = pr->pr_ip4[0].s_addr;
1795 	mtx_unlock(&pr->pr_mtx);
1796 	return (0);
1797 }
1798 
1799 /*
1800  * Make sure our (source) address is set to something meaningful to this
1801  * jail.
1802  *
1803  * Returns 0 if not jailed or if address belongs to jail, EADDRNOTAVAIL if
1804  * the address doesn't belong, or EAFNOSUPPORT if the jail doesn't allow IPv4.
1805  * Address passed in in NBO and returned in NBO.
1806  */
1807 int
1808 prison_local_ip4(struct ucred *cred, struct in_addr *ia)
1809 {
1810 	struct prison *pr;
1811 	struct in_addr ia0;
1812 	int error;
1813 
1814 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1815 	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
1816 
1817 	if (!jailed(cred))
1818 		return (0);
1819 	pr = cred->cr_prison;
1820 	mtx_lock(&pr->pr_mtx);
1821 	if (pr->pr_ip4 == NULL) {
1822 		mtx_unlock(&pr->pr_mtx);
1823 		return (EAFNOSUPPORT);
1824 	}
1825 
1826 	ia0.s_addr = ntohl(ia->s_addr);
1827 	if (ia0.s_addr == INADDR_LOOPBACK) {
1828 		ia->s_addr = pr->pr_ip4[0].s_addr;
1829 		mtx_unlock(&pr->pr_mtx);
1830 		return (0);
1831 	}
1832 
1833 	if (ia0.s_addr == INADDR_ANY) {
1834 		/*
1835 		 * In case there is only 1 IPv4 address, bind directly.
1836 		 */
1837 		if (pr->pr_ip4s == 1)
1838 			ia->s_addr = pr->pr_ip4[0].s_addr;
1839 		mtx_unlock(&pr->pr_mtx);
1840 		return (0);
1841 	}
1842 
1843 	error = _prison_check_ip4(pr, ia);
1844 	mtx_unlock(&pr->pr_mtx);
1845 	return (error);
1846 }
1847 
1848 /*
1849  * Rewrite destination address in case we will connect to loopback address.
1850  *
1851  * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv4.
1852  * Address passed in in NBO and returned in NBO.
1853  */
1854 int
1855 prison_remote_ip4(struct ucred *cred, struct in_addr *ia)
1856 {
1857 	struct prison *pr;
1858 
1859 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1860 	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
1861 
1862 	if (!jailed(cred))
1863 		return (0);
1864 	pr = cred->cr_prison;
1865 	mtx_lock(&pr->pr_mtx);
1866 	if (pr->pr_ip4 == NULL) {
1867 		mtx_unlock(&pr->pr_mtx);
1868 		return (EAFNOSUPPORT);
1869 	}
1870 
1871 	if (ntohl(ia->s_addr) == INADDR_LOOPBACK) {
1872 		ia->s_addr = pr->pr_ip4[0].s_addr;
1873 		mtx_unlock(&pr->pr_mtx);
1874 		return (0);
1875 	}
1876 
1877 	/*
1878 	 * Return success because nothing had to be changed.
1879 	 */
1880 	mtx_unlock(&pr->pr_mtx);
1881 	return (0);
1882 }
1883 
1884 /*
1885  * Check if given address belongs to the jail referenced by cred/prison.
1886  *
1887  * Returns 0 if not jailed or if address belongs to jail, EADDRNOTAVAIL if
1888  * the address doesn't belong, or EAFNOSUPPORT if the jail doesn't allow IPv4.
1889  * Address passed in in NBO.
1890  */
1891 static int
1892 _prison_check_ip4(struct prison *pr, struct in_addr *ia)
1893 {
1894 	int i, a, z, d;
1895 
1896 	/*
1897 	 * Check the primary IP.
1898 	 */
1899 	if (pr->pr_ip4[0].s_addr == ia->s_addr)
1900 		return (0);
1901 
1902 	/*
1903 	 * All the other IPs are sorted so we can do a binary search.
1904 	 */
1905 	a = 0;
1906 	z = pr->pr_ip4s - 2;
1907 	while (a <= z) {
1908 		i = (a + z) / 2;
1909 		d = qcmp_v4(&pr->pr_ip4[i+1], ia);
1910 		if (d > 0)
1911 			z = i - 1;
1912 		else if (d < 0)
1913 			a = i + 1;
1914 		else
1915 			return (0);
1916 	}
1917 
1918 	return (EADDRNOTAVAIL);
1919 }
1920 
1921 int
1922 prison_check_ip4(struct ucred *cred, struct in_addr *ia)
1923 {
1924 	struct prison *pr;
1925 	int error;
1926 
1927 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1928 	KASSERT(ia != NULL, ("%s: ia is NULL", __func__));
1929 
1930 	if (!jailed(cred))
1931 		return (0);
1932 	pr = cred->cr_prison;
1933 	mtx_lock(&pr->pr_mtx);
1934 	if (pr->pr_ip4 == NULL) {
1935 		mtx_unlock(&pr->pr_mtx);
1936 		return (EAFNOSUPPORT);
1937 	}
1938 
1939 	error = _prison_check_ip4(pr, ia);
1940 	mtx_unlock(&pr->pr_mtx);
1941 	return (error);
1942 }
1943 #endif
1944 
1945 #ifdef INET6
1946 /*
1947  * Pass back primary IPv6 address for this jail.
1948  *
1949  * If not jailed return success but do not alter the address.  Caller has to
1950  * make sure to initialize it correctly (e.g. IN6ADDR_ANY_INIT).
1951  *
1952  * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv6.
1953  */
1954 int
1955 prison_get_ip6(struct ucred *cred, struct in6_addr *ia6)
1956 {
1957 	struct prison *pr;
1958 
1959 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1960 	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
1961 
1962 	if (!jailed(cred))
1963 		return (0);
1964 	pr = cred->cr_prison;
1965 	mtx_lock(&pr->pr_mtx);
1966 	if (pr->pr_ip6 == NULL) {
1967 		mtx_unlock(&pr->pr_mtx);
1968 		return (EAFNOSUPPORT);
1969 	}
1970 
1971 	bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
1972 	mtx_unlock(&pr->pr_mtx);
1973 	return (0);
1974 }
1975 
1976 /*
1977  * Make sure our (source) address is set to something meaningful to this jail.
1978  *
1979  * v6only should be set based on (inp->inp_flags & IN6P_IPV6_V6ONLY != 0)
1980  * when needed while binding.
1981  *
1982  * Returns 0 if not jailed or if address belongs to jail, EADDRNOTAVAIL if
1983  * the address doesn't belong, or EAFNOSUPPORT if the jail doesn't allow IPv6.
1984  */
1985 int
1986 prison_local_ip6(struct ucred *cred, struct in6_addr *ia6, int v6only)
1987 {
1988 	struct prison *pr;
1989 	int error;
1990 
1991 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
1992 	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
1993 
1994 	if (!jailed(cred))
1995 		return (0);
1996 	pr = cred->cr_prison;
1997 	mtx_lock(&pr->pr_mtx);
1998 	if (pr->pr_ip6 == NULL) {
1999 		mtx_unlock(&pr->pr_mtx);
2000 		return (EAFNOSUPPORT);
2001 	}
2002 
2003 	if (IN6_IS_ADDR_LOOPBACK(ia6)) {
2004 		bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
2005 		mtx_unlock(&pr->pr_mtx);
2006 		return (0);
2007 	}
2008 
2009 	if (IN6_IS_ADDR_UNSPECIFIED(ia6)) {
2010 		/*
2011 		 * In case there is only 1 IPv6 address, and v6only is true,
2012 		 * then bind directly.
2013 		 */
2014 		if (v6only != 0 && pr->pr_ip6s == 1)
2015 			bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
2016 		mtx_unlock(&pr->pr_mtx);
2017 		return (0);
2018 	}
2019 
2020 	error = _prison_check_ip6(pr, ia6);
2021 	mtx_unlock(&pr->pr_mtx);
2022 	return (error);
2023 }
2024 
2025 /*
2026  * Rewrite destination address in case we will connect to loopback address.
2027  *
2028  * Returns 0 on success, EAFNOSUPPORT if the jail doesn't allow IPv6.
2029  */
2030 int
2031 prison_remote_ip6(struct ucred *cred, struct in6_addr *ia6)
2032 {
2033 	struct prison *pr;
2034 
2035 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2036 	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
2037 
2038 	if (!jailed(cred))
2039 		return (0);
2040 	pr = cred->cr_prison;
2041 	mtx_lock(&pr->pr_mtx);
2042 	if (pr->pr_ip6 == NULL) {
2043 		mtx_unlock(&pr->pr_mtx);
2044 		return (EAFNOSUPPORT);
2045 	}
2046 
2047 	if (IN6_IS_ADDR_LOOPBACK(ia6)) {
2048 		bcopy(&pr->pr_ip6[0], ia6, sizeof(struct in6_addr));
2049 		mtx_unlock(&pr->pr_mtx);
2050 		return (0);
2051 	}
2052 
2053 	/*
2054 	 * Return success because nothing had to be changed.
2055 	 */
2056 	mtx_unlock(&pr->pr_mtx);
2057 	return (0);
2058 }
2059 
2060 /*
2061  * Check if given address belongs to the jail referenced by cred/prison.
2062  *
2063  * Returns 0 if not jailed or if address belongs to jail, EADDRNOTAVAIL if
2064  * the address doesn't belong, or EAFNOSUPPORT if the jail doesn't allow IPv6.
2065  */
2066 static int
2067 _prison_check_ip6(struct prison *pr, struct in6_addr *ia6)
2068 {
2069 	int i, a, z, d;
2070 
2071 	/*
2072 	 * Check the primary IP.
2073 	 */
2074 	if (IN6_ARE_ADDR_EQUAL(&pr->pr_ip6[0], ia6))
2075 		return (0);
2076 
2077 	/*
2078 	 * All the other IPs are sorted so we can do a binary search.
2079 	 */
2080 	a = 0;
2081 	z = pr->pr_ip6s - 2;
2082 	while (a <= z) {
2083 		i = (a + z) / 2;
2084 		d = qcmp_v6(&pr->pr_ip6[i+1], ia6);
2085 		if (d > 0)
2086 			z = i - 1;
2087 		else if (d < 0)
2088 			a = i + 1;
2089 		else
2090 			return (0);
2091 	}
2092 
2093 	return (EADDRNOTAVAIL);
2094 }
2095 
2096 int
2097 prison_check_ip6(struct ucred *cred, struct in6_addr *ia6)
2098 {
2099 	struct prison *pr;
2100 	int error;
2101 
2102 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2103 	KASSERT(ia6 != NULL, ("%s: ia6 is NULL", __func__));
2104 
2105 	if (!jailed(cred))
2106 		return (0);
2107 	pr = cred->cr_prison;
2108 	mtx_lock(&pr->pr_mtx);
2109 	if (pr->pr_ip6 == NULL) {
2110 		mtx_unlock(&pr->pr_mtx);
2111 		return (EAFNOSUPPORT);
2112 	}
2113 
2114 	error = _prison_check_ip6(pr, ia6);
2115 	mtx_unlock(&pr->pr_mtx);
2116 	return (error);
2117 }
2118 #endif
2119 
2120 /*
2121  * Check if a jail supports the given address family.
2122  *
2123  * Returns 0 if not jailed or the address family is supported, EAFNOSUPPORT
2124  * if not.
2125  */
2126 int
2127 prison_check_af(struct ucred *cred, int af)
2128 {
2129 	int error;
2130 
2131 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2132 
2133 
2134 	if (!jailed(cred))
2135 		return (0);
2136 
2137 	error = 0;
2138 	switch (af)
2139 	{
2140 #ifdef INET
2141 	case AF_INET:
2142 		if (cred->cr_prison->pr_ip4 == NULL)
2143 			error = EAFNOSUPPORT;
2144 		break;
2145 #endif
2146 #ifdef INET6
2147 	case AF_INET6:
2148 		if (cred->cr_prison->pr_ip6 == NULL)
2149 			error = EAFNOSUPPORT;
2150 		break;
2151 #endif
2152 	case AF_LOCAL:
2153 	case AF_ROUTE:
2154 		break;
2155 	default:
2156 		if (jail_socket_unixiproute_only)
2157 			error = EAFNOSUPPORT;
2158 	}
2159 	return (error);
2160 }
2161 
2162 /*
2163  * Check if given address belongs to the jail referenced by cred (wrapper to
2164  * prison_check_ip[46]).
2165  *
2166  * Returns 0 if not jailed or if address belongs to jail, EADDRNOTAVAIL if
2167  * the address doesn't belong, or EAFNOSUPPORT if the jail doesn't allow
2168  * the address family.  IPv4 Address passed in in NBO.
2169  */
2170 int
2171 prison_if(struct ucred *cred, struct sockaddr *sa)
2172 {
2173 #ifdef INET
2174 	struct sockaddr_in *sai;
2175 #endif
2176 #ifdef INET6
2177 	struct sockaddr_in6 *sai6;
2178 #endif
2179 	int error;
2180 
2181 	KASSERT(cred != NULL, ("%s: cred is NULL", __func__));
2182 	KASSERT(sa != NULL, ("%s: sa is NULL", __func__));
2183 
2184 	error = 0;
2185 	switch (sa->sa_family)
2186 	{
2187 #ifdef INET
2188 	case AF_INET:
2189 		sai = (struct sockaddr_in *)sa;
2190 		error = prison_check_ip4(cred, &sai->sin_addr);
2191 		break;
2192 #endif
2193 #ifdef INET6
2194 	case AF_INET6:
2195 		sai6 = (struct sockaddr_in6 *)sa;
2196 		error = prison_check_ip6(cred, &sai6->sin6_addr);
2197 		break;
2198 #endif
2199 	default:
2200 		if (jailed(cred) && jail_socket_unixiproute_only)
2201 			error = EAFNOSUPPORT;
2202 	}
2203 	return (error);
2204 }
2205 
2206 /*
2207  * Return 0 if jails permit p1 to frob p2, otherwise ESRCH.
2208  */
2209 int
2210 prison_check(struct ucred *cred1, struct ucred *cred2)
2211 {
2212 
2213 	if (jailed(cred1)) {
2214 		if (!jailed(cred2))
2215 			return (ESRCH);
2216 		if (cred2->cr_prison != cred1->cr_prison)
2217 			return (ESRCH);
2218 	}
2219 #ifdef VIMAGE
2220 	if (cred2->cr_vimage->v_procg != cred1->cr_vimage->v_procg)
2221 		return (ESRCH);
2222 #endif
2223 
2224 	return (0);
2225 }
2226 
2227 /*
2228  * Return 1 if the passed credential is in a jail, otherwise 0.
2229  */
2230 int
2231 jailed(struct ucred *cred)
2232 {
2233 
2234 	return (cred->cr_prison != NULL);
2235 }
2236 
2237 /*
2238  * Return the correct hostname for the passed credential.
2239  */
2240 void
2241 getcredhostname(struct ucred *cred, char *buf, size_t size)
2242 {
2243 	INIT_VPROCG(cred->cr_vimage->v_procg);
2244 
2245 	if (jailed(cred)) {
2246 		mtx_lock(&cred->cr_prison->pr_mtx);
2247 		strlcpy(buf, cred->cr_prison->pr_host, size);
2248 		mtx_unlock(&cred->cr_prison->pr_mtx);
2249 	} else {
2250 		mtx_lock(&hostname_mtx);
2251 		strlcpy(buf, V_hostname, size);
2252 		mtx_unlock(&hostname_mtx);
2253 	}
2254 }
2255 
2256 /*
2257  * Determine whether the subject represented by cred can "see"
2258  * status of a mount point.
2259  * Returns: 0 for permitted, ENOENT otherwise.
2260  * XXX: This function should be called cr_canseemount() and should be
2261  *      placed in kern_prot.c.
2262  */
2263 int
2264 prison_canseemount(struct ucred *cred, struct mount *mp)
2265 {
2266 	struct prison *pr;
2267 	struct statfs *sp;
2268 	size_t len;
2269 
2270 	if (!jailed(cred) || jail_enforce_statfs == 0)
2271 		return (0);
2272 	pr = cred->cr_prison;
2273 	if (pr->pr_root->v_mount == mp)
2274 		return (0);
2275 	if (jail_enforce_statfs == 2)
2276 		return (ENOENT);
2277 	/*
2278 	 * If jail's chroot directory is set to "/" we should be able to see
2279 	 * all mount-points from inside a jail.
2280 	 * This is ugly check, but this is the only situation when jail's
2281 	 * directory ends with '/'.
2282 	 */
2283 	if (strcmp(pr->pr_path, "/") == 0)
2284 		return (0);
2285 	len = strlen(pr->pr_path);
2286 	sp = &mp->mnt_stat;
2287 	if (strncmp(pr->pr_path, sp->f_mntonname, len) != 0)
2288 		return (ENOENT);
2289 	/*
2290 	 * Be sure that we don't have situation where jail's root directory
2291 	 * is "/some/path" and mount point is "/some/pathpath".
2292 	 */
2293 	if (sp->f_mntonname[len] != '\0' && sp->f_mntonname[len] != '/')
2294 		return (ENOENT);
2295 	return (0);
2296 }
2297 
2298 void
2299 prison_enforce_statfs(struct ucred *cred, struct mount *mp, struct statfs *sp)
2300 {
2301 	char jpath[MAXPATHLEN];
2302 	struct prison *pr;
2303 	size_t len;
2304 
2305 	if (!jailed(cred) || jail_enforce_statfs == 0)
2306 		return;
2307 	pr = cred->cr_prison;
2308 	if (prison_canseemount(cred, mp) != 0) {
2309 		bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
2310 		strlcpy(sp->f_mntonname, "[restricted]",
2311 		    sizeof(sp->f_mntonname));
2312 		return;
2313 	}
2314 	if (pr->pr_root->v_mount == mp) {
2315 		/*
2316 		 * Clear current buffer data, so we are sure nothing from
2317 		 * the valid path left there.
2318 		 */
2319 		bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
2320 		*sp->f_mntonname = '/';
2321 		return;
2322 	}
2323 	/*
2324 	 * If jail's chroot directory is set to "/" we should be able to see
2325 	 * all mount-points from inside a jail.
2326 	 */
2327 	if (strcmp(pr->pr_path, "/") == 0)
2328 		return;
2329 	len = strlen(pr->pr_path);
2330 	strlcpy(jpath, sp->f_mntonname + len, sizeof(jpath));
2331 	/*
2332 	 * Clear current buffer data, so we are sure nothing from
2333 	 * the valid path left there.
2334 	 */
2335 	bzero(sp->f_mntonname, sizeof(sp->f_mntonname));
2336 	if (*jpath == '\0') {
2337 		/* Should never happen. */
2338 		*sp->f_mntonname = '/';
2339 	} else {
2340 		strlcpy(sp->f_mntonname, jpath, sizeof(sp->f_mntonname));
2341 	}
2342 }
2343 
2344 /*
2345  * Check with permission for a specific privilege is granted within jail.  We
2346  * have a specific list of accepted privileges; the rest are denied.
2347  */
2348 int
2349 prison_priv_check(struct ucred *cred, int priv)
2350 {
2351 
2352 	if (!jailed(cred))
2353 		return (0);
2354 
2355 	switch (priv) {
2356 
2357 		/*
2358 		 * Allow ktrace privileges for root in jail.
2359 		 */
2360 	case PRIV_KTRACE:
2361 
2362 #if 0
2363 		/*
2364 		 * Allow jailed processes to configure audit identity and
2365 		 * submit audit records (login, etc).  In the future we may
2366 		 * want to further refine the relationship between audit and
2367 		 * jail.
2368 		 */
2369 	case PRIV_AUDIT_GETAUDIT:
2370 	case PRIV_AUDIT_SETAUDIT:
2371 	case PRIV_AUDIT_SUBMIT:
2372 #endif
2373 
2374 		/*
2375 		 * Allow jailed processes to manipulate process UNIX
2376 		 * credentials in any way they see fit.
2377 		 */
2378 	case PRIV_CRED_SETUID:
2379 	case PRIV_CRED_SETEUID:
2380 	case PRIV_CRED_SETGID:
2381 	case PRIV_CRED_SETEGID:
2382 	case PRIV_CRED_SETGROUPS:
2383 	case PRIV_CRED_SETREUID:
2384 	case PRIV_CRED_SETREGID:
2385 	case PRIV_CRED_SETRESUID:
2386 	case PRIV_CRED_SETRESGID:
2387 
2388 		/*
2389 		 * Jail implements visibility constraints already, so allow
2390 		 * jailed root to override uid/gid-based constraints.
2391 		 */
2392 	case PRIV_SEEOTHERGIDS:
2393 	case PRIV_SEEOTHERUIDS:
2394 
2395 		/*
2396 		 * Jail implements inter-process debugging limits already, so
2397 		 * allow jailed root various debugging privileges.
2398 		 */
2399 	case PRIV_DEBUG_DIFFCRED:
2400 	case PRIV_DEBUG_SUGID:
2401 	case PRIV_DEBUG_UNPRIV:
2402 
2403 		/*
2404 		 * Allow jail to set various resource limits and login
2405 		 * properties, and for now, exceed process resource limits.
2406 		 */
2407 	case PRIV_PROC_LIMIT:
2408 	case PRIV_PROC_SETLOGIN:
2409 	case PRIV_PROC_SETRLIMIT:
2410 
2411 		/*
2412 		 * System V and POSIX IPC privileges are granted in jail.
2413 		 */
2414 	case PRIV_IPC_READ:
2415 	case PRIV_IPC_WRITE:
2416 	case PRIV_IPC_ADMIN:
2417 	case PRIV_IPC_MSGSIZE:
2418 	case PRIV_MQ_ADMIN:
2419 
2420 		/*
2421 		 * Jail implements its own inter-process limits, so allow
2422 		 * root processes in jail to change scheduling on other
2423 		 * processes in the same jail.  Likewise for signalling.
2424 		 */
2425 	case PRIV_SCHED_DIFFCRED:
2426 	case PRIV_SCHED_CPUSET:
2427 	case PRIV_SIGNAL_DIFFCRED:
2428 	case PRIV_SIGNAL_SUGID:
2429 
2430 		/*
2431 		 * Allow jailed processes to write to sysctls marked as jail
2432 		 * writable.
2433 		 */
2434 	case PRIV_SYSCTL_WRITEJAIL:
2435 
2436 		/*
2437 		 * Allow root in jail to manage a variety of quota
2438 		 * properties.  These should likely be conditional on a
2439 		 * configuration option.
2440 		 */
2441 	case PRIV_VFS_GETQUOTA:
2442 	case PRIV_VFS_SETQUOTA:
2443 
2444 		/*
2445 		 * Since Jail relies on chroot() to implement file system
2446 		 * protections, grant many VFS privileges to root in jail.
2447 		 * Be careful to exclude mount-related and NFS-related
2448 		 * privileges.
2449 		 */
2450 	case PRIV_VFS_READ:
2451 	case PRIV_VFS_WRITE:
2452 	case PRIV_VFS_ADMIN:
2453 	case PRIV_VFS_EXEC:
2454 	case PRIV_VFS_LOOKUP:
2455 	case PRIV_VFS_BLOCKRESERVE:	/* XXXRW: Slightly surprising. */
2456 	case PRIV_VFS_CHFLAGS_DEV:
2457 	case PRIV_VFS_CHOWN:
2458 	case PRIV_VFS_CHROOT:
2459 	case PRIV_VFS_RETAINSUGID:
2460 	case PRIV_VFS_FCHROOT:
2461 	case PRIV_VFS_LINK:
2462 	case PRIV_VFS_SETGID:
2463 	case PRIV_VFS_STAT:
2464 	case PRIV_VFS_STICKYFILE:
2465 		return (0);
2466 
2467 		/*
2468 		 * Depending on the global setting, allow privilege of
2469 		 * setting system flags.
2470 		 */
2471 	case PRIV_VFS_SYSFLAGS:
2472 		if (jail_chflags_allowed)
2473 			return (0);
2474 		else
2475 			return (EPERM);
2476 
2477 		/*
2478 		 * Depending on the global setting, allow privilege of
2479 		 * mounting/unmounting file systems.
2480 		 */
2481 	case PRIV_VFS_MOUNT:
2482 	case PRIV_VFS_UNMOUNT:
2483 	case PRIV_VFS_MOUNT_NONUSER:
2484 	case PRIV_VFS_MOUNT_OWNER:
2485 		if (jail_mount_allowed)
2486 			return (0);
2487 		else
2488 			return (EPERM);
2489 
2490 		/*
2491 		 * Allow jailed root to bind reserved ports and reuse in-use
2492 		 * ports.
2493 		 */
2494 	case PRIV_NETINET_RESERVEDPORT:
2495 	case PRIV_NETINET_REUSEPORT:
2496 		return (0);
2497 
2498 		/*
2499 		 * Allow jailed root to set certian IPv4/6 (option) headers.
2500 		 */
2501 	case PRIV_NETINET_SETHDROPTS:
2502 		return (0);
2503 
2504 		/*
2505 		 * Conditionally allow creating raw sockets in jail.
2506 		 */
2507 	case PRIV_NETINET_RAW:
2508 		if (jail_allow_raw_sockets)
2509 			return (0);
2510 		else
2511 			return (EPERM);
2512 
2513 		/*
2514 		 * Since jail implements its own visibility limits on netstat
2515 		 * sysctls, allow getcred.  This allows identd to work in
2516 		 * jail.
2517 		 */
2518 	case PRIV_NETINET_GETCRED:
2519 		return (0);
2520 
2521 	default:
2522 		/*
2523 		 * In all remaining cases, deny the privilege request.  This
2524 		 * includes almost all network privileges, many system
2525 		 * configuration privileges.
2526 		 */
2527 		return (EPERM);
2528 	}
2529 }
2530 
2531 static int
2532 sysctl_jail_list(SYSCTL_HANDLER_ARGS)
2533 {
2534 	struct xprison *xp;
2535 	struct prison *pr;
2536 #ifdef INET
2537 	struct in_addr *ip4 = NULL;
2538 	int ip4s = 0;
2539 #endif
2540 #ifdef INET6
2541 	struct in_addr *ip6 = NULL;
2542 	int ip6s = 0;
2543 #endif
2544 	int error;
2545 
2546 	if (jailed(req->td->td_ucred))
2547 		return (0);
2548 
2549 	xp = malloc(sizeof(*xp), M_TEMP, M_WAITOK);
2550 	error = 0;
2551 	sx_slock(&allprison_lock);
2552 	TAILQ_FOREACH(pr, &allprison, pr_list) {
2553  again:
2554 		mtx_lock(&pr->pr_mtx);
2555 #ifdef INET
2556 		if (pr->pr_ip4s > 0) {
2557 			if (ip4s < pr->pr_ip4s) {
2558 				ip4s = pr->pr_ip4s;
2559 				mtx_unlock(&pr->pr_mtx);
2560 				ip4 = realloc(ip4, ip4s *
2561 				    sizeof(struct in_addr), M_TEMP, M_WAITOK);
2562 				goto again;
2563 			}
2564 			bcopy(pr->pr_ip4, ip4,
2565 			    pr->pr_ip4s * sizeof(struct in_addr));
2566 		}
2567 #endif
2568 #ifdef INET6
2569 		if (pr->pr_ip6s > 0) {
2570 			if (ip6s < pr->pr_ip6s) {
2571 				ip6s = pr->pr_ip6s;
2572 				mtx_unlock(&pr->pr_mtx);
2573 				ip6 = realloc(ip6, ip6s *
2574 				    sizeof(struct in6_addr), M_TEMP, M_WAITOK);
2575 				goto again;
2576 			}
2577 			bcopy(pr->pr_ip6, ip6,
2578 			    pr->pr_ip6s * sizeof(struct in6_addr));
2579 		}
2580 #endif
2581 		if (pr->pr_ref == 0) {
2582 			mtx_unlock(&pr->pr_mtx);
2583 			continue;
2584 		}
2585 		bzero(xp, sizeof(*xp));
2586 		xp->pr_version = XPRISON_VERSION;
2587 		xp->pr_id = pr->pr_id;
2588 		xp->pr_state = pr->pr_uref > 0
2589 		    ? PRISON_STATE_ALIVE : PRISON_STATE_DYING;
2590 		strlcpy(xp->pr_path, pr->pr_path, sizeof(xp->pr_path));
2591 		strlcpy(xp->pr_host, pr->pr_host, sizeof(xp->pr_host));
2592 		strlcpy(xp->pr_name, pr->pr_name, sizeof(xp->pr_name));
2593 #ifdef INET
2594 		xp->pr_ip4s = pr->pr_ip4s;
2595 #endif
2596 #ifdef INET6
2597 		xp->pr_ip6s = pr->pr_ip6s;
2598 #endif
2599 		mtx_unlock(&pr->pr_mtx);
2600 		error = SYSCTL_OUT(req, xp, sizeof(*xp));
2601 		if (error)
2602 			break;
2603 #ifdef INET
2604 		if (xp->pr_ip4s > 0) {
2605 			error = SYSCTL_OUT(req, ip4,
2606 			    xp->pr_ip4s * sizeof(struct in_addr));
2607 			if (error)
2608 				break;
2609 		}
2610 #endif
2611 #ifdef INET6
2612 		if (xp->pr_ip6s > 0) {
2613 			error = SYSCTL_OUT(req, ip6,
2614 			    xp->pr_ip6s * sizeof(struct in6_addr));
2615 			if (error)
2616 				break;
2617 		}
2618 #endif
2619 	}
2620 	sx_sunlock(&allprison_lock);
2621 	free(xp, M_TEMP);
2622 #ifdef INET
2623 	free(ip4, M_TEMP);
2624 #endif
2625 #ifdef INET6
2626 	free(ip6, M_TEMP);
2627 #endif
2628 	return (error);
2629 }
2630 
2631 SYSCTL_OID(_security_jail, OID_AUTO, list,
2632     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2633     sysctl_jail_list, "S", "List of active jails");
2634 
2635 static int
2636 sysctl_jail_jailed(SYSCTL_HANDLER_ARGS)
2637 {
2638 	int error, injail;
2639 
2640 	injail = jailed(req->td->td_ucred);
2641 	error = SYSCTL_OUT(req, &injail, sizeof(injail));
2642 
2643 	return (error);
2644 }
2645 SYSCTL_PROC(_security_jail, OID_AUTO, jailed,
2646     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2647     sysctl_jail_jailed, "I", "Process in jail?");
2648 
2649 #ifdef DDB
2650 
2651 static void
2652 db_show_prison(struct prison *pr)
2653 {
2654 #if defined(INET) || defined(INET6)
2655 	int ii;
2656 #endif
2657 #ifdef INET6
2658 	char ip6buf[INET6_ADDRSTRLEN];
2659 #endif
2660 
2661 	db_printf("prison %p:\n", pr);
2662 	db_printf(" jid             = %d\n", pr->pr_id);
2663 	db_printf(" name            = %s\n", pr->pr_name);
2664 	db_printf(" ref             = %d\n", pr->pr_ref);
2665 	db_printf(" uref            = %d\n", pr->pr_uref);
2666 	db_printf(" path            = %s\n", pr->pr_path);
2667 	db_printf(" cpuset          = %d\n", pr->pr_cpuset
2668 	    ? pr->pr_cpuset->cs_id : -1);
2669 	db_printf(" root            = %p\n", pr->pr_root);
2670 	db_printf(" securelevel     = %d\n", pr->pr_securelevel);
2671 	db_printf(" flags           = %x", pr->pr_flags);
2672 	if (pr->pr_flags & PR_PERSIST)
2673 		db_printf(" persist");
2674 	db_printf("\n");
2675 	db_printf(" host.hostname   = %s\n", pr->pr_host);
2676 #ifdef INET
2677 	db_printf(" ip4s            = %d\n", pr->pr_ip4s);
2678 	for (ii = 0; ii < pr->pr_ip4s; ii++)
2679 		db_printf(" %s %s\n",
2680 		    ii == 0 ? "ip4             =" : "                 ",
2681 		    inet_ntoa(pr->pr_ip4[ii]));
2682 #endif
2683 #ifdef INET6
2684 	db_printf(" ip6s            = %d\n", pr->pr_ip6s);
2685 	for (ii = 0; ii < pr->pr_ip6s; ii++)
2686 		db_printf(" %s %s\n",
2687 		    ii == 0 ? "ip6             =" : "                 ",
2688 		    ip6_sprintf(ip6buf, &pr->pr_ip6[ii]));
2689 #endif
2690 }
2691 
2692 DB_SHOW_COMMAND(prison, db_show_prison_command)
2693 {
2694 	struct prison *pr;
2695 
2696 	if (!have_addr) {
2697 		/* Show all prisons in the list. */
2698 		TAILQ_FOREACH(pr, &allprison, pr_list) {
2699 			db_show_prison(pr);
2700 			if (db_pager_quit)
2701 				break;
2702 		}
2703 		return;
2704 	}
2705 
2706 	/* Look for a prison with the ID and with references. */
2707 	TAILQ_FOREACH(pr, &allprison, pr_list)
2708 		if (pr->pr_id == addr && pr->pr_ref > 0)
2709 			break;
2710 	if (pr == NULL)
2711 		/* Look again, without requiring a reference. */
2712 		TAILQ_FOREACH(pr, &allprison, pr_list)
2713 			if (pr->pr_id == addr)
2714 				break;
2715 	if (pr == NULL)
2716 		/* Assume address points to a valid prison. */
2717 		pr = (struct prison *)addr;
2718 	db_show_prison(pr);
2719 }
2720 
2721 #endif /* DDB */
2722