xref: /linux/drivers/net/ovpn/udp.c (revision fbc988f236a60cf50a89da78fc6b7213daa9999c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*  OpenVPN data channel offload
3  *
4  *  Copyright (C) 2019-2025 OpenVPN, Inc.
5  *
6  *  Author:	Antonio Quartulli <antonio@openvpn.net>
7  */
8 
9 #include <linux/netdevice.h>
10 #include <linux/inetdevice.h>
11 #include <linux/skbuff.h>
12 #include <linux/socket.h>
13 #include <linux/udp.h>
14 #include <net/addrconf.h>
15 #include <net/dst_cache.h>
16 #include <net/route.h>
17 #include <net/transp_v6.h>
18 #include <net/udp.h>
19 #include <net/udp_tunnel.h>
20 
21 #include "ovpnpriv.h"
22 #include "main.h"
23 #include "bind.h"
24 #include "io.h"
25 #include "peer.h"
26 #include "proto.h"
27 #include "socket.h"
28 #include "udp.h"
29 
30 /* Retrieve the corresponding ovpn object from a UDP socket
31  * rcu_read_lock must be held on entry
32  */
33 static struct ovpn_socket *ovpn_socket_from_udp_sock(struct sock *sk)
34 {
35 	struct ovpn_socket *ovpn_sock;
36 
37 	if (unlikely(READ_ONCE(udp_sk(sk)->encap_type) != UDP_ENCAP_OVPNINUDP))
38 		return NULL;
39 
40 	ovpn_sock = rcu_dereference_sk_user_data(sk);
41 	if (unlikely(!ovpn_sock))
42 		return NULL;
43 
44 	/* make sure that sk matches our stored transport socket */
45 	if (unlikely(!ovpn_sock->sk || sk != ovpn_sock->sk))
46 		return NULL;
47 
48 	return ovpn_sock;
49 }
50 
51 /**
52  * ovpn_udp_encap_recv - Start processing a received UDP packet.
53  * @sk: socket over which the packet was received
54  * @skb: the received packet
55  *
56  * If the first byte of the payload is:
57  * - DATA_V2 the packet is accepted for further processing,
58  * - DATA_V1 the packet is dropped as not supported,
59  * - anything else the packet is forwarded to the UDP stack for
60  *   delivery to user space.
61  *
62  * Return:
63  *  0 if skb was consumed or dropped
64  * >0 if skb should be passed up to userspace as UDP (packet not consumed)
65  * <0 if skb should be resubmitted as proto -N (packet not consumed)
66  */
67 static int ovpn_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
68 {
69 	struct ovpn_socket *ovpn_sock;
70 	struct ovpn_priv *ovpn;
71 	struct ovpn_peer *peer;
72 	u32 peer_id;
73 	u8 opcode;
74 
75 	ovpn_sock = ovpn_socket_from_udp_sock(sk);
76 	if (unlikely(!ovpn_sock)) {
77 		net_err_ratelimited("ovpn: %s invoked on non ovpn socket\n",
78 				    __func__);
79 		goto drop_noovpn;
80 	}
81 
82 	ovpn = ovpn_sock->ovpn;
83 	if (unlikely(!ovpn)) {
84 		net_err_ratelimited("ovpn: cannot obtain ovpn object from UDP socket\n");
85 		goto drop_noovpn;
86 	}
87 
88 	/* Make sure the first 4 bytes of the skb data buffer after the UDP
89 	 * header are accessible.
90 	 * They are required to fetch the OP code, the key ID and the peer ID.
91 	 */
92 	if (unlikely(!pskb_may_pull(skb, sizeof(struct udphdr) +
93 				    OVPN_OPCODE_SIZE))) {
94 		net_dbg_ratelimited("%s: packet too small from UDP socket\n",
95 				    netdev_name(ovpn->dev));
96 		goto drop;
97 	}
98 
99 	opcode = ovpn_opcode_from_skb(skb, sizeof(struct udphdr));
100 	if (unlikely(opcode != OVPN_DATA_V2)) {
101 		/* DATA_V1 is not supported */
102 		if (opcode == OVPN_DATA_V1)
103 			goto drop;
104 
105 		/* unknown or control packet: let it bubble up to userspace */
106 		return 1;
107 	}
108 
109 	peer_id = ovpn_peer_id_from_skb(skb, sizeof(struct udphdr));
110 	/* some OpenVPN server implementations send data packets with the
111 	 * peer-id set to UNDEF. In this case we skip the peer lookup by peer-id
112 	 * and we try with the transport address
113 	 */
114 	if (peer_id == OVPN_PEER_ID_UNDEF)
115 		peer = ovpn_peer_get_by_transp_addr(ovpn, skb);
116 	else
117 		peer = ovpn_peer_get_by_id(ovpn, peer_id);
118 
119 	if (unlikely(!peer))
120 		goto drop;
121 
122 	/* pop off outer UDP header */
123 	__skb_pull(skb, sizeof(struct udphdr));
124 	ovpn_recv(peer, skb);
125 	return 0;
126 
127 drop:
128 	ovpn_dev_dstats_rx_dropped(ovpn->dev);
129 drop_noovpn:
130 	kfree_skb(skb);
131 	return 0;
132 }
133 
134 static bool ovpn_route_key_equal(const struct ovpn_route_key *a,
135 				 const struct ovpn_route_key *b)
136 {
137 	return a->mark == b->mark && a->sport == b->sport;
138 }
139 
140 /**
141  * ovpn_dst_cache_check_key - reset peer dst cache after key changes
142  * @peer: the peer owning the dst cache
143  * @cache: the cache that might need to be reset
144  * @key: the route key for the packet being transmitted
145  *
146  * Reset the peer dst cache if it was populated for a different route key.
147  */
148 static void ovpn_dst_cache_check_key(struct ovpn_peer *peer,
149 				     struct dst_cache *cache,
150 				     const struct ovpn_route_key *key)
151 {
152 	struct ovpn_route_key old_key;
153 	unsigned int seq;
154 
155 	/* snapshot the saved key before deciding whether the cache matches */
156 	do {
157 		seq = read_seqcount_begin(&peer->route_key_seq);
158 		old_key = peer->route_key;
159 	} while (read_seqcount_retry(&peer->route_key_seq, seq));
160 
161 	/* nothing changed: the current cache can be reused */
162 	if (likely(ovpn_route_key_equal(&old_key, key)))
163 		return;
164 
165 	/* recheck under lock because another path may have updated the key */
166 	spin_lock_bh(&peer->lock);
167 	if (!ovpn_route_key_equal(&peer->route_key, key)) {
168 		write_seqcount_begin(&peer->route_key_seq);
169 		peer->route_key = *key;
170 		dst_cache_reset(cache);
171 		write_seqcount_end(&peer->route_key_seq);
172 	}
173 	spin_unlock_bh(&peer->lock);
174 }
175 
176 /**
177  * ovpn_dst_cache_current - check whether a route lookup matches peer state
178  * @peer: the peer owning the bind and dst cache
179  * @bind: the RCU bind used for the route lookup
180  * @key: the route key used for the route lookup
181  *
182  * Check that @bind is still the current peer bind and that @key still matches
183  * the peer route key. The caller must hold @peer->lock. The TX path keeps
184  * @bind inside an RCU read-side critical section, so pointer identity is enough
185  * to detect whether the bind was replaced while the route lookup was running.
186  *
187  * Return: true if the lookup result still matches the current peer state and
188  * may update the dst cache or replace the bind.
189  */
190 static bool ovpn_dst_cache_current(const struct ovpn_peer *peer,
191 				   const struct ovpn_bind *bind,
192 				   const struct ovpn_route_key *key)
193 {
194 	const struct ovpn_bind *curr_bind;
195 
196 	lockdep_assert_held(&peer->lock);
197 
198 	curr_bind = rcu_dereference_protected(peer->bind,
199 					      lockdep_is_held(&peer->lock));
200 
201 	return curr_bind == bind &&
202 	       ovpn_route_key_equal(key, &peer->route_key);
203 }
204 
205 /**
206  * ovpn_udp4_output - send IPv4 packet over udp socket
207  * @peer: the destination peer
208  * @bind: the binding related to the destination peer
209  * @cache: dst cache
210  * @sk: the socket to send the packet over
211  * @skb: the packet to send
212  * @key: the route key snapshot used for cache validation and flow lookup
213  *
214  * Return: 0 on success or a negative error code otherwise
215  */
216 static int ovpn_udp4_output(struct ovpn_peer *peer, struct ovpn_bind *bind,
217 			    struct dst_cache *cache, struct sock *sk,
218 			    struct sk_buff *skb,
219 			    const struct ovpn_route_key *key)
220 {
221 	struct sockaddr_storage remote;
222 	struct in_addr local = {};
223 	bool reset_local = false;
224 	struct rtable *rt;
225 	struct flowi4 fl = {
226 		.saddr = bind->local.ipv4.s_addr,
227 		.daddr = bind->remote.in4.sin_addr.s_addr,
228 		.fl4_sport = key->sport,
229 		.fl4_dport = bind->remote.in4.sin_port,
230 		.flowi4_proto = sk->sk_protocol,
231 		.flowi4_mark = key->mark,
232 	};
233 	int ret;
234 
235 	local_bh_disable();
236 	rt = dst_cache_get_ip4(cache, &fl.saddr);
237 	if (rt)
238 		goto transmit;
239 
240 	if (fl.saddr && unlikely(!inet_confirm_addr(sock_net(sk), NULL, 0,
241 						    fl.saddr, RT_SCOPE_HOST))) {
242 		/* The learned local address is not usable anymore.
243 		 * Retry with source address autoselection.
244 		 */
245 		fl.saddr = 0;
246 		reset_local = true;
247 	}
248 
249 	rt = ip_route_output_flow(sock_net(sk), &fl, sk);
250 	if (IS_ERR(rt) && PTR_ERR(rt) == -EINVAL) {
251 		fl.saddr = 0;
252 		reset_local = true;
253 
254 		rt = ip_route_output_flow(sock_net(sk), &fl, sk);
255 	}
256 
257 	if (IS_ERR(rt)) {
258 		ret = PTR_ERR(rt);
259 		net_dbg_ratelimited("%s: no route to host %pISpc: %d\n",
260 				    netdev_name(peer->ovpn->dev),
261 				    &bind->remote.in4,
262 				    ret);
263 		goto err;
264 	}
265 
266 	/* avoid storing a stale cache or local address */
267 	spin_lock_bh(&peer->lock);
268 	if (likely(ovpn_dst_cache_current(peer, bind, key))) {
269 		if (!reset_local) {
270 			dst_cache_set_ip4(cache, &rt->dst, fl.saddr);
271 			spin_unlock_bh(&peer->lock);
272 			goto transmit;
273 		}
274 
275 		/* invalidate per-CPU dst entries that may still carry
276 		 * the stale source
277 		 */
278 		dst_cache_reset(cache);
279 
280 		/* preserve the current remote */
281 		memcpy(&remote, &bind->remote, sizeof(struct sockaddr_in));
282 		/* The current packet already has a valid wildcard-source route.
283 		 * If replacing the bind fails, leave the stale local in place;
284 		 * a later cache miss will retry the repair.
285 		 */
286 		ovpn_peer_reset_sockaddr(peer, &remote, &local);
287 	}
288 	spin_unlock_bh(&peer->lock);
289 
290 transmit:
291 	udp_tunnel_xmit_skb(rt, sk, skb, fl.saddr, fl.daddr, 0,
292 			    ip4_dst_hoplimit(&rt->dst), 0, fl.fl4_sport,
293 			    fl.fl4_dport, false, sk->sk_no_check_tx, 0);
294 	ret = 0;
295 err:
296 	local_bh_enable();
297 	return ret;
298 }
299 
300 #if IS_ENABLED(CONFIG_IPV6)
301 /**
302  * ovpn_udp6_output - send IPv6 packet over udp socket
303  * @peer: the destination peer
304  * @bind: the binding related to the destination peer
305  * @cache: dst cache
306  * @sk: the socket to send the packet over
307  * @skb: the packet to send
308  * @key: the route key snapshot used for cache validation and flow lookup
309  *
310  * Return: 0 on success or a negative error code otherwise
311  */
312 static int ovpn_udp6_output(struct ovpn_peer *peer, struct ovpn_bind *bind,
313 			    struct dst_cache *cache, struct sock *sk,
314 			    struct sk_buff *skb,
315 			    const struct ovpn_route_key *key)
316 {
317 	struct in6_addr local = in6addr_any;
318 	struct sockaddr_storage remote;
319 	bool reset_local = false;
320 	struct dst_entry *dst;
321 	int ret;
322 
323 	struct flowi6 fl = {
324 		.saddr = bind->local.ipv6,
325 		.daddr = bind->remote.in6.sin6_addr,
326 		.fl6_sport = key->sport,
327 		.fl6_dport = bind->remote.in6.sin6_port,
328 		.flowi6_proto = sk->sk_protocol,
329 		.flowi6_mark = key->mark,
330 		.flowi6_oif = bind->remote.in6.sin6_scope_id,
331 	};
332 
333 	local_bh_disable();
334 	dst = dst_cache_get_ip6(cache, &fl.saddr);
335 	if (dst)
336 		goto transmit;
337 
338 	if (!ipv6_addr_any(&fl.saddr) &&
339 	    unlikely(!ipv6_chk_addr(sock_net(sk), &fl.saddr, NULL, 0))) {
340 		/* The learned local address is not usable anymore.
341 		 * Retry with source address autoselection.
342 		 */
343 		fl.saddr = in6addr_any;
344 		reset_local = true;
345 	}
346 
347 	dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl, NULL);
348 	if (IS_ERR(dst)) {
349 		ret = PTR_ERR(dst);
350 		net_dbg_ratelimited("%s: no route to host %pISpc: %d\n",
351 				    netdev_name(peer->ovpn->dev),
352 				    &bind->remote.in6, ret);
353 		goto err;
354 	}
355 
356 	/* avoid storing a stale cache or local address */
357 	spin_lock_bh(&peer->lock);
358 	if (likely(ovpn_dst_cache_current(peer, bind, key))) {
359 		if (!reset_local) {
360 			dst_cache_set_ip6(cache, dst, &fl.saddr);
361 			spin_unlock_bh(&peer->lock);
362 			goto transmit;
363 		}
364 
365 		/* invalidate per-CPU dst entries that may still carry
366 		 * the stale source
367 		 */
368 		dst_cache_reset(cache);
369 
370 		/* preserve the current remote */
371 		memcpy(&remote, &bind->remote, sizeof(struct sockaddr_in6));
372 		/* The current packet already has a valid wildcard-source route.
373 		 * If replacing the bind fails, leave the stale local in place;
374 		 * a later cache miss will retry the repair.
375 		 */
376 		ovpn_peer_reset_sockaddr(peer, &remote, &local);
377 	}
378 	spin_unlock_bh(&peer->lock);
379 
380 transmit:
381 	/* user IPv6 packets may be larger than the transport interface
382 	 * MTU (after encapsulation), however, since they are locally
383 	 * generated we should ensure they get fragmented.
384 	 * Setting the ignore_df flag to 1 will instruct ip6_fragment() to
385 	 * fragment packets if needed.
386 	 *
387 	 * NOTE: this is not needed for IPv4 because we pass df=0 to
388 	 * udp_tunnel_xmit_skb()
389 	 */
390 	skb->ignore_df = 1;
391 	udp_tunnel6_xmit_skb(dst, sk, skb, skb->dev, &fl.saddr, &fl.daddr, 0,
392 			     ip6_dst_hoplimit(dst), 0, fl.fl6_sport,
393 			     fl.fl6_dport, udp_get_no_check6_tx(sk), 0);
394 	ret = 0;
395 err:
396 	local_bh_enable();
397 	return ret;
398 }
399 #endif
400 
401 /**
402  * ovpn_udp_output - transmit skb using udp-tunnel
403  * @peer: the destination peer
404  * @cache: dst cache
405  * @sk: the socket to send the packet over
406  * @skb: the packet to send
407  * @key: route key snapshot used for cache validation and flow lookup
408  *
409  * rcu_read_lock should be held on entry.
410  * On return, the skb is consumed.
411  *
412  * Return: 0 on success or a negative error code otherwise
413  */
414 static int ovpn_udp_output(struct ovpn_peer *peer, struct dst_cache *cache,
415 			   struct sock *sk, struct sk_buff *skb,
416 			   struct ovpn_route_key *key)
417 {
418 	struct ovpn_bind *bind;
419 	int ret;
420 
421 	/* set sk to null if skb is already orphaned */
422 	if (!skb->destructor)
423 		skb->sk = NULL;
424 
425 	rcu_read_lock();
426 	bind = rcu_dereference(peer->bind);
427 	if (unlikely(!bind)) {
428 		net_warn_ratelimited("%s: no bind for remote peer %u\n",
429 				     netdev_name(peer->ovpn->dev), peer->id);
430 		ret = -ENODEV;
431 		goto out;
432 	}
433 
434 	switch (bind->remote.in4.sin_family) {
435 	case AF_INET:
436 		ret = ovpn_udp4_output(peer, bind, cache, sk, skb, key);
437 		break;
438 #if IS_ENABLED(CONFIG_IPV6)
439 	case AF_INET6:
440 		ret = ovpn_udp6_output(peer, bind, cache, sk, skb, key);
441 		break;
442 #endif
443 	default:
444 		ret = -EAFNOSUPPORT;
445 		break;
446 	}
447 
448 out:
449 	rcu_read_unlock();
450 	return ret;
451 }
452 
453 /**
454  * ovpn_udp_send_skb - prepare skb and send it over via UDP
455  * @peer: the destination peer
456  * @sk: peer socket
457  * @skb: the packet to send
458  */
459 void ovpn_udp_send_skb(struct ovpn_peer *peer, struct sock *sk,
460 		       struct sk_buff *skb)
461 {
462 	struct ovpn_route_key key = {
463 		.mark = READ_ONCE(sk->sk_mark),
464 		.sport = READ_ONCE(inet_sk(sk)->inet_sport),
465 	};
466 	int ret;
467 
468 	skb->dev = peer->ovpn->dev;
469 	skb->mark = key.mark;
470 	/* no checksum performed at this layer */
471 	skb->ip_summed = CHECKSUM_NONE;
472 
473 	ovpn_dst_cache_check_key(peer, &peer->dst_cache, &key);
474 
475 	/* crypto layer -> transport (UDP) */
476 	ret = ovpn_udp_output(peer, &peer->dst_cache, sk, skb, &key);
477 	if (unlikely(ret < 0))
478 		kfree_skb(skb);
479 }
480 
481 static void ovpn_udp_encap_destroy(struct sock *sk)
482 {
483 	struct ovpn_socket *sock;
484 	struct ovpn_priv *ovpn;
485 
486 	rcu_read_lock();
487 	sock = rcu_dereference_sk_user_data(sk);
488 	if (!sock || !sock->ovpn) {
489 		rcu_read_unlock();
490 		return;
491 	}
492 	ovpn = sock->ovpn;
493 	rcu_read_unlock();
494 
495 	ovpn_peers_free(ovpn, sk, OVPN_DEL_PEER_REASON_TRANSPORT_DISCONNECT);
496 }
497 
498 /**
499  * ovpn_udp_socket_attach - set udp-tunnel CBs on socket and link it to ovpn
500  * @ovpn_sock: socket to configure
501  * @sock: the socket container to be passed to setup_udp_tunnel_sock()
502  * @ovpn: the openvp instance to link
503  *
504  * After invoking this function, the sock will be controlled by ovpn so that
505  * any incoming packet may be processed by ovpn first.
506  *
507  * Return: 0 on success or a negative error code otherwise
508  */
509 int ovpn_udp_socket_attach(struct ovpn_socket *ovpn_sock, struct socket *sock,
510 			   struct ovpn_priv *ovpn)
511 {
512 	struct udp_tunnel_sock_cfg cfg = {
513 		.sk_user_data = ovpn_sock,
514 		.encap_type = UDP_ENCAP_OVPNINUDP,
515 		.encap_rcv = ovpn_udp_encap_recv,
516 		.encap_destroy = ovpn_udp_encap_destroy,
517 	};
518 	struct ovpn_socket *old_data;
519 	int ret;
520 
521 	/* make sure no pre-existing encapsulation handler exists */
522 	rcu_read_lock();
523 	old_data = rcu_dereference_sk_user_data(ovpn_sock->sk);
524 	if (!old_data) {
525 		/* socket is currently unused - we can take it */
526 		rcu_read_unlock();
527 		setup_udp_tunnel_sock(sock_net(ovpn_sock->sk), sock->sk, &cfg);
528 		return 0;
529 	}
530 
531 	/* socket is in use. We need to understand if it's owned by this ovpn
532 	 * instance or by something else.
533 	 * In the former case, we can increase the refcounter and happily
534 	 * use it, because the same UDP socket is expected to be shared among
535 	 * different peers.
536 	 *
537 	 * Unlikely TCP, a single UDP socket can be used to talk to many remote
538 	 * hosts and therefore openvpn instantiates one only for all its peers
539 	 */
540 	if ((READ_ONCE(udp_sk(ovpn_sock->sk)->encap_type) == UDP_ENCAP_OVPNINUDP) &&
541 	    old_data->ovpn == ovpn) {
542 		netdev_dbg(ovpn->dev,
543 			   "provided socket already owned by this interface\n");
544 		ret = -EALREADY;
545 	} else {
546 		netdev_dbg(ovpn->dev,
547 			   "provided socket already taken by other user\n");
548 		ret = -EBUSY;
549 	}
550 	rcu_read_unlock();
551 
552 	return ret;
553 }
554 
555 /**
556  * ovpn_udp_socket_detach - clean udp-tunnel status for this socket
557  * @ovpn_sock: the socket to clean
558  */
559 void ovpn_udp_socket_detach(struct ovpn_socket *ovpn_sock)
560 {
561 	struct sock *sk = ovpn_sock->sk;
562 
563 	/* Re-enable multicast loopback */
564 	inet_set_bit(MC_LOOP, sk);
565 	/* Disable CHECKSUM_UNNECESSARY to CHECKSUM_COMPLETE conversion */
566 	inet_dec_convert_csum(sk);
567 
568 	WRITE_ONCE(udp_sk(sk)->encap_type, 0);
569 	WRITE_ONCE(udp_sk(sk)->encap_rcv, NULL);
570 	WRITE_ONCE(udp_sk(sk)->encap_destroy, NULL);
571 
572 	rcu_assign_sk_user_data(sk, NULL);
573 }
574