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