[NETFILTER]: ip_conntrack: properly use RCU for ip_conntrack_destroyed callback
[linux-2.6.22.y-op.git] / net / ipv4 / netfilter / ip_nat_core.c
blob40737fdbe9a73126dd17e59f97371973989c2cfb
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.
9 */
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>
18 #include <net/icmp.h>
19 #include <net/ip.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 #include <linux/netfilter_ipv4/ip_conntrack.h>
26 #include <linux/netfilter_ipv4/ip_conntrack_core.h>
27 #include <linux/netfilter_ipv4/ip_conntrack_protocol.h>
28 #include <linux/netfilter_ipv4/ip_nat.h>
29 #include <linux/netfilter_ipv4/ip_nat_protocol.h>
30 #include <linux/netfilter_ipv4/ip_nat_core.h>
31 #include <linux/netfilter_ipv4/ip_nat_helper.h>
32 #include <linux/netfilter_ipv4/ip_conntrack_helper.h>
34 #if 0
35 #define DEBUGP printk
36 #else
37 #define DEBUGP(format, args...)
38 #endif
40 DEFINE_RWLOCK(ip_nat_lock);
42 /* Calculated at init based on memory size */
43 static unsigned int ip_nat_htable_size;
45 static struct list_head *bysource;
47 #define MAX_IP_NAT_PROTO 256
48 static struct ip_nat_protocol *ip_nat_protos[MAX_IP_NAT_PROTO];
50 static inline struct ip_nat_protocol *
51 __ip_nat_proto_find(u_int8_t protonum)
53 return rcu_dereference(ip_nat_protos[protonum]);
56 struct ip_nat_protocol *
57 ip_nat_proto_find_get(u_int8_t protonum)
59 struct ip_nat_protocol *p;
61 rcu_read_lock();
62 p = __ip_nat_proto_find(protonum);
63 if (!try_module_get(p->me))
64 p = &ip_nat_unknown_protocol;
65 rcu_read_unlock();
67 return p;
69 EXPORT_SYMBOL_GPL(ip_nat_proto_find_get);
71 void
72 ip_nat_proto_put(struct ip_nat_protocol *p)
74 module_put(p->me);
76 EXPORT_SYMBOL_GPL(ip_nat_proto_put);
78 /* We keep an extra hash for each conntrack, for fast searching. */
79 static inline unsigned int
80 hash_by_src(const struct ip_conntrack_tuple *tuple)
82 /* Original src, to ensure we map it consistently if poss. */
83 return jhash_3words((__force u32)tuple->src.ip, tuple->src.u.all,
84 tuple->dst.protonum, 0) % ip_nat_htable_size;
87 /* Noone using conntrack by the time this called. */
88 static void ip_nat_cleanup_conntrack(struct ip_conntrack *conn)
90 if (!(conn->status & IPS_NAT_DONE_MASK))
91 return;
93 write_lock_bh(&ip_nat_lock);
94 list_del(&conn->nat.info.bysource);
95 write_unlock_bh(&ip_nat_lock);
98 /* Is this tuple already taken? (not by us) */
99 int
100 ip_nat_used_tuple(const struct ip_conntrack_tuple *tuple,
101 const struct ip_conntrack *ignored_conntrack)
103 /* Conntrack tracking doesn't keep track of outgoing tuples; only
104 incoming ones. NAT means they don't have a fixed mapping,
105 so we invert the tuple and look for the incoming reply.
107 We could keep a separate hash if this proves too slow. */
108 struct ip_conntrack_tuple reply;
110 invert_tuplepr(&reply, tuple);
111 return ip_conntrack_tuple_taken(&reply, ignored_conntrack);
113 EXPORT_SYMBOL(ip_nat_used_tuple);
115 /* If we source map this tuple so reply looks like reply_tuple, will
116 * that meet the constraints of range. */
117 static int
118 in_range(const struct ip_conntrack_tuple *tuple,
119 const struct ip_nat_range *range)
121 struct ip_nat_protocol *proto;
122 int ret = 0;
124 /* If we are supposed to map IPs, then we must be in the
125 range specified, otherwise let this drag us onto a new src IP. */
126 if (range->flags & IP_NAT_RANGE_MAP_IPS) {
127 if (ntohl(tuple->src.ip) < ntohl(range->min_ip)
128 || ntohl(tuple->src.ip) > ntohl(range->max_ip))
129 return 0;
132 rcu_read_lock();
133 proto = __ip_nat_proto_find(tuple->dst.protonum);
134 if (!(range->flags & IP_NAT_RANGE_PROTO_SPECIFIED)
135 || proto->in_range(tuple, IP_NAT_MANIP_SRC,
136 &range->min, &range->max))
137 ret = 1;
138 rcu_read_unlock();
140 return ret;
143 static inline int
144 same_src(const struct ip_conntrack *ct,
145 const struct ip_conntrack_tuple *tuple)
147 return (ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.protonum
148 == tuple->dst.protonum
149 && ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.ip
150 == tuple->src.ip
151 && ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all
152 == tuple->src.u.all);
155 /* Only called for SRC manip */
156 static int
157 find_appropriate_src(const struct ip_conntrack_tuple *tuple,
158 struct ip_conntrack_tuple *result,
159 const struct ip_nat_range *range)
161 unsigned int h = hash_by_src(tuple);
162 struct ip_conntrack *ct;
164 read_lock_bh(&ip_nat_lock);
165 list_for_each_entry(ct, &bysource[h], nat.info.bysource) {
166 if (same_src(ct, tuple)) {
167 /* Copy source part from reply tuple. */
168 invert_tuplepr(result,
169 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
170 result->dst = tuple->dst;
172 if (in_range(result, range)) {
173 read_unlock_bh(&ip_nat_lock);
174 return 1;
178 read_unlock_bh(&ip_nat_lock);
179 return 0;
182 /* For [FUTURE] fragmentation handling, we want the least-used
183 src-ip/dst-ip/proto triple. Fairness doesn't come into it. Thus
184 if the range specifies 1.2.3.4 ports 10000-10005 and 1.2.3.5 ports
185 1-65535, we don't do pro-rata allocation based on ports; we choose
186 the ip with the lowest src-ip/dst-ip/proto usage.
188 static void
189 find_best_ips_proto(struct ip_conntrack_tuple *tuple,
190 const struct ip_nat_range *range,
191 const struct ip_conntrack *conntrack,
192 enum ip_nat_manip_type maniptype)
194 __be32 *var_ipp;
195 /* Host order */
196 u_int32_t minip, maxip, j;
198 /* No IP mapping? Do nothing. */
199 if (!(range->flags & IP_NAT_RANGE_MAP_IPS))
200 return;
202 if (maniptype == IP_NAT_MANIP_SRC)
203 var_ipp = &tuple->src.ip;
204 else
205 var_ipp = &tuple->dst.ip;
207 /* Fast path: only one choice. */
208 if (range->min_ip == range->max_ip) {
209 *var_ipp = range->min_ip;
210 return;
213 /* Hashing source and destination IPs gives a fairly even
214 * spread in practice (if there are a small number of IPs
215 * involved, there usually aren't that many connections
216 * anyway). The consistency means that servers see the same
217 * client coming from the same IP (some Internet Banking sites
218 * like this), even across reboots. */
219 minip = ntohl(range->min_ip);
220 maxip = ntohl(range->max_ip);
221 j = jhash_2words((__force u32)tuple->src.ip, (__force u32)tuple->dst.ip, 0);
222 *var_ipp = htonl(minip + j % (maxip - minip + 1));
225 /* Manipulate the tuple into the range given. For NF_IP_POST_ROUTING,
226 * we change the source to map into the range. For NF_IP_PRE_ROUTING
227 * and NF_IP_LOCAL_OUT, we change the destination to map into the
228 * range. It might not be possible to get a unique tuple, but we try.
229 * At worst (or if we race), we will end up with a final duplicate in
230 * __ip_conntrack_confirm and drop the packet. */
231 static void
232 get_unique_tuple(struct ip_conntrack_tuple *tuple,
233 const struct ip_conntrack_tuple *orig_tuple,
234 const struct ip_nat_range *range,
235 struct ip_conntrack *conntrack,
236 enum ip_nat_manip_type maniptype)
238 struct ip_nat_protocol *proto;
240 /* 1) If this srcip/proto/src-proto-part is currently mapped,
241 and that same mapping gives a unique tuple within the given
242 range, use that.
244 This is only required for source (ie. NAT/masq) mappings.
245 So far, we don't do local source mappings, so multiple
246 manips not an issue. */
247 if (maniptype == IP_NAT_MANIP_SRC) {
248 if (find_appropriate_src(orig_tuple, tuple, range)) {
249 DEBUGP("get_unique_tuple: Found current src map\n");
250 if (!(range->flags & IP_NAT_RANGE_PROTO_RANDOM))
251 if (!ip_nat_used_tuple(tuple, conntrack))
252 return;
256 /* 2) Select the least-used IP/proto combination in the given
257 range. */
258 *tuple = *orig_tuple;
259 find_best_ips_proto(tuple, range, conntrack, maniptype);
261 /* 3) The per-protocol part of the manip is made to map into
262 the range to make a unique tuple. */
264 rcu_read_lock();
265 proto = __ip_nat_proto_find(orig_tuple->dst.protonum);
267 /* Change protocol info to have some randomization */
268 if (range->flags & IP_NAT_RANGE_PROTO_RANDOM) {
269 proto->unique_tuple(tuple, range, maniptype, conntrack);
270 goto out;
273 /* Only bother mapping if it's not already in range and unique */
274 if ((!(range->flags & IP_NAT_RANGE_PROTO_SPECIFIED)
275 || proto->in_range(tuple, maniptype, &range->min, &range->max))
276 && !ip_nat_used_tuple(tuple, conntrack))
277 goto out;
279 /* Last change: get protocol to try to obtain unique tuple. */
280 proto->unique_tuple(tuple, range, maniptype, conntrack);
281 out:
282 rcu_read_unlock();
285 unsigned int
286 ip_nat_setup_info(struct ip_conntrack *conntrack,
287 const struct ip_nat_range *range,
288 unsigned int hooknum)
290 struct ip_conntrack_tuple curr_tuple, new_tuple;
291 struct ip_nat_info *info = &conntrack->nat.info;
292 int have_to_hash = !(conntrack->status & IPS_NAT_DONE_MASK);
293 enum ip_nat_manip_type maniptype = HOOK2MANIP(hooknum);
295 IP_NF_ASSERT(hooknum == NF_IP_PRE_ROUTING
296 || hooknum == NF_IP_POST_ROUTING
297 || hooknum == NF_IP_LOCAL_IN
298 || hooknum == NF_IP_LOCAL_OUT);
299 BUG_ON(ip_nat_initialized(conntrack, maniptype));
301 /* What we've got will look like inverse of reply. Normally
302 this is what is in the conntrack, except for prior
303 manipulations (future optimization: if num_manips == 0,
304 orig_tp =
305 conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple) */
306 invert_tuplepr(&curr_tuple,
307 &conntrack->tuplehash[IP_CT_DIR_REPLY].tuple);
309 get_unique_tuple(&new_tuple, &curr_tuple, range, conntrack, maniptype);
311 if (!ip_ct_tuple_equal(&new_tuple, &curr_tuple)) {
312 struct ip_conntrack_tuple reply;
314 /* Alter conntrack table so will recognize replies. */
315 invert_tuplepr(&reply, &new_tuple);
316 ip_conntrack_alter_reply(conntrack, &reply);
318 /* Non-atomic: we own this at the moment. */
319 if (maniptype == IP_NAT_MANIP_SRC)
320 conntrack->status |= IPS_SRC_NAT;
321 else
322 conntrack->status |= IPS_DST_NAT;
325 /* Place in source hash if this is the first time. */
326 if (have_to_hash) {
327 unsigned int srchash
328 = hash_by_src(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL]
329 .tuple);
330 write_lock_bh(&ip_nat_lock);
331 list_add(&info->bysource, &bysource[srchash]);
332 write_unlock_bh(&ip_nat_lock);
335 /* It's done. */
336 if (maniptype == IP_NAT_MANIP_DST)
337 set_bit(IPS_DST_NAT_DONE_BIT, &conntrack->status);
338 else
339 set_bit(IPS_SRC_NAT_DONE_BIT, &conntrack->status);
341 return NF_ACCEPT;
343 EXPORT_SYMBOL(ip_nat_setup_info);
345 /* Returns true if succeeded. */
346 static int
347 manip_pkt(u_int16_t proto,
348 struct sk_buff **pskb,
349 unsigned int iphdroff,
350 const struct ip_conntrack_tuple *target,
351 enum ip_nat_manip_type maniptype)
353 struct iphdr *iph;
354 struct ip_nat_protocol *p;
356 if (!skb_make_writable(pskb, iphdroff + sizeof(*iph)))
357 return 0;
359 iph = (void *)(*pskb)->data + iphdroff;
361 /* Manipulate protcol part. */
363 /* rcu_read_lock()ed by nf_hook_slow */
364 p = __ip_nat_proto_find(proto);
365 if (!p->manip_pkt(pskb, iphdroff, target, maniptype))
366 return 0;
368 iph = (void *)(*pskb)->data + iphdroff;
370 if (maniptype == IP_NAT_MANIP_SRC) {
371 nf_csum_replace4(&iph->check, iph->saddr, target->src.ip);
372 iph->saddr = target->src.ip;
373 } else {
374 nf_csum_replace4(&iph->check, iph->daddr, target->dst.ip);
375 iph->daddr = target->dst.ip;
377 return 1;
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;
392 else
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))
407 return NF_DROP;
409 return NF_ACCEPT;
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)
419 struct {
420 struct icmphdr icmp;
421 struct iphdr ip;
422 } *inside;
423 struct ip_conntrack_protocol *proto;
424 struct ip_conntrack_tuple inner, target;
425 int hdrlen = (*pskb)->nh.iph->ihl * 4;
426 enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
427 unsigned long statusbit;
428 enum ip_nat_manip_type manip = HOOK2MANIP(hooknum);
430 if (!skb_make_writable(pskb, hdrlen + sizeof(*inside)))
431 return 0;
433 inside = (void *)(*pskb)->data + (*pskb)->nh.iph->ihl*4;
435 /* We're actually going to mangle it beyond trivial checksum
436 adjustment, so make sure the current checksum is correct. */
437 if (nf_ip_checksum(*pskb, hooknum, hdrlen, 0))
438 return 0;
440 /* Must be RELATED */
441 IP_NF_ASSERT((*pskb)->nfctinfo == IP_CT_RELATED ||
442 (*pskb)->nfctinfo == IP_CT_RELATED+IP_CT_IS_REPLY);
444 /* Redirects on non-null nats must be dropped, else they'll
445 start talking to each other without our translation, and be
446 confused... --RR */
447 if (inside->icmp.type == ICMP_REDIRECT) {
448 /* If NAT isn't finished, assume it and drop. */
449 if ((ct->status & IPS_NAT_DONE_MASK) != IPS_NAT_DONE_MASK)
450 return 0;
452 if (ct->status & IPS_NAT_MASK)
453 return 0;
456 DEBUGP("icmp_reply_translation: translating error %p manp %u dir %s\n",
457 *pskb, manip, dir == IP_CT_DIR_ORIGINAL ? "ORIG" : "REPLY");
459 /* rcu_read_lock()ed by nf_hook_slow */
460 proto = __ip_conntrack_proto_find(inside->ip.protocol);
461 if (!ip_ct_get_tuple(&inside->ip, *pskb, (*pskb)->nh.iph->ihl*4 +
462 sizeof(struct icmphdr) + inside->ip.ihl*4,
463 &inner, proto))
464 return 0;
466 /* Change inner back to look like incoming packet. We do the
467 opposite manip on this hook to normal, because it might not
468 pass all hooks (locally-generated ICMP). Consider incoming
469 packet: PREROUTING (DST manip), routing produces ICMP, goes
470 through POSTROUTING (which must correct the DST manip). */
471 if (!manip_pkt(inside->ip.protocol, pskb,
472 (*pskb)->nh.iph->ihl*4
473 + sizeof(inside->icmp),
474 &ct->tuplehash[!dir].tuple,
475 !manip))
476 return 0;
478 if ((*pskb)->ip_summed != CHECKSUM_PARTIAL) {
479 /* Reloading "inside" here since manip_pkt inner. */
480 inside = (void *)(*pskb)->data + (*pskb)->nh.iph->ihl*4;
481 inside->icmp.checksum = 0;
482 inside->icmp.checksum = csum_fold(skb_checksum(*pskb, hdrlen,
483 (*pskb)->len - hdrlen,
484 0));
487 /* Change outer to look the reply to an incoming packet
488 * (proto 0 means don't invert per-proto part). */
489 if (manip == IP_NAT_MANIP_SRC)
490 statusbit = IPS_SRC_NAT;
491 else
492 statusbit = IPS_DST_NAT;
494 /* Invert if this is reply dir. */
495 if (dir == IP_CT_DIR_REPLY)
496 statusbit ^= IPS_NAT_MASK;
498 if (ct->status & statusbit) {
499 invert_tuplepr(&target, &ct->tuplehash[!dir].tuple);
500 if (!manip_pkt(0, pskb, 0, &target, manip))
501 return 0;
504 return 1;
506 EXPORT_SYMBOL_GPL(ip_nat_icmp_reply_translation);
508 /* Protocol registration. */
509 int ip_nat_protocol_register(struct ip_nat_protocol *proto)
511 int ret = 0;
513 write_lock_bh(&ip_nat_lock);
514 if (ip_nat_protos[proto->protonum] != &ip_nat_unknown_protocol) {
515 ret = -EBUSY;
516 goto out;
518 rcu_assign_pointer(ip_nat_protos[proto->protonum], proto);
519 out:
520 write_unlock_bh(&ip_nat_lock);
521 return ret;
523 EXPORT_SYMBOL(ip_nat_protocol_register);
525 /* Noone stores the protocol anywhere; simply delete it. */
526 void ip_nat_protocol_unregister(struct ip_nat_protocol *proto)
528 write_lock_bh(&ip_nat_lock);
529 rcu_assign_pointer(ip_nat_protos[proto->protonum],
530 &ip_nat_unknown_protocol);
531 write_unlock_bh(&ip_nat_lock);
532 synchronize_rcu();
534 EXPORT_SYMBOL(ip_nat_protocol_unregister);
536 #if defined(CONFIG_IP_NF_CONNTRACK_NETLINK) || \
537 defined(CONFIG_IP_NF_CONNTRACK_NETLINK_MODULE)
539 ip_nat_port_range_to_nfattr(struct sk_buff *skb,
540 const struct ip_nat_range *range)
542 NFA_PUT(skb, CTA_PROTONAT_PORT_MIN, sizeof(__be16),
543 &range->min.tcp.port);
544 NFA_PUT(skb, CTA_PROTONAT_PORT_MAX, sizeof(__be16),
545 &range->max.tcp.port);
547 return 0;
549 nfattr_failure:
550 return -1;
554 ip_nat_port_nfattr_to_range(struct nfattr *tb[], struct ip_nat_range *range)
556 int ret = 0;
558 /* we have to return whether we actually parsed something or not */
560 if (tb[CTA_PROTONAT_PORT_MIN-1]) {
561 ret = 1;
562 range->min.tcp.port =
563 *(__be16 *)NFA_DATA(tb[CTA_PROTONAT_PORT_MIN-1]);
566 if (!tb[CTA_PROTONAT_PORT_MAX-1]) {
567 if (ret)
568 range->max.tcp.port = range->min.tcp.port;
569 } else {
570 ret = 1;
571 range->max.tcp.port =
572 *(__be16 *)NFA_DATA(tb[CTA_PROTONAT_PORT_MAX-1]);
575 return ret;
577 EXPORT_SYMBOL_GPL(ip_nat_port_nfattr_to_range);
578 EXPORT_SYMBOL_GPL(ip_nat_port_range_to_nfattr);
579 #endif
581 static int __init ip_nat_init(void)
583 size_t i;
585 /* Leave them the same for the moment. */
586 ip_nat_htable_size = ip_conntrack_htable_size;
588 /* One vmalloc for both hash tables */
589 bysource = vmalloc(sizeof(struct list_head) * ip_nat_htable_size);
590 if (!bysource)
591 return -ENOMEM;
593 /* Sew in builtin protocols. */
594 write_lock_bh(&ip_nat_lock);
595 for (i = 0; i < MAX_IP_NAT_PROTO; i++)
596 rcu_assign_pointer(ip_nat_protos[i], &ip_nat_unknown_protocol);
597 rcu_assign_pointer(ip_nat_protos[IPPROTO_TCP], &ip_nat_protocol_tcp);
598 rcu_assign_pointer(ip_nat_protos[IPPROTO_UDP], &ip_nat_protocol_udp);
599 rcu_assign_pointer(ip_nat_protos[IPPROTO_ICMP], &ip_nat_protocol_icmp);
600 write_unlock_bh(&ip_nat_lock);
602 for (i = 0; i < ip_nat_htable_size; i++) {
603 INIT_LIST_HEAD(&bysource[i]);
606 /* FIXME: Man, this is a hack. <SIGH> */
607 IP_NF_ASSERT(rcu_dereference(ip_conntrack_destroyed) == NULL);
608 rcu_assign_pointer(ip_conntrack_destroyed, ip_nat_cleanup_conntrack);
610 /* Initialize fake conntrack so that NAT will skip it */
611 ip_conntrack_untracked.status |= IPS_NAT_DONE_MASK;
612 return 0;
615 /* Clear NAT section of all conntracks, in case we're loaded again. */
616 static int clean_nat(struct ip_conntrack *i, void *data)
618 memset(&i->nat, 0, sizeof(i->nat));
619 i->status &= ~(IPS_NAT_MASK | IPS_NAT_DONE_MASK | IPS_SEQ_ADJUST);
620 return 0;
623 static void __exit ip_nat_cleanup(void)
625 ip_ct_iterate_cleanup(&clean_nat, NULL);
626 rcu_assign_pointer(ip_conntrack_destroyed, NULL);
627 synchronize_rcu();
628 vfree(bysource);
631 MODULE_LICENSE("GPL");
633 module_init(ip_nat_init);
634 module_exit(ip_nat_cleanup);