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