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