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