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