2268b10a9dcf844b8ce9d8d43c6b32e943553496
[linux-2.6-microblaze.git] / net / netfilter / nf_nat_core.c
1 /*
2  * (C) 1999-2001 Paul `Rusty' Russell
3  * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
4  * (C) 2011 Patrick McHardy <kaber@trash.net>
5  *
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  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/module.h>
14 #include <linux/types.h>
15 #include <linux/timer.h>
16 #include <linux/skbuff.h>
17 #include <linux/gfp.h>
18 #include <net/xfrm.h>
19 #include <linux/jhash.h>
20 #include <linux/rtnetlink.h>
21
22 #include <net/netfilter/nf_conntrack.h>
23 #include <net/netfilter/nf_conntrack_core.h>
24 #include <net/netfilter/nf_nat.h>
25 #include <net/netfilter/nf_nat_l3proto.h>
26 #include <net/netfilter/nf_nat_l4proto.h>
27 #include <net/netfilter/nf_nat_core.h>
28 #include <net/netfilter/nf_nat_helper.h>
29 #include <net/netfilter/nf_conntrack_helper.h>
30 #include <net/netfilter/nf_conntrack_seqadj.h>
31 #include <net/netfilter/nf_conntrack_zones.h>
32 #include <linux/netfilter/nf_nat.h>
33
34 #include "nf_internals.h"
35
36 static spinlock_t nf_nat_locks[CONNTRACK_LOCKS];
37
38 static DEFINE_MUTEX(nf_nat_proto_mutex);
39 static const struct nf_nat_l3proto __rcu *nf_nat_l3protos[NFPROTO_NUMPROTO]
40                                                 __read_mostly;
41 static const struct nf_nat_l4proto __rcu **nf_nat_l4protos[NFPROTO_NUMPROTO]
42                                                 __read_mostly;
43 static unsigned int nat_net_id __read_mostly;
44
45 static struct hlist_head *nf_nat_bysource __read_mostly;
46 static unsigned int nf_nat_htable_size __read_mostly;
47 static unsigned int nf_nat_hash_rnd __read_mostly;
48
49 struct nf_nat_lookup_hook_priv {
50         struct nf_hook_entries __rcu *entries;
51
52         struct rcu_head rcu_head;
53 };
54
55 struct nf_nat_hooks_net {
56         struct nf_hook_ops *nat_hook_ops;
57         unsigned int users;
58 };
59
60 struct nat_net {
61         struct nf_nat_hooks_net nat_proto_net[NFPROTO_NUMPROTO];
62 };
63
64 inline const struct nf_nat_l3proto *
65 __nf_nat_l3proto_find(u8 family)
66 {
67         return rcu_dereference(nf_nat_l3protos[family]);
68 }
69
70 inline const struct nf_nat_l4proto *
71 __nf_nat_l4proto_find(u8 family, u8 protonum)
72 {
73         return rcu_dereference(nf_nat_l4protos[family][protonum]);
74 }
75 EXPORT_SYMBOL_GPL(__nf_nat_l4proto_find);
76
77 #ifdef CONFIG_XFRM
78 static void __nf_nat_decode_session(struct sk_buff *skb, struct flowi *fl)
79 {
80         const struct nf_nat_l3proto *l3proto;
81         const struct nf_conn *ct;
82         enum ip_conntrack_info ctinfo;
83         enum ip_conntrack_dir dir;
84         unsigned  long statusbit;
85         u8 family;
86
87         ct = nf_ct_get(skb, &ctinfo);
88         if (ct == NULL)
89                 return;
90
91         family = nf_ct_l3num(ct);
92         l3proto = __nf_nat_l3proto_find(family);
93         if (l3proto == NULL)
94                 return;
95
96         dir = CTINFO2DIR(ctinfo);
97         if (dir == IP_CT_DIR_ORIGINAL)
98                 statusbit = IPS_DST_NAT;
99         else
100                 statusbit = IPS_SRC_NAT;
101
102         l3proto->decode_session(skb, ct, dir, statusbit, fl);
103 }
104
105 int nf_xfrm_me_harder(struct net *net, struct sk_buff *skb, unsigned int family)
106 {
107         struct flowi fl;
108         unsigned int hh_len;
109         struct dst_entry *dst;
110         struct sock *sk = skb->sk;
111         int err;
112
113         err = xfrm_decode_session(skb, &fl, family);
114         if (err < 0)
115                 return err;
116
117         dst = skb_dst(skb);
118         if (dst->xfrm)
119                 dst = ((struct xfrm_dst *)dst)->route;
120         if (!dst_hold_safe(dst))
121                 return -EHOSTUNREACH;
122
123         if (sk && !net_eq(net, sock_net(sk)))
124                 sk = NULL;
125
126         dst = xfrm_lookup(net, dst, &fl, sk, 0);
127         if (IS_ERR(dst))
128                 return PTR_ERR(dst);
129
130         skb_dst_drop(skb);
131         skb_dst_set(skb, dst);
132
133         /* Change in oif may mean change in hh_len. */
134         hh_len = skb_dst(skb)->dev->hard_header_len;
135         if (skb_headroom(skb) < hh_len &&
136             pskb_expand_head(skb, hh_len - skb_headroom(skb), 0, GFP_ATOMIC))
137                 return -ENOMEM;
138         return 0;
139 }
140 EXPORT_SYMBOL(nf_xfrm_me_harder);
141 #endif /* CONFIG_XFRM */
142
143 /* We keep an extra hash for each conntrack, for fast searching. */
144 static unsigned int
145 hash_by_src(const struct net *n, const struct nf_conntrack_tuple *tuple)
146 {
147         unsigned int hash;
148
149         get_random_once(&nf_nat_hash_rnd, sizeof(nf_nat_hash_rnd));
150
151         /* Original src, to ensure we map it consistently if poss. */
152         hash = jhash2((u32 *)&tuple->src, sizeof(tuple->src) / sizeof(u32),
153                       tuple->dst.protonum ^ nf_nat_hash_rnd ^ net_hash_mix(n));
154
155         return reciprocal_scale(hash, nf_nat_htable_size);
156 }
157
158 /* Is this tuple already taken? (not by us) */
159 int
160 nf_nat_used_tuple(const struct nf_conntrack_tuple *tuple,
161                   const struct nf_conn *ignored_conntrack)
162 {
163         /* Conntrack tracking doesn't keep track of outgoing tuples; only
164          * incoming ones.  NAT means they don't have a fixed mapping,
165          * so we invert the tuple and look for the incoming reply.
166          *
167          * We could keep a separate hash if this proves too slow.
168          */
169         struct nf_conntrack_tuple reply;
170
171         nf_ct_invert_tuplepr(&reply, tuple);
172         return nf_conntrack_tuple_taken(&reply, ignored_conntrack);
173 }
174 EXPORT_SYMBOL(nf_nat_used_tuple);
175
176 /* If we source map this tuple so reply looks like reply_tuple, will
177  * that meet the constraints of range.
178  */
179 static int in_range(const struct nf_nat_l3proto *l3proto,
180                     const struct nf_nat_l4proto *l4proto,
181                     const struct nf_conntrack_tuple *tuple,
182                     const struct nf_nat_range2 *range)
183 {
184         /* If we are supposed to map IPs, then we must be in the
185          * range specified, otherwise let this drag us onto a new src IP.
186          */
187         if (range->flags & NF_NAT_RANGE_MAP_IPS &&
188             !l3proto->in_range(tuple, range))
189                 return 0;
190
191         if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) ||
192             l4proto->in_range(tuple, NF_NAT_MANIP_SRC,
193                               &range->min_proto, &range->max_proto))
194                 return 1;
195
196         return 0;
197 }
198
199 static inline int
200 same_src(const struct nf_conn *ct,
201          const struct nf_conntrack_tuple *tuple)
202 {
203         const struct nf_conntrack_tuple *t;
204
205         t = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
206         return (t->dst.protonum == tuple->dst.protonum &&
207                 nf_inet_addr_cmp(&t->src.u3, &tuple->src.u3) &&
208                 t->src.u.all == tuple->src.u.all);
209 }
210
211 /* Only called for SRC manip */
212 static int
213 find_appropriate_src(struct net *net,
214                      const struct nf_conntrack_zone *zone,
215                      const struct nf_nat_l3proto *l3proto,
216                      const struct nf_nat_l4proto *l4proto,
217                      const struct nf_conntrack_tuple *tuple,
218                      struct nf_conntrack_tuple *result,
219                      const struct nf_nat_range2 *range)
220 {
221         unsigned int h = hash_by_src(net, tuple);
222         const struct nf_conn *ct;
223
224         hlist_for_each_entry_rcu(ct, &nf_nat_bysource[h], nat_bysource) {
225                 if (same_src(ct, tuple) &&
226                     net_eq(net, nf_ct_net(ct)) &&
227                     nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL)) {
228                         /* Copy source part from reply tuple. */
229                         nf_ct_invert_tuplepr(result,
230                                        &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
231                         result->dst = tuple->dst;
232
233                         if (in_range(l3proto, l4proto, result, range))
234                                 return 1;
235                 }
236         }
237         return 0;
238 }
239
240 /* For [FUTURE] fragmentation handling, we want the least-used
241  * src-ip/dst-ip/proto triple.  Fairness doesn't come into it.  Thus
242  * if the range specifies 1.2.3.4 ports 10000-10005 and 1.2.3.5 ports
243  * 1-65535, we don't do pro-rata allocation based on ports; we choose
244  * the ip with the lowest src-ip/dst-ip/proto usage.
245  */
246 static void
247 find_best_ips_proto(const struct nf_conntrack_zone *zone,
248                     struct nf_conntrack_tuple *tuple,
249                     const struct nf_nat_range2 *range,
250                     const struct nf_conn *ct,
251                     enum nf_nat_manip_type maniptype)
252 {
253         union nf_inet_addr *var_ipp;
254         unsigned int i, max;
255         /* Host order */
256         u32 minip, maxip, j, dist;
257         bool full_range;
258
259         /* No IP mapping?  Do nothing. */
260         if (!(range->flags & NF_NAT_RANGE_MAP_IPS))
261                 return;
262
263         if (maniptype == NF_NAT_MANIP_SRC)
264                 var_ipp = &tuple->src.u3;
265         else
266                 var_ipp = &tuple->dst.u3;
267
268         /* Fast path: only one choice. */
269         if (nf_inet_addr_cmp(&range->min_addr, &range->max_addr)) {
270                 *var_ipp = range->min_addr;
271                 return;
272         }
273
274         if (nf_ct_l3num(ct) == NFPROTO_IPV4)
275                 max = sizeof(var_ipp->ip) / sizeof(u32) - 1;
276         else
277                 max = sizeof(var_ipp->ip6) / sizeof(u32) - 1;
278
279         /* Hashing source and destination IPs gives a fairly even
280          * spread in practice (if there are a small number of IPs
281          * involved, there usually aren't that many connections
282          * anyway).  The consistency means that servers see the same
283          * client coming from the same IP (some Internet Banking sites
284          * like this), even across reboots.
285          */
286         j = jhash2((u32 *)&tuple->src.u3, sizeof(tuple->src.u3) / sizeof(u32),
287                    range->flags & NF_NAT_RANGE_PERSISTENT ?
288                         0 : (__force u32)tuple->dst.u3.all[max] ^ zone->id);
289
290         full_range = false;
291         for (i = 0; i <= max; i++) {
292                 /* If first bytes of the address are at the maximum, use the
293                  * distance. Otherwise use the full range.
294                  */
295                 if (!full_range) {
296                         minip = ntohl((__force __be32)range->min_addr.all[i]);
297                         maxip = ntohl((__force __be32)range->max_addr.all[i]);
298                         dist  = maxip - minip + 1;
299                 } else {
300                         minip = 0;
301                         dist  = ~0;
302                 }
303
304                 var_ipp->all[i] = (__force __u32)
305                         htonl(minip + reciprocal_scale(j, dist));
306                 if (var_ipp->all[i] != range->max_addr.all[i])
307                         full_range = true;
308
309                 if (!(range->flags & NF_NAT_RANGE_PERSISTENT))
310                         j ^= (__force u32)tuple->dst.u3.all[i];
311         }
312 }
313
314 /* Manipulate the tuple into the range given. For NF_INET_POST_ROUTING,
315  * we change the source to map into the range. For NF_INET_PRE_ROUTING
316  * and NF_INET_LOCAL_OUT, we change the destination to map into the
317  * range. It might not be possible to get a unique tuple, but we try.
318  * At worst (or if we race), we will end up with a final duplicate in
319  * __ip_conntrack_confirm and drop the packet. */
320 static void
321 get_unique_tuple(struct nf_conntrack_tuple *tuple,
322                  const struct nf_conntrack_tuple *orig_tuple,
323                  const struct nf_nat_range2 *range,
324                  struct nf_conn *ct,
325                  enum nf_nat_manip_type maniptype)
326 {
327         const struct nf_conntrack_zone *zone;
328         const struct nf_nat_l3proto *l3proto;
329         const struct nf_nat_l4proto *l4proto;
330         struct net *net = nf_ct_net(ct);
331
332         zone = nf_ct_zone(ct);
333
334         rcu_read_lock();
335         l3proto = __nf_nat_l3proto_find(orig_tuple->src.l3num);
336         l4proto = __nf_nat_l4proto_find(orig_tuple->src.l3num,
337                                         orig_tuple->dst.protonum);
338
339         /* 1) If this srcip/proto/src-proto-part is currently mapped,
340          * and that same mapping gives a unique tuple within the given
341          * range, use that.
342          *
343          * This is only required for source (ie. NAT/masq) mappings.
344          * So far, we don't do local source mappings, so multiple
345          * manips not an issue.
346          */
347         if (maniptype == NF_NAT_MANIP_SRC &&
348             !(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
349                 /* try the original tuple first */
350                 if (in_range(l3proto, l4proto, orig_tuple, range)) {
351                         if (!nf_nat_used_tuple(orig_tuple, ct)) {
352                                 *tuple = *orig_tuple;
353                                 goto out;
354                         }
355                 } else if (find_appropriate_src(net, zone, l3proto, l4proto,
356                                                 orig_tuple, tuple, range)) {
357                         pr_debug("get_unique_tuple: Found current src map\n");
358                         if (!nf_nat_used_tuple(tuple, ct))
359                                 goto out;
360                 }
361         }
362
363         /* 2) Select the least-used IP/proto combination in the given range */
364         *tuple = *orig_tuple;
365         find_best_ips_proto(zone, tuple, range, ct, maniptype);
366
367         /* 3) The per-protocol part of the manip is made to map into
368          * the range to make a unique tuple.
369          */
370
371         /* Only bother mapping if it's not already in range and unique */
372         if (!(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
373                 if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
374                         if (!(range->flags & NF_NAT_RANGE_PROTO_OFFSET) &&
375                             l4proto->in_range(tuple, maniptype,
376                                   &range->min_proto,
377                                   &range->max_proto) &&
378                             (range->min_proto.all == range->max_proto.all ||
379                              !nf_nat_used_tuple(tuple, ct)))
380                                 goto out;
381                 } else if (!nf_nat_used_tuple(tuple, ct)) {
382                         goto out;
383                 }
384         }
385
386         /* Last chance: get protocol to try to obtain unique tuple. */
387         l4proto->unique_tuple(l3proto, tuple, range, maniptype, ct);
388 out:
389         rcu_read_unlock();
390 }
391
392 struct nf_conn_nat *nf_ct_nat_ext_add(struct nf_conn *ct)
393 {
394         struct nf_conn_nat *nat = nfct_nat(ct);
395         if (nat)
396                 return nat;
397
398         if (!nf_ct_is_confirmed(ct))
399                 nat = nf_ct_ext_add(ct, NF_CT_EXT_NAT, GFP_ATOMIC);
400
401         return nat;
402 }
403 EXPORT_SYMBOL_GPL(nf_ct_nat_ext_add);
404
405 unsigned int
406 nf_nat_setup_info(struct nf_conn *ct,
407                   const struct nf_nat_range2 *range,
408                   enum nf_nat_manip_type maniptype)
409 {
410         struct net *net = nf_ct_net(ct);
411         struct nf_conntrack_tuple curr_tuple, new_tuple;
412
413         /* Can't setup nat info for confirmed ct. */
414         if (nf_ct_is_confirmed(ct))
415                 return NF_ACCEPT;
416
417         WARN_ON(maniptype != NF_NAT_MANIP_SRC &&
418                 maniptype != NF_NAT_MANIP_DST);
419
420         if (WARN_ON(nf_nat_initialized(ct, maniptype)))
421                 return NF_DROP;
422
423         /* What we've got will look like inverse of reply. Normally
424          * this is what is in the conntrack, except for prior
425          * manipulations (future optimization: if num_manips == 0,
426          * orig_tp = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple)
427          */
428         nf_ct_invert_tuplepr(&curr_tuple,
429                              &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
430
431         get_unique_tuple(&new_tuple, &curr_tuple, range, ct, maniptype);
432
433         if (!nf_ct_tuple_equal(&new_tuple, &curr_tuple)) {
434                 struct nf_conntrack_tuple reply;
435
436                 /* Alter conntrack table so will recognize replies. */
437                 nf_ct_invert_tuplepr(&reply, &new_tuple);
438                 nf_conntrack_alter_reply(ct, &reply);
439
440                 /* Non-atomic: we own this at the moment. */
441                 if (maniptype == NF_NAT_MANIP_SRC)
442                         ct->status |= IPS_SRC_NAT;
443                 else
444                         ct->status |= IPS_DST_NAT;
445
446                 if (nfct_help(ct) && !nfct_seqadj(ct))
447                         if (!nfct_seqadj_ext_add(ct))
448                                 return NF_DROP;
449         }
450
451         if (maniptype == NF_NAT_MANIP_SRC) {
452                 unsigned int srchash;
453                 spinlock_t *lock;
454
455                 srchash = hash_by_src(net,
456                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
457                 lock = &nf_nat_locks[srchash % CONNTRACK_LOCKS];
458                 spin_lock_bh(lock);
459                 hlist_add_head_rcu(&ct->nat_bysource,
460                                    &nf_nat_bysource[srchash]);
461                 spin_unlock_bh(lock);
462         }
463
464         /* It's done. */
465         if (maniptype == NF_NAT_MANIP_DST)
466                 ct->status |= IPS_DST_NAT_DONE;
467         else
468                 ct->status |= IPS_SRC_NAT_DONE;
469
470         return NF_ACCEPT;
471 }
472 EXPORT_SYMBOL(nf_nat_setup_info);
473
474 static unsigned int
475 __nf_nat_alloc_null_binding(struct nf_conn *ct, enum nf_nat_manip_type manip)
476 {
477         /* Force range to this IP; let proto decide mapping for
478          * per-proto parts (hence not IP_NAT_RANGE_PROTO_SPECIFIED).
479          * Use reply in case it's already been mangled (eg local packet).
480          */
481         union nf_inet_addr ip =
482                 (manip == NF_NAT_MANIP_SRC ?
483                 ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3 :
484                 ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3);
485         struct nf_nat_range2 range = {
486                 .flags          = NF_NAT_RANGE_MAP_IPS,
487                 .min_addr       = ip,
488                 .max_addr       = ip,
489         };
490         return nf_nat_setup_info(ct, &range, manip);
491 }
492
493 unsigned int
494 nf_nat_alloc_null_binding(struct nf_conn *ct, unsigned int hooknum)
495 {
496         return __nf_nat_alloc_null_binding(ct, HOOK2MANIP(hooknum));
497 }
498 EXPORT_SYMBOL_GPL(nf_nat_alloc_null_binding);
499
500 static unsigned int nf_nat_manip_pkt(struct sk_buff *skb, struct nf_conn *ct,
501                                      enum nf_nat_manip_type mtype,
502                                      enum ip_conntrack_dir dir)
503 {
504         const struct nf_nat_l3proto *l3proto;
505         const struct nf_nat_l4proto *l4proto;
506         struct nf_conntrack_tuple target;
507
508         /* We are aiming to look like inverse of other direction. */
509         nf_ct_invert_tuplepr(&target, &ct->tuplehash[!dir].tuple);
510
511         l3proto = __nf_nat_l3proto_find(target.src.l3num);
512         l4proto = __nf_nat_l4proto_find(target.src.l3num,
513                                         target.dst.protonum);
514         if (!l3proto->manip_pkt(skb, 0, l4proto, &target, mtype))
515                 return NF_DROP;
516
517         return NF_ACCEPT;
518 }
519
520 /* Do packet manipulations according to nf_nat_setup_info. */
521 unsigned int nf_nat_packet(struct nf_conn *ct,
522                            enum ip_conntrack_info ctinfo,
523                            unsigned int hooknum,
524                            struct sk_buff *skb)
525 {
526         enum nf_nat_manip_type mtype = HOOK2MANIP(hooknum);
527         enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
528         unsigned int verdict = NF_ACCEPT;
529         unsigned long statusbit;
530
531         if (mtype == NF_NAT_MANIP_SRC)
532                 statusbit = IPS_SRC_NAT;
533         else
534                 statusbit = IPS_DST_NAT;
535
536         /* Invert if this is reply dir. */
537         if (dir == IP_CT_DIR_REPLY)
538                 statusbit ^= IPS_NAT_MASK;
539
540         /* Non-atomic: these bits don't change. */
541         if (ct->status & statusbit)
542                 verdict = nf_nat_manip_pkt(skb, ct, mtype, dir);
543
544         return verdict;
545 }
546 EXPORT_SYMBOL_GPL(nf_nat_packet);
547
548 unsigned int
549 nf_nat_inet_fn(void *priv, struct sk_buff *skb,
550                const struct nf_hook_state *state)
551 {
552         struct nf_conn *ct;
553         enum ip_conntrack_info ctinfo;
554         struct nf_conn_nat *nat;
555         /* maniptype == SRC for postrouting. */
556         enum nf_nat_manip_type maniptype = HOOK2MANIP(state->hook);
557
558         ct = nf_ct_get(skb, &ctinfo);
559         /* Can't track?  It's not due to stress, or conntrack would
560          * have dropped it.  Hence it's the user's responsibilty to
561          * packet filter it out, or implement conntrack/NAT for that
562          * protocol. 8) --RR
563          */
564         if (!ct)
565                 return NF_ACCEPT;
566
567         nat = nfct_nat(ct);
568
569         switch (ctinfo) {
570         case IP_CT_RELATED:
571         case IP_CT_RELATED_REPLY:
572                 /* Only ICMPs can be IP_CT_IS_REPLY.  Fallthrough */
573         case IP_CT_NEW:
574                 /* Seen it before?  This can happen for loopback, retrans,
575                  * or local packets.
576                  */
577                 if (!nf_nat_initialized(ct, maniptype)) {
578                         struct nf_nat_lookup_hook_priv *lpriv = priv;
579                         struct nf_hook_entries *e = rcu_dereference(lpriv->entries);
580                         unsigned int ret;
581                         int i;
582
583                         if (!e)
584                                 goto null_bind;
585
586                         for (i = 0; i < e->num_hook_entries; i++) {
587                                 ret = e->hooks[i].hook(e->hooks[i].priv, skb,
588                                                        state);
589                                 if (ret != NF_ACCEPT)
590                                         return ret;
591                                 if (nf_nat_initialized(ct, maniptype))
592                                         goto do_nat;
593                         }
594 null_bind:
595                         ret = nf_nat_alloc_null_binding(ct, state->hook);
596                         if (ret != NF_ACCEPT)
597                                 return ret;
598                 } else {
599                         pr_debug("Already setup manip %s for ct %p (status bits 0x%lx)\n",
600                                  maniptype == NF_NAT_MANIP_SRC ? "SRC" : "DST",
601                                  ct, ct->status);
602                         if (nf_nat_oif_changed(state->hook, ctinfo, nat,
603                                                state->out))
604                                 goto oif_changed;
605                 }
606                 break;
607         default:
608                 /* ESTABLISHED */
609                 WARN_ON(ctinfo != IP_CT_ESTABLISHED &&
610                         ctinfo != IP_CT_ESTABLISHED_REPLY);
611                 if (nf_nat_oif_changed(state->hook, ctinfo, nat, state->out))
612                         goto oif_changed;
613         }
614 do_nat:
615         return nf_nat_packet(ct, ctinfo, state->hook, skb);
616
617 oif_changed:
618         nf_ct_kill_acct(ct, ctinfo, skb);
619         return NF_DROP;
620 }
621 EXPORT_SYMBOL_GPL(nf_nat_inet_fn);
622
623 struct nf_nat_proto_clean {
624         u8      l3proto;
625         u8      l4proto;
626 };
627
628 /* kill conntracks with affected NAT section */
629 static int nf_nat_proto_remove(struct nf_conn *i, void *data)
630 {
631         const struct nf_nat_proto_clean *clean = data;
632
633         if ((clean->l3proto && nf_ct_l3num(i) != clean->l3proto) ||
634             (clean->l4proto && nf_ct_protonum(i) != clean->l4proto))
635                 return 0;
636
637         return i->status & IPS_NAT_MASK ? 1 : 0;
638 }
639
640 static void __nf_nat_cleanup_conntrack(struct nf_conn *ct)
641 {
642         unsigned int h;
643
644         h = hash_by_src(nf_ct_net(ct), &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
645         spin_lock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
646         hlist_del_rcu(&ct->nat_bysource);
647         spin_unlock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
648 }
649
650 static int nf_nat_proto_clean(struct nf_conn *ct, void *data)
651 {
652         if (nf_nat_proto_remove(ct, data))
653                 return 1;
654
655         /* This module is being removed and conntrack has nat null binding.
656          * Remove it from bysource hash, as the table will be freed soon.
657          *
658          * Else, when the conntrack is destoyed, nf_nat_cleanup_conntrack()
659          * will delete entry from already-freed table.
660          */
661         if (test_and_clear_bit(IPS_SRC_NAT_DONE_BIT, &ct->status))
662                 __nf_nat_cleanup_conntrack(ct);
663
664         /* don't delete conntrack.  Although that would make things a lot
665          * simpler, we'd end up flushing all conntracks on nat rmmod.
666          */
667         return 0;
668 }
669
670 static void nf_nat_l4proto_clean(u8 l3proto, u8 l4proto)
671 {
672         struct nf_nat_proto_clean clean = {
673                 .l3proto = l3proto,
674                 .l4proto = l4proto,
675         };
676
677         nf_ct_iterate_destroy(nf_nat_proto_remove, &clean);
678 }
679
680 static void nf_nat_l3proto_clean(u8 l3proto)
681 {
682         struct nf_nat_proto_clean clean = {
683                 .l3proto = l3proto,
684         };
685
686         nf_ct_iterate_destroy(nf_nat_proto_remove, &clean);
687 }
688
689 /* Protocol registration. */
690 int nf_nat_l4proto_register(u8 l3proto, const struct nf_nat_l4proto *l4proto)
691 {
692         const struct nf_nat_l4proto **l4protos;
693         unsigned int i;
694         int ret = 0;
695
696         mutex_lock(&nf_nat_proto_mutex);
697         if (nf_nat_l4protos[l3proto] == NULL) {
698                 l4protos = kmalloc_array(IPPROTO_MAX,
699                                          sizeof(struct nf_nat_l4proto *),
700                                          GFP_KERNEL);
701                 if (l4protos == NULL) {
702                         ret = -ENOMEM;
703                         goto out;
704                 }
705
706                 for (i = 0; i < IPPROTO_MAX; i++)
707                         RCU_INIT_POINTER(l4protos[i], &nf_nat_l4proto_unknown);
708
709                 /* Before making proto_array visible to lockless readers,
710                  * we must make sure its content is committed to memory.
711                  */
712                 smp_wmb();
713
714                 nf_nat_l4protos[l3proto] = l4protos;
715         }
716
717         if (rcu_dereference_protected(
718                         nf_nat_l4protos[l3proto][l4proto->l4proto],
719                         lockdep_is_held(&nf_nat_proto_mutex)
720                         ) != &nf_nat_l4proto_unknown) {
721                 ret = -EBUSY;
722                 goto out;
723         }
724         RCU_INIT_POINTER(nf_nat_l4protos[l3proto][l4proto->l4proto], l4proto);
725  out:
726         mutex_unlock(&nf_nat_proto_mutex);
727         return ret;
728 }
729 EXPORT_SYMBOL_GPL(nf_nat_l4proto_register);
730
731 /* No one stores the protocol anywhere; simply delete it. */
732 void nf_nat_l4proto_unregister(u8 l3proto, const struct nf_nat_l4proto *l4proto)
733 {
734         mutex_lock(&nf_nat_proto_mutex);
735         RCU_INIT_POINTER(nf_nat_l4protos[l3proto][l4proto->l4proto],
736                          &nf_nat_l4proto_unknown);
737         mutex_unlock(&nf_nat_proto_mutex);
738         synchronize_rcu();
739
740         nf_nat_l4proto_clean(l3proto, l4proto->l4proto);
741 }
742 EXPORT_SYMBOL_GPL(nf_nat_l4proto_unregister);
743
744 int nf_nat_l3proto_register(const struct nf_nat_l3proto *l3proto)
745 {
746         mutex_lock(&nf_nat_proto_mutex);
747         RCU_INIT_POINTER(nf_nat_l4protos[l3proto->l3proto][IPPROTO_TCP],
748                          &nf_nat_l4proto_tcp);
749         RCU_INIT_POINTER(nf_nat_l4protos[l3proto->l3proto][IPPROTO_UDP],
750                          &nf_nat_l4proto_udp);
751 #ifdef CONFIG_NF_NAT_PROTO_DCCP
752         RCU_INIT_POINTER(nf_nat_l4protos[l3proto->l3proto][IPPROTO_DCCP],
753                          &nf_nat_l4proto_dccp);
754 #endif
755 #ifdef CONFIG_NF_NAT_PROTO_SCTP
756         RCU_INIT_POINTER(nf_nat_l4protos[l3proto->l3proto][IPPROTO_SCTP],
757                          &nf_nat_l4proto_sctp);
758 #endif
759 #ifdef CONFIG_NF_NAT_PROTO_UDPLITE
760         RCU_INIT_POINTER(nf_nat_l4protos[l3proto->l3proto][IPPROTO_UDPLITE],
761                          &nf_nat_l4proto_udplite);
762 #endif
763         mutex_unlock(&nf_nat_proto_mutex);
764
765         RCU_INIT_POINTER(nf_nat_l3protos[l3proto->l3proto], l3proto);
766         return 0;
767 }
768 EXPORT_SYMBOL_GPL(nf_nat_l3proto_register);
769
770 void nf_nat_l3proto_unregister(const struct nf_nat_l3proto *l3proto)
771 {
772         mutex_lock(&nf_nat_proto_mutex);
773         RCU_INIT_POINTER(nf_nat_l3protos[l3proto->l3proto], NULL);
774         mutex_unlock(&nf_nat_proto_mutex);
775         synchronize_rcu();
776
777         nf_nat_l3proto_clean(l3proto->l3proto);
778 }
779 EXPORT_SYMBOL_GPL(nf_nat_l3proto_unregister);
780
781 /* No one using conntrack by the time this called. */
782 static void nf_nat_cleanup_conntrack(struct nf_conn *ct)
783 {
784         if (ct->status & IPS_SRC_NAT_DONE)
785                 __nf_nat_cleanup_conntrack(ct);
786 }
787
788 static struct nf_ct_ext_type nat_extend __read_mostly = {
789         .len            = sizeof(struct nf_conn_nat),
790         .align          = __alignof__(struct nf_conn_nat),
791         .destroy        = nf_nat_cleanup_conntrack,
792         .id             = NF_CT_EXT_NAT,
793 };
794
795 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
796
797 #include <linux/netfilter/nfnetlink.h>
798 #include <linux/netfilter/nfnetlink_conntrack.h>
799
800 static const struct nla_policy protonat_nla_policy[CTA_PROTONAT_MAX+1] = {
801         [CTA_PROTONAT_PORT_MIN] = { .type = NLA_U16 },
802         [CTA_PROTONAT_PORT_MAX] = { .type = NLA_U16 },
803 };
804
805 static int nfnetlink_parse_nat_proto(struct nlattr *attr,
806                                      const struct nf_conn *ct,
807                                      struct nf_nat_range2 *range)
808 {
809         struct nlattr *tb[CTA_PROTONAT_MAX+1];
810         const struct nf_nat_l4proto *l4proto;
811         int err;
812
813         err = nla_parse_nested(tb, CTA_PROTONAT_MAX, attr,
814                                protonat_nla_policy, NULL);
815         if (err < 0)
816                 return err;
817
818         l4proto = __nf_nat_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
819         if (l4proto->nlattr_to_range)
820                 err = l4proto->nlattr_to_range(tb, range);
821
822         return err;
823 }
824
825 static const struct nla_policy nat_nla_policy[CTA_NAT_MAX+1] = {
826         [CTA_NAT_V4_MINIP]      = { .type = NLA_U32 },
827         [CTA_NAT_V4_MAXIP]      = { .type = NLA_U32 },
828         [CTA_NAT_V6_MINIP]      = { .len = sizeof(struct in6_addr) },
829         [CTA_NAT_V6_MAXIP]      = { .len = sizeof(struct in6_addr) },
830         [CTA_NAT_PROTO]         = { .type = NLA_NESTED },
831 };
832
833 static int
834 nfnetlink_parse_nat(const struct nlattr *nat,
835                     const struct nf_conn *ct, struct nf_nat_range2 *range,
836                     const struct nf_nat_l3proto *l3proto)
837 {
838         struct nlattr *tb[CTA_NAT_MAX+1];
839         int err;
840
841         memset(range, 0, sizeof(*range));
842
843         err = nla_parse_nested(tb, CTA_NAT_MAX, nat, nat_nla_policy, NULL);
844         if (err < 0)
845                 return err;
846
847         err = l3proto->nlattr_to_range(tb, range);
848         if (err < 0)
849                 return err;
850
851         if (!tb[CTA_NAT_PROTO])
852                 return 0;
853
854         return nfnetlink_parse_nat_proto(tb[CTA_NAT_PROTO], ct, range);
855 }
856
857 /* This function is called under rcu_read_lock() */
858 static int
859 nfnetlink_parse_nat_setup(struct nf_conn *ct,
860                           enum nf_nat_manip_type manip,
861                           const struct nlattr *attr)
862 {
863         struct nf_nat_range2 range;
864         const struct nf_nat_l3proto *l3proto;
865         int err;
866
867         /* Should not happen, restricted to creating new conntracks
868          * via ctnetlink.
869          */
870         if (WARN_ON_ONCE(nf_nat_initialized(ct, manip)))
871                 return -EEXIST;
872
873         /* Make sure that L3 NAT is there by when we call nf_nat_setup_info to
874          * attach the null binding, otherwise this may oops.
875          */
876         l3proto = __nf_nat_l3proto_find(nf_ct_l3num(ct));
877         if (l3proto == NULL)
878                 return -EAGAIN;
879
880         /* No NAT information has been passed, allocate the null-binding */
881         if (attr == NULL)
882                 return __nf_nat_alloc_null_binding(ct, manip) == NF_DROP ? -ENOMEM : 0;
883
884         err = nfnetlink_parse_nat(attr, ct, &range, l3proto);
885         if (err < 0)
886                 return err;
887
888         return nf_nat_setup_info(ct, &range, manip) == NF_DROP ? -ENOMEM : 0;
889 }
890 #else
891 static int
892 nfnetlink_parse_nat_setup(struct nf_conn *ct,
893                           enum nf_nat_manip_type manip,
894                           const struct nlattr *attr)
895 {
896         return -EOPNOTSUPP;
897 }
898 #endif
899
900 static struct nf_ct_helper_expectfn follow_master_nat = {
901         .name           = "nat-follow-master",
902         .expectfn       = nf_nat_follow_master,
903 };
904
905 int nf_nat_register_fn(struct net *net, const struct nf_hook_ops *ops,
906                        const struct nf_hook_ops *orig_nat_ops, unsigned int ops_count)
907 {
908         struct nat_net *nat_net = net_generic(net, nat_net_id);
909         struct nf_nat_hooks_net *nat_proto_net;
910         struct nf_nat_lookup_hook_priv *priv;
911         unsigned int hooknum = ops->hooknum;
912         struct nf_hook_ops *nat_ops;
913         int i, ret;
914
915         if (WARN_ON_ONCE(ops->pf >= ARRAY_SIZE(nat_net->nat_proto_net)))
916                 return -EINVAL;
917
918         nat_proto_net = &nat_net->nat_proto_net[ops->pf];
919
920         for (i = 0; i < ops_count; i++) {
921                 if (WARN_ON(orig_nat_ops[i].pf != ops->pf))
922                         return -EINVAL;
923                 if (orig_nat_ops[i].hooknum == hooknum) {
924                         hooknum = i;
925                         break;
926                 }
927         }
928
929         if (WARN_ON_ONCE(i == ops_count))
930                 return -EINVAL;
931
932         mutex_lock(&nf_nat_proto_mutex);
933         if (!nat_proto_net->nat_hook_ops) {
934                 WARN_ON(nat_proto_net->users != 0);
935
936                 nat_ops = kmemdup(orig_nat_ops, sizeof(*orig_nat_ops) * ops_count, GFP_KERNEL);
937                 if (!nat_ops) {
938                         mutex_unlock(&nf_nat_proto_mutex);
939                         return -ENOMEM;
940                 }
941
942                 for (i = 0; i < ops_count; i++) {
943                         priv = kzalloc(sizeof(*priv), GFP_KERNEL);
944                         if (priv) {
945                                 nat_ops[i].priv = priv;
946                                 continue;
947                         }
948                         mutex_unlock(&nf_nat_proto_mutex);
949                         while (i)
950                                 kfree(nat_ops[--i].priv);
951                         kfree(nat_ops);
952                         return -ENOMEM;
953                 }
954
955                 ret = nf_register_net_hooks(net, nat_ops, ops_count);
956                 if (ret < 0) {
957                         mutex_unlock(&nf_nat_proto_mutex);
958                         for (i = 0; i < ops_count; i++)
959                                 kfree(nat_ops[i].priv);
960                         kfree(nat_ops);
961                         return ret;
962                 }
963
964                 nat_proto_net->nat_hook_ops = nat_ops;
965         }
966
967         nat_ops = nat_proto_net->nat_hook_ops;
968         priv = nat_ops[hooknum].priv;
969         if (WARN_ON_ONCE(!priv)) {
970                 mutex_unlock(&nf_nat_proto_mutex);
971                 return -EOPNOTSUPP;
972         }
973
974         ret = nf_hook_entries_insert_raw(&priv->entries, ops);
975         if (ret == 0)
976                 nat_proto_net->users++;
977
978         mutex_unlock(&nf_nat_proto_mutex);
979         return ret;
980 }
981 EXPORT_SYMBOL_GPL(nf_nat_register_fn);
982
983 void nf_nat_unregister_fn(struct net *net, const struct nf_hook_ops *ops,
984                           unsigned int ops_count)
985 {
986         struct nat_net *nat_net = net_generic(net, nat_net_id);
987         struct nf_nat_hooks_net *nat_proto_net;
988         struct nf_nat_lookup_hook_priv *priv;
989         struct nf_hook_ops *nat_ops;
990         int hooknum = ops->hooknum;
991         int i;
992
993         if (ops->pf >= ARRAY_SIZE(nat_net->nat_proto_net))
994                 return;
995
996         nat_proto_net = &nat_net->nat_proto_net[ops->pf];
997
998         mutex_lock(&nf_nat_proto_mutex);
999         if (WARN_ON(nat_proto_net->users == 0))
1000                 goto unlock;
1001
1002         nat_proto_net->users--;
1003
1004         nat_ops = nat_proto_net->nat_hook_ops;
1005         for (i = 0; i < ops_count; i++) {
1006                 if (nat_ops[i].hooknum == hooknum) {
1007                         hooknum = i;
1008                         break;
1009                 }
1010         }
1011         if (WARN_ON_ONCE(i == ops_count))
1012                 goto unlock;
1013         priv = nat_ops[hooknum].priv;
1014         nf_hook_entries_delete_raw(&priv->entries, ops);
1015
1016         if (nat_proto_net->users == 0) {
1017                 nf_unregister_net_hooks(net, nat_ops, ops_count);
1018
1019                 for (i = 0; i < ops_count; i++) {
1020                         priv = nat_ops[i].priv;
1021                         kfree_rcu(priv, rcu_head);
1022                 }
1023
1024                 nat_proto_net->nat_hook_ops = NULL;
1025                 kfree(nat_ops);
1026         }
1027 unlock:
1028         mutex_unlock(&nf_nat_proto_mutex);
1029 }
1030 EXPORT_SYMBOL_GPL(nf_nat_unregister_fn);
1031
1032 static struct pernet_operations nat_net_ops = {
1033         .id = &nat_net_id,
1034         .size = sizeof(struct nat_net),
1035 };
1036
1037 static struct nf_nat_hook nat_hook = {
1038         .parse_nat_setup        = nfnetlink_parse_nat_setup,
1039 #ifdef CONFIG_XFRM
1040         .decode_session         = __nf_nat_decode_session,
1041 #endif
1042         .manip_pkt              = nf_nat_manip_pkt,
1043 };
1044
1045 static int __init nf_nat_init(void)
1046 {
1047         int ret, i;
1048
1049         /* Leave them the same for the moment. */
1050         nf_nat_htable_size = nf_conntrack_htable_size;
1051         if (nf_nat_htable_size < CONNTRACK_LOCKS)
1052                 nf_nat_htable_size = CONNTRACK_LOCKS;
1053
1054         nf_nat_bysource = nf_ct_alloc_hashtable(&nf_nat_htable_size, 0);
1055         if (!nf_nat_bysource)
1056                 return -ENOMEM;
1057
1058         ret = nf_ct_extend_register(&nat_extend);
1059         if (ret < 0) {
1060                 kvfree(nf_nat_bysource);
1061                 pr_err("Unable to register extension\n");
1062                 return ret;
1063         }
1064
1065         for (i = 0; i < CONNTRACK_LOCKS; i++)
1066                 spin_lock_init(&nf_nat_locks[i]);
1067
1068         ret = register_pernet_subsys(&nat_net_ops);
1069         if (ret < 0) {
1070                 nf_ct_extend_unregister(&nat_extend);
1071                 return ret;
1072         }
1073
1074         nf_ct_helper_expectfn_register(&follow_master_nat);
1075
1076         WARN_ON(nf_nat_hook != NULL);
1077         RCU_INIT_POINTER(nf_nat_hook, &nat_hook);
1078
1079         return 0;
1080 }
1081
1082 static void __exit nf_nat_cleanup(void)
1083 {
1084         struct nf_nat_proto_clean clean = {};
1085         unsigned int i;
1086
1087         nf_ct_iterate_destroy(nf_nat_proto_clean, &clean);
1088
1089         nf_ct_extend_unregister(&nat_extend);
1090         nf_ct_helper_expectfn_unregister(&follow_master_nat);
1091         RCU_INIT_POINTER(nf_nat_hook, NULL);
1092
1093         synchronize_rcu();
1094
1095         for (i = 0; i < NFPROTO_NUMPROTO; i++)
1096                 kfree(nf_nat_l4protos[i]);
1097         synchronize_net();
1098         kvfree(nf_nat_bysource);
1099         unregister_pernet_subsys(&nat_net_ops);
1100 }
1101
1102 MODULE_LICENSE("GPL");
1103
1104 module_init(nf_nat_init);
1105 module_exit(nf_nat_cleanup);