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