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