xref: /openbmc/linux/net/l2tp/l2tp_core.c (revision aa5b395b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * L2TP core.
4  *
5  * Copyright (c) 2008,2009,2010 Katalix Systems Ltd
6  *
7  * This file contains some code of the original L2TPv2 pppol2tp
8  * driver, which has the following copyright:
9  *
10  * Authors:	Martijn van Oosterhout <kleptog@svana.org>
11  *		James Chapman (jchapman@katalix.com)
12  * Contributors:
13  *		Michal Ostrowski <mostrows@speakeasy.net>
14  *		Arnaldo Carvalho de Melo <acme@xconectiva.com.br>
15  *		David S. Miller (davem@redhat.com)
16  */
17 
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 
20 #include <linux/module.h>
21 #include <linux/string.h>
22 #include <linux/list.h>
23 #include <linux/rculist.h>
24 #include <linux/uaccess.h>
25 
26 #include <linux/kernel.h>
27 #include <linux/spinlock.h>
28 #include <linux/kthread.h>
29 #include <linux/sched.h>
30 #include <linux/slab.h>
31 #include <linux/errno.h>
32 #include <linux/jiffies.h>
33 
34 #include <linux/netdevice.h>
35 #include <linux/net.h>
36 #include <linux/inetdevice.h>
37 #include <linux/skbuff.h>
38 #include <linux/init.h>
39 #include <linux/in.h>
40 #include <linux/ip.h>
41 #include <linux/udp.h>
42 #include <linux/l2tp.h>
43 #include <linux/hash.h>
44 #include <linux/sort.h>
45 #include <linux/file.h>
46 #include <linux/nsproxy.h>
47 #include <net/net_namespace.h>
48 #include <net/netns/generic.h>
49 #include <net/dst.h>
50 #include <net/ip.h>
51 #include <net/udp.h>
52 #include <net/udp_tunnel.h>
53 #include <net/inet_common.h>
54 #include <net/xfrm.h>
55 #include <net/protocol.h>
56 #include <net/inet6_connection_sock.h>
57 #include <net/inet_ecn.h>
58 #include <net/ip6_route.h>
59 #include <net/ip6_checksum.h>
60 
61 #include <asm/byteorder.h>
62 #include <linux/atomic.h>
63 
64 #include "l2tp_core.h"
65 
66 #define L2TP_DRV_VERSION	"V2.0"
67 
68 /* L2TP header constants */
69 #define L2TP_HDRFLAG_T	   0x8000
70 #define L2TP_HDRFLAG_L	   0x4000
71 #define L2TP_HDRFLAG_S	   0x0800
72 #define L2TP_HDRFLAG_O	   0x0200
73 #define L2TP_HDRFLAG_P	   0x0100
74 
75 #define L2TP_HDR_VER_MASK  0x000F
76 #define L2TP_HDR_VER_2	   0x0002
77 #define L2TP_HDR_VER_3	   0x0003
78 
79 /* L2TPv3 default L2-specific sublayer */
80 #define L2TP_SLFLAG_S	   0x40000000
81 #define L2TP_SL_SEQ_MASK   0x00ffffff
82 
83 #define L2TP_HDR_SIZE_MAX		14
84 
85 /* Default trace flags */
86 #define L2TP_DEFAULT_DEBUG_FLAGS	0
87 
88 /* Private data stored for received packets in the skb.
89  */
90 struct l2tp_skb_cb {
91 	u32			ns;
92 	u16			has_seq;
93 	u16			length;
94 	unsigned long		expires;
95 };
96 
97 #define L2TP_SKB_CB(skb)	((struct l2tp_skb_cb *) &skb->cb[sizeof(struct inet_skb_parm)])
98 
99 static struct workqueue_struct *l2tp_wq;
100 
101 /* per-net private data for this module */
102 static unsigned int l2tp_net_id;
103 struct l2tp_net {
104 	struct list_head l2tp_tunnel_list;
105 	spinlock_t l2tp_tunnel_list_lock;
106 	struct hlist_head l2tp_session_hlist[L2TP_HASH_SIZE_2];
107 	spinlock_t l2tp_session_hlist_lock;
108 };
109 
110 #if IS_ENABLED(CONFIG_IPV6)
111 static bool l2tp_sk_is_v6(struct sock *sk)
112 {
113 	return sk->sk_family == PF_INET6 &&
114 	       !ipv6_addr_v4mapped(&sk->sk_v6_daddr);
115 }
116 #endif
117 
118 static inline struct l2tp_tunnel *l2tp_tunnel(struct sock *sk)
119 {
120 	return sk->sk_user_data;
121 }
122 
123 static inline struct l2tp_net *l2tp_pernet(const struct net *net)
124 {
125 	return net_generic(net, l2tp_net_id);
126 }
127 
128 /* Session hash global list for L2TPv3.
129  * The session_id SHOULD be random according to RFC3931, but several
130  * L2TP implementations use incrementing session_ids.  So we do a real
131  * hash on the session_id, rather than a simple bitmask.
132  */
133 static inline struct hlist_head *
134 l2tp_session_id_hash_2(struct l2tp_net *pn, u32 session_id)
135 {
136 	return &pn->l2tp_session_hlist[hash_32(session_id, L2TP_HASH_BITS_2)];
137 
138 }
139 
140 /* Session hash list.
141  * The session_id SHOULD be random according to RFC2661, but several
142  * L2TP implementations (Cisco and Microsoft) use incrementing
143  * session_ids.  So we do a real hash on the session_id, rather than a
144  * simple bitmask.
145  */
146 static inline struct hlist_head *
147 l2tp_session_id_hash(struct l2tp_tunnel *tunnel, u32 session_id)
148 {
149 	return &tunnel->session_hlist[hash_32(session_id, L2TP_HASH_BITS)];
150 }
151 
152 void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
153 {
154 	sock_put(tunnel->sock);
155 	/* the tunnel is freed in the socket destructor */
156 }
157 EXPORT_SYMBOL(l2tp_tunnel_free);
158 
159 /* Lookup a tunnel. A new reference is held on the returned tunnel. */
160 struct l2tp_tunnel *l2tp_tunnel_get(const struct net *net, u32 tunnel_id)
161 {
162 	const struct l2tp_net *pn = l2tp_pernet(net);
163 	struct l2tp_tunnel *tunnel;
164 
165 	rcu_read_lock_bh();
166 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
167 		if (tunnel->tunnel_id == tunnel_id &&
168 		    refcount_inc_not_zero(&tunnel->ref_count)) {
169 			rcu_read_unlock_bh();
170 
171 			return tunnel;
172 		}
173 	}
174 	rcu_read_unlock_bh();
175 
176 	return NULL;
177 }
178 EXPORT_SYMBOL_GPL(l2tp_tunnel_get);
179 
180 struct l2tp_tunnel *l2tp_tunnel_get_nth(const struct net *net, int nth)
181 {
182 	const struct l2tp_net *pn = l2tp_pernet(net);
183 	struct l2tp_tunnel *tunnel;
184 	int count = 0;
185 
186 	rcu_read_lock_bh();
187 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
188 		if (++count > nth &&
189 		    refcount_inc_not_zero(&tunnel->ref_count)) {
190 			rcu_read_unlock_bh();
191 			return tunnel;
192 		}
193 	}
194 	rcu_read_unlock_bh();
195 
196 	return NULL;
197 }
198 EXPORT_SYMBOL_GPL(l2tp_tunnel_get_nth);
199 
200 struct l2tp_session *l2tp_tunnel_get_session(struct l2tp_tunnel *tunnel,
201 					     u32 session_id)
202 {
203 	struct hlist_head *session_list;
204 	struct l2tp_session *session;
205 
206 	session_list = l2tp_session_id_hash(tunnel, session_id);
207 
208 	read_lock_bh(&tunnel->hlist_lock);
209 	hlist_for_each_entry(session, session_list, hlist)
210 		if (session->session_id == session_id) {
211 			l2tp_session_inc_refcount(session);
212 			read_unlock_bh(&tunnel->hlist_lock);
213 
214 			return session;
215 		}
216 	read_unlock_bh(&tunnel->hlist_lock);
217 
218 	return NULL;
219 }
220 EXPORT_SYMBOL_GPL(l2tp_tunnel_get_session);
221 
222 struct l2tp_session *l2tp_session_get(const struct net *net, u32 session_id)
223 {
224 	struct hlist_head *session_list;
225 	struct l2tp_session *session;
226 
227 	session_list = l2tp_session_id_hash_2(l2tp_pernet(net), session_id);
228 
229 	rcu_read_lock_bh();
230 	hlist_for_each_entry_rcu(session, session_list, global_hlist)
231 		if (session->session_id == session_id) {
232 			l2tp_session_inc_refcount(session);
233 			rcu_read_unlock_bh();
234 
235 			return session;
236 		}
237 	rcu_read_unlock_bh();
238 
239 	return NULL;
240 }
241 EXPORT_SYMBOL_GPL(l2tp_session_get);
242 
243 struct l2tp_session *l2tp_session_get_nth(struct l2tp_tunnel *tunnel, int nth)
244 {
245 	int hash;
246 	struct l2tp_session *session;
247 	int count = 0;
248 
249 	read_lock_bh(&tunnel->hlist_lock);
250 	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
251 		hlist_for_each_entry(session, &tunnel->session_hlist[hash], hlist) {
252 			if (++count > nth) {
253 				l2tp_session_inc_refcount(session);
254 				read_unlock_bh(&tunnel->hlist_lock);
255 				return session;
256 			}
257 		}
258 	}
259 
260 	read_unlock_bh(&tunnel->hlist_lock);
261 
262 	return NULL;
263 }
264 EXPORT_SYMBOL_GPL(l2tp_session_get_nth);
265 
266 /* Lookup a session by interface name.
267  * This is very inefficient but is only used by management interfaces.
268  */
269 struct l2tp_session *l2tp_session_get_by_ifname(const struct net *net,
270 						const char *ifname)
271 {
272 	struct l2tp_net *pn = l2tp_pernet(net);
273 	int hash;
274 	struct l2tp_session *session;
275 
276 	rcu_read_lock_bh();
277 	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++) {
278 		hlist_for_each_entry_rcu(session, &pn->l2tp_session_hlist[hash], global_hlist) {
279 			if (!strcmp(session->ifname, ifname)) {
280 				l2tp_session_inc_refcount(session);
281 				rcu_read_unlock_bh();
282 
283 				return session;
284 			}
285 		}
286 	}
287 
288 	rcu_read_unlock_bh();
289 
290 	return NULL;
291 }
292 EXPORT_SYMBOL_GPL(l2tp_session_get_by_ifname);
293 
294 int l2tp_session_register(struct l2tp_session *session,
295 			  struct l2tp_tunnel *tunnel)
296 {
297 	struct l2tp_session *session_walk;
298 	struct hlist_head *g_head;
299 	struct hlist_head *head;
300 	struct l2tp_net *pn;
301 	int err;
302 
303 	head = l2tp_session_id_hash(tunnel, session->session_id);
304 
305 	write_lock_bh(&tunnel->hlist_lock);
306 	if (!tunnel->acpt_newsess) {
307 		err = -ENODEV;
308 		goto err_tlock;
309 	}
310 
311 	hlist_for_each_entry(session_walk, head, hlist)
312 		if (session_walk->session_id == session->session_id) {
313 			err = -EEXIST;
314 			goto err_tlock;
315 		}
316 
317 	if (tunnel->version == L2TP_HDR_VER_3) {
318 		pn = l2tp_pernet(tunnel->l2tp_net);
319 		g_head = l2tp_session_id_hash_2(pn, session->session_id);
320 
321 		spin_lock_bh(&pn->l2tp_session_hlist_lock);
322 
323 		hlist_for_each_entry(session_walk, g_head, global_hlist)
324 			if (session_walk->session_id == session->session_id) {
325 				err = -EEXIST;
326 				goto err_tlock_pnlock;
327 			}
328 
329 		l2tp_tunnel_inc_refcount(tunnel);
330 		hlist_add_head_rcu(&session->global_hlist, g_head);
331 
332 		spin_unlock_bh(&pn->l2tp_session_hlist_lock);
333 	} else {
334 		l2tp_tunnel_inc_refcount(tunnel);
335 	}
336 
337 	hlist_add_head(&session->hlist, head);
338 	write_unlock_bh(&tunnel->hlist_lock);
339 
340 	return 0;
341 
342 err_tlock_pnlock:
343 	spin_unlock_bh(&pn->l2tp_session_hlist_lock);
344 err_tlock:
345 	write_unlock_bh(&tunnel->hlist_lock);
346 
347 	return err;
348 }
349 EXPORT_SYMBOL_GPL(l2tp_session_register);
350 
351 /*****************************************************************************
352  * Receive data handling
353  *****************************************************************************/
354 
355 /* Queue a skb in order. We come here only if the skb has an L2TP sequence
356  * number.
357  */
358 static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
359 {
360 	struct sk_buff *skbp;
361 	struct sk_buff *tmp;
362 	u32 ns = L2TP_SKB_CB(skb)->ns;
363 
364 	spin_lock_bh(&session->reorder_q.lock);
365 	skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
366 		if (L2TP_SKB_CB(skbp)->ns > ns) {
367 			__skb_queue_before(&session->reorder_q, skbp, skb);
368 			l2tp_dbg(session, L2TP_MSG_SEQ,
369 				 "%s: pkt %hu, inserted before %hu, reorder_q len=%d\n",
370 				 session->name, ns, L2TP_SKB_CB(skbp)->ns,
371 				 skb_queue_len(&session->reorder_q));
372 			atomic_long_inc(&session->stats.rx_oos_packets);
373 			goto out;
374 		}
375 	}
376 
377 	__skb_queue_tail(&session->reorder_q, skb);
378 
379 out:
380 	spin_unlock_bh(&session->reorder_q.lock);
381 }
382 
383 /* Dequeue a single skb.
384  */
385 static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
386 {
387 	struct l2tp_tunnel *tunnel = session->tunnel;
388 	int length = L2TP_SKB_CB(skb)->length;
389 
390 	/* We're about to requeue the skb, so return resources
391 	 * to its current owner (a socket receive buffer).
392 	 */
393 	skb_orphan(skb);
394 
395 	atomic_long_inc(&tunnel->stats.rx_packets);
396 	atomic_long_add(length, &tunnel->stats.rx_bytes);
397 	atomic_long_inc(&session->stats.rx_packets);
398 	atomic_long_add(length, &session->stats.rx_bytes);
399 
400 	if (L2TP_SKB_CB(skb)->has_seq) {
401 		/* Bump our Nr */
402 		session->nr++;
403 		session->nr &= session->nr_max;
404 
405 		l2tp_dbg(session, L2TP_MSG_SEQ, "%s: updated nr to %hu\n",
406 			 session->name, session->nr);
407 	}
408 
409 	/* call private receive handler */
410 	if (session->recv_skb != NULL)
411 		(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
412 	else
413 		kfree_skb(skb);
414 }
415 
416 /* Dequeue skbs from the session's reorder_q, subject to packet order.
417  * Skbs that have been in the queue for too long are simply discarded.
418  */
419 static void l2tp_recv_dequeue(struct l2tp_session *session)
420 {
421 	struct sk_buff *skb;
422 	struct sk_buff *tmp;
423 
424 	/* If the pkt at the head of the queue has the nr that we
425 	 * expect to send up next, dequeue it and any other
426 	 * in-sequence packets behind it.
427 	 */
428 start:
429 	spin_lock_bh(&session->reorder_q.lock);
430 	skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
431 		if (time_after(jiffies, L2TP_SKB_CB(skb)->expires)) {
432 			atomic_long_inc(&session->stats.rx_seq_discards);
433 			atomic_long_inc(&session->stats.rx_errors);
434 			l2tp_dbg(session, L2TP_MSG_SEQ,
435 				 "%s: oos pkt %u len %d discarded (too old), waiting for %u, reorder_q_len=%d\n",
436 				 session->name, L2TP_SKB_CB(skb)->ns,
437 				 L2TP_SKB_CB(skb)->length, session->nr,
438 				 skb_queue_len(&session->reorder_q));
439 			session->reorder_skip = 1;
440 			__skb_unlink(skb, &session->reorder_q);
441 			kfree_skb(skb);
442 			continue;
443 		}
444 
445 		if (L2TP_SKB_CB(skb)->has_seq) {
446 			if (session->reorder_skip) {
447 				l2tp_dbg(session, L2TP_MSG_SEQ,
448 					 "%s: advancing nr to next pkt: %u -> %u",
449 					 session->name, session->nr,
450 					 L2TP_SKB_CB(skb)->ns);
451 				session->reorder_skip = 0;
452 				session->nr = L2TP_SKB_CB(skb)->ns;
453 			}
454 			if (L2TP_SKB_CB(skb)->ns != session->nr) {
455 				l2tp_dbg(session, L2TP_MSG_SEQ,
456 					 "%s: holding oos pkt %u len %d, waiting for %u, reorder_q_len=%d\n",
457 					 session->name, L2TP_SKB_CB(skb)->ns,
458 					 L2TP_SKB_CB(skb)->length, session->nr,
459 					 skb_queue_len(&session->reorder_q));
460 				goto out;
461 			}
462 		}
463 		__skb_unlink(skb, &session->reorder_q);
464 
465 		/* Process the skb. We release the queue lock while we
466 		 * do so to let other contexts process the queue.
467 		 */
468 		spin_unlock_bh(&session->reorder_q.lock);
469 		l2tp_recv_dequeue_skb(session, skb);
470 		goto start;
471 	}
472 
473 out:
474 	spin_unlock_bh(&session->reorder_q.lock);
475 }
476 
477 static int l2tp_seq_check_rx_window(struct l2tp_session *session, u32 nr)
478 {
479 	u32 nws;
480 
481 	if (nr >= session->nr)
482 		nws = nr - session->nr;
483 	else
484 		nws = (session->nr_max + 1) - (session->nr - nr);
485 
486 	return nws < session->nr_window_size;
487 }
488 
489 /* If packet has sequence numbers, queue it if acceptable. Returns 0 if
490  * acceptable, else non-zero.
491  */
492 static int l2tp_recv_data_seq(struct l2tp_session *session, struct sk_buff *skb)
493 {
494 	if (!l2tp_seq_check_rx_window(session, L2TP_SKB_CB(skb)->ns)) {
495 		/* Packet sequence number is outside allowed window.
496 		 * Discard it.
497 		 */
498 		l2tp_dbg(session, L2TP_MSG_SEQ,
499 			 "%s: pkt %u len %d discarded, outside window, nr=%u\n",
500 			 session->name, L2TP_SKB_CB(skb)->ns,
501 			 L2TP_SKB_CB(skb)->length, session->nr);
502 		goto discard;
503 	}
504 
505 	if (session->reorder_timeout != 0) {
506 		/* Packet reordering enabled. Add skb to session's
507 		 * reorder queue, in order of ns.
508 		 */
509 		l2tp_recv_queue_skb(session, skb);
510 		goto out;
511 	}
512 
513 	/* Packet reordering disabled. Discard out-of-sequence packets, while
514 	 * tracking the number if in-sequence packets after the first OOS packet
515 	 * is seen. After nr_oos_count_max in-sequence packets, reset the
516 	 * sequence number to re-enable packet reception.
517 	 */
518 	if (L2TP_SKB_CB(skb)->ns == session->nr) {
519 		skb_queue_tail(&session->reorder_q, skb);
520 	} else {
521 		u32 nr_oos = L2TP_SKB_CB(skb)->ns;
522 		u32 nr_next = (session->nr_oos + 1) & session->nr_max;
523 
524 		if (nr_oos == nr_next)
525 			session->nr_oos_count++;
526 		else
527 			session->nr_oos_count = 0;
528 
529 		session->nr_oos = nr_oos;
530 		if (session->nr_oos_count > session->nr_oos_count_max) {
531 			session->reorder_skip = 1;
532 			l2tp_dbg(session, L2TP_MSG_SEQ,
533 				 "%s: %d oos packets received. Resetting sequence numbers\n",
534 				 session->name, session->nr_oos_count);
535 		}
536 		if (!session->reorder_skip) {
537 			atomic_long_inc(&session->stats.rx_seq_discards);
538 			l2tp_dbg(session, L2TP_MSG_SEQ,
539 				 "%s: oos pkt %u len %d discarded, waiting for %u, reorder_q_len=%d\n",
540 				 session->name, L2TP_SKB_CB(skb)->ns,
541 				 L2TP_SKB_CB(skb)->length, session->nr,
542 				 skb_queue_len(&session->reorder_q));
543 			goto discard;
544 		}
545 		skb_queue_tail(&session->reorder_q, skb);
546 	}
547 
548 out:
549 	return 0;
550 
551 discard:
552 	return 1;
553 }
554 
555 /* Do receive processing of L2TP data frames. We handle both L2TPv2
556  * and L2TPv3 data frames here.
557  *
558  * L2TPv2 Data Message Header
559  *
560  *  0                   1                   2                   3
561  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
562  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
563  * |T|L|x|x|S|x|O|P|x|x|x|x|  Ver  |          Length (opt)         |
564  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
565  * |           Tunnel ID           |           Session ID          |
566  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
567  * |             Ns (opt)          |             Nr (opt)          |
568  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
569  * |      Offset Size (opt)        |    Offset pad... (opt)
570  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
571  *
572  * Data frames are marked by T=0. All other fields are the same as
573  * those in L2TP control frames.
574  *
575  * L2TPv3 Data Message Header
576  *
577  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
578  * |                      L2TP Session Header                      |
579  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
580  * |                      L2-Specific Sublayer                     |
581  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
582  * |                        Tunnel Payload                      ...
583  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
584  *
585  * L2TPv3 Session Header Over IP
586  *
587  *  0                   1                   2                   3
588  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
589  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
590  * |                           Session ID                          |
591  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
592  * |               Cookie (optional, maximum 64 bits)...
593  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
594  *                                                                 |
595  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
596  *
597  * L2TPv3 L2-Specific Sublayer Format
598  *
599  *  0                   1                   2                   3
600  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
601  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
602  * |x|S|x|x|x|x|x|x|              Sequence Number                  |
603  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
604  *
605  * Cookie value and sublayer format are negotiated with the peer when
606  * the session is set up. Unlike L2TPv2, we do not need to parse the
607  * packet header to determine if optional fields are present.
608  *
609  * Caller must already have parsed the frame and determined that it is
610  * a data (not control) frame before coming here. Fields up to the
611  * session-id have already been parsed and ptr points to the data
612  * after the session-id.
613  */
614 void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
615 		      unsigned char *ptr, unsigned char *optr, u16 hdrflags,
616 		      int length)
617 {
618 	struct l2tp_tunnel *tunnel = session->tunnel;
619 	int offset;
620 	u32 ns, nr;
621 
622 	/* Parse and check optional cookie */
623 	if (session->peer_cookie_len > 0) {
624 		if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
625 			l2tp_info(tunnel, L2TP_MSG_DATA,
626 				  "%s: cookie mismatch (%u/%u). Discarding.\n",
627 				  tunnel->name, tunnel->tunnel_id,
628 				  session->session_id);
629 			atomic_long_inc(&session->stats.rx_cookie_discards);
630 			goto discard;
631 		}
632 		ptr += session->peer_cookie_len;
633 	}
634 
635 	/* Handle the optional sequence numbers. Sequence numbers are
636 	 * in different places for L2TPv2 and L2TPv3.
637 	 *
638 	 * If we are the LAC, enable/disable sequence numbers under
639 	 * the control of the LNS.  If no sequence numbers present but
640 	 * we were expecting them, discard frame.
641 	 */
642 	ns = nr = 0;
643 	L2TP_SKB_CB(skb)->has_seq = 0;
644 	if (tunnel->version == L2TP_HDR_VER_2) {
645 		if (hdrflags & L2TP_HDRFLAG_S) {
646 			ns = ntohs(*(__be16 *) ptr);
647 			ptr += 2;
648 			nr = ntohs(*(__be16 *) ptr);
649 			ptr += 2;
650 
651 			/* Store L2TP info in the skb */
652 			L2TP_SKB_CB(skb)->ns = ns;
653 			L2TP_SKB_CB(skb)->has_seq = 1;
654 
655 			l2tp_dbg(session, L2TP_MSG_SEQ,
656 				 "%s: recv data ns=%u, nr=%u, session nr=%u\n",
657 				 session->name, ns, nr, session->nr);
658 		}
659 	} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
660 		u32 l2h = ntohl(*(__be32 *) ptr);
661 
662 		if (l2h & 0x40000000) {
663 			ns = l2h & 0x00ffffff;
664 
665 			/* Store L2TP info in the skb */
666 			L2TP_SKB_CB(skb)->ns = ns;
667 			L2TP_SKB_CB(skb)->has_seq = 1;
668 
669 			l2tp_dbg(session, L2TP_MSG_SEQ,
670 				 "%s: recv data ns=%u, session nr=%u\n",
671 				 session->name, ns, session->nr);
672 		}
673 		ptr += 4;
674 	}
675 
676 	if (L2TP_SKB_CB(skb)->has_seq) {
677 		/* Received a packet with sequence numbers. If we're the LNS,
678 		 * check if we sre sending sequence numbers and if not,
679 		 * configure it so.
680 		 */
681 		if ((!session->lns_mode) && (!session->send_seq)) {
682 			l2tp_info(session, L2TP_MSG_SEQ,
683 				  "%s: requested to enable seq numbers by LNS\n",
684 				  session->name);
685 			session->send_seq = 1;
686 			l2tp_session_set_header_len(session, tunnel->version);
687 		}
688 	} else {
689 		/* No sequence numbers.
690 		 * If user has configured mandatory sequence numbers, discard.
691 		 */
692 		if (session->recv_seq) {
693 			l2tp_warn(session, L2TP_MSG_SEQ,
694 				  "%s: recv data has no seq numbers when required. Discarding.\n",
695 				  session->name);
696 			atomic_long_inc(&session->stats.rx_seq_discards);
697 			goto discard;
698 		}
699 
700 		/* If we're the LAC and we're sending sequence numbers, the
701 		 * LNS has requested that we no longer send sequence numbers.
702 		 * If we're the LNS and we're sending sequence numbers, the
703 		 * LAC is broken. Discard the frame.
704 		 */
705 		if ((!session->lns_mode) && (session->send_seq)) {
706 			l2tp_info(session, L2TP_MSG_SEQ,
707 				  "%s: requested to disable seq numbers by LNS\n",
708 				  session->name);
709 			session->send_seq = 0;
710 			l2tp_session_set_header_len(session, tunnel->version);
711 		} else if (session->send_seq) {
712 			l2tp_warn(session, L2TP_MSG_SEQ,
713 				  "%s: recv data has no seq numbers when required. Discarding.\n",
714 				  session->name);
715 			atomic_long_inc(&session->stats.rx_seq_discards);
716 			goto discard;
717 		}
718 	}
719 
720 	/* Session data offset is defined only for L2TPv2 and is
721 	 * indicated by an optional 16-bit value in the header.
722 	 */
723 	if (tunnel->version == L2TP_HDR_VER_2) {
724 		/* If offset bit set, skip it. */
725 		if (hdrflags & L2TP_HDRFLAG_O) {
726 			offset = ntohs(*(__be16 *)ptr);
727 			ptr += 2 + offset;
728 		}
729 	}
730 
731 	offset = ptr - optr;
732 	if (!pskb_may_pull(skb, offset))
733 		goto discard;
734 
735 	__skb_pull(skb, offset);
736 
737 	/* Prepare skb for adding to the session's reorder_q.  Hold
738 	 * packets for max reorder_timeout or 1 second if not
739 	 * reordering.
740 	 */
741 	L2TP_SKB_CB(skb)->length = length;
742 	L2TP_SKB_CB(skb)->expires = jiffies +
743 		(session->reorder_timeout ? session->reorder_timeout : HZ);
744 
745 	/* Add packet to the session's receive queue. Reordering is done here, if
746 	 * enabled. Saved L2TP protocol info is stored in skb->sb[].
747 	 */
748 	if (L2TP_SKB_CB(skb)->has_seq) {
749 		if (l2tp_recv_data_seq(session, skb))
750 			goto discard;
751 	} else {
752 		/* No sequence numbers. Add the skb to the tail of the
753 		 * reorder queue. This ensures that it will be
754 		 * delivered after all previous sequenced skbs.
755 		 */
756 		skb_queue_tail(&session->reorder_q, skb);
757 	}
758 
759 	/* Try to dequeue as many skbs from reorder_q as we can. */
760 	l2tp_recv_dequeue(session);
761 
762 	return;
763 
764 discard:
765 	atomic_long_inc(&session->stats.rx_errors);
766 	kfree_skb(skb);
767 }
768 EXPORT_SYMBOL(l2tp_recv_common);
769 
770 /* Drop skbs from the session's reorder_q
771  */
772 static int l2tp_session_queue_purge(struct l2tp_session *session)
773 {
774 	struct sk_buff *skb = NULL;
775 	BUG_ON(!session);
776 	BUG_ON(session->magic != L2TP_SESSION_MAGIC);
777 	while ((skb = skb_dequeue(&session->reorder_q))) {
778 		atomic_long_inc(&session->stats.rx_errors);
779 		kfree_skb(skb);
780 	}
781 	return 0;
782 }
783 
784 /* Internal UDP receive frame. Do the real work of receiving an L2TP data frame
785  * here. The skb is not on a list when we get here.
786  * Returns 0 if the packet was a data packet and was successfully passed on.
787  * Returns 1 if the packet was not a good data packet and could not be
788  * forwarded.  All such packets are passed up to userspace to deal with.
789  */
790 static int l2tp_udp_recv_core(struct l2tp_tunnel *tunnel, struct sk_buff *skb)
791 {
792 	struct l2tp_session *session = NULL;
793 	unsigned char *ptr, *optr;
794 	u16 hdrflags;
795 	u32 tunnel_id, session_id;
796 	u16 version;
797 	int length;
798 
799 	/* UDP has verifed checksum */
800 
801 	/* UDP always verifies the packet length. */
802 	__skb_pull(skb, sizeof(struct udphdr));
803 
804 	/* Short packet? */
805 	if (!pskb_may_pull(skb, L2TP_HDR_SIZE_MAX)) {
806 		l2tp_info(tunnel, L2TP_MSG_DATA,
807 			  "%s: recv short packet (len=%d)\n",
808 			  tunnel->name, skb->len);
809 		goto error;
810 	}
811 
812 	/* Trace packet contents, if enabled */
813 	if (tunnel->debug & L2TP_MSG_DATA) {
814 		length = min(32u, skb->len);
815 		if (!pskb_may_pull(skb, length))
816 			goto error;
817 
818 		pr_debug("%s: recv\n", tunnel->name);
819 		print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, skb->data, length);
820 	}
821 
822 	/* Point to L2TP header */
823 	optr = ptr = skb->data;
824 
825 	/* Get L2TP header flags */
826 	hdrflags = ntohs(*(__be16 *) ptr);
827 
828 	/* Check protocol version */
829 	version = hdrflags & L2TP_HDR_VER_MASK;
830 	if (version != tunnel->version) {
831 		l2tp_info(tunnel, L2TP_MSG_DATA,
832 			  "%s: recv protocol version mismatch: got %d expected %d\n",
833 			  tunnel->name, version, tunnel->version);
834 		goto error;
835 	}
836 
837 	/* Get length of L2TP packet */
838 	length = skb->len;
839 
840 	/* If type is control packet, it is handled by userspace. */
841 	if (hdrflags & L2TP_HDRFLAG_T) {
842 		l2tp_dbg(tunnel, L2TP_MSG_DATA,
843 			 "%s: recv control packet, len=%d\n",
844 			 tunnel->name, length);
845 		goto error;
846 	}
847 
848 	/* Skip flags */
849 	ptr += 2;
850 
851 	if (tunnel->version == L2TP_HDR_VER_2) {
852 		/* If length is present, skip it */
853 		if (hdrflags & L2TP_HDRFLAG_L)
854 			ptr += 2;
855 
856 		/* Extract tunnel and session ID */
857 		tunnel_id = ntohs(*(__be16 *) ptr);
858 		ptr += 2;
859 		session_id = ntohs(*(__be16 *) ptr);
860 		ptr += 2;
861 	} else {
862 		ptr += 2;	/* skip reserved bits */
863 		tunnel_id = tunnel->tunnel_id;
864 		session_id = ntohl(*(__be32 *) ptr);
865 		ptr += 4;
866 	}
867 
868 	/* Find the session context */
869 	session = l2tp_tunnel_get_session(tunnel, session_id);
870 	if (!session || !session->recv_skb) {
871 		if (session)
872 			l2tp_session_dec_refcount(session);
873 
874 		/* Not found? Pass to userspace to deal with */
875 		l2tp_info(tunnel, L2TP_MSG_DATA,
876 			  "%s: no session found (%u/%u). Passing up.\n",
877 			  tunnel->name, tunnel_id, session_id);
878 		goto error;
879 	}
880 
881 	if (tunnel->version == L2TP_HDR_VER_3 &&
882 	    l2tp_v3_ensure_opt_in_linear(session, skb, &ptr, &optr))
883 		goto error;
884 
885 	l2tp_recv_common(session, skb, ptr, optr, hdrflags, length);
886 	l2tp_session_dec_refcount(session);
887 
888 	return 0;
889 
890 error:
891 	/* Put UDP header back */
892 	__skb_push(skb, sizeof(struct udphdr));
893 
894 	return 1;
895 }
896 
897 /* UDP encapsulation receive handler. See net/ipv4/udp.c.
898  * Return codes:
899  * 0 : success.
900  * <0: error
901  * >0: skb should be passed up to userspace as UDP.
902  */
903 int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
904 {
905 	struct l2tp_tunnel *tunnel;
906 
907 	tunnel = rcu_dereference_sk_user_data(sk);
908 	if (tunnel == NULL)
909 		goto pass_up;
910 
911 	l2tp_dbg(tunnel, L2TP_MSG_DATA, "%s: received %d bytes\n",
912 		 tunnel->name, skb->len);
913 
914 	if (l2tp_udp_recv_core(tunnel, skb))
915 		goto pass_up;
916 
917 	return 0;
918 
919 pass_up:
920 	return 1;
921 }
922 EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
923 
924 /************************************************************************
925  * Transmit handling
926  ***********************************************************************/
927 
928 /* Build an L2TP header for the session into the buffer provided.
929  */
930 static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
931 {
932 	struct l2tp_tunnel *tunnel = session->tunnel;
933 	__be16 *bufp = buf;
934 	__be16 *optr = buf;
935 	u16 flags = L2TP_HDR_VER_2;
936 	u32 tunnel_id = tunnel->peer_tunnel_id;
937 	u32 session_id = session->peer_session_id;
938 
939 	if (session->send_seq)
940 		flags |= L2TP_HDRFLAG_S;
941 
942 	/* Setup L2TP header. */
943 	*bufp++ = htons(flags);
944 	*bufp++ = htons(tunnel_id);
945 	*bufp++ = htons(session_id);
946 	if (session->send_seq) {
947 		*bufp++ = htons(session->ns);
948 		*bufp++ = 0;
949 		session->ns++;
950 		session->ns &= 0xffff;
951 		l2tp_dbg(session, L2TP_MSG_SEQ, "%s: updated ns to %u\n",
952 			 session->name, session->ns);
953 	}
954 
955 	return bufp - optr;
956 }
957 
958 static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
959 {
960 	struct l2tp_tunnel *tunnel = session->tunnel;
961 	char *bufp = buf;
962 	char *optr = bufp;
963 
964 	/* Setup L2TP header. The header differs slightly for UDP and
965 	 * IP encapsulations. For UDP, there is 4 bytes of flags.
966 	 */
967 	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
968 		u16 flags = L2TP_HDR_VER_3;
969 		*((__be16 *) bufp) = htons(flags);
970 		bufp += 2;
971 		*((__be16 *) bufp) = 0;
972 		bufp += 2;
973 	}
974 
975 	*((__be32 *) bufp) = htonl(session->peer_session_id);
976 	bufp += 4;
977 	if (session->cookie_len) {
978 		memcpy(bufp, &session->cookie[0], session->cookie_len);
979 		bufp += session->cookie_len;
980 	}
981 	if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
982 		u32 l2h = 0;
983 
984 		if (session->send_seq) {
985 			l2h = 0x40000000 | session->ns;
986 			session->ns++;
987 			session->ns &= 0xffffff;
988 			l2tp_dbg(session, L2TP_MSG_SEQ,
989 				 "%s: updated ns to %u\n",
990 				 session->name, session->ns);
991 		}
992 
993 		*((__be32 *)bufp) = htonl(l2h);
994 		bufp += 4;
995 	}
996 
997 	return bufp - optr;
998 }
999 
1000 static void l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb,
1001 			   struct flowi *fl, size_t data_len)
1002 {
1003 	struct l2tp_tunnel *tunnel = session->tunnel;
1004 	unsigned int len = skb->len;
1005 	int error;
1006 
1007 	/* Debug */
1008 	if (session->send_seq)
1009 		l2tp_dbg(session, L2TP_MSG_DATA, "%s: send %zd bytes, ns=%u\n",
1010 			 session->name, data_len, session->ns - 1);
1011 	else
1012 		l2tp_dbg(session, L2TP_MSG_DATA, "%s: send %zd bytes\n",
1013 			 session->name, data_len);
1014 
1015 	if (session->debug & L2TP_MSG_DATA) {
1016 		int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
1017 		unsigned char *datap = skb->data + uhlen;
1018 
1019 		pr_debug("%s: xmit\n", session->name);
1020 		print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
1021 				     datap, min_t(size_t, 32, len - uhlen));
1022 	}
1023 
1024 	/* Queue the packet to IP for output */
1025 	skb->ignore_df = 1;
1026 #if IS_ENABLED(CONFIG_IPV6)
1027 	if (l2tp_sk_is_v6(tunnel->sock))
1028 		error = inet6_csk_xmit(tunnel->sock, skb, NULL);
1029 	else
1030 #endif
1031 		error = ip_queue_xmit(tunnel->sock, skb, fl);
1032 
1033 	/* Update stats */
1034 	if (error >= 0) {
1035 		atomic_long_inc(&tunnel->stats.tx_packets);
1036 		atomic_long_add(len, &tunnel->stats.tx_bytes);
1037 		atomic_long_inc(&session->stats.tx_packets);
1038 		atomic_long_add(len, &session->stats.tx_bytes);
1039 	} else {
1040 		atomic_long_inc(&tunnel->stats.tx_errors);
1041 		atomic_long_inc(&session->stats.tx_errors);
1042 	}
1043 }
1044 
1045 /* If caller requires the skb to have a ppp header, the header must be
1046  * inserted in the skb data before calling this function.
1047  */
1048 int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb, int hdr_len)
1049 {
1050 	int data_len = skb->len;
1051 	struct l2tp_tunnel *tunnel = session->tunnel;
1052 	struct sock *sk = tunnel->sock;
1053 	struct flowi *fl;
1054 	struct udphdr *uh;
1055 	struct inet_sock *inet;
1056 	int headroom;
1057 	int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
1058 	int udp_len;
1059 	int ret = NET_XMIT_SUCCESS;
1060 
1061 	/* Check that there's enough headroom in the skb to insert IP,
1062 	 * UDP and L2TP headers. If not enough, expand it to
1063 	 * make room. Adjust truesize.
1064 	 */
1065 	headroom = NET_SKB_PAD + sizeof(struct iphdr) +
1066 		uhlen + hdr_len;
1067 	if (skb_cow_head(skb, headroom)) {
1068 		kfree_skb(skb);
1069 		return NET_XMIT_DROP;
1070 	}
1071 
1072 	/* Setup L2TP header */
1073 	session->build_header(session, __skb_push(skb, hdr_len));
1074 
1075 	/* Reset skb netfilter state */
1076 	memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1077 	IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED |
1078 			      IPSKB_REROUTED);
1079 	nf_reset_ct(skb);
1080 
1081 	bh_lock_sock(sk);
1082 	if (sock_owned_by_user(sk)) {
1083 		kfree_skb(skb);
1084 		ret = NET_XMIT_DROP;
1085 		goto out_unlock;
1086 	}
1087 
1088 	/* The user-space may change the connection status for the user-space
1089 	 * provided socket at run time: we must check it under the socket lock
1090 	 */
1091 	if (tunnel->fd >= 0 && sk->sk_state != TCP_ESTABLISHED) {
1092 		kfree_skb(skb);
1093 		ret = NET_XMIT_DROP;
1094 		goto out_unlock;
1095 	}
1096 
1097 	/* Get routing info from the tunnel socket */
1098 	skb_dst_drop(skb);
1099 	skb_dst_set(skb, sk_dst_check(sk, 0));
1100 
1101 	inet = inet_sk(sk);
1102 	fl = &inet->cork.fl;
1103 	switch (tunnel->encap) {
1104 	case L2TP_ENCAPTYPE_UDP:
1105 		/* Setup UDP header */
1106 		__skb_push(skb, sizeof(*uh));
1107 		skb_reset_transport_header(skb);
1108 		uh = udp_hdr(skb);
1109 		uh->source = inet->inet_sport;
1110 		uh->dest = inet->inet_dport;
1111 		udp_len = uhlen + hdr_len + data_len;
1112 		uh->len = htons(udp_len);
1113 
1114 		/* Calculate UDP checksum if configured to do so */
1115 #if IS_ENABLED(CONFIG_IPV6)
1116 		if (l2tp_sk_is_v6(sk))
1117 			udp6_set_csum(udp_get_no_check6_tx(sk),
1118 				      skb, &inet6_sk(sk)->saddr,
1119 				      &sk->sk_v6_daddr, udp_len);
1120 		else
1121 #endif
1122 		udp_set_csum(sk->sk_no_check_tx, skb, inet->inet_saddr,
1123 			     inet->inet_daddr, udp_len);
1124 		break;
1125 
1126 	case L2TP_ENCAPTYPE_IP:
1127 		break;
1128 	}
1129 
1130 	l2tp_xmit_core(session, skb, fl, data_len);
1131 out_unlock:
1132 	bh_unlock_sock(sk);
1133 
1134 	return ret;
1135 }
1136 EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
1137 
1138 /*****************************************************************************
1139  * Tinnel and session create/destroy.
1140  *****************************************************************************/
1141 
1142 /* Tunnel socket destruct hook.
1143  * The tunnel context is deleted only when all session sockets have been
1144  * closed.
1145  */
1146 static void l2tp_tunnel_destruct(struct sock *sk)
1147 {
1148 	struct l2tp_tunnel *tunnel = l2tp_tunnel(sk);
1149 
1150 	if (tunnel == NULL)
1151 		goto end;
1152 
1153 	l2tp_info(tunnel, L2TP_MSG_CONTROL, "%s: closing...\n", tunnel->name);
1154 
1155 	/* Disable udp encapsulation */
1156 	switch (tunnel->encap) {
1157 	case L2TP_ENCAPTYPE_UDP:
1158 		/* No longer an encapsulation socket. See net/ipv4/udp.c */
1159 		(udp_sk(sk))->encap_type = 0;
1160 		(udp_sk(sk))->encap_rcv = NULL;
1161 		(udp_sk(sk))->encap_destroy = NULL;
1162 		break;
1163 	case L2TP_ENCAPTYPE_IP:
1164 		break;
1165 	}
1166 
1167 	/* Remove hooks into tunnel socket */
1168 	sk->sk_destruct = tunnel->old_sk_destruct;
1169 	sk->sk_user_data = NULL;
1170 
1171 	/* Call the original destructor */
1172 	if (sk->sk_destruct)
1173 		(*sk->sk_destruct)(sk);
1174 
1175 	kfree_rcu(tunnel, rcu);
1176 end:
1177 	return;
1178 }
1179 
1180 /* When the tunnel is closed, all the attached sessions need to go too.
1181  */
1182 static void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
1183 {
1184 	int hash;
1185 	struct hlist_node *walk;
1186 	struct hlist_node *tmp;
1187 	struct l2tp_session *session;
1188 
1189 	BUG_ON(tunnel == NULL);
1190 
1191 	l2tp_info(tunnel, L2TP_MSG_CONTROL, "%s: closing all sessions...\n",
1192 		  tunnel->name);
1193 
1194 	write_lock_bh(&tunnel->hlist_lock);
1195 	tunnel->acpt_newsess = false;
1196 	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
1197 again:
1198 		hlist_for_each_safe(walk, tmp, &tunnel->session_hlist[hash]) {
1199 			session = hlist_entry(walk, struct l2tp_session, hlist);
1200 
1201 			l2tp_info(session, L2TP_MSG_CONTROL,
1202 				  "%s: closing session\n", session->name);
1203 
1204 			hlist_del_init(&session->hlist);
1205 
1206 			if (test_and_set_bit(0, &session->dead))
1207 				goto again;
1208 
1209 			write_unlock_bh(&tunnel->hlist_lock);
1210 
1211 			__l2tp_session_unhash(session);
1212 			l2tp_session_queue_purge(session);
1213 
1214 			if (session->session_close != NULL)
1215 				(*session->session_close)(session);
1216 
1217 			l2tp_session_dec_refcount(session);
1218 
1219 			write_lock_bh(&tunnel->hlist_lock);
1220 
1221 			/* Now restart from the beginning of this hash
1222 			 * chain.  We always remove a session from the
1223 			 * list so we are guaranteed to make forward
1224 			 * progress.
1225 			 */
1226 			goto again;
1227 		}
1228 	}
1229 	write_unlock_bh(&tunnel->hlist_lock);
1230 }
1231 
1232 /* Tunnel socket destroy hook for UDP encapsulation */
1233 static void l2tp_udp_encap_destroy(struct sock *sk)
1234 {
1235 	struct l2tp_tunnel *tunnel = l2tp_tunnel(sk);
1236 
1237 	if (tunnel)
1238 		l2tp_tunnel_delete(tunnel);
1239 }
1240 
1241 /* Workqueue tunnel deletion function */
1242 static void l2tp_tunnel_del_work(struct work_struct *work)
1243 {
1244 	struct l2tp_tunnel *tunnel = container_of(work, struct l2tp_tunnel,
1245 						  del_work);
1246 	struct sock *sk = tunnel->sock;
1247 	struct socket *sock = sk->sk_socket;
1248 	struct l2tp_net *pn;
1249 
1250 	l2tp_tunnel_closeall(tunnel);
1251 
1252 	/* If the tunnel socket was created within the kernel, use
1253 	 * the sk API to release it here.
1254 	 */
1255 	if (tunnel->fd < 0) {
1256 		if (sock) {
1257 			kernel_sock_shutdown(sock, SHUT_RDWR);
1258 			sock_release(sock);
1259 		}
1260 	}
1261 
1262 	/* Remove the tunnel struct from the tunnel list */
1263 	pn = l2tp_pernet(tunnel->l2tp_net);
1264 	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1265 	list_del_rcu(&tunnel->list);
1266 	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1267 
1268 	/* drop initial ref */
1269 	l2tp_tunnel_dec_refcount(tunnel);
1270 
1271 	/* drop workqueue ref */
1272 	l2tp_tunnel_dec_refcount(tunnel);
1273 }
1274 
1275 /* Create a socket for the tunnel, if one isn't set up by
1276  * userspace. This is used for static tunnels where there is no
1277  * managing L2TP daemon.
1278  *
1279  * Since we don't want these sockets to keep a namespace alive by
1280  * themselves, we drop the socket's namespace refcount after creation.
1281  * These sockets are freed when the namespace exits using the pernet
1282  * exit hook.
1283  */
1284 static int l2tp_tunnel_sock_create(struct net *net,
1285 				u32 tunnel_id,
1286 				u32 peer_tunnel_id,
1287 				struct l2tp_tunnel_cfg *cfg,
1288 				struct socket **sockp)
1289 {
1290 	int err = -EINVAL;
1291 	struct socket *sock = NULL;
1292 	struct udp_port_cfg udp_conf;
1293 
1294 	switch (cfg->encap) {
1295 	case L2TP_ENCAPTYPE_UDP:
1296 		memset(&udp_conf, 0, sizeof(udp_conf));
1297 
1298 #if IS_ENABLED(CONFIG_IPV6)
1299 		if (cfg->local_ip6 && cfg->peer_ip6) {
1300 			udp_conf.family = AF_INET6;
1301 			memcpy(&udp_conf.local_ip6, cfg->local_ip6,
1302 			       sizeof(udp_conf.local_ip6));
1303 			memcpy(&udp_conf.peer_ip6, cfg->peer_ip6,
1304 			       sizeof(udp_conf.peer_ip6));
1305 			udp_conf.use_udp6_tx_checksums =
1306 			  ! cfg->udp6_zero_tx_checksums;
1307 			udp_conf.use_udp6_rx_checksums =
1308 			  ! cfg->udp6_zero_rx_checksums;
1309 		} else
1310 #endif
1311 		{
1312 			udp_conf.family = AF_INET;
1313 			udp_conf.local_ip = cfg->local_ip;
1314 			udp_conf.peer_ip = cfg->peer_ip;
1315 			udp_conf.use_udp_checksums = cfg->use_udp_checksums;
1316 		}
1317 
1318 		udp_conf.local_udp_port = htons(cfg->local_udp_port);
1319 		udp_conf.peer_udp_port = htons(cfg->peer_udp_port);
1320 
1321 		err = udp_sock_create(net, &udp_conf, &sock);
1322 		if (err < 0)
1323 			goto out;
1324 
1325 		break;
1326 
1327 	case L2TP_ENCAPTYPE_IP:
1328 #if IS_ENABLED(CONFIG_IPV6)
1329 		if (cfg->local_ip6 && cfg->peer_ip6) {
1330 			struct sockaddr_l2tpip6 ip6_addr = {0};
1331 
1332 			err = sock_create_kern(net, AF_INET6, SOCK_DGRAM,
1333 					  IPPROTO_L2TP, &sock);
1334 			if (err < 0)
1335 				goto out;
1336 
1337 			ip6_addr.l2tp_family = AF_INET6;
1338 			memcpy(&ip6_addr.l2tp_addr, cfg->local_ip6,
1339 			       sizeof(ip6_addr.l2tp_addr));
1340 			ip6_addr.l2tp_conn_id = tunnel_id;
1341 			err = kernel_bind(sock, (struct sockaddr *) &ip6_addr,
1342 					  sizeof(ip6_addr));
1343 			if (err < 0)
1344 				goto out;
1345 
1346 			ip6_addr.l2tp_family = AF_INET6;
1347 			memcpy(&ip6_addr.l2tp_addr, cfg->peer_ip6,
1348 			       sizeof(ip6_addr.l2tp_addr));
1349 			ip6_addr.l2tp_conn_id = peer_tunnel_id;
1350 			err = kernel_connect(sock,
1351 					     (struct sockaddr *) &ip6_addr,
1352 					     sizeof(ip6_addr), 0);
1353 			if (err < 0)
1354 				goto out;
1355 		} else
1356 #endif
1357 		{
1358 			struct sockaddr_l2tpip ip_addr = {0};
1359 
1360 			err = sock_create_kern(net, AF_INET, SOCK_DGRAM,
1361 					  IPPROTO_L2TP, &sock);
1362 			if (err < 0)
1363 				goto out;
1364 
1365 			ip_addr.l2tp_family = AF_INET;
1366 			ip_addr.l2tp_addr = cfg->local_ip;
1367 			ip_addr.l2tp_conn_id = tunnel_id;
1368 			err = kernel_bind(sock, (struct sockaddr *) &ip_addr,
1369 					  sizeof(ip_addr));
1370 			if (err < 0)
1371 				goto out;
1372 
1373 			ip_addr.l2tp_family = AF_INET;
1374 			ip_addr.l2tp_addr = cfg->peer_ip;
1375 			ip_addr.l2tp_conn_id = peer_tunnel_id;
1376 			err = kernel_connect(sock, (struct sockaddr *) &ip_addr,
1377 					     sizeof(ip_addr), 0);
1378 			if (err < 0)
1379 				goto out;
1380 		}
1381 		break;
1382 
1383 	default:
1384 		goto out;
1385 	}
1386 
1387 out:
1388 	*sockp = sock;
1389 	if ((err < 0) && sock) {
1390 		kernel_sock_shutdown(sock, SHUT_RDWR);
1391 		sock_release(sock);
1392 		*sockp = NULL;
1393 	}
1394 
1395 	return err;
1396 }
1397 
1398 static struct lock_class_key l2tp_socket_class;
1399 
1400 int l2tp_tunnel_create(struct net *net, int fd, int version, u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
1401 {
1402 	struct l2tp_tunnel *tunnel = NULL;
1403 	int err;
1404 	enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
1405 
1406 	if (cfg != NULL)
1407 		encap = cfg->encap;
1408 
1409 	tunnel = kzalloc(sizeof(struct l2tp_tunnel), GFP_KERNEL);
1410 	if (tunnel == NULL) {
1411 		err = -ENOMEM;
1412 		goto err;
1413 	}
1414 
1415 	tunnel->version = version;
1416 	tunnel->tunnel_id = tunnel_id;
1417 	tunnel->peer_tunnel_id = peer_tunnel_id;
1418 	tunnel->debug = L2TP_DEFAULT_DEBUG_FLAGS;
1419 
1420 	tunnel->magic = L2TP_TUNNEL_MAGIC;
1421 	sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
1422 	rwlock_init(&tunnel->hlist_lock);
1423 	tunnel->acpt_newsess = true;
1424 
1425 	if (cfg != NULL)
1426 		tunnel->debug = cfg->debug;
1427 
1428 	tunnel->encap = encap;
1429 
1430 	refcount_set(&tunnel->ref_count, 1);
1431 	tunnel->fd = fd;
1432 
1433 	/* Init delete workqueue struct */
1434 	INIT_WORK(&tunnel->del_work, l2tp_tunnel_del_work);
1435 
1436 	INIT_LIST_HEAD(&tunnel->list);
1437 
1438 	err = 0;
1439 err:
1440 	if (tunnelp)
1441 		*tunnelp = tunnel;
1442 
1443 	return err;
1444 }
1445 EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
1446 
1447 static int l2tp_validate_socket(const struct sock *sk, const struct net *net,
1448 				enum l2tp_encap_type encap)
1449 {
1450 	if (!net_eq(sock_net(sk), net))
1451 		return -EINVAL;
1452 
1453 	if (sk->sk_type != SOCK_DGRAM)
1454 		return -EPROTONOSUPPORT;
1455 
1456 	if ((encap == L2TP_ENCAPTYPE_UDP && sk->sk_protocol != IPPROTO_UDP) ||
1457 	    (encap == L2TP_ENCAPTYPE_IP && sk->sk_protocol != IPPROTO_L2TP))
1458 		return -EPROTONOSUPPORT;
1459 
1460 	if (sk->sk_user_data)
1461 		return -EBUSY;
1462 
1463 	return 0;
1464 }
1465 
1466 int l2tp_tunnel_register(struct l2tp_tunnel *tunnel, struct net *net,
1467 			 struct l2tp_tunnel_cfg *cfg)
1468 {
1469 	struct l2tp_tunnel *tunnel_walk;
1470 	struct l2tp_net *pn;
1471 	struct socket *sock;
1472 	struct sock *sk;
1473 	int ret;
1474 
1475 	if (tunnel->fd < 0) {
1476 		ret = l2tp_tunnel_sock_create(net, tunnel->tunnel_id,
1477 					      tunnel->peer_tunnel_id, cfg,
1478 					      &sock);
1479 		if (ret < 0)
1480 			goto err;
1481 	} else {
1482 		sock = sockfd_lookup(tunnel->fd, &ret);
1483 		if (!sock)
1484 			goto err;
1485 
1486 		ret = l2tp_validate_socket(sock->sk, net, tunnel->encap);
1487 		if (ret < 0)
1488 			goto err_sock;
1489 	}
1490 
1491 	tunnel->l2tp_net = net;
1492 	pn = l2tp_pernet(net);
1493 
1494 	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1495 	list_for_each_entry(tunnel_walk, &pn->l2tp_tunnel_list, list) {
1496 		if (tunnel_walk->tunnel_id == tunnel->tunnel_id) {
1497 			spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1498 
1499 			ret = -EEXIST;
1500 			goto err_sock;
1501 		}
1502 	}
1503 	list_add_rcu(&tunnel->list, &pn->l2tp_tunnel_list);
1504 	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1505 
1506 	sk = sock->sk;
1507 	sock_hold(sk);
1508 	tunnel->sock = sk;
1509 
1510 	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
1511 		struct udp_tunnel_sock_cfg udp_cfg = {
1512 			.sk_user_data = tunnel,
1513 			.encap_type = UDP_ENCAP_L2TPINUDP,
1514 			.encap_rcv = l2tp_udp_encap_recv,
1515 			.encap_destroy = l2tp_udp_encap_destroy,
1516 		};
1517 
1518 		setup_udp_tunnel_sock(net, sock, &udp_cfg);
1519 	} else {
1520 		sk->sk_user_data = tunnel;
1521 	}
1522 
1523 	tunnel->old_sk_destruct = sk->sk_destruct;
1524 	sk->sk_destruct = &l2tp_tunnel_destruct;
1525 	lockdep_set_class_and_name(&sk->sk_lock.slock, &l2tp_socket_class,
1526 				   "l2tp_sock");
1527 	sk->sk_allocation = GFP_ATOMIC;
1528 
1529 	if (tunnel->fd >= 0)
1530 		sockfd_put(sock);
1531 
1532 	return 0;
1533 
1534 err_sock:
1535 	if (tunnel->fd < 0)
1536 		sock_release(sock);
1537 	else
1538 		sockfd_put(sock);
1539 err:
1540 	return ret;
1541 }
1542 EXPORT_SYMBOL_GPL(l2tp_tunnel_register);
1543 
1544 /* This function is used by the netlink TUNNEL_DELETE command.
1545  */
1546 void l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
1547 {
1548 	if (!test_and_set_bit(0, &tunnel->dead)) {
1549 		l2tp_tunnel_inc_refcount(tunnel);
1550 		queue_work(l2tp_wq, &tunnel->del_work);
1551 	}
1552 }
1553 EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
1554 
1555 /* Really kill the session.
1556  */
1557 void l2tp_session_free(struct l2tp_session *session)
1558 {
1559 	struct l2tp_tunnel *tunnel = session->tunnel;
1560 
1561 	BUG_ON(refcount_read(&session->ref_count) != 0);
1562 
1563 	if (tunnel) {
1564 		BUG_ON(tunnel->magic != L2TP_TUNNEL_MAGIC);
1565 		l2tp_tunnel_dec_refcount(tunnel);
1566 	}
1567 
1568 	kfree(session);
1569 }
1570 EXPORT_SYMBOL_GPL(l2tp_session_free);
1571 
1572 /* Remove an l2tp session from l2tp_core's hash lists.
1573  * Provides a tidyup interface for pseudowire code which can't just route all
1574  * shutdown via. l2tp_session_delete and a pseudowire-specific session_close
1575  * callback.
1576  */
1577 void __l2tp_session_unhash(struct l2tp_session *session)
1578 {
1579 	struct l2tp_tunnel *tunnel = session->tunnel;
1580 
1581 	/* Remove the session from core hashes */
1582 	if (tunnel) {
1583 		/* Remove from the per-tunnel hash */
1584 		write_lock_bh(&tunnel->hlist_lock);
1585 		hlist_del_init(&session->hlist);
1586 		write_unlock_bh(&tunnel->hlist_lock);
1587 
1588 		/* For L2TPv3 we have a per-net hash: remove from there, too */
1589 		if (tunnel->version != L2TP_HDR_VER_2) {
1590 			struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1591 			spin_lock_bh(&pn->l2tp_session_hlist_lock);
1592 			hlist_del_init_rcu(&session->global_hlist);
1593 			spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1594 			synchronize_rcu();
1595 		}
1596 	}
1597 }
1598 EXPORT_SYMBOL_GPL(__l2tp_session_unhash);
1599 
1600 /* This function is used by the netlink SESSION_DELETE command and by
1601    pseudowire modules.
1602  */
1603 int l2tp_session_delete(struct l2tp_session *session)
1604 {
1605 	if (test_and_set_bit(0, &session->dead))
1606 		return 0;
1607 
1608 	__l2tp_session_unhash(session);
1609 	l2tp_session_queue_purge(session);
1610 	if (session->session_close != NULL)
1611 		(*session->session_close)(session);
1612 
1613 	l2tp_session_dec_refcount(session);
1614 
1615 	return 0;
1616 }
1617 EXPORT_SYMBOL_GPL(l2tp_session_delete);
1618 
1619 /* We come here whenever a session's send_seq, cookie_len or
1620  * l2specific_type parameters are set.
1621  */
1622 void l2tp_session_set_header_len(struct l2tp_session *session, int version)
1623 {
1624 	if (version == L2TP_HDR_VER_2) {
1625 		session->hdr_len = 6;
1626 		if (session->send_seq)
1627 			session->hdr_len += 4;
1628 	} else {
1629 		session->hdr_len = 4 + session->cookie_len;
1630 		session->hdr_len += l2tp_get_l2specific_len(session);
1631 		if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
1632 			session->hdr_len += 4;
1633 	}
1634 
1635 }
1636 EXPORT_SYMBOL_GPL(l2tp_session_set_header_len);
1637 
1638 struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
1639 {
1640 	struct l2tp_session *session;
1641 
1642 	session = kzalloc(sizeof(struct l2tp_session) + priv_size, GFP_KERNEL);
1643 	if (session != NULL) {
1644 		session->magic = L2TP_SESSION_MAGIC;
1645 		session->tunnel = tunnel;
1646 
1647 		session->session_id = session_id;
1648 		session->peer_session_id = peer_session_id;
1649 		session->nr = 0;
1650 		if (tunnel->version == L2TP_HDR_VER_2)
1651 			session->nr_max = 0xffff;
1652 		else
1653 			session->nr_max = 0xffffff;
1654 		session->nr_window_size = session->nr_max / 2;
1655 		session->nr_oos_count_max = 4;
1656 
1657 		/* Use NR of first received packet */
1658 		session->reorder_skip = 1;
1659 
1660 		sprintf(&session->name[0], "sess %u/%u",
1661 			tunnel->tunnel_id, session->session_id);
1662 
1663 		skb_queue_head_init(&session->reorder_q);
1664 
1665 		INIT_HLIST_NODE(&session->hlist);
1666 		INIT_HLIST_NODE(&session->global_hlist);
1667 
1668 		/* Inherit debug options from tunnel */
1669 		session->debug = tunnel->debug;
1670 
1671 		if (cfg) {
1672 			session->pwtype = cfg->pw_type;
1673 			session->debug = cfg->debug;
1674 			session->send_seq = cfg->send_seq;
1675 			session->recv_seq = cfg->recv_seq;
1676 			session->lns_mode = cfg->lns_mode;
1677 			session->reorder_timeout = cfg->reorder_timeout;
1678 			session->l2specific_type = cfg->l2specific_type;
1679 			session->cookie_len = cfg->cookie_len;
1680 			memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
1681 			session->peer_cookie_len = cfg->peer_cookie_len;
1682 			memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
1683 		}
1684 
1685 		if (tunnel->version == L2TP_HDR_VER_2)
1686 			session->build_header = l2tp_build_l2tpv2_header;
1687 		else
1688 			session->build_header = l2tp_build_l2tpv3_header;
1689 
1690 		l2tp_session_set_header_len(session, tunnel->version);
1691 
1692 		refcount_set(&session->ref_count, 1);
1693 
1694 		return session;
1695 	}
1696 
1697 	return ERR_PTR(-ENOMEM);
1698 }
1699 EXPORT_SYMBOL_GPL(l2tp_session_create);
1700 
1701 /*****************************************************************************
1702  * Init and cleanup
1703  *****************************************************************************/
1704 
1705 static __net_init int l2tp_init_net(struct net *net)
1706 {
1707 	struct l2tp_net *pn = net_generic(net, l2tp_net_id);
1708 	int hash;
1709 
1710 	INIT_LIST_HEAD(&pn->l2tp_tunnel_list);
1711 	spin_lock_init(&pn->l2tp_tunnel_list_lock);
1712 
1713 	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
1714 		INIT_HLIST_HEAD(&pn->l2tp_session_hlist[hash]);
1715 
1716 	spin_lock_init(&pn->l2tp_session_hlist_lock);
1717 
1718 	return 0;
1719 }
1720 
1721 static __net_exit void l2tp_exit_net(struct net *net)
1722 {
1723 	struct l2tp_net *pn = l2tp_pernet(net);
1724 	struct l2tp_tunnel *tunnel = NULL;
1725 	int hash;
1726 
1727 	rcu_read_lock_bh();
1728 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
1729 		l2tp_tunnel_delete(tunnel);
1730 	}
1731 	rcu_read_unlock_bh();
1732 
1733 	if (l2tp_wq)
1734 		flush_workqueue(l2tp_wq);
1735 	rcu_barrier();
1736 
1737 	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
1738 		WARN_ON_ONCE(!hlist_empty(&pn->l2tp_session_hlist[hash]));
1739 }
1740 
1741 static struct pernet_operations l2tp_net_ops = {
1742 	.init = l2tp_init_net,
1743 	.exit = l2tp_exit_net,
1744 	.id   = &l2tp_net_id,
1745 	.size = sizeof(struct l2tp_net),
1746 };
1747 
1748 static int __init l2tp_init(void)
1749 {
1750 	int rc = 0;
1751 
1752 	rc = register_pernet_device(&l2tp_net_ops);
1753 	if (rc)
1754 		goto out;
1755 
1756 	l2tp_wq = alloc_workqueue("l2tp", WQ_UNBOUND, 0);
1757 	if (!l2tp_wq) {
1758 		pr_err("alloc_workqueue failed\n");
1759 		unregister_pernet_device(&l2tp_net_ops);
1760 		rc = -ENOMEM;
1761 		goto out;
1762 	}
1763 
1764 	pr_info("L2TP core driver, %s\n", L2TP_DRV_VERSION);
1765 
1766 out:
1767 	return rc;
1768 }
1769 
1770 static void __exit l2tp_exit(void)
1771 {
1772 	unregister_pernet_device(&l2tp_net_ops);
1773 	if (l2tp_wq) {
1774 		destroy_workqueue(l2tp_wq);
1775 		l2tp_wq = NULL;
1776 	}
1777 }
1778 
1779 module_init(l2tp_init);
1780 module_exit(l2tp_exit);
1781 
1782 MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
1783 MODULE_DESCRIPTION("L2TP core");
1784 MODULE_LICENSE("GPL");
1785 MODULE_VERSION(L2TP_DRV_VERSION);
1786