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 void
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 nf_nat_proto_unique_tuple(tuple, range, maniptype, ct, &tcp_port_rover);
30}
31
32static bool
33tcp_manip_pkt(struct sk_buff *skb,
34 unsigned int iphdroff,
35 const struct nf_conntrack_tuple *tuple,
36 enum nf_nat_manip_type maniptype)
37{
38 const struct iphdr *iph = (struct iphdr *)(skb->data + iphdroff);
39 struct tcphdr *hdr;
40 unsigned int hdroff = iphdroff + iph->ihl*4;
41 __be32 oldip, newip;
42 __be16 *portptr, newport, oldport;
43 int hdrsize = 8;
44
45
46
47
48 if (skb->len >= hdroff + sizeof(struct tcphdr))
49 hdrsize = sizeof(struct tcphdr);
50
51 if (!skb_make_writable(skb, hdroff + hdrsize))
52 return false;
53
54 iph = (struct iphdr *)(skb->data + iphdroff);
55 hdr = (struct tcphdr *)(skb->data + hdroff);
56
57 if (maniptype == IP_NAT_MANIP_SRC) {
58
59 oldip = iph->saddr;
60 newip = tuple->src.u3.ip;
61 newport = tuple->src.u.tcp.port;
62 portptr = &hdr->source;
63 } else {
64
65 oldip = iph->daddr;
66 newip = tuple->dst.u3.ip;
67 newport = tuple->dst.u.tcp.port;
68 portptr = &hdr->dest;
69 }
70
71 oldport = *portptr;
72 *portptr = newport;
73
74 if (hdrsize < sizeof(*hdr))
75 return true;
76
77 inet_proto_csum_replace4(&hdr->check, skb, oldip, newip, 1);
78 inet_proto_csum_replace2(&hdr->check, skb, oldport, newport, 0);
79 return true;
80}
81
82const struct nf_nat_protocol nf_nat_protocol_tcp = {
83 .protonum = IPPROTO_TCP,
84 .me = THIS_MODULE,
85 .manip_pkt = tcp_manip_pkt,
86 .in_range = nf_nat_proto_in_range,
87 .unique_tuple = tcp_unique_tuple,
88#if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
89 .range_to_nlattr = nf_nat_proto_range_to_nlattr,
90 .nlattr_to_range = nf_nat_proto_nlattr_to_range,
91#endif
92};
93