xref: /freebsd/sys/security/mac_portacl/mac_portacl.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
1 /*-
2  * Copyright (c) 2003-2004 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by Network
6  * Associates Laboratories, the Security Research Division of Network
7  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
8  * as part of the DARPA CHATS research program.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33 
34 /*
35  * Developed by the TrustedBSD Project.
36  *
37  * Administratively limit access to local UDP/TCP ports for binding purposes.
38  * Intended to be combined with net.inet.ip.portrange.reservedhigh to allow
39  * specific uids and gids to bind specific ports for specific purposes,
40  * while not opening the door to any user replacing an "official" service
41  * while you're restarting it.  This only affects ports explicitly bound by
42  * the user process (either for listen/outgoing socket for TCP, or send/
43  * receive for UDP).  This module will not limit ports bound implicitly for
44  * out-going connections where the process hasn't explicitly selected a port:
45  * these are automatically selected by the IP stack.
46  *
47  * To use this module, security.mac.enforce_socket must be enabled, and
48  * you will probably want to twiddle the net.inet sysctl listed above.
49  * Then use sysctl(8) to modify the rules string:
50  *
51  * # sysctl security.mac.portacl.rules="uid:425:tcp:80,uid:425:tcp:79"
52  *
53  * This ruleset, for example, permits uid 425 to bind TCP ports 80 (http)
54  * and 79 (finger).  User names and group names can't be used directly
55  * because the kernel only knows about uids and gids.
56  */
57 
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/conf.h>
61 #include <sys/domain.h>
62 #include <sys/kernel.h>
63 #include <sys/libkern.h>
64 #include <sys/mac.h>
65 #include <sys/malloc.h>
66 #include <sys/mount.h>
67 #include <sys/proc.h>
68 #include <sys/protosw.h>
69 #include <sys/queue.h>
70 #include <sys/systm.h>
71 #include <sys/sysproto.h>
72 #include <sys/sysent.h>
73 #include <sys/vnode.h>
74 #include <sys/file.h>
75 #include <sys/sbuf.h>
76 #include <sys/socket.h>
77 #include <sys/socketvar.h>
78 #include <sys/sx.h>
79 #include <sys/sysctl.h>
80 
81 #include <netinet/in.h>
82 
83 #include <vm/vm.h>
84 
85 #include <sys/mac_policy.h>
86 
87 SYSCTL_DECL(_security_mac);
88 
89 SYSCTL_NODE(_security_mac, OID_AUTO, portacl, CTLFLAG_RW, 0,
90     "TrustedBSD mac_portacl policy controls");
91 
92 static int	mac_portacl_enabled = 1;
93 SYSCTL_INT(_security_mac_portacl, OID_AUTO, enabled, CTLFLAG_RW,
94     &mac_portacl_enabled, 0, "Enforce portacl policy");
95 TUNABLE_INT("security.mac.portacl.enabled", &mac_portacl_enabled);
96 
97 static int	mac_portacl_suser_exempt = 1;
98 SYSCTL_INT(_security_mac_portacl, OID_AUTO, suser_exempt, CTLFLAG_RW,
99     &mac_portacl_suser_exempt, 0, "Privilege permits binding of any port");
100 TUNABLE_INT("security.mac.portacl.suser_exempt",
101     &mac_portacl_suser_exempt);
102 
103 static int	mac_portacl_port_high = 1023;
104 SYSCTL_INT(_security_mac_portacl, OID_AUTO, port_high, CTLFLAG_RW,
105     &mac_portacl_port_high, 0, "Highest port to enforce for");
106 TUNABLE_INT("security.mac.portacl.port_high", &mac_portacl_port_high);
107 
108 MALLOC_DEFINE(M_PORTACL, "portacl rule", "Rules for mac_portacl");
109 
110 #define	MAC_RULE_STRING_LEN	1024
111 
112 #define	RULE_GID	1
113 #define	RULE_UID	2
114 #define	RULE_PROTO_TCP	1
115 #define	RULE_PROTO_UDP	2
116 struct rule {
117 	id_t			r_id;
118 	int			r_idtype;
119 	u_int16_t		r_port;
120 	int			r_protocol;
121 
122 	TAILQ_ENTRY(rule)	r_entries;
123 };
124 
125 #define	GID_STRING	"gid"
126 #define	TCP_STRING	"tcp"
127 #define	UID_STRING	"uid"
128 #define	UDP_STRING	"udp"
129 
130 /*
131  * Text format for the rule string is that a rule consists of a
132  * comma-seperated list of elements.  Each element is in the form
133  * idtype:id:protocol:portnumber, and constitutes granting of permission
134  * for the specified binding.
135  */
136 
137 static struct sx			rule_sx;
138 static TAILQ_HEAD(rulehead, rule)	rule_head;
139 static char				rule_string[MAC_RULE_STRING_LEN];
140 
141 static void
142 toast_rules(struct rulehead *head)
143 {
144 	struct rule *rule;
145 
146 	while ((rule = TAILQ_FIRST(head)) != NULL) {
147 		TAILQ_REMOVE(head, rule, r_entries);
148 		free(rule, M_PORTACL);
149 	}
150 }
151 
152 /*
153  * Note that there is an inherent race condition in the unload of modules
154  * and access via sysctl.
155  */
156 static void
157 destroy(struct mac_policy_conf *mpc)
158 {
159 
160 	sx_destroy(&rule_sx);
161 	toast_rules(&rule_head);
162 }
163 
164 static void
165 init(struct mac_policy_conf *mpc)
166 {
167 
168 	sx_init(&rule_sx, "rule_sx");
169 	TAILQ_INIT(&rule_head);
170 }
171 
172 /*
173  * Note: parsing routines are destructive on the passed string.
174  */
175 static int
176 parse_rule_element(char *element, struct rule **rule)
177 {
178 	char *idtype, *id, *protocol, *portnumber, *p;
179 	struct rule *new;
180 	int error;
181 
182 	error = 0;
183 	new = malloc(sizeof(*new), M_PORTACL, M_ZERO | M_WAITOK);
184 
185 	idtype = strsep(&element, ":");
186 	if (idtype == NULL) {
187 		error = EINVAL;
188 		goto out;
189 	}
190 	id = strsep(&element, ":");
191 	if (id == NULL) {
192 		error = EINVAL;
193 		goto out;
194 	}
195 	new->r_id = strtol(id, &p, 10);
196 	if (*p != '\0') {
197 		error = EINVAL;
198 		goto out;
199 	}
200 	if (strcmp(idtype, UID_STRING) == 0)
201 		new->r_idtype = RULE_UID;
202 	else if (strcmp(idtype, GID_STRING) == 0)
203 		new->r_idtype = RULE_GID;
204 	else {
205 		error = EINVAL;
206 		goto out;
207 	}
208 	protocol = strsep(&element, ":");
209 	if (protocol == NULL) {
210 		error = EINVAL;
211 		goto out;
212 	}
213 	if (strcmp(protocol, TCP_STRING) == 0)
214 		new->r_protocol = RULE_PROTO_TCP;
215 	else if (strcmp(protocol, UDP_STRING) == 0)
216 		new->r_protocol = RULE_PROTO_UDP;
217 	else {
218 		error = EINVAL;
219 		goto out;
220 	}
221 	portnumber = element;
222 	if (portnumber == NULL) {
223 		error = EINVAL;
224 		goto out;
225 	}
226 	new->r_port = strtol(portnumber, &p, 10);
227 	if (*p != '\0') {
228 		error = EINVAL;
229 		goto out;
230 	}
231 
232 out:
233 	if (error != 0) {
234 		free(new, M_PORTACL);
235 		*rule = NULL;
236 	} else
237 		*rule = new;
238 	return (error);
239 }
240 
241 static int
242 parse_rules(char *string, struct rulehead *head)
243 {
244 	struct rule *new;
245 	char *element;
246 	int error;
247 
248 	error = 0;
249 	while ((element = strsep(&string, ",")) != NULL) {
250 		if (strlen(element) == 0)
251 			continue;
252 		error = parse_rule_element(element, &new);
253 		if (error)
254 			goto out;
255 		TAILQ_INSERT_TAIL(head, new, r_entries);
256 	}
257 out:
258 	if (error != 0)
259 		toast_rules(head);
260 	return (error);
261 }
262 
263 #if 0
264 static void
265 rule_printf(struct sbuf *sb, struct rule *rule)
266 {
267 	const char *idtype, *protocol;
268 
269 	switch(rule->r_idtype) {
270 	case RULE_GID:
271 		idtype = GID_STRING;
272 		break;
273 	case RULE_UID:
274 		idtype = UID_STRING;
275 		break;
276 	default:
277 		panic("rule_printf: unknown idtype (%d)\n", rule->r_idtype);
278 	}
279 
280 	switch (rule->r_protocol) {
281 	case RULE_PROTO_TCP:
282 		protocol = TCP_STRING;
283 		break;
284 	case RULE_PROTO_UDP:
285 		protocol = UDP_STRING;
286 		break;
287 	default:
288 		panic("rule_printf: unknown protocol (%d)\n",
289 		    rule->r_protocol);
290 	}
291 	sbuf_printf(sb, "%s:%jd:%s:%d", idtype, (intmax_t)rule->r_id,
292 	    protocol, rule->r_port);
293 }
294 
295 static char *
296 rules_to_string(void)
297 {
298 	struct rule *rule;
299 	struct sbuf *sb;
300 	int needcomma;
301 	char *temp;
302 
303 	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
304 	needcomma = 0;
305 	sx_slock(&rule_sx);
306 	for (rule = TAILQ_FIRST(&rule_head); rule != NULL;
307 	    rule = TAILQ_NEXT(rule, r_entries)) {
308 		if (!needcomma)
309 			needcomma = 1;
310 		else
311 			sbuf_printf(sb, ",");
312 		rule_printf(sb, rule);
313 	}
314 	sx_sunlock(&rule_sx);
315 	sbuf_finish(sb);
316 	temp = strdup(sbuf_data(sb), M_PORTACL);
317 	sbuf_delete(sb);
318 	return (temp);
319 }
320 #endif
321 
322 /*
323  * Note: due to races, there is not a single serializable order
324  * between parallel calls to the sysctl.
325  */
326 static int
327 sysctl_rules(SYSCTL_HANDLER_ARGS)
328 {
329 	char *string, *copy_string, *new_string;
330 	struct rulehead head, save_head;
331 	struct rule *rule;
332 	int error;
333 
334 	new_string = NULL;
335 	if (req->newptr == NULL) {
336 		new_string = malloc(MAC_RULE_STRING_LEN, M_PORTACL,
337 		    M_WAITOK | M_ZERO);
338 		strcpy(new_string, rule_string);
339 		string = new_string;
340 	} else
341 		string = rule_string;
342 
343 	error = sysctl_handle_string(oidp, string, MAC_RULE_STRING_LEN, req);
344 	if (error)
345 		goto out;
346 
347 	if (req->newptr != NULL) {
348 		copy_string = strdup(string, M_PORTACL);
349 		TAILQ_INIT(&head);
350 		error = parse_rules(copy_string, &head);
351 		free(copy_string, M_PORTACL);
352 		if (error)
353 			goto out;
354 
355 		TAILQ_INIT(&save_head);
356 		sx_xlock(&rule_sx);
357 		/*
358 		 * XXX: Unfortunately, TAILQ doesn't yet have a supported
359 		 * assignment operator to copy one queue to another, due
360 	 	 * to a self-referential pointer in the tailq header.
361 		 * For now, do it the old-fashioned way.
362 		 */
363 		while ((rule = TAILQ_FIRST(&rule_head)) != NULL) {
364 			TAILQ_REMOVE(&rule_head, rule, r_entries);
365 			TAILQ_INSERT_HEAD(&save_head, rule, r_entries);
366 		}
367 		while ((rule = TAILQ_FIRST(&head)) != NULL) {
368 			TAILQ_REMOVE(&head, rule, r_entries);
369 			TAILQ_INSERT_HEAD(&rule_head, rule, r_entries);
370 		}
371 		strcpy(rule_string, string);
372 		sx_xunlock(&rule_sx);
373 		toast_rules(&save_head);
374 	}
375 out:
376 	if (new_string != NULL)
377 		free(new_string, M_PORTACL);
378 	return (error);
379 }
380 
381 SYSCTL_PROC(_security_mac_portacl, OID_AUTO, rules,
382        CTLTYPE_STRING|CTLFLAG_RW, 0, 0, sysctl_rules, "A", "Rules");
383 
384 static int
385 rules_check(struct ucred *cred, int family, int type, u_int16_t port)
386 {
387 	struct rule *rule;
388 	int error;
389 
390 #if 0
391 	printf("Check requested for euid %d, family %d, type %d, port %d\n",
392 	    cred->cr_uid, family, type, port);
393 #endif
394 
395 	if (port > mac_portacl_port_high)
396 		return (0);
397 
398 	error = EPERM;
399 	sx_slock(&rule_sx);
400 	for (rule = TAILQ_FIRST(&rule_head);
401 	    rule != NULL;
402 	    rule = TAILQ_NEXT(rule, r_entries)) {
403 		if (type == SOCK_DGRAM && rule->r_protocol != RULE_PROTO_UDP)
404 			continue;
405 		if (type == SOCK_STREAM && rule->r_protocol != RULE_PROTO_TCP)
406 			continue;
407 		if (port != rule->r_port)
408 			continue;
409 		if (rule->r_idtype == RULE_UID) {
410 			if (cred->cr_uid == rule->r_id) {
411 				error = 0;
412 				break;
413 			}
414 		} else if (rule->r_idtype == RULE_GID) {
415 			if (cred->cr_gid == rule->r_id) {
416 				error = 0;
417 				break;
418 			} else if (groupmember(rule->r_id, cred)) {
419 				error = 0;
420 				break;
421 			}
422 		} else
423 			panic("rules_check: unknown rule type %d",
424 			    rule->r_idtype);
425 	}
426 	sx_sunlock(&rule_sx);
427 
428 	if (error != 0 && mac_portacl_suser_exempt != 0)
429 		error = suser_cred(cred, 0);
430 
431 	return (error);
432 }
433 
434 /*
435  * Note, this only limits the ability to explicitly bind a port, it
436  * doesn't limit implicitly bound ports for outgoing connections where
437  * the source port is left up to the IP stack to determine automatically.
438  */
439 static int
440 check_socket_bind(struct ucred *cred, struct socket *so,
441     struct label *socketlabel, struct sockaddr *sockaddr)
442 {
443 	struct sockaddr_in *sin;
444 	int family, type;
445 	u_int16_t port;
446 
447 	/* Only run if we are enabled. */
448 	if (mac_portacl_enabled == 0)
449 		return (0);
450 
451 	/* Only interested in IPv4 and IPv6 sockets. */
452 	if (so->so_proto->pr_domain->dom_family != PF_INET &&
453 	    so->so_proto->pr_domain->dom_family != PF_INET6)
454 		return (0);
455 
456 	/* Currently, we don't attempt to deal with SOCK_RAW, etc. */
457 	if (so->so_type != SOCK_DGRAM &&
458 	    so->so_type != SOCK_STREAM)
459 		return (0);
460 
461 	/* Reject addresses we don't understand; fail closed. */
462 	if (sockaddr->sa_family != AF_INET &&
463 	    sockaddr->sa_family != AF_INET6)
464 		return (EINVAL);
465 
466 	family = so->so_proto->pr_domain->dom_family;
467 	type = so->so_type;
468 	sin = (struct sockaddr_in *) sockaddr;
469 	port = ntohs(sin->sin_port);
470 
471 	return (rules_check(cred, family, type, port));
472 }
473 
474 static struct mac_policy_ops mac_portacl_ops =
475 {
476 	.mpo_destroy = destroy,
477 	.mpo_init = init,
478 	.mpo_check_socket_bind = check_socket_bind,
479 };
480 
481 MAC_POLICY_SET(&mac_portacl_ops, trustedbsd_mac_portacl,
482     "TrustedBSD MAC/portacl", MPC_LOADTIME_FLAG_UNLOADOK, NULL);
483