xref: /linux/net/netfilter/nf_nat_core.c (revision 16d464013ec2267b00a83f4bfbb97b3ecc63bfa7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * (C) 1999-2001 Paul `Rusty' Russell
4  * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
5  * (C) 2011 Patrick McHardy <kaber@trash.net>
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include <linux/module.h>
11 #include <linux/types.h>
12 #include <linux/timer.h>
13 #include <linux/skbuff.h>
14 #include <linux/gfp.h>
15 #include <net/xfrm.h>
16 #include <linux/siphash.h>
17 #include <linux/rtnetlink.h>
18 
19 #include <net/netfilter/nf_conntrack_bpf.h>
20 #include <net/netfilter/nf_conntrack_core.h>
21 #include <net/netfilter/nf_conntrack_helper.h>
22 #include <net/netfilter/nf_conntrack_seqadj.h>
23 #include <net/netfilter/nf_conntrack_zones.h>
24 #include <net/netfilter/nf_nat.h>
25 #include <net/netfilter/nf_nat_helper.h>
26 #include <uapi/linux/netfilter/nf_nat.h>
27 
28 #include "nf_internals.h"
29 
30 #define NF_NAT_MAX_ATTEMPTS	128
31 #define NF_NAT_HARDER_THRESH	(NF_NAT_MAX_ATTEMPTS / 4)
32 
33 static spinlock_t nf_nat_locks[CONNTRACK_LOCKS];
34 
35 static DEFINE_MUTEX(nf_nat_proto_mutex);
36 static unsigned int nat_net_id __read_mostly;
37 
38 static struct hlist_head *nf_nat_bysource __read_mostly;
39 static unsigned int nf_nat_htable_size __read_mostly;
40 static siphash_aligned_key_t nf_nat_hash_rnd;
41 
42 struct nf_nat_hooks_net {
43 	struct nf_hook_ops *nat_hook_ops;
44 	unsigned int users;
45 };
46 
47 struct nat_net {
48 	struct nf_nat_hooks_net nat_proto_net[NFPROTO_NUMPROTO];
49 };
50 
51 #ifdef CONFIG_XFRM
52 static void nf_nat_ipv4_decode_session(struct sk_buff *skb,
53 				       const struct nf_conn *ct,
54 				       enum ip_conntrack_dir dir,
55 				       unsigned long statusbit,
56 				       struct flowi *fl)
57 {
58 	const struct nf_conntrack_tuple *t = &ct->tuplehash[dir].tuple;
59 	struct flowi4 *fl4 = &fl->u.ip4;
60 
61 	if (ct->status & statusbit) {
62 		fl4->daddr = t->dst.u3.ip;
63 		if (t->dst.protonum == IPPROTO_TCP ||
64 		    t->dst.protonum == IPPROTO_UDP ||
65 		    t->dst.protonum == IPPROTO_SCTP)
66 			fl4->fl4_dport = t->dst.u.all;
67 	}
68 
69 	statusbit ^= IPS_NAT_MASK;
70 
71 	if (ct->status & statusbit) {
72 		fl4->saddr = t->src.u3.ip;
73 		if (t->dst.protonum == IPPROTO_TCP ||
74 		    t->dst.protonum == IPPROTO_UDP ||
75 		    t->dst.protonum == IPPROTO_SCTP)
76 			fl4->fl4_sport = t->src.u.all;
77 	}
78 }
79 
80 static void nf_nat_ipv6_decode_session(struct sk_buff *skb,
81 				       const struct nf_conn *ct,
82 				       enum ip_conntrack_dir dir,
83 				       unsigned long statusbit,
84 				       struct flowi *fl)
85 {
86 #if IS_ENABLED(CONFIG_IPV6)
87 	const struct nf_conntrack_tuple *t = &ct->tuplehash[dir].tuple;
88 	struct flowi6 *fl6 = &fl->u.ip6;
89 
90 	if (ct->status & statusbit) {
91 		fl6->daddr = t->dst.u3.in6;
92 		if (t->dst.protonum == IPPROTO_TCP ||
93 		    t->dst.protonum == IPPROTO_UDP ||
94 		    t->dst.protonum == IPPROTO_SCTP)
95 			fl6->fl6_dport = t->dst.u.all;
96 	}
97 
98 	statusbit ^= IPS_NAT_MASK;
99 
100 	if (ct->status & statusbit) {
101 		fl6->saddr = t->src.u3.in6;
102 		if (t->dst.protonum == IPPROTO_TCP ||
103 		    t->dst.protonum == IPPROTO_UDP ||
104 		    t->dst.protonum == IPPROTO_SCTP)
105 			fl6->fl6_sport = t->src.u.all;
106 	}
107 #endif
108 }
109 
110 static void __nf_nat_decode_session(struct sk_buff *skb, struct flowi *fl)
111 {
112 	const struct nf_conn *ct;
113 	enum ip_conntrack_info ctinfo;
114 	enum ip_conntrack_dir dir;
115 	unsigned  long statusbit;
116 	u8 family;
117 
118 	ct = nf_ct_get(skb, &ctinfo);
119 	if (ct == NULL)
120 		return;
121 
122 	family = nf_ct_l3num(ct);
123 	dir = CTINFO2DIR(ctinfo);
124 	if (dir == IP_CT_DIR_ORIGINAL)
125 		statusbit = IPS_DST_NAT;
126 	else
127 		statusbit = IPS_SRC_NAT;
128 
129 	switch (family) {
130 	case NFPROTO_IPV4:
131 		nf_nat_ipv4_decode_session(skb, ct, dir, statusbit, fl);
132 		return;
133 	case NFPROTO_IPV6:
134 		nf_nat_ipv6_decode_session(skb, ct, dir, statusbit, fl);
135 		return;
136 	}
137 }
138 #endif /* CONFIG_XFRM */
139 
140 /* We keep an extra hash for each conntrack, for fast searching. */
141 static unsigned int
142 hash_by_src(const struct net *net,
143 	    const struct nf_conntrack_zone *zone,
144 	    const struct nf_conntrack_tuple *tuple)
145 {
146 	unsigned int hash;
147 	struct {
148 		struct nf_conntrack_man src;
149 		u32 net_mix;
150 		u32 protonum;
151 		u32 zone;
152 	} __aligned(SIPHASH_ALIGNMENT) combined;
153 
154 	get_random_once(&nf_nat_hash_rnd, sizeof(nf_nat_hash_rnd));
155 
156 	memset(&combined, 0, sizeof(combined));
157 
158 	/* Original src, to ensure we map it consistently if poss. */
159 	combined.src = tuple->src;
160 	combined.net_mix = net_hash_mix(net);
161 	combined.protonum = tuple->dst.protonum;
162 
163 	/* Zone ID can be used provided its valid for both directions */
164 	if (zone->dir == NF_CT_DEFAULT_ZONE_DIR)
165 		combined.zone = zone->id;
166 
167 	hash = siphash(&combined, sizeof(combined), &nf_nat_hash_rnd);
168 
169 	return reciprocal_scale(hash, nf_nat_htable_size);
170 }
171 
172 /**
173  * nf_nat_used_tuple - check if proposed nat tuple clashes with existing entry
174  * @tuple: proposed NAT binding
175  * @ignored_conntrack: our (unconfirmed) conntrack entry
176  *
177  * A conntrack entry can be inserted to the connection tracking table
178  * if there is no existing entry with an identical tuple in either direction.
179  *
180  * Example:
181  * INITIATOR -> NAT/PAT -> RESPONDER
182  *
183  * INITIATOR passes through NAT/PAT ("us") and SNAT is done (saddr rewrite).
184  * Then, later, NAT/PAT itself also connects to RESPONDER.
185  *
186  * This will not work if the SNAT done earlier has same IP:PORT source pair.
187  *
188  * Conntrack table has:
189  * ORIGINAL: $IP_INITIATOR:$SPORT -> $IP_RESPONDER:$DPORT
190  * REPLY:    $IP_RESPONDER:$DPORT -> $IP_NAT:$SPORT
191  *
192  * and new locally originating connection wants:
193  * ORIGINAL: $IP_NAT:$SPORT -> $IP_RESPONDER:$DPORT
194  * REPLY:    $IP_RESPONDER:$DPORT -> $IP_NAT:$SPORT
195  *
196  * ... which would mean incoming packets cannot be distinguished between
197  * the existing and the newly added entry (identical IP_CT_DIR_REPLY tuple).
198  *
199  * @return: true if the proposed NAT mapping collides with an existing entry.
200  */
201 static int
202 nf_nat_used_tuple(const struct nf_conntrack_tuple *tuple,
203 		  const struct nf_conn *ignored_conntrack)
204 {
205 	/* Conntrack tracking doesn't keep track of outgoing tuples; only
206 	 * incoming ones.  NAT means they don't have a fixed mapping,
207 	 * so we invert the tuple and look for the incoming reply.
208 	 *
209 	 * We could keep a separate hash if this proves too slow.
210 	 */
211 	struct nf_conntrack_tuple reply;
212 
213 	nf_ct_invert_tuple(&reply, tuple);
214 	return nf_conntrack_tuple_taken(&reply, ignored_conntrack);
215 }
216 
217 static bool nf_nat_allow_clash(const struct nf_conn *ct)
218 {
219 	return nf_ct_l4proto_find(nf_ct_protonum(ct))->allow_clash;
220 }
221 
222 /**
223  * nf_nat_used_tuple_new - check if to-be-inserted conntrack collides with existing entry
224  * @tuple: proposed NAT binding
225  * @ignored_ct: our (unconfirmed) conntrack entry
226  *
227  * Same as nf_nat_used_tuple, but also check for rare clash in reverse
228  * direction. Should be called only when @tuple has not been altered, i.e.
229  * @ignored_conntrack will not be subject to NAT.
230  *
231  * @return: true if the proposed NAT mapping collides with existing entry.
232  */
233 static noinline bool
234 nf_nat_used_tuple_new(const struct nf_conntrack_tuple *tuple,
235 		      const struct nf_conn *ignored_ct)
236 {
237 	static const unsigned long uses_nat = IPS_NAT_MASK | IPS_SEQ_ADJUST;
238 	const struct nf_conntrack_tuple_hash *thash;
239 	const struct nf_conntrack_zone *zone;
240 	struct nf_conn *ct;
241 	bool taken = true;
242 	struct net *net;
243 
244 	if (!nf_nat_used_tuple(tuple, ignored_ct))
245 		return false;
246 
247 	if (!nf_nat_allow_clash(ignored_ct))
248 		return true;
249 
250 	/* Initial choice clashes with existing conntrack.
251 	 * Check for (rare) reverse collision.
252 	 *
253 	 * This can happen when new packets are received in both directions
254 	 * at the exact same time on different CPUs.
255 	 *
256 	 * Without SMP, first packet creates new conntrack entry and second
257 	 * packet is resolved as established reply packet.
258 	 *
259 	 * With parallel processing, both packets could be picked up as
260 	 * new and both get their own ct entry allocated.
261 	 *
262 	 * If ignored_conntrack and colliding ct are not subject to NAT then
263 	 * pretend the tuple is available and let later clash resolution
264 	 * handle this at insertion time.
265 	 *
266 	 * Without it, the 'reply' packet has its source port rewritten
267 	 * by nat engine.
268 	 */
269 	if (READ_ONCE(ignored_ct->status) & uses_nat)
270 		return true;
271 
272 	net = nf_ct_net(ignored_ct);
273 	zone = nf_ct_zone(ignored_ct);
274 
275 	thash = nf_conntrack_find_get(net, zone, tuple);
276 	if (unlikely(!thash)) {
277 		struct nf_conntrack_tuple reply;
278 
279 		nf_ct_invert_tuple(&reply, tuple);
280 		thash = nf_conntrack_find_get(net, zone, &reply);
281 		if (!thash) /* clashing entry went away */
282 			return false;
283 	}
284 
285 	ct = nf_ct_tuplehash_to_ctrack(thash);
286 
287 	/* clashing connection subject to NAT? Retry with new tuple. */
288 	if (READ_ONCE(ct->status) & uses_nat)
289 		goto out;
290 
291 	if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
292 			      &ignored_ct->tuplehash[IP_CT_DIR_REPLY].tuple))
293 		taken = false;
294 out:
295 	nf_ct_put(ct);
296 	return taken;
297 }
298 
299 static bool nf_nat_may_kill(struct nf_conn *ct, unsigned long flags)
300 {
301 	static const unsigned long flags_refuse = IPS_FIXED_TIMEOUT |
302 						  IPS_DYING;
303 	static const unsigned long flags_needed = IPS_SRC_NAT;
304 	enum tcp_conntrack old_state;
305 
306 	old_state = READ_ONCE(ct->proto.tcp.state);
307 	if (old_state < TCP_CONNTRACK_TIME_WAIT)
308 		return false;
309 
310 	if (flags & flags_refuse)
311 		return false;
312 
313 	return (flags & flags_needed) == flags_needed;
314 }
315 
316 /* reverse direction will send packets to new source, so
317  * make sure such packets are invalid.
318  */
319 static bool nf_seq_has_advanced(const struct nf_conn *old, const struct nf_conn *new)
320 {
321 	return (__s32)(new->proto.tcp.seen[0].td_end -
322 		       old->proto.tcp.seen[0].td_end) > 0;
323 }
324 
325 static int
326 nf_nat_used_tuple_harder(const struct nf_conntrack_tuple *tuple,
327 			 const struct nf_conn *ignored_conntrack,
328 			 unsigned int attempts_left)
329 {
330 	static const unsigned long flags_offload = IPS_OFFLOAD | IPS_HW_OFFLOAD;
331 	struct nf_conntrack_tuple_hash *thash;
332 	const struct nf_conntrack_zone *zone;
333 	struct nf_conntrack_tuple reply;
334 	unsigned long flags;
335 	struct nf_conn *ct;
336 	bool taken = true;
337 	struct net *net;
338 
339 	nf_ct_invert_tuple(&reply, tuple);
340 
341 	if (attempts_left > NF_NAT_HARDER_THRESH ||
342 	    tuple->dst.protonum != IPPROTO_TCP ||
343 	    ignored_conntrack->proto.tcp.state != TCP_CONNTRACK_SYN_SENT)
344 		return nf_conntrack_tuple_taken(&reply, ignored_conntrack);
345 
346 	/* :ast few attempts to find a free tcp port. Destructive
347 	 * action: evict colliding if its in timewait state and the
348 	 * tcp sequence number has advanced past the one used by the
349 	 * old entry.
350 	 */
351 	net = nf_ct_net(ignored_conntrack);
352 	zone = nf_ct_zone(ignored_conntrack);
353 
354 	thash = nf_conntrack_find_get(net, zone, &reply);
355 	if (!thash)
356 		return false;
357 
358 	ct = nf_ct_tuplehash_to_ctrack(thash);
359 
360 	if (thash->tuple.dst.dir == IP_CT_DIR_ORIGINAL)
361 		goto out;
362 
363 	if (WARN_ON_ONCE(ct == ignored_conntrack))
364 		goto out;
365 
366 	flags = READ_ONCE(ct->status);
367 	if (!nf_nat_may_kill(ct, flags))
368 		goto out;
369 
370 	if (!nf_seq_has_advanced(ct, ignored_conntrack))
371 		goto out;
372 
373 	/* Even if we can evict do not reuse if entry is offloaded. */
374 	if (nf_ct_kill(ct))
375 		taken = flags & flags_offload;
376 out:
377 	nf_ct_put(ct);
378 	return taken;
379 }
380 
381 static bool nf_nat_inet_in_range(const struct nf_conntrack_tuple *t,
382 				 const struct nf_nat_range2 *range)
383 {
384 	if (t->src.l3num == NFPROTO_IPV4)
385 		return ntohl(t->src.u3.ip) >= ntohl(range->min_addr.ip) &&
386 		       ntohl(t->src.u3.ip) <= ntohl(range->max_addr.ip);
387 
388 	return ipv6_addr_cmp(&t->src.u3.in6, &range->min_addr.in6) >= 0 &&
389 	       ipv6_addr_cmp(&t->src.u3.in6, &range->max_addr.in6) <= 0;
390 }
391 
392 /* Is the manipable part of the tuple between min and max incl? */
393 static bool l4proto_in_range(const struct nf_conntrack_tuple *tuple,
394 			     enum nf_nat_manip_type maniptype,
395 			     const union nf_conntrack_man_proto *min,
396 			     const union nf_conntrack_man_proto *max)
397 {
398 	__be16 port;
399 
400 	switch (tuple->dst.protonum) {
401 	case IPPROTO_ICMP:
402 	case IPPROTO_ICMPV6:
403 		return ntohs(tuple->src.u.icmp.id) >= ntohs(min->icmp.id) &&
404 		       ntohs(tuple->src.u.icmp.id) <= ntohs(max->icmp.id);
405 	case IPPROTO_GRE: /* all fall though */
406 	case IPPROTO_TCP:
407 	case IPPROTO_UDP:
408 	case IPPROTO_SCTP:
409 		if (maniptype == NF_NAT_MANIP_SRC)
410 			port = tuple->src.u.all;
411 		else
412 			port = tuple->dst.u.all;
413 
414 		return ntohs(port) >= ntohs(min->all) &&
415 		       ntohs(port) <= ntohs(max->all);
416 	default:
417 		return true;
418 	}
419 }
420 
421 /* If we source map this tuple so reply looks like reply_tuple, will
422  * that meet the constraints of range.
423  */
424 static int nf_in_range(const struct nf_conntrack_tuple *tuple,
425 		    const struct nf_nat_range2 *range)
426 {
427 	/* If we are supposed to map IPs, then we must be in the
428 	 * range specified, otherwise let this drag us onto a new src IP.
429 	 */
430 	if (range->flags & NF_NAT_RANGE_MAP_IPS &&
431 	    !nf_nat_inet_in_range(tuple, range))
432 		return 0;
433 
434 	if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED))
435 		return 1;
436 
437 	return l4proto_in_range(tuple, NF_NAT_MANIP_SRC,
438 				&range->min_proto, &range->max_proto);
439 }
440 
441 static inline int
442 same_src(const struct nf_conn *ct,
443 	 const struct nf_conntrack_tuple *tuple)
444 {
445 	const struct nf_conntrack_tuple *t;
446 
447 	t = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
448 	return (t->dst.protonum == tuple->dst.protonum &&
449 		nf_inet_addr_cmp(&t->src.u3, &tuple->src.u3) &&
450 		t->src.u.all == tuple->src.u.all);
451 }
452 
453 /* Only called for SRC manip */
454 static int
455 find_appropriate_src(struct net *net,
456 		     const struct nf_conntrack_zone *zone,
457 		     const struct nf_conntrack_tuple *tuple,
458 		     struct nf_conntrack_tuple *result,
459 		     const struct nf_nat_range2 *range)
460 {
461 	unsigned int h = hash_by_src(net, zone, tuple);
462 	const struct nf_conn *ct;
463 
464 	hlist_for_each_entry_rcu(ct, &nf_nat_bysource[h], nat_bysource) {
465 		if (same_src(ct, tuple) &&
466 		    net_eq(net, nf_ct_net(ct)) &&
467 		    nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL)) {
468 			/* Copy source part from reply tuple. */
469 			nf_ct_invert_tuple(result,
470 				       &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
471 			result->dst = tuple->dst;
472 
473 			if (nf_in_range(result, range))
474 				return 1;
475 		}
476 	}
477 	return 0;
478 }
479 
480 /* For [FUTURE] fragmentation handling, we want the least-used
481  * src-ip/dst-ip/proto triple.  Fairness doesn't come into it.  Thus
482  * if the range specifies 1.2.3.4 ports 10000-10005 and 1.2.3.5 ports
483  * 1-65535, we don't do pro-rata allocation based on ports; we choose
484  * the ip with the lowest src-ip/dst-ip/proto usage.
485  */
486 static void
487 find_best_ips_proto(const struct nf_conntrack_zone *zone,
488 		    struct nf_conntrack_tuple *tuple,
489 		    const struct nf_nat_range2 *range,
490 		    const struct nf_conn *ct,
491 		    enum nf_nat_manip_type maniptype)
492 {
493 	union nf_inet_addr *var_ipp;
494 	unsigned int i, max;
495 	/* Host order */
496 	u32 minip, maxip, j, dist;
497 	bool full_range;
498 
499 	/* No IP mapping?  Do nothing. */
500 	if (!(range->flags & NF_NAT_RANGE_MAP_IPS))
501 		return;
502 
503 	if (maniptype == NF_NAT_MANIP_SRC)
504 		var_ipp = &tuple->src.u3;
505 	else
506 		var_ipp = &tuple->dst.u3;
507 
508 	/* Fast path: only one choice. */
509 	if (nf_inet_addr_cmp(&range->min_addr, &range->max_addr)) {
510 		*var_ipp = range->min_addr;
511 		return;
512 	}
513 
514 	if (nf_ct_l3num(ct) == NFPROTO_IPV4)
515 		max = sizeof(var_ipp->ip) / sizeof(u32) - 1;
516 	else
517 		max = sizeof(var_ipp->ip6) / sizeof(u32) - 1;
518 
519 	/* Hashing source and destination IPs gives a fairly even
520 	 * spread in practice (if there are a small number of IPs
521 	 * involved, there usually aren't that many connections
522 	 * anyway).  The consistency means that servers see the same
523 	 * client coming from the same IP (some Internet Banking sites
524 	 * like this), even across reboots.
525 	 */
526 	j = jhash2((u32 *)&tuple->src.u3, sizeof(tuple->src.u3) / sizeof(u32),
527 		   range->flags & NF_NAT_RANGE_PERSISTENT ?
528 			0 : (__force u32)tuple->dst.u3.all[max] ^ zone->id);
529 
530 	full_range = false;
531 	for (i = 0; i <= max; i++) {
532 		/* If first bytes of the address are at the maximum, use the
533 		 * distance. Otherwise use the full range.
534 		 */
535 		if (!full_range) {
536 			minip = ntohl((__force __be32)range->min_addr.all[i]);
537 			maxip = ntohl((__force __be32)range->max_addr.all[i]);
538 			dist  = maxip - minip + 1;
539 		} else {
540 			minip = 0;
541 			dist  = ~0;
542 		}
543 
544 		var_ipp->all[i] = (__force __u32)
545 			htonl(minip + reciprocal_scale(j, dist));
546 		if (var_ipp->all[i] != range->max_addr.all[i])
547 			full_range = true;
548 
549 		if (!(range->flags & NF_NAT_RANGE_PERSISTENT))
550 			j ^= (__force u32)tuple->dst.u3.all[i];
551 	}
552 }
553 
554 /* Alter the per-proto part of the tuple (depending on maniptype), to
555  * give a unique tuple in the given range if possible.
556  *
557  * Per-protocol part of tuple is initialized to the incoming packet.
558  */
559 static void nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple *tuple,
560 					const struct nf_nat_range2 *range,
561 					enum nf_nat_manip_type maniptype,
562 					const struct nf_conn *ct)
563 {
564 	unsigned int range_size, min, max, i, attempts;
565 	__be16 *keyptr;
566 	u16 off;
567 
568 	switch (tuple->dst.protonum) {
569 	case IPPROTO_ICMP:
570 	case IPPROTO_ICMPV6:
571 		/* id is same for either direction... */
572 		keyptr = &tuple->src.u.icmp.id;
573 		if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) {
574 			min = 0;
575 			range_size = 65536;
576 		} else {
577 			min = ntohs(range->min_proto.icmp.id);
578 			range_size = ntohs(range->max_proto.icmp.id) -
579 				     ntohs(range->min_proto.icmp.id) + 1;
580 		}
581 		goto find_free_id;
582 #if IS_ENABLED(CONFIG_NF_CT_PROTO_GRE)
583 	case IPPROTO_GRE:
584 		/* If there is no master conntrack we are not PPTP,
585 		   do not change tuples */
586 		if (!ct->master)
587 			return;
588 
589 		if (maniptype == NF_NAT_MANIP_SRC)
590 			keyptr = &tuple->src.u.gre.key;
591 		else
592 			keyptr = &tuple->dst.u.gre.key;
593 
594 		if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) {
595 			min = 1;
596 			range_size = 65535;
597 		} else {
598 			min = ntohs(range->min_proto.gre.key);
599 			range_size = ntohs(range->max_proto.gre.key) - min + 1;
600 		}
601 		goto find_free_id;
602 #endif
603 	case IPPROTO_UDP:
604 	case IPPROTO_TCP:
605 	case IPPROTO_SCTP:
606 		if (maniptype == NF_NAT_MANIP_SRC)
607 			keyptr = &tuple->src.u.all;
608 		else
609 			keyptr = &tuple->dst.u.all;
610 
611 		break;
612 	default:
613 		return;
614 	}
615 
616 	/* If no range specified... */
617 	if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) {
618 		/* If it's dst rewrite, can't change port */
619 		if (maniptype == NF_NAT_MANIP_DST)
620 			return;
621 
622 		if (ntohs(*keyptr) < 1024) {
623 			/* Loose convention: >> 512 is credential passing */
624 			if (ntohs(*keyptr) < 512) {
625 				min = 1;
626 				range_size = 511 - min + 1;
627 			} else {
628 				min = 600;
629 				range_size = 1023 - min + 1;
630 			}
631 		} else {
632 			min = 1024;
633 			range_size = 65535 - 1024 + 1;
634 		}
635 	} else {
636 		min = ntohs(range->min_proto.all);
637 		max = ntohs(range->max_proto.all);
638 		if (unlikely(max < min))
639 			swap(max, min);
640 		range_size = max - min + 1;
641 	}
642 
643 find_free_id:
644 	if (range->flags & NF_NAT_RANGE_PROTO_OFFSET)
645 		off = (ntohs(*keyptr) - ntohs(range->base_proto.all));
646 	else if ((range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL) ||
647 		 maniptype != NF_NAT_MANIP_DST)
648 		off = get_random_u16();
649 	else
650 		off = 0;
651 
652 	attempts = range_size;
653 	if (attempts > NF_NAT_MAX_ATTEMPTS)
654 		attempts = NF_NAT_MAX_ATTEMPTS;
655 
656 	/* We are in softirq; doing a search of the entire range risks
657 	 * soft lockup when all tuples are already used.
658 	 *
659 	 * If we can't find any free port from first offset, pick a new
660 	 * one and try again, with ever smaller search window.
661 	 */
662 another_round:
663 	for (i = 0; i < attempts; i++, off++) {
664 		*keyptr = htons(min + off % range_size);
665 		if (!nf_nat_used_tuple_harder(tuple, ct, attempts - i))
666 			return;
667 	}
668 
669 	if (attempts >= range_size || attempts < 16)
670 		return;
671 	attempts /= 2;
672 	off = get_random_u16();
673 	goto another_round;
674 }
675 
676 /* Manipulate the tuple into the range given. For NF_INET_POST_ROUTING,
677  * we change the source to map into the range. For NF_INET_PRE_ROUTING
678  * and NF_INET_LOCAL_OUT, we change the destination to map into the
679  * range. It might not be possible to get a unique tuple, but we try.
680  * At worst (or if we race), we will end up with a final duplicate in
681  * __nf_conntrack_confirm and drop the packet. */
682 static void
683 get_unique_tuple(struct nf_conntrack_tuple *tuple,
684 		 const struct nf_conntrack_tuple *orig_tuple,
685 		 const struct nf_nat_range2 *range,
686 		 struct nf_conn *ct,
687 		 enum nf_nat_manip_type maniptype)
688 {
689 	const struct nf_conntrack_zone *zone;
690 	struct net *net = nf_ct_net(ct);
691 
692 	zone = nf_ct_zone(ct);
693 
694 	/* 1) If this srcip/proto/src-proto-part is currently mapped,
695 	 * and that same mapping gives a unique tuple within the given
696 	 * range, use that.
697 	 *
698 	 * This is only required for source (ie. NAT/masq) mappings.
699 	 * So far, we don't do local source mappings, so multiple
700 	 * manips not an issue.
701 	 */
702 	if (maniptype == NF_NAT_MANIP_SRC &&
703 	    !(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
704 		/* try the original tuple first */
705 		if (nf_in_range(orig_tuple, range)) {
706 			if (!nf_nat_used_tuple_new(orig_tuple, ct)) {
707 				*tuple = *orig_tuple;
708 				return;
709 			}
710 		} else if (find_appropriate_src(net, zone,
711 						orig_tuple, tuple, range)) {
712 			pr_debug("get_unique_tuple: Found current src map\n");
713 			if (!nf_nat_used_tuple(tuple, ct))
714 				return;
715 		}
716 	}
717 
718 	/* 2) Select the least-used IP/proto combination in the given range */
719 	*tuple = *orig_tuple;
720 	find_best_ips_proto(zone, tuple, range, ct, maniptype);
721 
722 	/* 3) The per-protocol part of the manip is made to map into
723 	 * the range to make a unique tuple.
724 	 */
725 
726 	/* Only bother mapping if it's not already in range and unique */
727 	if (!(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
728 		if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
729 			if (!(range->flags & NF_NAT_RANGE_PROTO_OFFSET) &&
730 			    l4proto_in_range(tuple, maniptype,
731 					     &range->min_proto,
732 					     &range->max_proto) &&
733 			    (range->min_proto.all == range->max_proto.all ||
734 			     !nf_nat_used_tuple(tuple, ct)))
735 				return;
736 		} else if (!nf_nat_used_tuple(tuple, ct)) {
737 			return;
738 		}
739 	}
740 
741 	/* Last chance: get protocol to try to obtain unique tuple. */
742 	nf_nat_l4proto_unique_tuple(tuple, range, maniptype, ct);
743 }
744 
745 struct nf_conn_nat *nf_ct_nat_ext_add(struct nf_conn *ct)
746 {
747 	struct nf_conn_nat *nat = nfct_nat(ct);
748 	if (nat)
749 		return nat;
750 
751 	if (!nf_ct_is_confirmed(ct))
752 		nat = nf_ct_ext_add(ct, NF_CT_EXT_NAT, GFP_ATOMIC);
753 
754 	return nat;
755 }
756 EXPORT_SYMBOL_GPL(nf_ct_nat_ext_add);
757 
758 unsigned int
759 nf_nat_setup_info(struct nf_conn *ct,
760 		  const struct nf_nat_range2 *range,
761 		  enum nf_nat_manip_type maniptype)
762 {
763 	struct net *net = nf_ct_net(ct);
764 	struct nf_conntrack_tuple curr_tuple, new_tuple;
765 
766 	/* Can't setup nat info for confirmed ct. */
767 	if (nf_ct_is_confirmed(ct))
768 		return NF_ACCEPT;
769 
770 	if (WARN_ON(maniptype != NF_NAT_MANIP_SRC &&
771 		    maniptype != NF_NAT_MANIP_DST))
772 		return NF_DROP;
773 
774 	if (WARN_ON(nf_nat_initialized(ct, maniptype)))
775 		return NF_DROP;
776 
777 	/* What we've got will look like inverse of reply. Normally
778 	 * this is what is in the conntrack, except for prior
779 	 * manipulations (future optimization: if num_manips == 0,
780 	 * orig_tp = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple)
781 	 */
782 	nf_ct_invert_tuple(&curr_tuple,
783 			   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
784 
785 	get_unique_tuple(&new_tuple, &curr_tuple, range, ct, maniptype);
786 
787 	if (!nf_ct_tuple_equal(&new_tuple, &curr_tuple)) {
788 		struct nf_conntrack_tuple reply;
789 
790 		/* Alter conntrack table so will recognize replies. */
791 		nf_ct_invert_tuple(&reply, &new_tuple);
792 		nf_conntrack_alter_reply(ct, &reply);
793 
794 		/* Non-atomic: we own this at the moment. */
795 		if (maniptype == NF_NAT_MANIP_SRC)
796 			ct->status |= IPS_SRC_NAT;
797 		else
798 			ct->status |= IPS_DST_NAT;
799 
800 		if (nfct_help(ct) && !nfct_seqadj(ct))
801 			if (!nfct_seqadj_ext_add(ct))
802 				return NF_DROP;
803 	}
804 
805 	if (maniptype == NF_NAT_MANIP_SRC) {
806 		unsigned int srchash;
807 		spinlock_t *lock;
808 
809 		srchash = hash_by_src(net, nf_ct_zone(ct),
810 				      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
811 		lock = &nf_nat_locks[srchash % CONNTRACK_LOCKS];
812 		spin_lock_bh(lock);
813 		hlist_add_head_rcu(&ct->nat_bysource,
814 				   &nf_nat_bysource[srchash]);
815 		spin_unlock_bh(lock);
816 	}
817 
818 	/* It's done. */
819 	if (maniptype == NF_NAT_MANIP_DST)
820 		ct->status |= IPS_DST_NAT_DONE;
821 	else
822 		ct->status |= IPS_SRC_NAT_DONE;
823 
824 	return NF_ACCEPT;
825 }
826 EXPORT_SYMBOL(nf_nat_setup_info);
827 
828 static unsigned int
829 __nf_nat_alloc_null_binding(struct nf_conn *ct, enum nf_nat_manip_type manip)
830 {
831 	/* Force range to this IP; let proto decide mapping for
832 	 * per-proto parts (hence not IP_NAT_RANGE_PROTO_SPECIFIED).
833 	 * Use reply in case it's already been mangled (eg local packet).
834 	 */
835 	union nf_inet_addr ip =
836 		(manip == NF_NAT_MANIP_SRC ?
837 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3 :
838 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3);
839 	struct nf_nat_range2 range = {
840 		.flags		= NF_NAT_RANGE_MAP_IPS,
841 		.min_addr	= ip,
842 		.max_addr	= ip,
843 	};
844 	return nf_nat_setup_info(ct, &range, manip);
845 }
846 
847 unsigned int
848 nf_nat_alloc_null_binding(struct nf_conn *ct, unsigned int hooknum)
849 {
850 	return __nf_nat_alloc_null_binding(ct, HOOK2MANIP(hooknum));
851 }
852 EXPORT_SYMBOL_GPL(nf_nat_alloc_null_binding);
853 
854 /* Do packet manipulations according to nf_nat_setup_info. */
855 unsigned int nf_nat_packet(struct nf_conn *ct,
856 			   enum ip_conntrack_info ctinfo,
857 			   unsigned int hooknum,
858 			   struct sk_buff *skb)
859 {
860 	enum nf_nat_manip_type mtype = HOOK2MANIP(hooknum);
861 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
862 	unsigned int verdict = NF_ACCEPT;
863 	unsigned long statusbit;
864 
865 	if (mtype == NF_NAT_MANIP_SRC)
866 		statusbit = IPS_SRC_NAT;
867 	else
868 		statusbit = IPS_DST_NAT;
869 
870 	/* Invert if this is reply dir. */
871 	if (dir == IP_CT_DIR_REPLY)
872 		statusbit ^= IPS_NAT_MASK;
873 
874 	/* Non-atomic: these bits don't change. */
875 	if (ct->status & statusbit)
876 		verdict = nf_nat_manip_pkt(skb, ct, mtype, dir);
877 
878 	return verdict;
879 }
880 EXPORT_SYMBOL_GPL(nf_nat_packet);
881 
882 static bool in_vrf_postrouting(const struct nf_hook_state *state)
883 {
884 #if IS_ENABLED(CONFIG_NET_L3_MASTER_DEV)
885 	if (state->hook == NF_INET_POST_ROUTING &&
886 	    netif_is_l3_master(state->out))
887 		return true;
888 #endif
889 	return false;
890 }
891 
892 unsigned int
893 nf_nat_inet_fn(void *priv, struct sk_buff *skb,
894 	       const struct nf_hook_state *state)
895 {
896 	struct nf_conn *ct;
897 	enum ip_conntrack_info ctinfo;
898 	struct nf_conn_nat *nat;
899 	/* maniptype == SRC for postrouting. */
900 	enum nf_nat_manip_type maniptype = HOOK2MANIP(state->hook);
901 
902 	ct = nf_ct_get(skb, &ctinfo);
903 	/* Can't track?  It's not due to stress, or conntrack would
904 	 * have dropped it.  Hence it's the user's responsibilty to
905 	 * packet filter it out, or implement conntrack/NAT for that
906 	 * protocol. 8) --RR
907 	 */
908 	if (!ct || in_vrf_postrouting(state))
909 		return NF_ACCEPT;
910 
911 	nat = nfct_nat(ct);
912 
913 	switch (ctinfo) {
914 	case IP_CT_RELATED:
915 	case IP_CT_RELATED_REPLY:
916 		/* Only ICMPs can be IP_CT_IS_REPLY.  Fallthrough */
917 	case IP_CT_NEW:
918 		/* Seen it before?  This can happen for loopback, retrans,
919 		 * or local packets.
920 		 */
921 		if (!nf_nat_initialized(ct, maniptype)) {
922 			struct nf_nat_lookup_hook_priv *lpriv = priv;
923 			struct nf_hook_entries *e = rcu_dereference(lpriv->entries);
924 			unsigned int ret;
925 			int i;
926 
927 			if (!e)
928 				goto null_bind;
929 
930 			for (i = 0; i < e->num_hook_entries; i++) {
931 				ret = e->hooks[i].hook(e->hooks[i].priv, skb,
932 						       state);
933 				if (ret != NF_ACCEPT)
934 					return ret;
935 				if (nf_nat_initialized(ct, maniptype))
936 					goto do_nat;
937 			}
938 null_bind:
939 			ret = nf_nat_alloc_null_binding(ct, state->hook);
940 			if (ret != NF_ACCEPT)
941 				return ret;
942 		} else {
943 			pr_debug("Already setup manip %s for ct %p (status bits 0x%lx)\n",
944 				 maniptype == NF_NAT_MANIP_SRC ? "SRC" : "DST",
945 				 ct, ct->status);
946 			if (nf_nat_oif_changed(state->hook, ctinfo, nat,
947 					       state->out))
948 				goto oif_changed;
949 		}
950 		break;
951 	default:
952 		/* ESTABLISHED */
953 		WARN_ON(ctinfo != IP_CT_ESTABLISHED &&
954 			ctinfo != IP_CT_ESTABLISHED_REPLY);
955 		if (nf_nat_oif_changed(state->hook, ctinfo, nat, state->out))
956 			goto oif_changed;
957 	}
958 do_nat:
959 	return nf_nat_packet(ct, ctinfo, state->hook, skb);
960 
961 oif_changed:
962 	nf_ct_kill_acct(ct, ctinfo, skb);
963 	return NF_DROP;
964 }
965 EXPORT_SYMBOL_GPL(nf_nat_inet_fn);
966 
967 struct nf_nat_proto_clean {
968 	u8	l3proto;
969 	u8	l4proto;
970 };
971 
972 /* kill conntracks with affected NAT section */
973 static int nf_nat_proto_remove(struct nf_conn *i, void *data)
974 {
975 	const struct nf_nat_proto_clean *clean = data;
976 
977 	if ((clean->l3proto && nf_ct_l3num(i) != clean->l3proto) ||
978 	    (clean->l4proto && nf_ct_protonum(i) != clean->l4proto))
979 		return 0;
980 
981 	return i->status & IPS_NAT_MASK ? 1 : 0;
982 }
983 
984 static void nf_nat_cleanup_conntrack(struct nf_conn *ct)
985 {
986 	unsigned int h;
987 
988 	h = hash_by_src(nf_ct_net(ct), nf_ct_zone(ct), &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
989 	spin_lock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
990 	hlist_del_rcu(&ct->nat_bysource);
991 	spin_unlock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
992 }
993 
994 static int nf_nat_proto_clean(struct nf_conn *ct, void *data)
995 {
996 	if (nf_nat_proto_remove(ct, data))
997 		return 1;
998 
999 	/* This module is being removed and conntrack has nat null binding.
1000 	 * Remove it from bysource hash, as the table will be freed soon.
1001 	 *
1002 	 * Else, when the conntrack is destoyed, nf_nat_cleanup_conntrack()
1003 	 * will delete entry from already-freed table.
1004 	 */
1005 	if (test_and_clear_bit(IPS_SRC_NAT_DONE_BIT, &ct->status))
1006 		nf_nat_cleanup_conntrack(ct);
1007 
1008 	/* don't delete conntrack.  Although that would make things a lot
1009 	 * simpler, we'd end up flushing all conntracks on nat rmmod.
1010 	 */
1011 	return 0;
1012 }
1013 
1014 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1015 
1016 #include <linux/netfilter/nfnetlink.h>
1017 #include <linux/netfilter/nfnetlink_conntrack.h>
1018 
1019 static const struct nla_policy protonat_nla_policy[CTA_PROTONAT_MAX+1] = {
1020 	[CTA_PROTONAT_PORT_MIN]	= { .type = NLA_U16 },
1021 	[CTA_PROTONAT_PORT_MAX]	= { .type = NLA_U16 },
1022 };
1023 
1024 static int nf_nat_l4proto_nlattr_to_range(struct nlattr *tb[],
1025 					  struct nf_nat_range2 *range)
1026 {
1027 	if (tb[CTA_PROTONAT_PORT_MIN]) {
1028 		range->min_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MIN]);
1029 		range->max_proto.all = range->min_proto.all;
1030 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1031 	}
1032 	if (tb[CTA_PROTONAT_PORT_MAX]) {
1033 		range->max_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MAX]);
1034 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1035 	}
1036 	return 0;
1037 }
1038 
1039 static int nfnetlink_parse_nat_proto(struct nlattr *attr,
1040 				     const struct nf_conn *ct,
1041 				     struct nf_nat_range2 *range)
1042 {
1043 	struct nlattr *tb[CTA_PROTONAT_MAX+1];
1044 	int err;
1045 
1046 	err = nla_parse_nested_deprecated(tb, CTA_PROTONAT_MAX, attr,
1047 					  protonat_nla_policy, NULL);
1048 	if (err < 0)
1049 		return err;
1050 
1051 	return nf_nat_l4proto_nlattr_to_range(tb, range);
1052 }
1053 
1054 static const struct nla_policy nat_nla_policy[CTA_NAT_MAX+1] = {
1055 	[CTA_NAT_V4_MINIP]	= { .type = NLA_U32 },
1056 	[CTA_NAT_V4_MAXIP]	= { .type = NLA_U32 },
1057 	[CTA_NAT_V6_MINIP]	= { .len = sizeof(struct in6_addr) },
1058 	[CTA_NAT_V6_MAXIP]	= { .len = sizeof(struct in6_addr) },
1059 	[CTA_NAT_PROTO]		= { .type = NLA_NESTED },
1060 };
1061 
1062 static int nf_nat_ipv4_nlattr_to_range(struct nlattr *tb[],
1063 				       struct nf_nat_range2 *range)
1064 {
1065 	if (tb[CTA_NAT_V4_MINIP]) {
1066 		range->min_addr.ip = nla_get_be32(tb[CTA_NAT_V4_MINIP]);
1067 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1068 	}
1069 
1070 	range->max_addr.ip = nla_get_be32_default(tb[CTA_NAT_V4_MAXIP],
1071 						  range->min_addr.ip);
1072 
1073 	return 0;
1074 }
1075 
1076 static int nf_nat_ipv6_nlattr_to_range(struct nlattr *tb[],
1077 				       struct nf_nat_range2 *range)
1078 {
1079 	if (tb[CTA_NAT_V6_MINIP]) {
1080 		nla_memcpy(&range->min_addr.ip6, tb[CTA_NAT_V6_MINIP],
1081 			   sizeof(struct in6_addr));
1082 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1083 	}
1084 
1085 	if (tb[CTA_NAT_V6_MAXIP])
1086 		nla_memcpy(&range->max_addr.ip6, tb[CTA_NAT_V6_MAXIP],
1087 			   sizeof(struct in6_addr));
1088 	else
1089 		range->max_addr = range->min_addr;
1090 
1091 	return 0;
1092 }
1093 
1094 static int
1095 nfnetlink_parse_nat(const struct nlattr *nat,
1096 		    const struct nf_conn *ct, struct nf_nat_range2 *range)
1097 {
1098 	struct nlattr *tb[CTA_NAT_MAX+1];
1099 	int err;
1100 
1101 	memset(range, 0, sizeof(*range));
1102 
1103 	err = nla_parse_nested_deprecated(tb, CTA_NAT_MAX, nat,
1104 					  nat_nla_policy, NULL);
1105 	if (err < 0)
1106 		return err;
1107 
1108 	switch (nf_ct_l3num(ct)) {
1109 	case NFPROTO_IPV4:
1110 		err = nf_nat_ipv4_nlattr_to_range(tb, range);
1111 		break;
1112 	case NFPROTO_IPV6:
1113 		err = nf_nat_ipv6_nlattr_to_range(tb, range);
1114 		break;
1115 	default:
1116 		err = -EPROTONOSUPPORT;
1117 		break;
1118 	}
1119 
1120 	if (err)
1121 		return err;
1122 
1123 	if (!tb[CTA_NAT_PROTO])
1124 		return 0;
1125 
1126 	return nfnetlink_parse_nat_proto(tb[CTA_NAT_PROTO], ct, range);
1127 }
1128 
1129 /* This function is called under rcu_read_lock() */
1130 static int
1131 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1132 			  enum nf_nat_manip_type manip,
1133 			  const struct nlattr *attr)
1134 {
1135 	struct nf_nat_range2 range;
1136 	int err;
1137 
1138 	/* Should not happen, restricted to creating new conntracks
1139 	 * via ctnetlink.
1140 	 */
1141 	if (WARN_ON_ONCE(nf_nat_initialized(ct, manip)))
1142 		return -EEXIST;
1143 
1144 	/* No NAT information has been passed, allocate the null-binding */
1145 	if (attr == NULL)
1146 		return __nf_nat_alloc_null_binding(ct, manip) == NF_DROP ? -ENOMEM : 0;
1147 
1148 	err = nfnetlink_parse_nat(attr, ct, &range);
1149 	if (err < 0)
1150 		return err;
1151 
1152 	return nf_nat_setup_info(ct, &range, manip) == NF_DROP ? -ENOMEM : 0;
1153 }
1154 #else
1155 static int
1156 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1157 			  enum nf_nat_manip_type manip,
1158 			  const struct nlattr *attr)
1159 {
1160 	return -EOPNOTSUPP;
1161 }
1162 #endif
1163 
1164 static struct nf_ct_helper_expectfn follow_master_nat = {
1165 	.name		= "nat-follow-master",
1166 	.expectfn	= nf_nat_follow_master,
1167 };
1168 
1169 int nf_nat_register_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1170 		       const struct nf_hook_ops *orig_nat_ops, unsigned int ops_count)
1171 {
1172 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1173 	struct nf_nat_hooks_net *nat_proto_net;
1174 	struct nf_nat_lookup_hook_priv *priv;
1175 	unsigned int hooknum = ops->hooknum;
1176 	struct nf_hook_ops *nat_ops;
1177 	int i, ret;
1178 
1179 #ifndef MODULE
1180 	/* If nf_nat_core is built-in and nf_nat_init() fails, dependent
1181 	 * modules like nft_chain_nat.ko may still call this function.
1182 	 * However, nat_net would be invalid, likely pointing to some other
1183 	 * per-net structure.
1184 	 */
1185 	if (WARN_ON_ONCE(!nf_nat_hook))
1186 		return -EOPNOTSUPP;
1187 #endif
1188 
1189 	if (WARN_ON_ONCE(pf >= ARRAY_SIZE(nat_net->nat_proto_net)))
1190 		return -EINVAL;
1191 
1192 	nat_proto_net = &nat_net->nat_proto_net[pf];
1193 
1194 	for (i = 0; i < ops_count; i++) {
1195 		if (orig_nat_ops[i].hooknum == hooknum) {
1196 			hooknum = i;
1197 			break;
1198 		}
1199 	}
1200 
1201 	if (WARN_ON_ONCE(i == ops_count))
1202 		return -EINVAL;
1203 
1204 	mutex_lock(&nf_nat_proto_mutex);
1205 	if (!nat_proto_net->nat_hook_ops) {
1206 		WARN_ON(nat_proto_net->users != 0);
1207 
1208 		nat_ops = kmemdup_array(orig_nat_ops, ops_count, sizeof(*orig_nat_ops), GFP_KERNEL);
1209 		if (!nat_ops) {
1210 			mutex_unlock(&nf_nat_proto_mutex);
1211 			return -ENOMEM;
1212 		}
1213 
1214 		for (i = 0; i < ops_count; i++) {
1215 			priv = kzalloc_obj(*priv);
1216 			if (priv) {
1217 				nat_ops[i].priv = priv;
1218 				continue;
1219 			}
1220 			mutex_unlock(&nf_nat_proto_mutex);
1221 			while (i)
1222 				kfree(nat_ops[--i].priv);
1223 			kfree(nat_ops);
1224 			return -ENOMEM;
1225 		}
1226 
1227 		ret = nf_register_net_hooks(net, nat_ops, ops_count);
1228 		if (ret < 0)
1229 			goto err_free_hooks;
1230 	} else {
1231 		nat_ops = nat_proto_net->nat_hook_ops;
1232 	}
1233 
1234 	priv = nat_ops[hooknum].priv;
1235 	if (WARN_ON_ONCE(!priv)) {
1236 		ret = -EOPNOTSUPP;
1237 		goto err_unregister_hooks;
1238 	}
1239 
1240 	ret = nf_hook_entries_insert_raw(&priv->entries, ops);
1241 	if (ret)
1242 		goto err_unregister_hooks;
1243 
1244 	if (!nat_proto_net->nat_hook_ops)
1245 		nat_proto_net->nat_hook_ops = nat_ops;
1246 
1247 	nat_proto_net->users++;
1248 
1249 	mutex_unlock(&nf_nat_proto_mutex);
1250 
1251 	return 0;
1252 
1253 err_unregister_hooks:
1254 	if (nat_proto_net->nat_hook_ops) {
1255 		mutex_unlock(&nf_nat_proto_mutex);
1256 		return ret;
1257 	}
1258 	nf_unregister_net_hooks(net, nat_ops, ops_count);
1259 err_free_hooks:
1260 	mutex_unlock(&nf_nat_proto_mutex);
1261 	for (i = 0; i < ops_count; i++) {
1262 		priv = nat_ops[i].priv;
1263 		kfree_rcu(priv, rcu_head);
1264 	}
1265 	kfree_rcu(nat_ops, rcu);
1266 
1267 	return ret;
1268 }
1269 
1270 void nf_nat_unregister_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1271 			  unsigned int ops_count)
1272 {
1273 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1274 	struct nf_nat_hooks_net *nat_proto_net;
1275 	struct nf_nat_lookup_hook_priv *priv;
1276 	struct nf_hook_ops *nat_ops;
1277 	int hooknum = ops->hooknum;
1278 	int i;
1279 
1280 	if (pf >= ARRAY_SIZE(nat_net->nat_proto_net))
1281 		return;
1282 
1283 	nat_proto_net = &nat_net->nat_proto_net[pf];
1284 
1285 	mutex_lock(&nf_nat_proto_mutex);
1286 	if (WARN_ON(nat_proto_net->users == 0))
1287 		goto unlock;
1288 
1289 	nat_proto_net->users--;
1290 
1291 	nat_ops = nat_proto_net->nat_hook_ops;
1292 	for (i = 0; i < ops_count; i++) {
1293 		if (nat_ops[i].hooknum == hooknum) {
1294 			hooknum = i;
1295 			break;
1296 		}
1297 	}
1298 	if (WARN_ON_ONCE(i == ops_count))
1299 		goto unlock;
1300 	priv = nat_ops[hooknum].priv;
1301 	nf_hook_entries_delete_raw(&priv->entries, ops);
1302 
1303 	if (nat_proto_net->users == 0) {
1304 		nf_unregister_net_hooks(net, nat_ops, ops_count);
1305 
1306 		for (i = 0; i < ops_count; i++) {
1307 			priv = nat_ops[i].priv;
1308 			kfree_rcu(priv, rcu_head);
1309 		}
1310 
1311 		nat_proto_net->nat_hook_ops = NULL;
1312 		kfree_rcu(nat_ops, rcu);
1313 	}
1314 unlock:
1315 	mutex_unlock(&nf_nat_proto_mutex);
1316 }
1317 
1318 static struct pernet_operations nat_net_ops = {
1319 	.id = &nat_net_id,
1320 	.size = sizeof(struct nat_net),
1321 };
1322 
1323 static const struct nf_nat_hook nat_hook = {
1324 	.parse_nat_setup	= nfnetlink_parse_nat_setup,
1325 #ifdef CONFIG_XFRM
1326 	.decode_session		= __nf_nat_decode_session,
1327 #endif
1328 	.remove_nat_bysrc	= nf_nat_cleanup_conntrack,
1329 };
1330 
1331 static int __init nf_nat_init(void)
1332 {
1333 	int ret, i;
1334 
1335 	/* Leave them the same for the moment. */
1336 	nf_nat_htable_size = nf_conntrack_htable_size;
1337 	if (nf_nat_htable_size < CONNTRACK_LOCKS)
1338 		nf_nat_htable_size = CONNTRACK_LOCKS;
1339 
1340 	nf_nat_bysource = nf_ct_alloc_hashtable(&nf_nat_htable_size, 0);
1341 	if (!nf_nat_bysource)
1342 		return -ENOMEM;
1343 
1344 	for (i = 0; i < CONNTRACK_LOCKS; i++)
1345 		spin_lock_init(&nf_nat_locks[i]);
1346 
1347 	ret = register_pernet_subsys(&nat_net_ops);
1348 	if (ret < 0) {
1349 		kvfree(nf_nat_bysource);
1350 		return ret;
1351 	}
1352 
1353 	nf_ct_helper_expectfn_register(&follow_master_nat);
1354 
1355 	WARN_ON(nf_nat_hook != NULL);
1356 	RCU_INIT_POINTER(nf_nat_hook, &nat_hook);
1357 
1358 	ret = register_nf_nat_bpf();
1359 	if (ret < 0) {
1360 		RCU_INIT_POINTER(nf_nat_hook, NULL);
1361 		nf_ct_helper_expectfn_unregister(&follow_master_nat);
1362 		synchronize_net();
1363 		nf_ct_helper_expectfn_destroy(&follow_master_nat);
1364 		unregister_pernet_subsys(&nat_net_ops);
1365 		kvfree(nf_nat_bysource);
1366 	}
1367 
1368 	return ret;
1369 }
1370 
1371 static void __exit nf_nat_cleanup(void)
1372 {
1373 	struct nf_nat_proto_clean clean = {};
1374 
1375 	nf_ct_iterate_destroy(nf_nat_proto_clean, &clean);
1376 
1377 	nf_ct_helper_expectfn_unregister(&follow_master_nat);
1378 	RCU_INIT_POINTER(nf_nat_hook, NULL);
1379 
1380 	synchronize_net();
1381 	nf_ct_helper_expectfn_destroy(&follow_master_nat);
1382 	kvfree(nf_nat_bysource);
1383 	unregister_pernet_subsys(&nat_net_ops);
1384 }
1385 
1386 MODULE_LICENSE("GPL");
1387 MODULE_DESCRIPTION("Network address translation core");
1388 
1389 module_init(nf_nat_init);
1390 module_exit(nf_nat_cleanup);
1391