1
2
3
4
5
6
7
8
9#include <linux/types.h>
10#include <linux/init.h>
11#include <linux/ip.h>
12#include <linux/tcp.h>
13
14#include <linux/netfilter.h>
15#include <linux/netfilter/nfnetlink_conntrack.h>
16#include <net/netfilter/nf_nat.h>
17#include <net/netfilter/nf_nat_rule.h>
18#include <net/netfilter/nf_nat_protocol.h>
19#include <net/netfilter/nf_nat_core.h>
20
21static u_int16_t tcp_port_rover;
22
23static bool
24tcp_unique_tuple(struct nf_conntrack_tuple *tuple,
25 const struct nf_nat_range *range,
26 enum nf_nat_manip_type maniptype,
27 const struct nf_conn *ct)
28{
29 return nf_nat_proto_unique_tuple(tuple, range, maniptype, ct,
30 &tcp_port_rover);
31}
32
33static bool
34tcp_manip_pkt(struct sk_buff *skb,
35 unsigned int iphdroff,
36 const struct nf_conntrack_tuple *tuple,
37 enum nf_nat_manip_type maniptype)
38{
39 const struct iphdr *iph = (struct iphdr *)(skb->data + iphdroff);
40 struct tcphdr *hdr;
41 unsigned int hdroff = iphdroff + iph->ihl*4;
42 __be32 oldip, newip;
43 __be16 *portptr, newport, oldport;
44 int hdrsize = 8;
45
46
47
48
49 if (skb->len >= hdroff + sizeof(struct tcphdr))
50 hdrsize = sizeof(struct tcphdr);
51
52 if (!skb_make_writable(skb, hdroff + hdrsize))
53 return false;
54
55 iph = (struct iphdr *)(skb->data + iphdroff);
56 hdr = (struct tcphdr *)(skb->data + hdroff);
57
58 if (maniptype == IP_NAT_MANIP_SRC) {
59
60 oldip = iph->saddr;
61 newip = tuple->src.u3.ip;
62 newport = tuple->src.u.tcp.port;
63 portptr = &hdr->source;
64 } else {
65
66 oldip = iph->daddr;
67 newip = tuple->dst.u3.ip;
68 newport = tuple->dst.u.tcp.port;
69 portptr = &hdr->dest;
70 }
71
72 oldport = *portptr;
73 *portptr = newport;
74
75 if (hdrsize < sizeof(*hdr))
76 return true;
77
78 inet_proto_csum_replace4(&hdr->check, skb, oldip, newip, 1);
79 inet_proto_csum_replace2(&hdr->check, skb, oldport, newport, 0);
80 return true;
81}
82
83const struct nf_nat_protocol nf_nat_protocol_tcp = {
84 .protonum = IPPROTO_TCP,
85 .me = THIS_MODULE,
86 .manip_pkt = tcp_manip_pkt,
87 .in_range = nf_nat_proto_in_range,
88 .unique_tuple = tcp_unique_tuple,
89#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
90 .range_to_nlattr = nf_nat_proto_range_to_nlattr,
91 .nlattr_to_range = nf_nat_proto_nlattr_to_range,
92#endif
93};
94