xref: /freebsd/sys/kern/kern_jail.c (revision c807777a43ef2b59786fa8a1a35c1f154fd069e5)
1 /*
2  * ----------------------------------------------------------------------------
3  * "THE BEER-WARE LICENSE" (Revision 42):
4  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5  * can do whatever you want with this stuff. If we meet some day, and you think
6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7  * ----------------------------------------------------------------------------
8  *
9  * $FreeBSD$
10  *
11  */
12 
13 #include <sys/param.h>
14 #include <sys/types.h>
15 #include <sys/kernel.h>
16 #include <sys/systm.h>
17 #include <sys/errno.h>
18 #include <sys/sysproto.h>
19 #include <sys/malloc.h>
20 #include <sys/proc.h>
21 #include <sys/jail.h>
22 #include <sys/socket.h>
23 #include <net/if.h>
24 #include <netinet/in.h>
25 
26 MALLOC_DEFINE(M_PRISON, "prison", "Prison structures");
27 
28 int
29 jail(p, uap)
30         struct proc *p;
31         struct jail_args /* {
32                 syscallarg(struct jail *) jail;
33         } */ *uap;
34 {
35 	int error;
36 	struct prison *pr;
37 	struct jail j;
38 	struct chroot_args ca;
39 
40 	error = suser(p);
41 	if (error)
42 		return (error);
43 	error = copyin(uap->jail, &j, sizeof j);
44 	if (error)
45 		return (error);
46 	if (j.version != 0)
47 		return (EINVAL);
48 	MALLOC(pr, struct prison *, sizeof *pr , M_PRISON, M_WAITOK);
49 	bzero((caddr_t)pr, sizeof *pr);
50 	error = copyinstr(j.hostname, &pr->pr_host, sizeof pr->pr_host, 0);
51 	if (error)
52 		goto bail;
53 	pr->pr_ip = j.ip_number;
54 
55 	ca.path = j.path;
56 	error = chroot(p, &ca);
57 	if (error)
58 		goto bail;
59 
60 	pr->pr_ref++;
61 	p->p_prison = pr;
62 	p->p_flag |= P_JAILED;
63 	return (0);
64 
65 bail:
66 	FREE(pr, M_PRISON);
67 	return (error);
68 }
69 
70 int
71 prison_ip(struct proc *p, int flag, u_int32_t *ip)
72 {
73 	u_int32_t tmp;
74 
75 	if (!p->p_prison)
76 		return (0);
77 	if (flag)
78 		tmp = *ip;
79 	else
80 		tmp = ntohl(*ip);
81 	if (tmp == INADDR_ANY) {
82 		if (flag)
83 			*ip = p->p_prison->pr_ip;
84 		else
85 			*ip = htonl(p->p_prison->pr_ip);
86 		return (0);
87 	}
88 	if (p->p_prison->pr_ip != tmp)
89 		return (1);
90 	return (0);
91 }
92 
93 void
94 prison_remote_ip(struct proc *p, int flag, u_int32_t *ip)
95 {
96 	u_int32_t tmp;
97 
98 	if (!p || !p->p_prison)
99 		return;
100 	if (flag)
101 		tmp = *ip;
102 	else
103 		tmp = ntohl(*ip);
104 	if (tmp == 0x7f000001) {
105 		if (flag)
106 			*ip = p->p_prison->pr_ip;
107 		else
108 			*ip = htonl(p->p_prison->pr_ip);
109 		return;
110 	}
111 	return;
112 }
113 
114 int
115 prison_if(struct proc *p, struct sockaddr *sa)
116 {
117 	struct sockaddr_in *sai = (struct sockaddr_in*) sa;
118 	int ok;
119 
120 	if (sai->sin_family != AF_INET)
121 		ok = 0;
122 	else if (p->p_prison->pr_ip != ntohl(sai->sin_addr.s_addr))
123 		ok = 1;
124 	else
125 		ok = 0;
126 	return (ok);
127 }
128