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