xref: /freebsd/sys/security/mac_portacl/mac_portacl.c (revision f856af0466c076beef4ea9b15d088e1119a945b8)
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/lock.h>
65 #include <sys/mac.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.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/sysproto.h>
75 #include <sys/sysent.h>
76 #include <sys/file.h>
77 #include <sys/sbuf.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/sysctl.h>
81 
82 #include <netinet/in.h>
83 #include <netinet/in_pcb.h>
84 
85 #include <vm/vm.h>
86 
87 #include <security/mac/mac_policy.h>
88 
89 SYSCTL_DECL(_security_mac);
90 
91 SYSCTL_NODE(_security_mac, OID_AUTO, portacl, CTLFLAG_RW, 0,
92     "TrustedBSD mac_portacl policy controls");
93 
94 static int	mac_portacl_enabled = 1;
95 SYSCTL_INT(_security_mac_portacl, OID_AUTO, enabled, CTLFLAG_RW,
96     &mac_portacl_enabled, 0, "Enforce portacl policy");
97 TUNABLE_INT("security.mac.portacl.enabled", &mac_portacl_enabled);
98 
99 static int	mac_portacl_suser_exempt = 1;
100 SYSCTL_INT(_security_mac_portacl, OID_AUTO, suser_exempt, CTLFLAG_RW,
101     &mac_portacl_suser_exempt, 0, "Privilege permits binding of any port");
102 TUNABLE_INT("security.mac.portacl.suser_exempt",
103     &mac_portacl_suser_exempt);
104 
105 static int	mac_portacl_autoport_exempt = 1;
106 SYSCTL_INT(_security_mac_portacl, OID_AUTO, autoport_exempt, CTLFLAG_RW,
107     &mac_portacl_autoport_exempt, 0, "Allow automatic allocation through "
108     "binding port 0 if not IP_PORTRANGELOW");
109 TUNABLE_INT("security.mac.portacl.autoport_exempt",
110     &mac_portacl_autoport_exempt);
111 
112 static int	mac_portacl_port_high = 1023;
113 SYSCTL_INT(_security_mac_portacl, OID_AUTO, port_high, CTLFLAG_RW,
114     &mac_portacl_port_high, 0, "Highest port to enforce for");
115 TUNABLE_INT("security.mac.portacl.port_high", &mac_portacl_port_high);
116 
117 MALLOC_DEFINE(M_PORTACL, "mac_portacl_rule", "Rules for mac_portacl");
118 
119 #define	MAC_RULE_STRING_LEN	1024
120 
121 #define	RULE_GID	1
122 #define	RULE_UID	2
123 #define	RULE_PROTO_TCP	1
124 #define	RULE_PROTO_UDP	2
125 struct rule {
126 	id_t			r_id;
127 	int			r_idtype;
128 	u_int16_t		r_port;
129 	int			r_protocol;
130 
131 	TAILQ_ENTRY(rule)	r_entries;
132 };
133 
134 #define	GID_STRING	"gid"
135 #define	TCP_STRING	"tcp"
136 #define	UID_STRING	"uid"
137 #define	UDP_STRING	"udp"
138 
139 /*
140  * Text format for the rule string is that a rule consists of a
141  * comma-seperated list of elements.  Each element is in the form
142  * idtype:id:protocol:portnumber, and constitutes granting of permission
143  * for the specified binding.
144  */
145 
146 static struct mtx			rule_mtx;
147 static TAILQ_HEAD(rulehead, rule)	rule_head;
148 static char				rule_string[MAC_RULE_STRING_LEN];
149 
150 static void
151 toast_rules(struct rulehead *head)
152 {
153 	struct rule *rule;
154 
155 	while ((rule = TAILQ_FIRST(head)) != NULL) {
156 		TAILQ_REMOVE(head, rule, r_entries);
157 		free(rule, M_PORTACL);
158 	}
159 }
160 
161 /*
162  * Note that there is an inherent race condition in the unload of modules
163  * and access via sysctl.
164  */
165 static void
166 destroy(struct mac_policy_conf *mpc)
167 {
168 
169 	mtx_destroy(&rule_mtx);
170 	toast_rules(&rule_head);
171 }
172 
173 static void
174 init(struct mac_policy_conf *mpc)
175 {
176 
177 	mtx_init(&rule_mtx, "rule_mtx", NULL, MTX_DEF);
178 	TAILQ_INIT(&rule_head);
179 }
180 
181 /*
182  * Note: parsing routines are destructive on the passed string.
183  */
184 static int
185 parse_rule_element(char *element, struct rule **rule)
186 {
187 	char *idtype, *id, *protocol, *portnumber, *p;
188 	struct rule *new;
189 	int error;
190 
191 	error = 0;
192 	new = malloc(sizeof(*new), M_PORTACL, M_ZERO | M_WAITOK);
193 
194 	idtype = strsep(&element, ":");
195 	if (idtype == NULL) {
196 		error = EINVAL;
197 		goto out;
198 	}
199 	id = strsep(&element, ":");
200 	if (id == NULL) {
201 		error = EINVAL;
202 		goto out;
203 	}
204 	new->r_id = strtol(id, &p, 10);
205 	if (*p != '\0') {
206 		error = EINVAL;
207 		goto out;
208 	}
209 	if (strcmp(idtype, UID_STRING) == 0)
210 		new->r_idtype = RULE_UID;
211 	else if (strcmp(idtype, GID_STRING) == 0)
212 		new->r_idtype = RULE_GID;
213 	else {
214 		error = EINVAL;
215 		goto out;
216 	}
217 	protocol = strsep(&element, ":");
218 	if (protocol == NULL) {
219 		error = EINVAL;
220 		goto out;
221 	}
222 	if (strcmp(protocol, TCP_STRING) == 0)
223 		new->r_protocol = RULE_PROTO_TCP;
224 	else if (strcmp(protocol, UDP_STRING) == 0)
225 		new->r_protocol = RULE_PROTO_UDP;
226 	else {
227 		error = EINVAL;
228 		goto out;
229 	}
230 	portnumber = element;
231 	if (portnumber == NULL) {
232 		error = EINVAL;
233 		goto out;
234 	}
235 	new->r_port = strtol(portnumber, &p, 10);
236 	if (*p != '\0') {
237 		error = EINVAL;
238 		goto out;
239 	}
240 
241 out:
242 	if (error != 0) {
243 		free(new, M_PORTACL);
244 		*rule = NULL;
245 	} else
246 		*rule = new;
247 	return (error);
248 }
249 
250 static int
251 parse_rules(char *string, struct rulehead *head)
252 {
253 	struct rule *new;
254 	char *element;
255 	int error;
256 
257 	error = 0;
258 	while ((element = strsep(&string, ",")) != NULL) {
259 		if (strlen(element) == 0)
260 			continue;
261 		error = parse_rule_element(element, &new);
262 		if (error)
263 			goto out;
264 		TAILQ_INSERT_TAIL(head, new, r_entries);
265 	}
266 out:
267 	if (error != 0)
268 		toast_rules(head);
269 	return (error);
270 }
271 
272 /*
273  * rule_printf() and rules_to_string() are unused currently because they rely
274  * on sbufs with auto-extension, which may sleep while holding a mutex.
275  * Instead, the non-canonical user-generated rule string is returned to the
276  * user when the rules are queried, which is faster anyway.
277  */
278 #if 0
279 static void
280 rule_printf(struct sbuf *sb, struct rule *rule)
281 {
282 	const char *idtype, *protocol;
283 
284 	switch(rule->r_idtype) {
285 	case RULE_GID:
286 		idtype = GID_STRING;
287 		break;
288 	case RULE_UID:
289 		idtype = UID_STRING;
290 		break;
291 	default:
292 		panic("rule_printf: unknown idtype (%d)\n", rule->r_idtype);
293 	}
294 
295 	switch (rule->r_protocol) {
296 	case RULE_PROTO_TCP:
297 		protocol = TCP_STRING;
298 		break;
299 	case RULE_PROTO_UDP:
300 		protocol = UDP_STRING;
301 		break;
302 	default:
303 		panic("rule_printf: unknown protocol (%d)\n",
304 		    rule->r_protocol);
305 	}
306 	sbuf_printf(sb, "%s:%jd:%s:%d", idtype, (intmax_t)rule->r_id,
307 	    protocol, rule->r_port);
308 }
309 
310 static char *
311 rules_to_string(void)
312 {
313 	struct rule *rule;
314 	struct sbuf *sb;
315 	int needcomma;
316 	char *temp;
317 
318 	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
319 	needcomma = 0;
320 	mtx_lock(&rule_mtx);
321 	for (rule = TAILQ_FIRST(&rule_head); rule != NULL;
322 	    rule = TAILQ_NEXT(rule, r_entries)) {
323 		if (!needcomma)
324 			needcomma = 1;
325 		else
326 			sbuf_printf(sb, ",");
327 		rule_printf(sb, rule);
328 	}
329 	mtx_unlock(&rule_mtx);
330 	sbuf_finish(sb);
331 	temp = strdup(sbuf_data(sb), M_PORTACL);
332 	sbuf_delete(sb);
333 	return (temp);
334 }
335 #endif
336 
337 /*
338  * Note: due to races, there is not a single serializable order
339  * between parallel calls to the sysctl.
340  */
341 static int
342 sysctl_rules(SYSCTL_HANDLER_ARGS)
343 {
344 	char *string, *copy_string, *new_string;
345 	struct rulehead head, save_head;
346 	int error;
347 
348 	new_string = NULL;
349 	if (req->newptr == NULL) {
350 		new_string = malloc(MAC_RULE_STRING_LEN, M_PORTACL,
351 		    M_WAITOK | M_ZERO);
352 		strcpy(new_string, rule_string);
353 		string = new_string;
354 	} else
355 		string = rule_string;
356 
357 	error = sysctl_handle_string(oidp, string, MAC_RULE_STRING_LEN, req);
358 	if (error)
359 		goto out;
360 
361 	if (req->newptr != NULL) {
362 		copy_string = strdup(string, M_PORTACL);
363 		TAILQ_INIT(&head);
364 		error = parse_rules(copy_string, &head);
365 		free(copy_string, M_PORTACL);
366 		if (error)
367 			goto out;
368 
369 		TAILQ_INIT(&save_head);
370 		mtx_lock(&rule_mtx);
371 		TAILQ_CONCAT(&save_head, &rule_head, r_entries);
372 		TAILQ_CONCAT(&rule_head, &head, r_entries);
373 		strcpy(rule_string, string);
374 		mtx_unlock(&rule_mtx);
375 		toast_rules(&save_head);
376 	}
377 out:
378 	if (new_string != NULL)
379 		free(new_string, M_PORTACL);
380 	return (error);
381 }
382 
383 SYSCTL_PROC(_security_mac_portacl, OID_AUTO, rules,
384        CTLTYPE_STRING|CTLFLAG_RW, 0, 0, sysctl_rules, "A", "Rules");
385 
386 static int
387 rules_check(struct ucred *cred, int family, int type, u_int16_t port)
388 {
389 	struct rule *rule;
390 	int error;
391 
392 #if 0
393 	printf("Check requested for euid %d, family %d, type %d, port %d\n",
394 	    cred->cr_uid, family, type, port);
395 #endif
396 
397 	if (port > mac_portacl_port_high)
398 		return (0);
399 
400 	error = EPERM;
401 	mtx_lock(&rule_mtx);
402 	for (rule = TAILQ_FIRST(&rule_head);
403 	    rule != NULL;
404 	    rule = TAILQ_NEXT(rule, r_entries)) {
405 		if (type == SOCK_DGRAM && rule->r_protocol != RULE_PROTO_UDP)
406 			continue;
407 		if (type == SOCK_STREAM && rule->r_protocol != RULE_PROTO_TCP)
408 			continue;
409 		if (port != rule->r_port)
410 			continue;
411 		if (rule->r_idtype == RULE_UID) {
412 			if (cred->cr_uid == rule->r_id) {
413 				error = 0;
414 				break;
415 			}
416 		} else if (rule->r_idtype == RULE_GID) {
417 			if (cred->cr_gid == rule->r_id) {
418 				error = 0;
419 				break;
420 			} else if (groupmember(rule->r_id, cred)) {
421 				error = 0;
422 				break;
423 			}
424 		} else
425 			panic("rules_check: unknown rule type %d",
426 			    rule->r_idtype);
427 	}
428 	mtx_unlock(&rule_mtx);
429 
430 	if (error != 0 && mac_portacl_suser_exempt != 0)
431 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
432 		    SUSER_ALLOWJAIL);
433 
434 	return (error);
435 }
436 
437 /*
438  * Note, this only limits the ability to explicitly bind a port, it
439  * doesn't limit implicitly bound ports for outgoing connections where
440  * the source port is left up to the IP stack to determine automatically.
441  */
442 static int
443 check_socket_bind(struct ucred *cred, struct socket *so,
444     struct label *socketlabel, struct sockaddr *sockaddr)
445 {
446 	struct sockaddr_in *sin;
447 	struct inpcb *inp;
448 	int family, type;
449 	u_int16_t port;
450 
451 	/* Only run if we are enabled. */
452 	if (mac_portacl_enabled == 0)
453 		return (0);
454 
455 	/* Only interested in IPv4 and IPv6 sockets. */
456 	if (so->so_proto->pr_domain->dom_family != PF_INET &&
457 	    so->so_proto->pr_domain->dom_family != PF_INET6)
458 		return (0);
459 
460 	/* Currently, we don't attempt to deal with SOCK_RAW, etc. */
461 	if (so->so_type != SOCK_DGRAM &&
462 	    so->so_type != SOCK_STREAM)
463 		return (0);
464 
465 	/* Reject addresses we don't understand; fail closed. */
466 	if (sockaddr->sa_family != AF_INET &&
467 	    sockaddr->sa_family != AF_INET6)
468 		return (EINVAL);
469 
470 	family = so->so_proto->pr_domain->dom_family;
471 	type = so->so_type;
472 	sin = (struct sockaddr_in *) sockaddr;
473 	port = ntohs(sin->sin_port);
474 
475 	/*
476 	 * Sockets are frequently bound with a specific IP address but a port
477 	 * number of '0' to request automatic port allocation.  This is often
478 	 * desirable as long as IP_PORTRANGELOW isn't set, which might permit
479 	 * automatic allocation of a "privileged" port.  The autoport exempt
480 	 * flag exempts port 0 allocation from rule checking as long as a low
481 	 * port isn't required.
482 	 */
483 	if (mac_portacl_autoport_exempt && port == 0) {
484 		inp = sotoinpcb(so);
485 		if ((inp->inp_flags & INP_LOWPORT) == 0)
486 			return (0);
487 	}
488 
489 	return (rules_check(cred, family, type, port));
490 }
491 
492 static struct mac_policy_ops mac_portacl_ops =
493 {
494 	.mpo_destroy = destroy,
495 	.mpo_init = init,
496 	.mpo_check_socket_bind = check_socket_bind,
497 };
498 
499 MAC_POLICY_SET(&mac_portacl_ops, trustedbsd_mac_portacl,
500     "TrustedBSD MAC/portacl", MPC_LOADTIME_FLAG_UNLOADOK, NULL);
501