xref: /openbmc/linux/net/netfilter/xt_TPROXY.c (revision e6c81cce)
1 /*
2  * Transparent proxy support for Linux/iptables
3  *
4  * Copyright (c) 2006-2010 BalaBit IT Ltd.
5  * Author: Balazs Scheidler, Krisztian Kovacs
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/module.h>
14 #include <linux/skbuff.h>
15 #include <linux/ip.h>
16 #include <net/checksum.h>
17 #include <net/udp.h>
18 #include <net/tcp.h>
19 #include <net/inet_sock.h>
20 #include <net/inet_hashtables.h>
21 #include <linux/inetdevice.h>
22 #include <linux/netfilter/x_tables.h>
23 #include <linux/netfilter_ipv4/ip_tables.h>
24 
25 #include <net/netfilter/ipv4/nf_defrag_ipv4.h>
26 
27 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
28 #define XT_TPROXY_HAVE_IPV6 1
29 #include <net/if_inet6.h>
30 #include <net/addrconf.h>
31 #include <net/inet6_hashtables.h>
32 #include <linux/netfilter_ipv6/ip6_tables.h>
33 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
34 #endif
35 
36 #include <linux/netfilter/xt_TPROXY.h>
37 
38 enum nf_tproxy_lookup_t {
39 	 NFT_LOOKUP_LISTENER,
40 	 NFT_LOOKUP_ESTABLISHED,
41 };
42 
43 static bool tproxy_sk_is_transparent(struct sock *sk)
44 {
45 	switch (sk->sk_state) {
46 	case TCP_TIME_WAIT:
47 		if (inet_twsk(sk)->tw_transparent)
48 			return true;
49 		break;
50 	case TCP_NEW_SYN_RECV:
51 		if (inet_rsk(inet_reqsk(sk))->no_srccheck)
52 			return true;
53 		break;
54 	default:
55 		if (inet_sk(sk)->transparent)
56 			return true;
57 	}
58 
59 	sock_gen_put(sk);
60 	return false;
61 }
62 
63 static inline __be32
64 tproxy_laddr4(struct sk_buff *skb, __be32 user_laddr, __be32 daddr)
65 {
66 	struct in_device *indev;
67 	__be32 laddr;
68 
69 	if (user_laddr)
70 		return user_laddr;
71 
72 	laddr = 0;
73 	rcu_read_lock();
74 	indev = __in_dev_get_rcu(skb->dev);
75 	for_primary_ifa(indev) {
76 		laddr = ifa->ifa_local;
77 		break;
78 	} endfor_ifa(indev);
79 	rcu_read_unlock();
80 
81 	return laddr ? laddr : daddr;
82 }
83 
84 /*
85  * This is used when the user wants to intercept a connection matching
86  * an explicit iptables rule. In this case the sockets are assumed
87  * matching in preference order:
88  *
89  *   - match: if there's a fully established connection matching the
90  *     _packet_ tuple, it is returned, assuming the redirection
91  *     already took place and we process a packet belonging to an
92  *     established connection
93  *
94  *   - match: if there's a listening socket matching the redirection
95  *     (e.g. on-port & on-ip of the connection), it is returned,
96  *     regardless if it was bound to 0.0.0.0 or an explicit
97  *     address. The reasoning is that if there's an explicit rule, it
98  *     does not really matter if the listener is bound to an interface
99  *     or to 0. The user already stated that he wants redirection
100  *     (since he added the rule).
101  *
102  * Please note that there's an overlap between what a TPROXY target
103  * and a socket match will match. Normally if you have both rules the
104  * "socket" match will be the first one, effectively all packets
105  * belonging to established connections going through that one.
106  */
107 static inline struct sock *
108 nf_tproxy_get_sock_v4(struct net *net, const u8 protocol,
109 		      const __be32 saddr, const __be32 daddr,
110 		      const __be16 sport, const __be16 dport,
111 		      const struct net_device *in,
112 		      const enum nf_tproxy_lookup_t lookup_type)
113 {
114 	struct sock *sk;
115 
116 	switch (protocol) {
117 	case IPPROTO_TCP:
118 		switch (lookup_type) {
119 		case NFT_LOOKUP_LISTENER:
120 			sk = inet_lookup_listener(net, &tcp_hashinfo,
121 						    saddr, sport,
122 						    daddr, dport,
123 						    in->ifindex);
124 
125 			/* NOTE: we return listeners even if bound to
126 			 * 0.0.0.0, those are filtered out in
127 			 * xt_socket, since xt_TPROXY needs 0 bound
128 			 * listeners too
129 			 */
130 			break;
131 		case NFT_LOOKUP_ESTABLISHED:
132 			sk = inet_lookup_established(net, &tcp_hashinfo,
133 						    saddr, sport, daddr, dport,
134 						    in->ifindex);
135 			break;
136 		default:
137 			BUG();
138 		}
139 		break;
140 	case IPPROTO_UDP:
141 		sk = udp4_lib_lookup(net, saddr, sport, daddr, dport,
142 				     in->ifindex);
143 		if (sk) {
144 			int connected = (sk->sk_state == TCP_ESTABLISHED);
145 			int wildcard = (inet_sk(sk)->inet_rcv_saddr == 0);
146 
147 			/* NOTE: we return listeners even if bound to
148 			 * 0.0.0.0, those are filtered out in
149 			 * xt_socket, since xt_TPROXY needs 0 bound
150 			 * listeners too
151 			 */
152 			if ((lookup_type == NFT_LOOKUP_ESTABLISHED && (!connected || wildcard)) ||
153 			    (lookup_type == NFT_LOOKUP_LISTENER && connected)) {
154 				sock_put(sk);
155 				sk = NULL;
156 			}
157 		}
158 		break;
159 	default:
160 		WARN_ON(1);
161 		sk = NULL;
162 	}
163 
164 	pr_debug("tproxy socket lookup: proto %u %08x:%u -> %08x:%u, lookup type: %d, sock %p\n",
165 		 protocol, ntohl(saddr), ntohs(sport), ntohl(daddr), ntohs(dport), lookup_type, sk);
166 
167 	return sk;
168 }
169 
170 #ifdef XT_TPROXY_HAVE_IPV6
171 static inline struct sock *
172 nf_tproxy_get_sock_v6(struct net *net, const u8 protocol,
173 		      const struct in6_addr *saddr, const struct in6_addr *daddr,
174 		      const __be16 sport, const __be16 dport,
175 		      const struct net_device *in,
176 		      const enum nf_tproxy_lookup_t lookup_type)
177 {
178 	struct sock *sk;
179 
180 	switch (protocol) {
181 	case IPPROTO_TCP:
182 		switch (lookup_type) {
183 		case NFT_LOOKUP_LISTENER:
184 			sk = inet6_lookup_listener(net, &tcp_hashinfo,
185 						   saddr, sport,
186 						   daddr, ntohs(dport),
187 						   in->ifindex);
188 
189 			/* NOTE: we return listeners even if bound to
190 			 * 0.0.0.0, those are filtered out in
191 			 * xt_socket, since xt_TPROXY needs 0 bound
192 			 * listeners too
193 			 */
194 			break;
195 		case NFT_LOOKUP_ESTABLISHED:
196 			sk = __inet6_lookup_established(net, &tcp_hashinfo,
197 							saddr, sport, daddr, ntohs(dport),
198 							in->ifindex);
199 			break;
200 		default:
201 			BUG();
202 		}
203 		break;
204 	case IPPROTO_UDP:
205 		sk = udp6_lib_lookup(net, saddr, sport, daddr, dport,
206 				     in->ifindex);
207 		if (sk) {
208 			int connected = (sk->sk_state == TCP_ESTABLISHED);
209 			int wildcard = ipv6_addr_any(&sk->sk_v6_rcv_saddr);
210 
211 			/* NOTE: we return listeners even if bound to
212 			 * 0.0.0.0, those are filtered out in
213 			 * xt_socket, since xt_TPROXY needs 0 bound
214 			 * listeners too
215 			 */
216 			if ((lookup_type == NFT_LOOKUP_ESTABLISHED && (!connected || wildcard)) ||
217 			    (lookup_type == NFT_LOOKUP_LISTENER && connected)) {
218 				sock_put(sk);
219 				sk = NULL;
220 			}
221 		}
222 		break;
223 	default:
224 		WARN_ON(1);
225 		sk = NULL;
226 	}
227 
228 	pr_debug("tproxy socket lookup: proto %u %pI6:%u -> %pI6:%u, lookup type: %d, sock %p\n",
229 		 protocol, saddr, ntohs(sport), daddr, ntohs(dport), lookup_type, sk);
230 
231 	return sk;
232 }
233 #endif
234 
235 /**
236  * tproxy_handle_time_wait4 - handle IPv4 TCP TIME_WAIT reopen redirections
237  * @skb:	The skb being processed.
238  * @laddr:	IPv4 address to redirect to or zero.
239  * @lport:	TCP port to redirect to or zero.
240  * @sk:		The TIME_WAIT TCP socket found by the lookup.
241  *
242  * We have to handle SYN packets arriving to TIME_WAIT sockets
243  * differently: instead of reopening the connection we should rather
244  * redirect the new connection to the proxy if there's a listener
245  * socket present.
246  *
247  * tproxy_handle_time_wait4() consumes the socket reference passed in.
248  *
249  * Returns the listener socket if there's one, the TIME_WAIT socket if
250  * no such listener is found, or NULL if the TCP header is incomplete.
251  */
252 static struct sock *
253 tproxy_handle_time_wait4(struct sk_buff *skb, __be32 laddr, __be16 lport,
254 			struct sock *sk)
255 {
256 	const struct iphdr *iph = ip_hdr(skb);
257 	struct tcphdr _hdr, *hp;
258 
259 	hp = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(_hdr), &_hdr);
260 	if (hp == NULL) {
261 		inet_twsk_put(inet_twsk(sk));
262 		return NULL;
263 	}
264 
265 	if (hp->syn && !hp->rst && !hp->ack && !hp->fin) {
266 		/* SYN to a TIME_WAIT socket, we'd rather redirect it
267 		 * to a listener socket if there's one */
268 		struct sock *sk2;
269 
270 		sk2 = nf_tproxy_get_sock_v4(dev_net(skb->dev), iph->protocol,
271 					    iph->saddr, laddr ? laddr : iph->daddr,
272 					    hp->source, lport ? lport : hp->dest,
273 					    skb->dev, NFT_LOOKUP_LISTENER);
274 		if (sk2) {
275 			inet_twsk_deschedule(inet_twsk(sk));
276 			inet_twsk_put(inet_twsk(sk));
277 			sk = sk2;
278 		}
279 	}
280 
281 	return sk;
282 }
283 
284 /* assign a socket to the skb -- consumes sk */
285 static void
286 nf_tproxy_assign_sock(struct sk_buff *skb, struct sock *sk)
287 {
288 	skb_orphan(skb);
289 	skb->sk = sk;
290 	skb->destructor = sock_edemux;
291 }
292 
293 static unsigned int
294 tproxy_tg4(struct sk_buff *skb, __be32 laddr, __be16 lport,
295 	   u_int32_t mark_mask, u_int32_t mark_value)
296 {
297 	const struct iphdr *iph = ip_hdr(skb);
298 	struct udphdr _hdr, *hp;
299 	struct sock *sk;
300 
301 	hp = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(_hdr), &_hdr);
302 	if (hp == NULL)
303 		return NF_DROP;
304 
305 	/* check if there's an ongoing connection on the packet
306 	 * addresses, this happens if the redirect already happened
307 	 * and the current packet belongs to an already established
308 	 * connection */
309 	sk = nf_tproxy_get_sock_v4(dev_net(skb->dev), iph->protocol,
310 				   iph->saddr, iph->daddr,
311 				   hp->source, hp->dest,
312 				   skb->dev, NFT_LOOKUP_ESTABLISHED);
313 
314 	laddr = tproxy_laddr4(skb, laddr, iph->daddr);
315 	if (!lport)
316 		lport = hp->dest;
317 
318 	/* UDP has no TCP_TIME_WAIT state, so we never enter here */
319 	if (sk && sk->sk_state == TCP_TIME_WAIT)
320 		/* reopening a TIME_WAIT connection needs special handling */
321 		sk = tproxy_handle_time_wait4(skb, laddr, lport, sk);
322 	else if (!sk)
323 		/* no, there's no established connection, check if
324 		 * there's a listener on the redirected addr/port */
325 		sk = nf_tproxy_get_sock_v4(dev_net(skb->dev), iph->protocol,
326 					   iph->saddr, laddr,
327 					   hp->source, lport,
328 					   skb->dev, NFT_LOOKUP_LISTENER);
329 
330 	/* NOTE: assign_sock consumes our sk reference */
331 	if (sk && tproxy_sk_is_transparent(sk)) {
332 		/* This should be in a separate target, but we don't do multiple
333 		   targets on the same rule yet */
334 		skb->mark = (skb->mark & ~mark_mask) ^ mark_value;
335 
336 		pr_debug("redirecting: proto %hhu %pI4:%hu -> %pI4:%hu, mark: %x\n",
337 			 iph->protocol, &iph->daddr, ntohs(hp->dest),
338 			 &laddr, ntohs(lport), skb->mark);
339 
340 		nf_tproxy_assign_sock(skb, sk);
341 		return NF_ACCEPT;
342 	}
343 
344 	pr_debug("no socket, dropping: proto %hhu %pI4:%hu -> %pI4:%hu, mark: %x\n",
345 		 iph->protocol, &iph->saddr, ntohs(hp->source),
346 		 &iph->daddr, ntohs(hp->dest), skb->mark);
347 	return NF_DROP;
348 }
349 
350 static unsigned int
351 tproxy_tg4_v0(struct sk_buff *skb, const struct xt_action_param *par)
352 {
353 	const struct xt_tproxy_target_info *tgi = par->targinfo;
354 
355 	return tproxy_tg4(skb, tgi->laddr, tgi->lport, tgi->mark_mask, tgi->mark_value);
356 }
357 
358 static unsigned int
359 tproxy_tg4_v1(struct sk_buff *skb, const struct xt_action_param *par)
360 {
361 	const struct xt_tproxy_target_info_v1 *tgi = par->targinfo;
362 
363 	return tproxy_tg4(skb, tgi->laddr.ip, tgi->lport, tgi->mark_mask, tgi->mark_value);
364 }
365 
366 #ifdef XT_TPROXY_HAVE_IPV6
367 
368 static inline const struct in6_addr *
369 tproxy_laddr6(struct sk_buff *skb, const struct in6_addr *user_laddr,
370 	      const struct in6_addr *daddr)
371 {
372 	struct inet6_dev *indev;
373 	struct inet6_ifaddr *ifa;
374 	struct in6_addr *laddr;
375 
376 	if (!ipv6_addr_any(user_laddr))
377 		return user_laddr;
378 	laddr = NULL;
379 
380 	rcu_read_lock();
381 	indev = __in6_dev_get(skb->dev);
382 	if (indev)
383 		list_for_each_entry(ifa, &indev->addr_list, if_list) {
384 			if (ifa->flags & (IFA_F_TENTATIVE | IFA_F_DEPRECATED))
385 				continue;
386 
387 			laddr = &ifa->addr;
388 			break;
389 		}
390 	rcu_read_unlock();
391 
392 	return laddr ? laddr : daddr;
393 }
394 
395 /**
396  * tproxy_handle_time_wait6 - handle IPv6 TCP TIME_WAIT reopen redirections
397  * @skb:	The skb being processed.
398  * @tproto:	Transport protocol.
399  * @thoff:	Transport protocol header offset.
400  * @par:	Iptables target parameters.
401  * @sk:		The TIME_WAIT TCP socket found by the lookup.
402  *
403  * We have to handle SYN packets arriving to TIME_WAIT sockets
404  * differently: instead of reopening the connection we should rather
405  * redirect the new connection to the proxy if there's a listener
406  * socket present.
407  *
408  * tproxy_handle_time_wait6() consumes the socket reference passed in.
409  *
410  * Returns the listener socket if there's one, the TIME_WAIT socket if
411  * no such listener is found, or NULL if the TCP header is incomplete.
412  */
413 static struct sock *
414 tproxy_handle_time_wait6(struct sk_buff *skb, int tproto, int thoff,
415 			 const struct xt_action_param *par,
416 			 struct sock *sk)
417 {
418 	const struct ipv6hdr *iph = ipv6_hdr(skb);
419 	struct tcphdr _hdr, *hp;
420 	const struct xt_tproxy_target_info_v1 *tgi = par->targinfo;
421 
422 	hp = skb_header_pointer(skb, thoff, sizeof(_hdr), &_hdr);
423 	if (hp == NULL) {
424 		inet_twsk_put(inet_twsk(sk));
425 		return NULL;
426 	}
427 
428 	if (hp->syn && !hp->rst && !hp->ack && !hp->fin) {
429 		/* SYN to a TIME_WAIT socket, we'd rather redirect it
430 		 * to a listener socket if there's one */
431 		struct sock *sk2;
432 
433 		sk2 = nf_tproxy_get_sock_v6(dev_net(skb->dev), tproto,
434 					    &iph->saddr,
435 					    tproxy_laddr6(skb, &tgi->laddr.in6, &iph->daddr),
436 					    hp->source,
437 					    tgi->lport ? tgi->lport : hp->dest,
438 					    skb->dev, NFT_LOOKUP_LISTENER);
439 		if (sk2) {
440 			inet_twsk_deschedule(inet_twsk(sk));
441 			inet_twsk_put(inet_twsk(sk));
442 			sk = sk2;
443 		}
444 	}
445 
446 	return sk;
447 }
448 
449 static unsigned int
450 tproxy_tg6_v1(struct sk_buff *skb, const struct xt_action_param *par)
451 {
452 	const struct ipv6hdr *iph = ipv6_hdr(skb);
453 	const struct xt_tproxy_target_info_v1 *tgi = par->targinfo;
454 	struct udphdr _hdr, *hp;
455 	struct sock *sk;
456 	const struct in6_addr *laddr;
457 	__be16 lport;
458 	int thoff = 0;
459 	int tproto;
460 
461 	tproto = ipv6_find_hdr(skb, &thoff, -1, NULL, NULL);
462 	if (tproto < 0) {
463 		pr_debug("unable to find transport header in IPv6 packet, dropping\n");
464 		return NF_DROP;
465 	}
466 
467 	hp = skb_header_pointer(skb, thoff, sizeof(_hdr), &_hdr);
468 	if (hp == NULL) {
469 		pr_debug("unable to grab transport header contents in IPv6 packet, dropping\n");
470 		return NF_DROP;
471 	}
472 
473 	/* check if there's an ongoing connection on the packet
474 	 * addresses, this happens if the redirect already happened
475 	 * and the current packet belongs to an already established
476 	 * connection */
477 	sk = nf_tproxy_get_sock_v6(dev_net(skb->dev), tproto,
478 				   &iph->saddr, &iph->daddr,
479 				   hp->source, hp->dest,
480 				   par->in, NFT_LOOKUP_ESTABLISHED);
481 
482 	laddr = tproxy_laddr6(skb, &tgi->laddr.in6, &iph->daddr);
483 	lport = tgi->lport ? tgi->lport : hp->dest;
484 
485 	/* UDP has no TCP_TIME_WAIT state, so we never enter here */
486 	if (sk && sk->sk_state == TCP_TIME_WAIT)
487 		/* reopening a TIME_WAIT connection needs special handling */
488 		sk = tproxy_handle_time_wait6(skb, tproto, thoff, par, sk);
489 	else if (!sk)
490 		/* no there's no established connection, check if
491 		 * there's a listener on the redirected addr/port */
492 		sk = nf_tproxy_get_sock_v6(dev_net(skb->dev), tproto,
493 					   &iph->saddr, laddr,
494 					   hp->source, lport,
495 					   par->in, NFT_LOOKUP_LISTENER);
496 
497 	/* NOTE: assign_sock consumes our sk reference */
498 	if (sk && tproxy_sk_is_transparent(sk)) {
499 		/* This should be in a separate target, but we don't do multiple
500 		   targets on the same rule yet */
501 		skb->mark = (skb->mark & ~tgi->mark_mask) ^ tgi->mark_value;
502 
503 		pr_debug("redirecting: proto %hhu %pI6:%hu -> %pI6:%hu, mark: %x\n",
504 			 tproto, &iph->saddr, ntohs(hp->source),
505 			 laddr, ntohs(lport), skb->mark);
506 
507 		nf_tproxy_assign_sock(skb, sk);
508 		return NF_ACCEPT;
509 	}
510 
511 	pr_debug("no socket, dropping: proto %hhu %pI6:%hu -> %pI6:%hu, mark: %x\n",
512 		 tproto, &iph->saddr, ntohs(hp->source),
513 		 &iph->daddr, ntohs(hp->dest), skb->mark);
514 
515 	return NF_DROP;
516 }
517 
518 static int tproxy_tg6_check(const struct xt_tgchk_param *par)
519 {
520 	const struct ip6t_ip6 *i = par->entryinfo;
521 
522 	if ((i->proto == IPPROTO_TCP || i->proto == IPPROTO_UDP) &&
523 	    !(i->invflags & IP6T_INV_PROTO))
524 		return 0;
525 
526 	pr_info("Can be used only in combination with "
527 		"either -p tcp or -p udp\n");
528 	return -EINVAL;
529 }
530 #endif
531 
532 static int tproxy_tg4_check(const struct xt_tgchk_param *par)
533 {
534 	const struct ipt_ip *i = par->entryinfo;
535 
536 	if ((i->proto == IPPROTO_TCP || i->proto == IPPROTO_UDP)
537 	    && !(i->invflags & IPT_INV_PROTO))
538 		return 0;
539 
540 	pr_info("Can be used only in combination with "
541 		"either -p tcp or -p udp\n");
542 	return -EINVAL;
543 }
544 
545 static struct xt_target tproxy_tg_reg[] __read_mostly = {
546 	{
547 		.name		= "TPROXY",
548 		.family		= NFPROTO_IPV4,
549 		.table		= "mangle",
550 		.target		= tproxy_tg4_v0,
551 		.revision	= 0,
552 		.targetsize	= sizeof(struct xt_tproxy_target_info),
553 		.checkentry	= tproxy_tg4_check,
554 		.hooks		= 1 << NF_INET_PRE_ROUTING,
555 		.me		= THIS_MODULE,
556 	},
557 	{
558 		.name		= "TPROXY",
559 		.family		= NFPROTO_IPV4,
560 		.table		= "mangle",
561 		.target		= tproxy_tg4_v1,
562 		.revision	= 1,
563 		.targetsize	= sizeof(struct xt_tproxy_target_info_v1),
564 		.checkentry	= tproxy_tg4_check,
565 		.hooks		= 1 << NF_INET_PRE_ROUTING,
566 		.me		= THIS_MODULE,
567 	},
568 #ifdef XT_TPROXY_HAVE_IPV6
569 	{
570 		.name		= "TPROXY",
571 		.family		= NFPROTO_IPV6,
572 		.table		= "mangle",
573 		.target		= tproxy_tg6_v1,
574 		.revision	= 1,
575 		.targetsize	= sizeof(struct xt_tproxy_target_info_v1),
576 		.checkentry	= tproxy_tg6_check,
577 		.hooks		= 1 << NF_INET_PRE_ROUTING,
578 		.me		= THIS_MODULE,
579 	},
580 #endif
581 
582 };
583 
584 static int __init tproxy_tg_init(void)
585 {
586 	nf_defrag_ipv4_enable();
587 #ifdef XT_TPROXY_HAVE_IPV6
588 	nf_defrag_ipv6_enable();
589 #endif
590 
591 	return xt_register_targets(tproxy_tg_reg, ARRAY_SIZE(tproxy_tg_reg));
592 }
593 
594 static void __exit tproxy_tg_exit(void)
595 {
596 	xt_unregister_targets(tproxy_tg_reg, ARRAY_SIZE(tproxy_tg_reg));
597 }
598 
599 module_init(tproxy_tg_init);
600 module_exit(tproxy_tg_exit);
601 MODULE_LICENSE("GPL");
602 MODULE_AUTHOR("Balazs Scheidler, Krisztian Kovacs");
603 MODULE_DESCRIPTION("Netfilter transparent proxy (TPROXY) target module.");
604 MODULE_ALIAS("ipt_TPROXY");
605 MODULE_ALIAS("ip6t_TPROXY");
606