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