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