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