1 /* NAT for netfilter; shared with compatibility layer. */
3 /* (C) 1999-2001 Paul `Rusty' Russell
4 * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
11 #include <linux/module.h>
12 #include <linux/types.h>
13 #include <linux/timer.h>
14 #include <linux/skbuff.h>
15 #include <linux/netfilter_ipv4.h>
16 #include <linux/vmalloc.h>
17 #include <net/checksum.h>
20 #include <net/tcp.h> /* For tcp_prot in getorigdst */
21 #include <linux/icmp.h>
22 #include <linux/udp.h>
23 #include <linux/jhash.h>
25 #define ASSERT_READ_LOCK(x)
26 #define ASSERT_WRITE_LOCK(x)
28 #include <linux/netfilter_ipv4/ip_conntrack.h>
29 #include <linux/netfilter_ipv4/ip_conntrack_core.h>
30 #include <linux/netfilter_ipv4/ip_conntrack_protocol.h>
31 #include <linux/netfilter_ipv4/ip_nat.h>
32 #include <linux/netfilter_ipv4/ip_nat_protocol.h>
33 #include <linux/netfilter_ipv4/ip_nat_core.h>
34 #include <linux/netfilter_ipv4/ip_nat_helper.h>
35 #include <linux/netfilter_ipv4/ip_conntrack_helper.h>
36 #include <linux/netfilter_ipv4/listhelp.h>
41 #define DEBUGP(format, args...)
44 DEFINE_RWLOCK(ip_nat_lock);
46 /* Calculated at init based on memory size */
47 static unsigned int ip_nat_htable_size;
49 static struct list_head *bysource;
51 #define MAX_IP_NAT_PROTO 256
52 static struct ip_nat_protocol *ip_nat_protos[MAX_IP_NAT_PROTO];
54 static inline struct ip_nat_protocol *
55 __ip_nat_proto_find(u_int8_t protonum)
57 return ip_nat_protos[protonum];
60 struct ip_nat_protocol *
61 ip_nat_proto_find_get(u_int8_t protonum)
63 struct ip_nat_protocol *p;
65 /* we need to disable preemption to make sure 'p' doesn't get
66 * removed until we've grabbed the reference */
68 p = __ip_nat_proto_find(protonum);
69 if (!try_module_get(p->me))
70 p = &ip_nat_unknown_protocol;
75 EXPORT_SYMBOL_GPL(ip_nat_proto_find_get);
78 ip_nat_proto_put(struct ip_nat_protocol *p)
82 EXPORT_SYMBOL_GPL(ip_nat_proto_put);
84 /* We keep an extra hash for each conntrack, for fast searching. */
85 static inline unsigned int
86 hash_by_src(const struct ip_conntrack_tuple *tuple)
88 /* Original src, to ensure we map it consistently if poss. */
89 return jhash_3words(tuple->src.ip, tuple->src.u.all,
90 tuple->dst.protonum, 0) % ip_nat_htable_size;
93 /* Noone using conntrack by the time this called. */
94 static void ip_nat_cleanup_conntrack(struct ip_conntrack *conn)
96 if (!(conn->status & IPS_NAT_DONE_MASK))
99 write_lock_bh(&ip_nat_lock);
100 list_del(&conn->nat.info.bysource);
101 write_unlock_bh(&ip_nat_lock);
104 /* Is this tuple already taken? (not by us) */
106 ip_nat_used_tuple(const struct ip_conntrack_tuple *tuple,
107 const struct ip_conntrack *ignored_conntrack)
109 /* Conntrack tracking doesn't keep track of outgoing tuples; only
110 incoming ones. NAT means they don't have a fixed mapping,
111 so we invert the tuple and look for the incoming reply.
113 We could keep a separate hash if this proves too slow. */
114 struct ip_conntrack_tuple reply;
116 invert_tuplepr(&reply, tuple);
117 return ip_conntrack_tuple_taken(&reply, ignored_conntrack);
119 EXPORT_SYMBOL(ip_nat_used_tuple);
121 /* If we source map this tuple so reply looks like reply_tuple, will
122 * that meet the constraints of range. */
124 in_range(const struct ip_conntrack_tuple *tuple,
125 const struct ip_nat_range *range)
127 struct ip_nat_protocol *proto =
128 __ip_nat_proto_find(tuple->dst.protonum);
130 /* If we are supposed to map IPs, then we must be in the
131 range specified, otherwise let this drag us onto a new src IP. */
132 if (range->flags & IP_NAT_RANGE_MAP_IPS) {
133 if (ntohl(tuple->src.ip) < ntohl(range->min_ip)
134 || ntohl(tuple->src.ip) > ntohl(range->max_ip))
138 if (!(range->flags & IP_NAT_RANGE_PROTO_SPECIFIED)
139 || proto->in_range(tuple, IP_NAT_MANIP_SRC,
140 &range->min, &range->max))
147 same_src(const struct ip_conntrack *ct,
148 const struct ip_conntrack_tuple *tuple)
150 return (ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.protonum
151 == tuple->dst.protonum
152 && ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.ip
154 && ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all
155 == tuple->src.u.all);
158 /* Only called for SRC manip */
160 find_appropriate_src(const struct ip_conntrack_tuple *tuple,
161 struct ip_conntrack_tuple *result,
162 const struct ip_nat_range *range)
164 unsigned int h = hash_by_src(tuple);
165 struct ip_conntrack *ct;
167 read_lock_bh(&ip_nat_lock);
168 list_for_each_entry(ct, &bysource[h], nat.info.bysource) {
169 if (same_src(ct, tuple)) {
170 /* Copy source part from reply tuple. */
171 invert_tuplepr(result,
172 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
173 result->dst = tuple->dst;
175 if (in_range(result, range)) {
176 read_unlock_bh(&ip_nat_lock);
181 read_unlock_bh(&ip_nat_lock);
185 /* For [FUTURE] fragmentation handling, we want the least-used
186 src-ip/dst-ip/proto triple. Fairness doesn't come into it. Thus
187 if the range specifies 1.2.3.4 ports 10000-10005 and 1.2.3.5 ports
188 1-65535, we don't do pro-rata allocation based on ports; we choose
189 the ip with the lowest src-ip/dst-ip/proto usage.
192 find_best_ips_proto(struct ip_conntrack_tuple *tuple,
193 const struct ip_nat_range *range,
194 const struct ip_conntrack *conntrack,
195 enum ip_nat_manip_type maniptype)
199 u_int32_t minip, maxip, j;
201 /* No IP mapping? Do nothing. */
202 if (!(range->flags & IP_NAT_RANGE_MAP_IPS))
205 if (maniptype == IP_NAT_MANIP_SRC)
206 var_ipp = &tuple->src.ip;
208 var_ipp = &tuple->dst.ip;
210 /* Fast path: only one choice. */
211 if (range->min_ip == range->max_ip) {
212 *var_ipp = range->min_ip;
216 /* Hashing source and destination IPs gives a fairly even
217 * spread in practice (if there are a small number of IPs
218 * involved, there usually aren't that many connections
219 * anyway). The consistency means that servers see the same
220 * client coming from the same IP (some Internet Banking sites
221 * like this), even across reboots. */
222 minip = ntohl(range->min_ip);
223 maxip = ntohl(range->max_ip);
224 j = jhash_2words(tuple->src.ip, tuple->dst.ip, 0);
225 *var_ipp = htonl(minip + j % (maxip - minip + 1));
228 /* Manipulate the tuple into the range given. For NF_IP_POST_ROUTING,
229 * we change the source to map into the range. For NF_IP_PRE_ROUTING
230 * and NF_IP_LOCAL_OUT, we change the destination to map into the
231 * range. It might not be possible to get a unique tuple, but we try.
232 * At worst (or if we race), we will end up with a final duplicate in
233 * __ip_conntrack_confirm and drop the packet. */
235 get_unique_tuple(struct ip_conntrack_tuple *tuple,
236 const struct ip_conntrack_tuple *orig_tuple,
237 const struct ip_nat_range *range,
238 struct ip_conntrack *conntrack,
239 enum ip_nat_manip_type maniptype)
241 struct ip_nat_protocol *proto;
243 /* 1) If this srcip/proto/src-proto-part is currently mapped,
244 and that same mapping gives a unique tuple within the given
247 This is only required for source (ie. NAT/masq) mappings.
248 So far, we don't do local source mappings, so multiple
249 manips not an issue. */
250 if (maniptype == IP_NAT_MANIP_SRC) {
251 if (find_appropriate_src(orig_tuple, tuple, range)) {
252 DEBUGP("get_unique_tuple: Found current src map\n");
253 if (!ip_nat_used_tuple(tuple, conntrack))
258 /* 2) Select the least-used IP/proto combination in the given
260 *tuple = *orig_tuple;
261 find_best_ips_proto(tuple, range, conntrack, maniptype);
263 /* 3) The per-protocol part of the manip is made to map into
264 the range to make a unique tuple. */
266 proto = ip_nat_proto_find_get(orig_tuple->dst.protonum);
268 /* Only bother mapping if it's not already in range and unique */
269 if ((!(range->flags & IP_NAT_RANGE_PROTO_SPECIFIED)
270 || proto->in_range(tuple, maniptype, &range->min, &range->max))
271 && !ip_nat_used_tuple(tuple, conntrack)) {
272 ip_nat_proto_put(proto);
276 /* Last change: get protocol to try to obtain unique tuple. */
277 proto->unique_tuple(tuple, range, maniptype, conntrack);
279 ip_nat_proto_put(proto);
283 ip_nat_setup_info(struct ip_conntrack *conntrack,
284 const struct ip_nat_range *range,
285 unsigned int hooknum)
287 struct ip_conntrack_tuple curr_tuple, new_tuple;
288 struct ip_nat_info *info = &conntrack->nat.info;
289 int have_to_hash = !(conntrack->status & IPS_NAT_DONE_MASK);
290 enum ip_nat_manip_type maniptype = HOOK2MANIP(hooknum);
292 IP_NF_ASSERT(hooknum == NF_IP_PRE_ROUTING
293 || hooknum == NF_IP_POST_ROUTING
294 || hooknum == NF_IP_LOCAL_IN
295 || hooknum == NF_IP_LOCAL_OUT);
296 BUG_ON(ip_nat_initialized(conntrack, maniptype));
298 /* What we've got will look like inverse of reply. Normally
299 this is what is in the conntrack, except for prior
300 manipulations (future optimization: if num_manips == 0,
302 conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple) */
303 invert_tuplepr(&curr_tuple,
304 &conntrack->tuplehash[IP_CT_DIR_REPLY].tuple);
306 get_unique_tuple(&new_tuple, &curr_tuple, range, conntrack, maniptype);
308 if (!ip_ct_tuple_equal(&new_tuple, &curr_tuple)) {
309 struct ip_conntrack_tuple reply;
311 /* Alter conntrack table so will recognize replies. */
312 invert_tuplepr(&reply, &new_tuple);
313 ip_conntrack_alter_reply(conntrack, &reply);
315 /* Non-atomic: we own this at the moment. */
316 if (maniptype == IP_NAT_MANIP_SRC)
317 conntrack->status |= IPS_SRC_NAT;
319 conntrack->status |= IPS_DST_NAT;
322 /* Place in source hash if this is the first time. */
325 = hash_by_src(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL]
327 write_lock_bh(&ip_nat_lock);
328 list_add(&info->bysource, &bysource[srchash]);
329 write_unlock_bh(&ip_nat_lock);
333 if (maniptype == IP_NAT_MANIP_DST)
334 set_bit(IPS_DST_NAT_DONE_BIT, &conntrack->status);
336 set_bit(IPS_SRC_NAT_DONE_BIT, &conntrack->status);
340 EXPORT_SYMBOL(ip_nat_setup_info);
342 /* Returns true if succeeded. */
344 manip_pkt(u_int16_t proto,
345 struct sk_buff **pskb,
346 unsigned int iphdroff,
347 const struct ip_conntrack_tuple *target,
348 enum ip_nat_manip_type maniptype)
351 struct ip_nat_protocol *p;
353 if (!skb_make_writable(pskb, iphdroff + sizeof(*iph)))
356 iph = (void *)(*pskb)->data + iphdroff;
358 /* Manipulate protcol part. */
359 p = ip_nat_proto_find_get(proto);
360 if (!p->manip_pkt(pskb, iphdroff, target, maniptype)) {
366 iph = (void *)(*pskb)->data + iphdroff;
368 if (maniptype == IP_NAT_MANIP_SRC) {
369 iph->check = nf_csum_update(~iph->saddr, target->src.ip,
371 iph->saddr = target->src.ip;
373 iph->check = nf_csum_update(~iph->daddr, target->dst.ip,
375 iph->daddr = target->dst.ip;
380 /* Do packet manipulations according to ip_nat_setup_info. */
381 unsigned int ip_nat_packet(struct ip_conntrack *ct,
382 enum ip_conntrack_info ctinfo,
383 unsigned int hooknum,
384 struct sk_buff **pskb)
386 enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
387 unsigned long statusbit;
388 enum ip_nat_manip_type mtype = HOOK2MANIP(hooknum);
390 if (mtype == IP_NAT_MANIP_SRC)
391 statusbit = IPS_SRC_NAT;
393 statusbit = IPS_DST_NAT;
395 /* Invert if this is reply dir. */
396 if (dir == IP_CT_DIR_REPLY)
397 statusbit ^= IPS_NAT_MASK;
399 /* Non-atomic: these bits don't change. */
400 if (ct->status & statusbit) {
401 struct ip_conntrack_tuple target;
403 /* We are aiming to look like inverse of other direction. */
404 invert_tuplepr(&target, &ct->tuplehash[!dir].tuple);
406 if (!manip_pkt(target.dst.protonum, pskb, 0, &target, mtype))
411 EXPORT_SYMBOL_GPL(ip_nat_packet);
413 /* Dir is direction ICMP is coming from (opposite to packet it contains) */
414 int ip_nat_icmp_reply_translation(struct ip_conntrack *ct,
415 enum ip_conntrack_info ctinfo,
416 unsigned int hooknum,
417 struct sk_buff **pskb)
423 struct ip_conntrack_tuple inner, target;
424 int hdrlen = (*pskb)->nh.iph->ihl * 4;
425 enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
426 unsigned long statusbit;
427 enum ip_nat_manip_type manip = HOOK2MANIP(hooknum);
429 if (!skb_make_writable(pskb, hdrlen + sizeof(*inside)))
432 inside = (void *)(*pskb)->data + (*pskb)->nh.iph->ihl*4;
434 /* We're actually going to mangle it beyond trivial checksum
435 adjustment, so make sure the current checksum is correct. */
436 if (nf_ip_checksum(*pskb, hooknum, hdrlen, 0))
439 /* Must be RELATED */
440 IP_NF_ASSERT((*pskb)->nfctinfo == IP_CT_RELATED ||
441 (*pskb)->nfctinfo == IP_CT_RELATED+IP_CT_IS_REPLY);
443 /* Redirects on non-null nats must be dropped, else they'll
444 start talking to each other without our translation, and be
446 if (inside->icmp.type == ICMP_REDIRECT) {
447 /* If NAT isn't finished, assume it and drop. */
448 if ((ct->status & IPS_NAT_DONE_MASK) != IPS_NAT_DONE_MASK)
451 if (ct->status & IPS_NAT_MASK)
455 DEBUGP("icmp_reply_translation: translating error %p manp %u dir %s\n",
456 *pskb, manip, dir == IP_CT_DIR_ORIGINAL ? "ORIG" : "REPLY");
458 if (!ip_ct_get_tuple(&inside->ip, *pskb, (*pskb)->nh.iph->ihl*4 +
459 sizeof(struct icmphdr) + inside->ip.ihl*4,
461 __ip_conntrack_proto_find(inside->ip.protocol)))
464 /* Change inner back to look like incoming packet. We do the
465 opposite manip on this hook to normal, because it might not
466 pass all hooks (locally-generated ICMP). Consider incoming
467 packet: PREROUTING (DST manip), routing produces ICMP, goes
468 through POSTROUTING (which must correct the DST manip). */
469 if (!manip_pkt(inside->ip.protocol, pskb,
470 (*pskb)->nh.iph->ihl*4
471 + sizeof(inside->icmp),
472 &ct->tuplehash[!dir].tuple,
476 if ((*pskb)->ip_summed != CHECKSUM_PARTIAL) {
477 /* Reloading "inside" here since manip_pkt inner. */
478 inside = (void *)(*pskb)->data + (*pskb)->nh.iph->ihl*4;
479 inside->icmp.checksum = 0;
480 inside->icmp.checksum = csum_fold(skb_checksum(*pskb, hdrlen,
481 (*pskb)->len - hdrlen,
485 /* Change outer to look the reply to an incoming packet
486 * (proto 0 means don't invert per-proto part). */
487 if (manip == IP_NAT_MANIP_SRC)
488 statusbit = IPS_SRC_NAT;
490 statusbit = IPS_DST_NAT;
492 /* Invert if this is reply dir. */
493 if (dir == IP_CT_DIR_REPLY)
494 statusbit ^= IPS_NAT_MASK;
496 if (ct->status & statusbit) {
497 invert_tuplepr(&target, &ct->tuplehash[!dir].tuple);
498 if (!manip_pkt(0, pskb, 0, &target, manip))
504 EXPORT_SYMBOL_GPL(ip_nat_icmp_reply_translation);
506 /* Protocol registration. */
507 int ip_nat_protocol_register(struct ip_nat_protocol *proto)
511 write_lock_bh(&ip_nat_lock);
512 if (ip_nat_protos[proto->protonum] != &ip_nat_unknown_protocol) {
516 ip_nat_protos[proto->protonum] = proto;
518 write_unlock_bh(&ip_nat_lock);
521 EXPORT_SYMBOL(ip_nat_protocol_register);
523 /* Noone stores the protocol anywhere; simply delete it. */
524 void ip_nat_protocol_unregister(struct ip_nat_protocol *proto)
526 write_lock_bh(&ip_nat_lock);
527 ip_nat_protos[proto->protonum] = &ip_nat_unknown_protocol;
528 write_unlock_bh(&ip_nat_lock);
530 /* Someone could be still looking at the proto in a bh. */
533 EXPORT_SYMBOL(ip_nat_protocol_unregister);
535 #if defined(CONFIG_IP_NF_CONNTRACK_NETLINK) || \
536 defined(CONFIG_IP_NF_CONNTRACK_NETLINK_MODULE)
538 ip_nat_port_range_to_nfattr(struct sk_buff *skb,
539 const struct ip_nat_range *range)
541 NFA_PUT(skb, CTA_PROTONAT_PORT_MIN, sizeof(u_int16_t),
542 &range->min.tcp.port);
543 NFA_PUT(skb, CTA_PROTONAT_PORT_MAX, sizeof(u_int16_t),
544 &range->max.tcp.port);
553 ip_nat_port_nfattr_to_range(struct nfattr *tb[], struct ip_nat_range *range)
557 /* we have to return whether we actually parsed something or not */
559 if (tb[CTA_PROTONAT_PORT_MIN-1]) {
561 range->min.tcp.port =
562 *(u_int16_t *)NFA_DATA(tb[CTA_PROTONAT_PORT_MIN-1]);
565 if (!tb[CTA_PROTONAT_PORT_MAX-1]) {
567 range->max.tcp.port = range->min.tcp.port;
570 range->max.tcp.port =
571 *(u_int16_t *)NFA_DATA(tb[CTA_PROTONAT_PORT_MAX-1]);
576 EXPORT_SYMBOL_GPL(ip_nat_port_nfattr_to_range);
577 EXPORT_SYMBOL_GPL(ip_nat_port_range_to_nfattr);
580 static int __init ip_nat_init(void)
584 /* Leave them the same for the moment. */
585 ip_nat_htable_size = ip_conntrack_htable_size;
587 /* One vmalloc for both hash tables */
588 bysource = vmalloc(sizeof(struct list_head) * ip_nat_htable_size);
592 /* Sew in builtin protocols. */
593 write_lock_bh(&ip_nat_lock);
594 for (i = 0; i < MAX_IP_NAT_PROTO; i++)
595 ip_nat_protos[i] = &ip_nat_unknown_protocol;
596 ip_nat_protos[IPPROTO_TCP] = &ip_nat_protocol_tcp;
597 ip_nat_protos[IPPROTO_UDP] = &ip_nat_protocol_udp;
598 ip_nat_protos[IPPROTO_ICMP] = &ip_nat_protocol_icmp;
599 write_unlock_bh(&ip_nat_lock);
601 for (i = 0; i < ip_nat_htable_size; i++) {
602 INIT_LIST_HEAD(&bysource[i]);
605 /* FIXME: Man, this is a hack. <SIGH> */
606 IP_NF_ASSERT(ip_conntrack_destroyed == NULL);
607 ip_conntrack_destroyed = &ip_nat_cleanup_conntrack;
609 /* Initialize fake conntrack so that NAT will skip it */
610 ip_conntrack_untracked.status |= IPS_NAT_DONE_MASK;
614 /* Clear NAT section of all conntracks, in case we're loaded again. */
615 static int clean_nat(struct ip_conntrack *i, void *data)
617 memset(&i->nat, 0, sizeof(i->nat));
618 i->status &= ~(IPS_NAT_MASK | IPS_NAT_DONE_MASK | IPS_SEQ_ADJUST);
622 static void __exit ip_nat_cleanup(void)
624 ip_ct_iterate_cleanup(&clean_nat, NULL);
625 ip_conntrack_destroyed = NULL;
629 MODULE_LICENSE("GPL");
631 module_init(ip_nat_init);
632 module_exit(ip_nat_cleanup);