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