1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2007-2008 BalaBit IT Ltd.
4 * Author: Krisztian Kovacs
7 #include <net/netfilter/nf_tproxy.h>
8 #include <linux/module.h>
9 #include <linux/skbuff.h>
11 #include <net/inet_sock.h>
13 #include <net/checksum.h>
16 #include <linux/inetdevice.h>
19 nf_tproxy_handle_time_wait4(struct net *net, struct sk_buff *skb,
20 __be32 laddr, __be16 lport, struct sock *sk)
22 const struct iphdr *iph = ip_hdr(skb);
23 struct tcphdr _hdr, *hp;
25 hp = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(_hdr), &_hdr);
27 inet_twsk_put(inet_twsk(sk));
31 if (hp->syn && !hp->rst && !hp->ack && !hp->fin) {
32 /* SYN to a TIME_WAIT socket, we'd rather redirect it
33 * to a listener socket if there's one */
36 sk2 = nf_tproxy_get_sock_v4(net, skb, iph->protocol,
37 iph->saddr, laddr ? laddr : iph->daddr,
38 hp->source, lport ? lport : hp->dest,
39 skb->dev, NF_TPROXY_LOOKUP_LISTENER);
41 inet_twsk_deschedule_put(inet_twsk(sk));
48 EXPORT_SYMBOL_GPL(nf_tproxy_handle_time_wait4);
50 __be32 nf_tproxy_laddr4(struct sk_buff *skb, __be32 user_laddr, __be32 daddr)
52 struct in_device *indev;
59 indev = __in_dev_get_rcu(skb->dev);
60 for_primary_ifa(indev) {
61 laddr = ifa->ifa_local;
65 return laddr ? laddr : daddr;
67 EXPORT_SYMBOL_GPL(nf_tproxy_laddr4);
70 nf_tproxy_get_sock_v4(struct net *net, struct sk_buff *skb,
72 const __be32 saddr, const __be32 daddr,
73 const __be16 sport, const __be16 dport,
74 const struct net_device *in,
75 const enum nf_tproxy_lookup_t lookup_type)
81 struct tcphdr _hdr, *hp;
83 hp = skb_header_pointer(skb, ip_hdrlen(skb),
84 sizeof(struct tcphdr), &_hdr);
88 switch (lookup_type) {
89 case NF_TPROXY_LOOKUP_LISTENER:
90 sk = inet_lookup_listener(net, &tcp_hashinfo, skb,
97 if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
99 /* NOTE: we return listeners even if bound to
100 * 0.0.0.0, those are filtered out in
101 * xt_socket, since xt_TPROXY needs 0 bound
105 case NF_TPROXY_LOOKUP_ESTABLISHED:
106 sk = inet_lookup_established(net, &tcp_hashinfo,
107 saddr, sport, daddr, dport,
116 sk = udp4_lib_lookup(net, saddr, sport, daddr, dport,
119 int connected = (sk->sk_state == TCP_ESTABLISHED);
120 int wildcard = (inet_sk(sk)->inet_rcv_saddr == 0);
122 /* NOTE: we return listeners even if bound to
123 * 0.0.0.0, those are filtered out in
124 * xt_socket, since xt_TPROXY needs 0 bound
127 if ((lookup_type == NF_TPROXY_LOOKUP_ESTABLISHED &&
128 (!connected || wildcard)) ||
129 (lookup_type == NF_TPROXY_LOOKUP_LISTENER && connected)) {
140 pr_debug("tproxy socket lookup: proto %u %08x:%u -> %08x:%u, lookup type: %d, sock %p\n",
141 protocol, ntohl(saddr), ntohs(sport), ntohl(daddr), ntohs(dport), lookup_type, sk);
145 EXPORT_SYMBOL_GPL(nf_tproxy_get_sock_v4);
147 MODULE_LICENSE("GPL");
148 MODULE_AUTHOR("Balazs Scheidler, Krisztian Kovacs");
149 MODULE_DESCRIPTION("Netfilter IPv4 transparent proxy support");