1/*
2 * L2TPv3 IP encapsulation support
3 *
4 * Copyright (c) 2008,2009,2010 Katalix Systems Ltd
5 *
6 *	This program is free software; you can redistribute it and/or
7 *	modify it under the terms of the GNU General Public License
8 *	as published by the Free Software Foundation; either version
9 *	2 of the License, or (at your option) any later version.
10 */
11
12#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13
14#include <linux/icmp.h>
15#include <linux/module.h>
16#include <linux/skbuff.h>
17#include <linux/random.h>
18#include <linux/socket.h>
19#include <linux/l2tp.h>
20#include <linux/in.h>
21#include <net/sock.h>
22#include <net/ip.h>
23#include <net/icmp.h>
24#include <net/udp.h>
25#include <net/inet_common.h>
26#include <net/inet_hashtables.h>
27#include <net/tcp_states.h>
28#include <net/protocol.h>
29#include <net/xfrm.h>
30
31#include "l2tp_core.h"
32
33struct l2tp_ip_sock {
34	/* inet_sock has to be the first member of l2tp_ip_sock */
35	struct inet_sock	inet;
36
37	u32			conn_id;
38	u32			peer_conn_id;
39};
40
41static DEFINE_RWLOCK(l2tp_ip_lock);
42static struct hlist_head l2tp_ip_table;
43static struct hlist_head l2tp_ip_bind_table;
44
45static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk)
46{
47	return (struct l2tp_ip_sock *)sk;
48}
49
50static struct sock *__l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
51{
52	struct sock *sk;
53
54	sk_for_each_bound(sk, &l2tp_ip_bind_table) {
55		struct inet_sock *inet = inet_sk(sk);
56		struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk);
57
58		if (l2tp == NULL)
59			continue;
60
61		if ((l2tp->conn_id == tunnel_id) &&
62		    net_eq(sock_net(sk), net) &&
63		    !(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) &&
64		    !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
65			goto found;
66	}
67
68	sk = NULL;
69found:
70	return sk;
71}
72
73static inline struct sock *l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
74{
75	struct sock *sk = __l2tp_ip_bind_lookup(net, laddr, dif, tunnel_id);
76	if (sk)
77		sock_hold(sk);
78
79	return sk;
80}
81
82/* When processing receive frames, there are two cases to
83 * consider. Data frames consist of a non-zero session-id and an
84 * optional cookie. Control frames consist of a regular L2TP header
85 * preceded by 32-bits of zeros.
86 *
87 * L2TPv3 Session Header Over IP
88 *
89 *  0                   1                   2                   3
90 *  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
91 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92 * |                           Session ID                          |
93 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94 * |               Cookie (optional, maximum 64 bits)...
95 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96 *                                                                 |
97 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98 *
99 * L2TPv3 Control Message Header Over IP
100 *
101 *  0                   1                   2                   3
102 *  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
103 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104 * |                      (32 bits of zeros)                       |
105 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106 * |T|L|x|x|S|x|x|x|x|x|x|x|  Ver  |             Length            |
107 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108 * |                     Control Connection ID                     |
109 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110 * |               Ns              |               Nr              |
111 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112 *
113 * All control frames are passed to userspace.
114 */
115static int l2tp_ip_recv(struct sk_buff *skb)
116{
117	struct net *net = dev_net(skb->dev);
118	struct sock *sk;
119	u32 session_id;
120	u32 tunnel_id;
121	unsigned char *ptr, *optr;
122	struct l2tp_session *session;
123	struct l2tp_tunnel *tunnel = NULL;
124	int length;
125
126	/* Point to L2TP header */
127	optr = ptr = skb->data;
128
129	if (!pskb_may_pull(skb, 4))
130		goto discard;
131
132	session_id = ntohl(*((__be32 *) ptr));
133	ptr += 4;
134
135	/* RFC3931: L2TP/IP packets have the first 4 bytes containing
136	 * the session_id. If it is 0, the packet is a L2TP control
137	 * frame and the session_id value can be discarded.
138	 */
139	if (session_id == 0) {
140		__skb_pull(skb, 4);
141		goto pass_up;
142	}
143
144	/* Ok, this is a data packet. Lookup the session. */
145	session = l2tp_session_find(net, NULL, session_id);
146	if (session == NULL)
147		goto discard;
148
149	tunnel = session->tunnel;
150	if (tunnel == NULL)
151		goto discard;
152
153	/* Trace packet contents, if enabled */
154	if (tunnel->debug & L2TP_MSG_DATA) {
155		length = min(32u, skb->len);
156		if (!pskb_may_pull(skb, length))
157			goto discard;
158
159		pr_debug("%s: ip recv\n", tunnel->name);
160		print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length);
161	}
162
163	l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook);
164
165	return 0;
166
167pass_up:
168	/* Get the tunnel_id from the L2TP header */
169	if (!pskb_may_pull(skb, 12))
170		goto discard;
171
172	if ((skb->data[0] & 0xc0) != 0xc0)
173		goto discard;
174
175	tunnel_id = ntohl(*(__be32 *) &skb->data[4]);
176	tunnel = l2tp_tunnel_find(net, tunnel_id);
177	if (tunnel != NULL)
178		sk = tunnel->sock;
179	else {
180		struct iphdr *iph = (struct iphdr *) skb_network_header(skb);
181
182		read_lock_bh(&l2tp_ip_lock);
183		sk = __l2tp_ip_bind_lookup(net, iph->daddr, 0, tunnel_id);
184		read_unlock_bh(&l2tp_ip_lock);
185	}
186
187	if (sk == NULL)
188		goto discard;
189
190	sock_hold(sk);
191
192	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
193		goto discard_put;
194
195	nf_reset(skb);
196
197	return sk_receive_skb(sk, skb, 1);
198
199discard_put:
200	sock_put(sk);
201
202discard:
203	kfree_skb(skb);
204	return 0;
205}
206
207static int l2tp_ip_open(struct sock *sk)
208{
209	/* Prevent autobind. We don't have ports. */
210	inet_sk(sk)->inet_num = IPPROTO_L2TP;
211
212	write_lock_bh(&l2tp_ip_lock);
213	sk_add_node(sk, &l2tp_ip_table);
214	write_unlock_bh(&l2tp_ip_lock);
215
216	return 0;
217}
218
219static void l2tp_ip_close(struct sock *sk, long timeout)
220{
221	write_lock_bh(&l2tp_ip_lock);
222	hlist_del_init(&sk->sk_bind_node);
223	sk_del_node_init(sk);
224	write_unlock_bh(&l2tp_ip_lock);
225	sk_common_release(sk);
226}
227
228static void l2tp_ip_destroy_sock(struct sock *sk)
229{
230	struct sk_buff *skb;
231	struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk);
232
233	while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL)
234		kfree_skb(skb);
235
236	if (tunnel) {
237		l2tp_tunnel_closeall(tunnel);
238		sock_put(sk);
239	}
240
241	sk_refcnt_debug_dec(sk);
242}
243
244static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
245{
246	struct inet_sock *inet = inet_sk(sk);
247	struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr;
248	struct net *net = sock_net(sk);
249	int ret;
250	int chk_addr_ret;
251
252	if (!sock_flag(sk, SOCK_ZAPPED))
253		return -EINVAL;
254	if (addr_len < sizeof(struct sockaddr_l2tpip))
255		return -EINVAL;
256	if (addr->l2tp_family != AF_INET)
257		return -EINVAL;
258
259	ret = -EADDRINUSE;
260	read_lock_bh(&l2tp_ip_lock);
261	if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr,
262				  sk->sk_bound_dev_if, addr->l2tp_conn_id))
263		goto out_in_use;
264
265	read_unlock_bh(&l2tp_ip_lock);
266
267	lock_sock(sk);
268	if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip))
269		goto out;
270
271	chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr);
272	ret = -EADDRNOTAVAIL;
273	if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
274	    chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
275		goto out;
276
277	if (addr->l2tp_addr.s_addr)
278		inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr;
279	if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
280		inet->inet_saddr = 0;  /* Use device */
281	sk_dst_reset(sk);
282
283	l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id;
284
285	write_lock_bh(&l2tp_ip_lock);
286	sk_add_bind_node(sk, &l2tp_ip_bind_table);
287	sk_del_node_init(sk);
288	write_unlock_bh(&l2tp_ip_lock);
289	ret = 0;
290	sock_reset_flag(sk, SOCK_ZAPPED);
291
292out:
293	release_sock(sk);
294
295	return ret;
296
297out_in_use:
298	read_unlock_bh(&l2tp_ip_lock);
299
300	return ret;
301}
302
303static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
304{
305	struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *) uaddr;
306	int rc;
307
308	if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */
309		return -EINVAL;
310
311	if (addr_len < sizeof(*lsa))
312		return -EINVAL;
313
314	if (ipv4_is_multicast(lsa->l2tp_addr.s_addr))
315		return -EINVAL;
316
317	rc = ip4_datagram_connect(sk, uaddr, addr_len);
318	if (rc < 0)
319		return rc;
320
321	lock_sock(sk);
322
323	l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id;
324
325	write_lock_bh(&l2tp_ip_lock);
326	hlist_del_init(&sk->sk_bind_node);
327	sk_add_bind_node(sk, &l2tp_ip_bind_table);
328	write_unlock_bh(&l2tp_ip_lock);
329
330	release_sock(sk);
331	return rc;
332}
333
334static int l2tp_ip_disconnect(struct sock *sk, int flags)
335{
336	if (sock_flag(sk, SOCK_ZAPPED))
337		return 0;
338
339	return udp_disconnect(sk, flags);
340}
341
342static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr,
343			   int *uaddr_len, int peer)
344{
345	struct sock *sk		= sock->sk;
346	struct inet_sock *inet	= inet_sk(sk);
347	struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk);
348	struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr;
349
350	memset(lsa, 0, sizeof(*lsa));
351	lsa->l2tp_family = AF_INET;
352	if (peer) {
353		if (!inet->inet_dport)
354			return -ENOTCONN;
355		lsa->l2tp_conn_id = lsk->peer_conn_id;
356		lsa->l2tp_addr.s_addr = inet->inet_daddr;
357	} else {
358		__be32 addr = inet->inet_rcv_saddr;
359		if (!addr)
360			addr = inet->inet_saddr;
361		lsa->l2tp_conn_id = lsk->conn_id;
362		lsa->l2tp_addr.s_addr = addr;
363	}
364	*uaddr_len = sizeof(*lsa);
365	return 0;
366}
367
368static int l2tp_ip_backlog_recv(struct sock *sk, struct sk_buff *skb)
369{
370	int rc;
371
372	/* Charge it to the socket, dropping if the queue is full. */
373	rc = sock_queue_rcv_skb(sk, skb);
374	if (rc < 0)
375		goto drop;
376
377	return 0;
378
379drop:
380	IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS);
381	kfree_skb(skb);
382	return -1;
383}
384
385/* Userspace will call sendmsg() on the tunnel socket to send L2TP
386 * control frames.
387 */
388static int l2tp_ip_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len)
389{
390	struct sk_buff *skb;
391	int rc;
392	struct inet_sock *inet = inet_sk(sk);
393	struct rtable *rt = NULL;
394	struct flowi4 *fl4;
395	int connected = 0;
396	__be32 daddr;
397
398	lock_sock(sk);
399
400	rc = -ENOTCONN;
401	if (sock_flag(sk, SOCK_DEAD))
402		goto out;
403
404	/* Get and verify the address. */
405	if (msg->msg_name) {
406		struct sockaddr_l2tpip *lip = (struct sockaddr_l2tpip *) msg->msg_name;
407		rc = -EINVAL;
408		if (msg->msg_namelen < sizeof(*lip))
409			goto out;
410
411		if (lip->l2tp_family != AF_INET) {
412			rc = -EAFNOSUPPORT;
413			if (lip->l2tp_family != AF_UNSPEC)
414				goto out;
415		}
416
417		daddr = lip->l2tp_addr.s_addr;
418	} else {
419		rc = -EDESTADDRREQ;
420		if (sk->sk_state != TCP_ESTABLISHED)
421			goto out;
422
423		daddr = inet->inet_daddr;
424		connected = 1;
425	}
426
427	/* Allocate a socket buffer */
428	rc = -ENOMEM;
429	skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) +
430			   4 + len, 0, GFP_KERNEL);
431	if (!skb)
432		goto error;
433
434	/* Reserve space for headers, putting IP header on 4-byte boundary. */
435	skb_reserve(skb, 2 + NET_SKB_PAD);
436	skb_reset_network_header(skb);
437	skb_reserve(skb, sizeof(struct iphdr));
438	skb_reset_transport_header(skb);
439
440	/* Insert 0 session_id */
441	*((__be32 *) skb_put(skb, 4)) = 0;
442
443	/* Copy user data into skb */
444	rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
445	if (rc < 0) {
446		kfree_skb(skb);
447		goto error;
448	}
449
450	fl4 = &inet->cork.fl.u.ip4;
451	if (connected)
452		rt = (struct rtable *) __sk_dst_check(sk, 0);
453
454	rcu_read_lock();
455	if (rt == NULL) {
456		const struct ip_options_rcu *inet_opt;
457
458		inet_opt = rcu_dereference(inet->inet_opt);
459
460		/* Use correct destination address if we have options. */
461		if (inet_opt && inet_opt->opt.srr)
462			daddr = inet_opt->opt.faddr;
463
464		/* If this fails, retransmit mechanism of transport layer will
465		 * keep trying until route appears or the connection times
466		 * itself out.
467		 */
468		rt = ip_route_output_ports(sock_net(sk), fl4, sk,
469					   daddr, inet->inet_saddr,
470					   inet->inet_dport, inet->inet_sport,
471					   sk->sk_protocol, RT_CONN_FLAGS(sk),
472					   sk->sk_bound_dev_if);
473		if (IS_ERR(rt))
474			goto no_route;
475		if (connected) {
476			sk_setup_caps(sk, &rt->dst);
477		} else {
478			skb_dst_set(skb, &rt->dst);
479			goto xmit;
480		}
481	}
482
483	/* We dont need to clone dst here, it is guaranteed to not disappear.
484	 *  __dev_xmit_skb() might force a refcount if needed.
485	 */
486	skb_dst_set_noref(skb, &rt->dst);
487
488xmit:
489	/* Queue the packet to IP for output */
490	rc = ip_queue_xmit(skb, &inet->cork.fl);
491	rcu_read_unlock();
492
493error:
494	if (rc >= 0)
495		rc = len;
496
497out:
498	release_sock(sk);
499	return rc;
500
501no_route:
502	rcu_read_unlock();
503	IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
504	kfree_skb(skb);
505	rc = -EHOSTUNREACH;
506	goto out;
507}
508
509static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
510			   size_t len, int noblock, int flags, int *addr_len)
511{
512	struct inet_sock *inet = inet_sk(sk);
513	size_t copied = 0;
514	int err = -EOPNOTSUPP;
515	struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
516	struct sk_buff *skb;
517
518	if (flags & MSG_OOB)
519		goto out;
520
521	if (addr_len)
522		*addr_len = sizeof(*sin);
523
524	skb = skb_recv_datagram(sk, flags, noblock, &err);
525	if (!skb)
526		goto out;
527
528	copied = skb->len;
529	if (len < copied) {
530		msg->msg_flags |= MSG_TRUNC;
531		copied = len;
532	}
533
534	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
535	if (err)
536		goto done;
537
538	sock_recv_timestamp(msg, sk, skb);
539
540	/* Copy the address. */
541	if (sin) {
542		sin->sin_family = AF_INET;
543		sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
544		sin->sin_port = 0;
545		memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
546	}
547	if (inet->cmsg_flags)
548		ip_cmsg_recv(msg, skb);
549	if (flags & MSG_TRUNC)
550		copied = skb->len;
551done:
552	skb_free_datagram(sk, skb);
553out:
554	return err ? err : copied;
555}
556
557static struct proto l2tp_ip_prot = {
558	.name		   = "L2TP/IP",
559	.owner		   = THIS_MODULE,
560	.init		   = l2tp_ip_open,
561	.close		   = l2tp_ip_close,
562	.bind		   = l2tp_ip_bind,
563	.connect	   = l2tp_ip_connect,
564	.disconnect	   = l2tp_ip_disconnect,
565	.ioctl		   = udp_ioctl,
566	.destroy	   = l2tp_ip_destroy_sock,
567	.setsockopt	   = ip_setsockopt,
568	.getsockopt	   = ip_getsockopt,
569	.sendmsg	   = l2tp_ip_sendmsg,
570	.recvmsg	   = l2tp_ip_recvmsg,
571	.backlog_rcv	   = l2tp_ip_backlog_recv,
572	.hash		   = inet_hash,
573	.unhash		   = inet_unhash,
574	.obj_size	   = sizeof(struct l2tp_ip_sock),
575#ifdef CONFIG_COMPAT
576	.compat_setsockopt = compat_ip_setsockopt,
577	.compat_getsockopt = compat_ip_getsockopt,
578#endif
579};
580
581static const struct proto_ops l2tp_ip_ops = {
582	.family		   = PF_INET,
583	.owner		   = THIS_MODULE,
584	.release	   = inet_release,
585	.bind		   = inet_bind,
586	.connect	   = inet_dgram_connect,
587	.socketpair	   = sock_no_socketpair,
588	.accept		   = sock_no_accept,
589	.getname	   = l2tp_ip_getname,
590	.poll		   = datagram_poll,
591	.ioctl		   = inet_ioctl,
592	.listen		   = sock_no_listen,
593	.shutdown	   = inet_shutdown,
594	.setsockopt	   = sock_common_setsockopt,
595	.getsockopt	   = sock_common_getsockopt,
596	.sendmsg	   = inet_sendmsg,
597	.recvmsg	   = sock_common_recvmsg,
598	.mmap		   = sock_no_mmap,
599	.sendpage	   = sock_no_sendpage,
600#ifdef CONFIG_COMPAT
601	.compat_setsockopt = compat_sock_common_setsockopt,
602	.compat_getsockopt = compat_sock_common_getsockopt,
603#endif
604};
605
606static struct inet_protosw l2tp_ip_protosw = {
607	.type		= SOCK_DGRAM,
608	.protocol	= IPPROTO_L2TP,
609	.prot		= &l2tp_ip_prot,
610	.ops		= &l2tp_ip_ops,
611	.no_check	= 0,
612};
613
614static struct net_protocol l2tp_ip_protocol __read_mostly = {
615	.handler	= l2tp_ip_recv,
616	.netns_ok	= 1,
617};
618
619static int __init l2tp_ip_init(void)
620{
621	int err;
622
623	pr_info("L2TP IP encapsulation support (L2TPv3)\n");
624
625	err = proto_register(&l2tp_ip_prot, 1);
626	if (err != 0)
627		goto out;
628
629	err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
630	if (err)
631		goto out1;
632
633	inet_register_protosw(&l2tp_ip_protosw);
634	return 0;
635
636out1:
637	proto_unregister(&l2tp_ip_prot);
638out:
639	return err;
640}
641
642static void __exit l2tp_ip_exit(void)
643{
644	inet_unregister_protosw(&l2tp_ip_protosw);
645	inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
646	proto_unregister(&l2tp_ip_prot);
647}
648
649module_init(l2tp_ip_init);
650module_exit(l2tp_ip_exit);
651
652MODULE_LICENSE("GPL");
653MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
654MODULE_DESCRIPTION("L2TP over IP");
655MODULE_VERSION("1.0");
656
657/* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like
658 * enums
659 */
660MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 2, IPPROTO_L2TP);
661