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