xref: /linux/net/psp/psp_main.c (revision fb3ddbe2b5774f97a428bfb26711d68b966fcd0a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include <linux/bitfield.h>
4 #include <linux/list.h>
5 #include <linux/netdevice.h>
6 #include <linux/xarray.h>
7 #include <net/net_namespace.h>
8 #include <net/psp.h>
9 #include <net/udp.h>
10 
11 #include "psp.h"
12 #include "psp-nl-gen.h"
13 
14 DEFINE_XARRAY_ALLOC1(psp_devs);
15 struct mutex psp_devs_lock;
16 
17 /**
18  * DOC: PSP locking
19  *
20  * psp_devs_lock protects the psp_devs xarray.
21  * Ordering is take the psp_devs_lock and then the instance lock.
22  * Each instance is protected by RCU, and has a refcount.
23  * When driver unregisters the instance gets flushed, but struct sticks around.
24  */
25 
26 /**
27  * psp_dev_check_access() - check if user in a given net ns can access PSP dev
28  * @psd:	PSP device structure user is trying to access
29  * @net:	net namespace user is in
30  * @admin:	If true, only allow access from @psd's main device's netns,
31  *		for admin operations like config changes and key rotation.
32  *		If false, also allow access from network namespaces that have
33  *		an associated device with @psd, for read-only and association
34  *		management operations.
35  *
36  * Return: 0 if PSP device should be visible in @net, errno otherwise.
37  */
38 int psp_dev_check_access(struct psp_dev *psd, struct net *net, bool admin)
39 {
40 	if (dev_net(psd->main_netdev) == net)
41 		return 0;
42 
43 	if (!admin && psp_has_assoc_dev_in_ns(psd, net))
44 		return 0;
45 
46 	return -ENOENT;
47 }
48 
49 /**
50  * psp_dev_create() - create and register PSP device
51  * @netdev:	main netdevice
52  * @psd_ops:	driver callbacks
53  * @psd_caps:	device capabilities
54  * @priv_ptr:	back-pointer to driver private data
55  *
56  * Return: pointer to allocated PSP device, or ERR_PTR.
57  */
58 struct psp_dev *
59 psp_dev_create(struct net_device *netdev,
60 	       struct psp_dev_ops *psd_ops, struct psp_dev_caps *psd_caps,
61 	       void *priv_ptr)
62 {
63 	struct psp_dev *psd;
64 	static u32 last_id;
65 	int err;
66 
67 	if (WARN_ON(!psd_caps->versions ||
68 		    !psd_ops->set_config ||
69 		    !psd_ops->key_rotate ||
70 		    !psd_ops->rx_spi_alloc ||
71 		    !psd_ops->get_stats ||
72 		    (!psd_ops->tx_key_add != !psd_ops->tx_key_del) ||
73 		    (psd_caps->assoc_drv_spc && !psd_ops->tx_key_add)))
74 		return ERR_PTR(-EINVAL);
75 
76 	psd = kzalloc_obj(*psd);
77 	if (!psd)
78 		return ERR_PTR(-ENOMEM);
79 
80 	psd->main_netdev = netdev;
81 	INIT_LIST_HEAD(&psd->assoc_dev_list);
82 	psd->ops = psd_ops;
83 	psd->caps = psd_caps;
84 	psd->drv_priv = priv_ptr;
85 
86 	mutex_init(&psd->lock);
87 	INIT_LIST_HEAD(&psd->active_assocs);
88 	INIT_LIST_HEAD(&psd->prev_assocs);
89 	INIT_LIST_HEAD(&psd->stale_assocs);
90 	refcount_set(&psd->refcnt, 1);
91 
92 	mutex_lock(&psp_devs_lock);
93 	err = xa_alloc_cyclic(&psp_devs, &psd->id, psd, xa_limit_16b,
94 			      &last_id, GFP_KERNEL);
95 	if (err) {
96 		mutex_unlock(&psp_devs_lock);
97 		kfree(psd);
98 		return ERR_PTR(err);
99 	}
100 	mutex_lock(&psd->lock);
101 	mutex_unlock(&psp_devs_lock);
102 
103 	/* notify before netdev assignment
104 	 * There's no strong reason for it, but thinking is to avoid creating
105 	 * implicit expectations about the PSP dev <> netdev relationship.
106 	 */
107 	psp_nl_notify_dev(psd, PSP_CMD_DEV_ADD_NTF);
108 
109 	rcu_assign_pointer(netdev->psp_dev, psd);
110 
111 	mutex_unlock(&psd->lock);
112 
113 	return psd;
114 }
115 EXPORT_SYMBOL(psp_dev_create);
116 
117 void psp_dev_free(struct psp_dev *psd)
118 {
119 	mutex_lock(&psp_devs_lock);
120 	xa_erase(&psp_devs, psd->id);
121 	mutex_unlock(&psp_devs_lock);
122 
123 	mutex_destroy(&psd->lock);
124 	kfree_rcu(psd, rcu);
125 }
126 
127 /**
128  * psp_dev_unregister() - unregister PSP device
129  * @psd:	PSP device structure
130  */
131 void psp_dev_unregister(struct psp_dev *psd)
132 {
133 	struct psp_assoc_dev *entry, *entry_tmp;
134 	struct psp_assoc *pas, *next;
135 
136 	mutex_lock(&psp_devs_lock);
137 	mutex_lock(&psd->lock);
138 
139 	psp_nl_notify_dev(psd, PSP_CMD_DEV_DEL_NTF);
140 
141 	/* Wait until psp_dev_free() to call xa_erase() to prevent a
142 	 * different psd from being added to the xarray with this id, while
143 	 * there are still references to this psd being held.
144 	 */
145 	xa_store(&psp_devs, psd->id, NULL, GFP_KERNEL);
146 	mutex_unlock(&psp_devs_lock);
147 
148 	list_splice_init(&psd->active_assocs, &psd->prev_assocs);
149 	list_splice_init(&psd->prev_assocs, &psd->stale_assocs);
150 	list_for_each_entry_safe(pas, next, &psd->stale_assocs, assocs_list) {
151 		if (psp_assoc_needs_tx_key_del(pas))
152 			psp_dev_tx_key_del(psd, pas);
153 		list_del(&pas->assocs_list);
154 	}
155 
156 	list_for_each_entry_safe(entry, entry_tmp, &psd->assoc_dev_list,
157 				 dev_list) {
158 		list_del(&entry->dev_list);
159 		rcu_assign_pointer(entry->assoc_dev->psp_dev, NULL);
160 		netdev_put(entry->assoc_dev, &entry->dev_tracker);
161 		kfree(entry);
162 	}
163 	psd->assoc_dev_cnt = 0;
164 
165 	rcu_assign_pointer(psd->main_netdev->psp_dev, NULL);
166 
167 	psd->ops = NULL;
168 	psd->drv_priv = NULL;
169 
170 	mutex_unlock(&psd->lock);
171 
172 	psp_dev_put(psd);
173 }
174 EXPORT_SYMBOL(psp_dev_unregister);
175 
176 unsigned int psp_key_size(u32 version)
177 {
178 	switch (version) {
179 	case PSP_VERSION_HDR0_AES_GCM_128:
180 	case PSP_VERSION_HDR0_AES_GMAC_128:
181 		return 16;
182 	case PSP_VERSION_HDR0_AES_GCM_256:
183 	case PSP_VERSION_HDR0_AES_GMAC_256:
184 		return 32;
185 	default:
186 		return 0;
187 	}
188 }
189 EXPORT_SYMBOL(psp_key_size);
190 
191 static void psp_write_headers(struct net *net, struct sk_buff *skb, __be32 spi,
192 			      u8 ver, unsigned int udp_len, __be16 sport)
193 {
194 	struct udphdr *uh = udp_hdr(skb);
195 	struct psphdr *psph = (struct psphdr *)(uh + 1);
196 	const struct sock *sk = skb->sk;
197 
198 	uh->dest = htons(PSP_DEFAULT_UDP_PORT);
199 
200 	/* A bit of theory: Selection of the source port.
201 	 *
202 	 * We need some entropy, so that multiple flows use different
203 	 * source ports for better RSS spreading at the receiver.
204 	 *
205 	 * We also need that all packets belonging to one TCP flow
206 	 * use the same source port through their duration,
207 	 * so that all these packets land in the same receive queue.
208 	 *
209 	 * udp_flow_src_port() is using sk_txhash, inherited from
210 	 * skb_set_hash_from_sk() call in __tcp_transmit_skb().
211 	 * This field is subject to reshuffling, thanks to
212 	 * sk_rethink_txhash() calls in various TCP functions.
213 	 *
214 	 * Instead, use sk->sk_hash which is constant through
215 	 * the whole flow duration.
216 	 */
217 	if (likely(sk)) {
218 		u32 hash = sk->sk_hash;
219 		int min, max;
220 
221 		/* These operations are cheap, no need to cache the result
222 		 * in another socket field.
223 		 */
224 		inet_get_local_port_range(net, &min, &max);
225 		/* Since this is being sent on the wire obfuscate hash a bit
226 		 * to minimize possibility that any useful information to an
227 		 * attacker is leaked. Only upper 16 bits are relevant in the
228 		 * computation for 16 bit port value because we use a
229 		 * reciprocal divide.
230 		 */
231 		hash ^= hash << 16;
232 		uh->source = htons(reciprocal_scale(hash, max - min + 1) + min);
233 	} else {
234 		uh->source = udp_flow_src_port(net, skb, 0, 0, false);
235 	}
236 	uh->check = 0;
237 	udp_set_len(uh, udp_len);
238 
239 	psph->nexthdr = IPPROTO_TCP;
240 	psph->hdrlen = PSP_HDRLEN_NOOPT;
241 	psph->crypt_offset = 0;
242 	psph->verfl = FIELD_PREP(PSPHDR_VERFL_VERSION, ver) |
243 		      FIELD_PREP(PSPHDR_VERFL_ONE, 1);
244 	psph->spi = spi;
245 	memset(&psph->iv, 0, sizeof(psph->iv));
246 }
247 
248 /* Encapsulate a TCP packet with PSP by adding the UDP+PSP headers and filling
249  * them in.
250  */
251 bool psp_dev_encapsulate(struct net *net, struct sk_buff *skb, __be32 spi,
252 			 u8 ver, __be16 sport)
253 {
254 	u32 network_len = skb_network_header_len(skb);
255 	u32 ethr_len = skb_mac_header_len(skb);
256 	u32 bufflen = ethr_len + network_len;
257 
258 	if (skb->protocol != htons(ETH_P_IP) &&
259 	    skb->protocol != htons(ETH_P_IPV6))
260 		return false;
261 
262 	if (skb_cow_head(skb, PSP_ENCAP_HLEN))
263 		return false;
264 
265 	skb_push(skb, PSP_ENCAP_HLEN);
266 	skb->mac_header		-= PSP_ENCAP_HLEN;
267 	skb->network_header	-= PSP_ENCAP_HLEN;
268 	skb->transport_header	-= PSP_ENCAP_HLEN;
269 	memmove(skb->data, skb->data + PSP_ENCAP_HLEN, bufflen);
270 
271 	if (skb->protocol == htons(ETH_P_IP)) {
272 		ip_hdr(skb)->protocol = IPPROTO_UDP;
273 		be16_add_cpu(&ip_hdr(skb)->tot_len, PSP_ENCAP_HLEN);
274 		ip_hdr(skb)->check = 0;
275 		ip_hdr(skb)->check =
276 			ip_fast_csum((u8 *)ip_hdr(skb), ip_hdr(skb)->ihl);
277 	} else {
278 		ipv6_hdr(skb)->nexthdr = IPPROTO_UDP;
279 		be16_add_cpu(&ipv6_hdr(skb)->payload_len, PSP_ENCAP_HLEN);
280 	}
281 
282 	skb_set_inner_ipproto(skb, IPPROTO_TCP);
283 	skb_set_inner_transport_header(skb, skb_transport_offset(skb) +
284 						    PSP_ENCAP_HLEN);
285 	skb->encapsulation = 1;
286 	psp_write_headers(net, skb, spi, ver,
287 			  skb->len - skb_transport_offset(skb), sport);
288 
289 	return true;
290 }
291 EXPORT_SYMBOL(psp_dev_encapsulate);
292 
293 /* Receive handler for PSP packets.
294  *
295  * Accepts only already-authenticated packets. The full PSP header is
296  * stripped according to psph->hdrlen; any optional fields it advertises
297  * (virtualization cookies, etc.) are ignored and discarded along with the
298  * rest of the header. The caller should ensure that skb->data is pointing
299  * to the mac header, and that skb->mac_len is set. This function does not
300  * currently adjust skb->csum (CHECKSUM_COMPLETE is not supported).
301  */
302 int psp_dev_rcv(struct sk_buff *skb, u16 dev_id, u8 generation, bool strip_icv)
303 {
304 	int l2_hlen = 0, l3_hlen, encap, psp_hlen;
305 	struct psp_skb_ext *pse;
306 	struct psphdr *psph;
307 	struct ethhdr *eth;
308 	struct udphdr *uh;
309 	__be16 proto;
310 	bool is_udp;
311 
312 	eth = (struct ethhdr *)skb->data;
313 	proto = __vlan_get_protocol(skb, eth->h_proto, &l2_hlen);
314 	if (proto == htons(ETH_P_IP))
315 		l3_hlen = sizeof(struct iphdr);
316 	else if (proto == htons(ETH_P_IPV6))
317 		l3_hlen = sizeof(struct ipv6hdr);
318 	else
319 		return -EINVAL;
320 
321 	if (unlikely(!pskb_may_pull(skb, l2_hlen + l3_hlen + PSP_ENCAP_HLEN)))
322 		return -EINVAL;
323 
324 	if (proto == htons(ETH_P_IP)) {
325 		struct iphdr *iph = (struct iphdr *)(skb->data + l2_hlen);
326 
327 		if (unlikely(iph->ihl < 5))
328 			return -EINVAL;
329 
330 		is_udp = iph->protocol == IPPROTO_UDP;
331 		l3_hlen = iph->ihl * 4;
332 		if (l3_hlen != sizeof(struct iphdr) &&
333 		    !pskb_may_pull(skb, l2_hlen + l3_hlen + PSP_ENCAP_HLEN))
334 			return -EINVAL;
335 	} else {
336 		struct ipv6hdr *ipv6h = (struct ipv6hdr *)(skb->data + l2_hlen);
337 
338 		is_udp = ipv6h->nexthdr == IPPROTO_UDP;
339 	}
340 
341 	if (unlikely(!is_udp))
342 		return -EINVAL;
343 
344 	uh = (struct udphdr *)(skb->data + l2_hlen + l3_hlen);
345 	if (unlikely(uh->dest != htons(PSP_DEFAULT_UDP_PORT)))
346 		return -EINVAL;
347 
348 	psph = (struct psphdr *)(skb->data + l2_hlen + l3_hlen +
349 				 sizeof(struct udphdr));
350 
351 	/* Strip the full PSP header per psph->hdrlen; VC/options are pulled
352 	 * into the linear region only so they can be discarded with the
353 	 * rest of the header.
354 	 */
355 	psp_hlen = (psph->hdrlen + 1) * 8;
356 
357 	if (unlikely(psp_hlen < sizeof(struct psphdr)))
358 		return -EINVAL;
359 
360 	if (psp_hlen > sizeof(struct psphdr) &&
361 	    !pskb_may_pull(skb, l2_hlen + l3_hlen +
362 				sizeof(struct udphdr) + psp_hlen))
363 		return -EINVAL;
364 
365 	psph = (struct psphdr *)(skb->data + l2_hlen + l3_hlen +
366 				 sizeof(struct udphdr));
367 
368 	pse = skb_ext_add(skb, SKB_EXT_PSP);
369 	if (!pse)
370 		return -EINVAL;
371 
372 	pse->spi = psph->spi;
373 	pse->dev_id = dev_id;
374 	pse->generation = generation;
375 	pse->version = FIELD_GET(PSPHDR_VERFL_VERSION, psph->verfl);
376 
377 	encap = sizeof(struct udphdr) + psp_hlen;
378 	encap += strip_icv ? PSP_TRL_SIZE : 0;
379 
380 	if (proto == htons(ETH_P_IP)) {
381 		struct iphdr *iph = (struct iphdr *)(skb->data + l2_hlen);
382 
383 		if (unlikely(ntohs(iph->tot_len) < l3_hlen + encap))
384 			return -EINVAL;
385 
386 		iph->protocol = psph->nexthdr;
387 		iph->tot_len = htons(ntohs(iph->tot_len) - encap);
388 		iph->check = 0;
389 		iph->check = ip_fast_csum((u8 *)iph, iph->ihl);
390 	} else {
391 		struct ipv6hdr *ipv6h = (struct ipv6hdr *)(skb->data + l2_hlen);
392 
393 		if (unlikely(ntohs(ipv6h->payload_len) < encap))
394 			return -EINVAL;
395 
396 		ipv6h->nexthdr = psph->nexthdr;
397 		ipv6h->payload_len = htons(ntohs(ipv6h->payload_len) - encap);
398 	}
399 
400 	memmove(skb->data + sizeof(struct udphdr) + psp_hlen,
401 		skb->data, l2_hlen + l3_hlen);
402 	skb_pull(skb, sizeof(struct udphdr) + psp_hlen);
403 
404 	if (strip_icv)
405 		pskb_trim(skb, skb->len - PSP_TRL_SIZE);
406 
407 	return 0;
408 }
409 EXPORT_SYMBOL(psp_dev_rcv);
410 
411 static bool psp_dev_disassoc_one(struct psp_dev *psd, struct net_device *dev)
412 {
413 	struct psp_assoc_dev *entry;
414 
415 	list_for_each_entry(entry, &psd->assoc_dev_list, dev_list) {
416 		if (entry->assoc_dev == dev) {
417 			list_del(&entry->dev_list);
418 			psd->assoc_dev_cnt--;
419 			rcu_assign_pointer(entry->assoc_dev->psp_dev, NULL);
420 			netdev_put(entry->assoc_dev, &entry->dev_tracker);
421 			kfree(entry);
422 			return true;
423 		}
424 	}
425 
426 	return false;
427 }
428 
429 static int psp_netdev_event(struct notifier_block *nb, unsigned long event,
430 			    void *ptr)
431 {
432 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
433 	struct psp_dev *psd;
434 
435 	if (event != NETDEV_UNREGISTER)
436 		return NOTIFY_DONE;
437 
438 	rcu_read_lock();
439 	psd = rcu_dereference(dev->psp_dev);
440 	if (psd && psp_dev_tryget(psd)) {
441 		rcu_read_unlock();
442 		mutex_lock(&psd->lock);
443 		/* Nothing to report if the device was never on the list,
444 		 * dev-assoc may have failed after publishing dev->psp_dev,
445 		 * and this is also the main netdevice's path.
446 		 */
447 		if (psp_dev_disassoc_one(psd, dev) &&
448 		    psp_dev_is_registered(psd))
449 			psp_nl_notify_disassoc(psd, dev_net(dev));
450 		mutex_unlock(&psd->lock);
451 		psp_dev_put(psd);
452 	} else {
453 		rcu_read_unlock();
454 	}
455 
456 	return NOTIFY_DONE;
457 }
458 
459 static struct notifier_block psp_netdev_notifier = {
460 	.notifier_call = psp_netdev_event,
461 };
462 
463 static DEFINE_MUTEX(psp_notifier_lock);
464 static bool psp_notifier_registered;
465 
466 /* Register the netdevice notifier when the first device association
467  * is created. In many installations no associations will be created and
468  * the notifier won't be needed.
469  *
470  * Must be called without psd->lock held, due to lock ordering:
471  * rtnl_lock -> psd->lock (the notifier callback runs under rtnl_lock
472  * and takes psd->lock).
473  */
474 int psp_attach_netdev_notifier(void)
475 {
476 	int err = 0;
477 
478 	if (READ_ONCE(psp_notifier_registered))
479 		return 0;
480 
481 	mutex_lock(&psp_notifier_lock);
482 	if (!psp_notifier_registered) {
483 		err = register_netdevice_notifier(&psp_netdev_notifier);
484 		if (!err)
485 			WRITE_ONCE(psp_notifier_registered, true);
486 	}
487 	mutex_unlock(&psp_notifier_lock);
488 
489 	return err;
490 }
491 
492 static int __init psp_init(void)
493 {
494 	mutex_init(&psp_devs_lock);
495 
496 	return genl_register_family(&psp_nl_family);
497 }
498 
499 subsys_initcall(psp_init);
500