xref: /freebsd/sys/security/mac_portacl/mac_portacl.c (revision bfe691b2f75de2224c7ceb304ebcdef2b42d4179)
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/param.h>
59 #include <sys/domain.h>
60 #include <sys/kernel.h>
61 #include <sys/lock.h>
62 #include <sys/malloc.h>
63 #include <sys/module.h>
64 #include <sys/mutex.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/protosw.h>
68 #include <sys/queue.h>
69 #include <sys/systm.h>
70 #include <sys/sbuf.h>
71 #include <sys/socket.h>
72 #include <sys/socketvar.h>
73 #include <sys/sysctl.h>
74 
75 #include <netinet/in.h>
76 #include <netinet/in_pcb.h>
77 
78 #include <security/mac/mac_policy.h>
79 
80 SYSCTL_DECL(_security_mac);
81 
82 SYSCTL_NODE(_security_mac, OID_AUTO, portacl, CTLFLAG_RW, 0,
83     "TrustedBSD mac_portacl policy controls");
84 
85 static int	mac_portacl_enabled = 1;
86 SYSCTL_INT(_security_mac_portacl, OID_AUTO, enabled, CTLFLAG_RW,
87     &mac_portacl_enabled, 0, "Enforce portacl policy");
88 TUNABLE_INT("security.mac.portacl.enabled", &mac_portacl_enabled);
89 
90 static int	mac_portacl_suser_exempt = 1;
91 SYSCTL_INT(_security_mac_portacl, OID_AUTO, suser_exempt, CTLFLAG_RW,
92     &mac_portacl_suser_exempt, 0, "Privilege permits binding of any port");
93 TUNABLE_INT("security.mac.portacl.suser_exempt",
94     &mac_portacl_suser_exempt);
95 
96 static int	mac_portacl_autoport_exempt = 1;
97 SYSCTL_INT(_security_mac_portacl, OID_AUTO, autoport_exempt, CTLFLAG_RW,
98     &mac_portacl_autoport_exempt, 0, "Allow automatic allocation through "
99     "binding port 0 if not IP_PORTRANGELOW");
100 TUNABLE_INT("security.mac.portacl.autoport_exempt",
101     &mac_portacl_autoport_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, "mac_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 mtx			rule_mtx;
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 	mtx_destroy(&rule_mtx);
161 	toast_rules(&rule_head);
162 }
163 
164 static void
165 init(struct mac_policy_conf *mpc)
166 {
167 
168 	mtx_init(&rule_mtx, "rule_mtx", NULL, MTX_DEF);
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 /*
264  * rule_printf() and rules_to_string() are unused currently because they rely
265  * on sbufs with auto-extension, which may sleep while holding a mutex.
266  * Instead, the non-canonical user-generated rule string is returned to the
267  * user when the rules are queried, which is faster anyway.
268  */
269 #if 0
270 static void
271 rule_printf(struct sbuf *sb, struct rule *rule)
272 {
273 	const char *idtype, *protocol;
274 
275 	switch(rule->r_idtype) {
276 	case RULE_GID:
277 		idtype = GID_STRING;
278 		break;
279 	case RULE_UID:
280 		idtype = UID_STRING;
281 		break;
282 	default:
283 		panic("rule_printf: unknown idtype (%d)\n", rule->r_idtype);
284 	}
285 
286 	switch (rule->r_protocol) {
287 	case RULE_PROTO_TCP:
288 		protocol = TCP_STRING;
289 		break;
290 	case RULE_PROTO_UDP:
291 		protocol = UDP_STRING;
292 		break;
293 	default:
294 		panic("rule_printf: unknown protocol (%d)\n",
295 		    rule->r_protocol);
296 	}
297 	sbuf_printf(sb, "%s:%jd:%s:%d", idtype, (intmax_t)rule->r_id,
298 	    protocol, rule->r_port);
299 }
300 
301 static char *
302 rules_to_string(void)
303 {
304 	struct rule *rule;
305 	struct sbuf *sb;
306 	int needcomma;
307 	char *temp;
308 
309 	sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
310 	needcomma = 0;
311 	mtx_lock(&rule_mtx);
312 	for (rule = TAILQ_FIRST(&rule_head); rule != NULL;
313 	    rule = TAILQ_NEXT(rule, r_entries)) {
314 		if (!needcomma)
315 			needcomma = 1;
316 		else
317 			sbuf_printf(sb, ",");
318 		rule_printf(sb, rule);
319 	}
320 	mtx_unlock(&rule_mtx);
321 	sbuf_finish(sb);
322 	temp = strdup(sbuf_data(sb), M_PORTACL);
323 	sbuf_delete(sb);
324 	return (temp);
325 }
326 #endif
327 
328 /*
329  * Note: due to races, there is not a single serializable order
330  * between parallel calls to the sysctl.
331  */
332 static int
333 sysctl_rules(SYSCTL_HANDLER_ARGS)
334 {
335 	char *string, *copy_string, *new_string;
336 	struct rulehead head, save_head;
337 	int error;
338 
339 	new_string = NULL;
340 	if (req->newptr == NULL) {
341 		new_string = malloc(MAC_RULE_STRING_LEN, M_PORTACL,
342 		    M_WAITOK | M_ZERO);
343 		strcpy(new_string, rule_string);
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 > mac_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 && mac_portacl_suser_exempt != 0)
422 		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
423 		    SUSER_ALLOWJAIL);
424 
425 	return (error);
426 }
427 
428 /*
429  * Note, this only limits the ability to explicitly bind a port, it
430  * doesn't limit implicitly bound ports for outgoing connections where
431  * the source port is left up to the IP stack to determine automatically.
432  */
433 static int
434 check_socket_bind(struct ucred *cred, struct socket *so,
435     struct label *socketlabel, struct sockaddr *sockaddr)
436 {
437 	struct sockaddr_in *sin;
438 	struct inpcb *inp;
439 	int family, type;
440 	u_int16_t port;
441 
442 	/* Only run if we are enabled. */
443 	if (mac_portacl_enabled == 0)
444 		return (0);
445 
446 	/* Only interested in IPv4 and IPv6 sockets. */
447 	if (so->so_proto->pr_domain->dom_family != PF_INET &&
448 	    so->so_proto->pr_domain->dom_family != PF_INET6)
449 		return (0);
450 
451 	/* Currently, we don't attempt to deal with SOCK_RAW, etc. */
452 	if (so->so_type != SOCK_DGRAM &&
453 	    so->so_type != SOCK_STREAM)
454 		return (0);
455 
456 	/* Reject addresses we don't understand; fail closed. */
457 	if (sockaddr->sa_family != AF_INET &&
458 	    sockaddr->sa_family != AF_INET6)
459 		return (EINVAL);
460 
461 	family = so->so_proto->pr_domain->dom_family;
462 	type = so->so_type;
463 	sin = (struct sockaddr_in *) sockaddr;
464 	port = ntohs(sin->sin_port);
465 
466 	/*
467 	 * Sockets are frequently bound with a specific IP address but a port
468 	 * number of '0' to request automatic port allocation.  This is often
469 	 * desirable as long as IP_PORTRANGELOW isn't set, which might permit
470 	 * automatic allocation of a "privileged" port.  The autoport exempt
471 	 * flag exempts port 0 allocation from rule checking as long as a low
472 	 * port isn't required.
473 	 */
474 	if (mac_portacl_autoport_exempt && port == 0) {
475 		inp = sotoinpcb(so);
476 		if ((inp->inp_flags & INP_LOWPORT) == 0)
477 			return (0);
478 	}
479 
480 	return (rules_check(cred, family, type, port));
481 }
482 
483 static struct mac_policy_ops mac_portacl_ops =
484 {
485 	.mpo_destroy = destroy,
486 	.mpo_init = init,
487 	.mpo_check_socket_bind = check_socket_bind,
488 };
489 
490 MAC_POLICY_SET(&mac_portacl_ops, trustedbsd_mac_portacl,
491     "TrustedBSD MAC/portacl", MPC_LOADTIME_FLAG_UNLOADOK, NULL);
492