xref: /linux/security/landlock/net.c (revision 415f2044228cc8b948dc04e079aaa86a4d1aa1d3)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Landlock - Network management and hooks
4  *
5  * Copyright © 2022-2023 Huawei Tech. Co., Ltd.
6  * Copyright © 2022-2025 Microsoft Corporation
7  */
8 
9 #include <linux/in.h>
10 #include <linux/lsm_audit.h>
11 #include <linux/net.h>
12 #include <linux/socket.h>
13 #include <net/ipv6.h>
14 
15 #include "common.h"
16 #include "cred.h"
17 #include "domain.h"
18 #include "limits.h"
19 #include "log.h"
20 #include "net.h"
21 #include "ruleset.h"
22 
23 #include <trace/events/landlock.h>
24 
landlock_append_net_rule(struct landlock_ruleset * const ruleset,const u16 port,access_mask_t access_rights,const u32 flags)25 int landlock_append_net_rule(struct landlock_ruleset *const ruleset,
26 			     const u16 port, access_mask_t access_rights,
27 			     const u32 flags)
28 {
29 	int err;
30 	const struct landlock_id id = {
31 		.key.data = (__force uintptr_t)htons(port),
32 		.type = LANDLOCK_KEY_NET_PORT,
33 	};
34 
35 	BUILD_BUG_ON(sizeof(port) > sizeof(id.key.data));
36 
37 	/* Transforms relative access rights to absolute ones. */
38 	access_rights |= LANDLOCK_MASK_ACCESS_NET & ~ruleset->handled_masks.net;
39 
40 	mutex_lock(&ruleset->lock);
41 	err = landlock_insert_rule(ruleset, id, access_rights, flags);
42 
43 	/*
44 	 * Emit after the rule insertion succeeds, so every event corresponds to
45 	 * a rule that is actually in the ruleset.  The ruleset lock is still
46 	 * held for BTF consistency (enforced by lockdep_assert_held in
47 	 * TP_fast_assign).
48 	 */
49 	if (!err)
50 		trace_landlock_add_rule_net_port(ruleset, flags, access_rights,
51 						 port);
52 	mutex_unlock(&ruleset->lock);
53 
54 	return err;
55 }
56 
unmask_layers_net(const struct landlock_domain * const domain,const struct landlock_id id,struct layer_masks * masks,access_mask_t access_request)57 static bool unmask_layers_net(const struct landlock_domain *const domain,
58 			      const struct landlock_id id,
59 			      struct layer_masks *masks,
60 			      access_mask_t access_request)
61 {
62 	const struct landlock_rule *rule = NULL;
63 	bool ret;
64 
65 	ret = landlock_unmask_layers(domain, id, masks, &rule);
66 	if (rule)
67 		trace_landlock_check_rule_net_port(
68 			domain, rule, access_request,
69 			ntohs((__force __be16)id.key.data));
70 	return ret;
71 }
72 
current_check_access_socket(struct socket * const sock,struct sockaddr * const address,const int addrlen,access_mask_t access_request,bool connecting)73 static int current_check_access_socket(struct socket *const sock,
74 				       struct sockaddr *const address,
75 				       const int addrlen,
76 				       access_mask_t access_request,
77 				       bool connecting)
78 {
79 	unsigned short sock_family;
80 	__be16 port;
81 	struct layer_masks layer_masks = {};
82 	struct landlock_id id = {
83 		.type = LANDLOCK_KEY_NET_PORT,
84 	};
85 	const struct access_masks masks = {
86 		.net = access_request,
87 	};
88 	const struct landlock_cred_security *const subject =
89 		landlock_get_applicable_subject(current_cred(), masks, NULL);
90 	struct lsm_network_audit audit_net = {};
91 
92 	if (!subject)
93 		return 0;
94 
95 	/* Checks for minimal header length to safely read sa_family. */
96 	if (addrlen < (int)offsetofend(typeof(*address), sa_family))
97 		return -EINVAL;
98 
99 	/*
100 	 * The socket is not locked, so sk_family can change concurrently due to
101 	 * e.g. setsockopt(IPV6_ADDRFORM).
102 	 */
103 	sock_family = READ_ONCE(sock->sk->sk_family);
104 
105 	switch (address->sa_family) {
106 	case AF_UNSPEC:
107 		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
108 		    (access_request == LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP &&
109 		     connecting)) {
110 			/*
111 			 * Connecting to an address with AF_UNSPEC dissolves the
112 			 * remote association while retaining the socket object
113 			 * (i.e., the file descriptor). For TCP, it has the same
114 			 * effect as closing the connection. For UDP, it removes
115 			 * any preset remote address. As for dropping
116 			 * privileges, these actions are always allowed.  Let
117 			 * the network stack handle potential inconsistencies
118 			 * and return -EINVAL if needed.
119 			 */
120 			return 0;
121 		} else if (access_request ==
122 			   LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP) {
123 			if (sock_family == AF_INET6) {
124 				/*
125 				 * We cannot allow sending UDP datagrams to an
126 				 * explicit AF_UNSPEC address on IPv6 sockets,
127 				 * even if AF_UNSPEC is treated as "no address"
128 				 * on such sockets (so it should always be
129 				 * allowed).  That's because the socket's family
130 				 * can change under our feet (if another thread
131 				 * calls setsockopt(IPV6_ADDRFORM)) to IPv4,
132 				 * which would then treat AF_UNSPEC as AF_INET.
133 				 */
134 				audit_net.family = AF_UNSPEC;
135 				audit_net.sk = sock->sk;
136 				landlock_init_layer_masks(
137 					subject->domain, access_request,
138 					&layer_masks, LANDLOCK_KEY_NET_PORT);
139 				landlock_log_denial(
140 					subject,
141 					&(struct landlock_request){
142 						.type = LANDLOCK_REQUEST_NET_ACCESS,
143 						.audit.type =
144 							LSM_AUDIT_DATA_NET,
145 						.audit.u.net = &audit_net,
146 						.access = access_request,
147 						.layer_masks = &layer_masks,
148 #ifdef CONFIG_TRACEPOINTS
149 						.trace_net =
150 							&(struct landlock_net_trace){
151 								.address =
152 									address,
153 								.addrlen =
154 									addrlen,
155 								.socket_family =
156 									sock_family,
157 							},
158 #endif /* CONFIG_TRACEPOINTS */
159 					});
160 				return -EACCES;
161 			}
162 		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
163 			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
164 			/*
165 			 * Binding to an AF_UNSPEC address is treated
166 			 * differently by IPv4 and IPv6 sockets. The socket's
167 			 * family may change under our feet due to
168 			 * setsockopt(IPV6_ADDRFORM), but that's ok: we either
169 			 * reject entirely for IPv6 or require
170 			 * %LANDLOCK_ACCESS_NET_BIND_TCP or
171 			 * %LANDLOCK_ACCESS_NET_BIND_UDP for IPv4, so it cannot
172 			 * be used to bypass the policy.
173 			 *
174 			 * IPv4 sockets map AF_UNSPEC to AF_INET for
175 			 * retrocompatibility for bind accesses, only if the
176 			 * address is INADDR_ANY (cf. __inet_bind). IPv6
177 			 * sockets always reject it.
178 			 *
179 			 * Checking the address is required to not wrongfully
180 			 * return -EACCES instead of -EAFNOSUPPORT or -EINVAL.
181 			 * We could return 0 and let the network stack handle
182 			 * these checks, but it is safer to return a proper
183 			 * error and test consistency thanks to kselftest.
184 			 */
185 			if (sock_family == AF_INET) {
186 				const struct sockaddr_in *const sockaddr =
187 					(struct sockaddr_in *)address;
188 
189 				if (addrlen < sizeof(struct sockaddr_in))
190 					return -EINVAL;
191 
192 				if (sockaddr->sin_addr.s_addr !=
193 				    htonl(INADDR_ANY))
194 					return -EAFNOSUPPORT;
195 			} else {
196 				if (addrlen < SIN6_LEN_RFC2133)
197 					return -EINVAL;
198 				else
199 					return -EAFNOSUPPORT;
200 			}
201 		} else {
202 			WARN_ON_ONCE(1);
203 		}
204 		/*
205 		 * AF_UNSPEC is treated as AF_INET only in
206 		 * bind(AF_UNSPEC+INADDR_ANY) on IPv4 sockets and when sending
207 		 * to AF_UNSPEC addresses on IPv4 sockets.
208 		 */
209 		fallthrough;
210 	case AF_INET: {
211 		const struct sockaddr_in *addr4;
212 
213 		if (addrlen < sizeof(struct sockaddr_in))
214 			return -EINVAL;
215 
216 		addr4 = (struct sockaddr_in *)address;
217 		port = addr4->sin_port;
218 
219 		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
220 		    access_request == LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP) {
221 			audit_net.dport = port;
222 			audit_net.v4info.daddr = addr4->sin_addr.s_addr;
223 		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
224 			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
225 			audit_net.sport = port;
226 			audit_net.v4info.saddr = addr4->sin_addr.s_addr;
227 		} else {
228 			WARN_ON_ONCE(1);
229 		}
230 		break;
231 	}
232 
233 #if IS_ENABLED(CONFIG_IPV6)
234 	case AF_INET6: {
235 		const struct sockaddr_in6 *addr6;
236 
237 		if (addrlen < SIN6_LEN_RFC2133)
238 			return -EINVAL;
239 
240 		addr6 = (struct sockaddr_in6 *)address;
241 		port = addr6->sin6_port;
242 
243 		if (access_request == LANDLOCK_ACCESS_NET_CONNECT_TCP ||
244 		    access_request == LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP) {
245 			audit_net.dport = port;
246 			audit_net.v6info.daddr = addr6->sin6_addr;
247 		} else if (access_request == LANDLOCK_ACCESS_NET_BIND_TCP ||
248 			   access_request == LANDLOCK_ACCESS_NET_BIND_UDP) {
249 			audit_net.sport = port;
250 			audit_net.v6info.saddr = addr6->sin6_addr;
251 		} else {
252 			WARN_ON_ONCE(1);
253 		}
254 		break;
255 	}
256 #endif /* IS_ENABLED(CONFIG_IPV6) */
257 
258 	default:
259 		return 0;
260 	}
261 
262 	/*
263 	 * Checks sa_family consistency to not wrongfully return
264 	 * -EACCES instead of -EINVAL.  Valid sa_family changes are
265 	 * only (from AF_INET or AF_INET6) to AF_UNSPEC.
266 	 *
267 	 * We could return 0 and let the network stack handle this
268 	 * check, but it is safer to return a proper error and test
269 	 * consistency thanks to kselftest.
270 	 */
271 	if (address->sa_family != sock_family &&
272 	    address->sa_family != AF_UNSPEC)
273 		return -EINVAL;
274 
275 	id.key.data = (__force uintptr_t)port;
276 	BUILD_BUG_ON(sizeof(port) > sizeof(id.key.data));
277 
278 	access_request = landlock_init_layer_masks(subject->domain,
279 						   access_request, &layer_masks,
280 						   LANDLOCK_KEY_NET_PORT);
281 	if (!access_request)
282 		return 0;
283 
284 	if (unmask_layers_net(subject->domain, id, &layer_masks,
285 			      access_request))
286 		return 0;
287 
288 	audit_net.family = address->sa_family;
289 	audit_net.sk = sock->sk;
290 	landlock_log_denial(
291 		subject, &(struct landlock_request){
292 				 .type = LANDLOCK_REQUEST_NET_ACCESS,
293 				 .audit.type = LSM_AUDIT_DATA_NET,
294 				 .audit.u.net = &audit_net,
295 				 .access = access_request,
296 				 .layer_masks = &layer_masks,
297 #ifdef CONFIG_TRACEPOINTS
298 				 .trace_net =
299 					 &(struct landlock_net_trace){
300 						 .address = address,
301 						 .addrlen = addrlen,
302 						 .socket_family = sock_family,
303 					 },
304 #endif /* CONFIG_TRACEPOINTS */
305 			 });
306 	return -EACCES;
307 }
308 
current_check_autobind_udp_socket(struct socket * const sock)309 static int current_check_autobind_udp_socket(struct socket *const sock)
310 {
311 	const struct access_masks bind_udp = {
312 		.net = LANDLOCK_ACCESS_NET_BIND_UDP,
313 	};
314 	struct sockaddr_storage port0 = {};
315 	unsigned short num;
316 	bool slow;
317 
318 	/* Quick return for non-Landlocked tasks. */
319 	if (!landlock_get_applicable_subject(current_cred(), bind_udp, NULL))
320 		return 0;
321 
322 	/*
323 	 * On UDP sockets, if a local port has not already been bound, calling
324 	 * connect() or sending a first datagram has the side effect of
325 	 * autobinding an ephemeral port: we also have to check that the process
326 	 * would have had the right to bind(0) explicitly.  Hold the socket lock
327 	 * around the inet_num read to exclude udp_lib_get_port()'s transient
328 	 * inet_num = snum write that is reverted to 0 on a failing reuseport
329 	 * bind.
330 	 */
331 	slow = lock_sock_fast(sock->sk);
332 	num = inet_sk(sock->sk)->inet_num;
333 	unlock_sock_fast(sock->sk, slow);
334 	if (num != 0)
335 		return 0;
336 
337 	/*
338 	 * Construct a struct sockaddr* with port 0 to pretend the process tried
339 	 * to bind() on that address.
340 	 */
341 	port0.ss_family = READ_ONCE(sock->sk->sk_family);
342 
343 	return current_check_access_socket(sock, (struct sockaddr *)&port0,
344 					   sizeof(port0), bind_udp.net, false);
345 }
346 
hook_socket_bind(struct socket * const sock,struct sockaddr * const address,const int addrlen)347 static int hook_socket_bind(struct socket *const sock,
348 			    struct sockaddr *const address, const int addrlen)
349 {
350 	access_mask_t access_request;
351 
352 	if (sk_is_tcp(sock->sk))
353 		access_request = LANDLOCK_ACCESS_NET_BIND_TCP;
354 	else if (sk_is_udp(sock->sk))
355 		access_request = LANDLOCK_ACCESS_NET_BIND_UDP;
356 	else
357 		return 0;
358 
359 	return current_check_access_socket(sock, address, addrlen,
360 					   access_request, false);
361 }
362 
hook_socket_connect(struct socket * const sock,struct sockaddr * const address,const int addrlen)363 static int hook_socket_connect(struct socket *const sock,
364 			       struct sockaddr *const address,
365 			       const int addrlen)
366 {
367 	access_mask_t access_request;
368 	int ret = 0;
369 
370 	if (sk_is_tcp(sock->sk))
371 		access_request = LANDLOCK_ACCESS_NET_CONNECT_TCP;
372 	else if (sk_is_udp(sock->sk))
373 		access_request = LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP;
374 	else
375 		return 0;
376 
377 	ret = current_check_access_socket(sock, address, addrlen,
378 					  access_request, true);
379 
380 	/*
381 	 * connect()ing to an AF_UNSPEC address does not trigger an autobind and
382 	 * should never be restricted.
383 	 */
384 	if (ret == 0 && sk_is_udp(sock->sk) &&
385 	    addrlen >= offsetofend(typeof(*address), sa_family) &&
386 	    address->sa_family != AF_UNSPEC)
387 		ret = current_check_autobind_udp_socket(sock);
388 
389 	return ret;
390 }
391 
hook_socket_sendmsg(struct socket * const sock,struct msghdr * const msg,const int size)392 static int hook_socket_sendmsg(struct socket *const sock,
393 			       struct msghdr *const msg, const int size)
394 {
395 	struct sockaddr *const address = msg->msg_name;
396 	const int addrlen = msg->msg_namelen;
397 	access_mask_t access_request;
398 	int ret = 0;
399 
400 	if ((msg->msg_flags & MSG_FASTOPEN) && address && sk_is_tcp(sock->sk)) {
401 		ret = current_check_access_socket(
402 			sock, address, addrlen, LANDLOCK_ACCESS_NET_CONNECT_TCP,
403 			true);
404 		if (ret != 0)
405 			return ret;
406 	}
407 
408 	if (sk_is_udp(sock->sk))
409 		access_request = LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP;
410 	else
411 		return 0;
412 
413 	if (address != NULL)
414 		ret = current_check_access_socket(sock, address, addrlen,
415 						  access_request, false);
416 
417 	if (ret == 0)
418 		ret = current_check_autobind_udp_socket(sock);
419 
420 	return ret;
421 }
422 
423 static struct security_hook_list landlock_hooks[] __ro_after_init = {
424 	LSM_HOOK_INIT(socket_bind, hook_socket_bind),
425 	LSM_HOOK_INIT(socket_connect, hook_socket_connect),
426 	LSM_HOOK_INIT(socket_sendmsg, hook_socket_sendmsg),
427 };
428 
landlock_add_net_hooks(void)429 __init void landlock_add_net_hooks(void)
430 {
431 	security_add_hooks(landlock_hooks, ARRAY_SIZE(landlock_hooks),
432 			   &landlock_lsmid);
433 }
434