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