xref: /linux/net/netfilter/nf_nat_core.c (revision 91ec2035134982b98fab0609a9fd8480e8217dc1)
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
nf_nat_ipv4_decode_session(struct sk_buff * skb,const struct nf_conn * ct,enum ip_conntrack_dir dir,unsigned long statusbit,struct flowi * fl)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 
nf_nat_ipv6_decode_session(struct sk_buff * skb,const struct nf_conn * ct,enum ip_conntrack_dir dir,unsigned long statusbit,struct flowi * fl)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 
__nf_nat_decode_session(struct sk_buff * skb,struct flowi * fl)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
hash_by_src(const struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * tuple)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
nf_nat_used_tuple(const struct nf_conntrack_tuple * tuple,const struct nf_conn * ignored_conntrack)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 
nf_nat_allow_clash(const struct nf_conn * ct)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
nf_nat_used_tuple_new(const struct nf_conntrack_tuple * tuple,const struct nf_conn * ignored_ct)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 
nf_nat_may_kill(struct nf_conn * ct,unsigned long flags)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  */
nf_seq_has_advanced(const struct nf_conn * old,const struct nf_conn * new)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
nf_nat_used_tuple_harder(const struct nf_conntrack_tuple * tuple,const struct nf_conn * ignored_conntrack,unsigned int attempts_left)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 
nf_nat_inet_in_range(const struct nf_conntrack_tuple * t,const struct nf_nat_range2 * range)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? */
l4proto_in_range(const struct nf_conntrack_tuple * tuple,enum nf_nat_manip_type maniptype,const union nf_conntrack_man_proto * min,const union nf_conntrack_man_proto * max)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  */
nf_in_range(const struct nf_conntrack_tuple * tuple,const struct nf_nat_range2 * range)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
same_src(const struct nf_conn * ct,const struct nf_conntrack_tuple * tuple)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
find_appropriate_src(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * tuple,struct nf_conntrack_tuple * result,const struct nf_nat_range2 * range)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
find_best_ips_proto(const struct nf_conntrack_zone * zone,struct nf_conntrack_tuple * tuple,const struct nf_nat_range2 * range,const struct nf_conn * ct,enum nf_nat_manip_type maniptype)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  */
nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple * tuple,const struct nf_nat_range2 * range,enum nf_nat_manip_type maniptype,const struct nf_conn * ct)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
get_unique_tuple(struct nf_conntrack_tuple * tuple,const struct nf_conntrack_tuple * orig_tuple,const struct nf_nat_range2 * range,struct nf_conn * ct,enum nf_nat_manip_type maniptype)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 
nf_ct_nat_ext_add(struct nf_conn * ct)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
nf_nat_setup_info(struct nf_conn * ct,const struct nf_nat_range2 * range,enum nf_nat_manip_type maniptype)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 	WARN_ON(maniptype != NF_NAT_MANIP_SRC &&
771 		maniptype != NF_NAT_MANIP_DST);
772 
773 	if (WARN_ON(nf_nat_initialized(ct, maniptype)))
774 		return NF_DROP;
775 
776 	/* What we've got will look like inverse of reply. Normally
777 	 * this is what is in the conntrack, except for prior
778 	 * manipulations (future optimization: if num_manips == 0,
779 	 * orig_tp = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple)
780 	 */
781 	nf_ct_invert_tuple(&curr_tuple,
782 			   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
783 
784 	get_unique_tuple(&new_tuple, &curr_tuple, range, ct, maniptype);
785 
786 	if (!nf_ct_tuple_equal(&new_tuple, &curr_tuple)) {
787 		struct nf_conntrack_tuple reply;
788 
789 		/* Alter conntrack table so will recognize replies. */
790 		nf_ct_invert_tuple(&reply, &new_tuple);
791 		nf_conntrack_alter_reply(ct, &reply);
792 
793 		/* Non-atomic: we own this at the moment. */
794 		if (maniptype == NF_NAT_MANIP_SRC)
795 			ct->status |= IPS_SRC_NAT;
796 		else
797 			ct->status |= IPS_DST_NAT;
798 
799 		if (nfct_help(ct) && !nfct_seqadj(ct))
800 			if (!nfct_seqadj_ext_add(ct))
801 				return NF_DROP;
802 	}
803 
804 	if (maniptype == NF_NAT_MANIP_SRC) {
805 		unsigned int srchash;
806 		spinlock_t *lock;
807 
808 		srchash = hash_by_src(net, nf_ct_zone(ct),
809 				      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
810 		lock = &nf_nat_locks[srchash % CONNTRACK_LOCKS];
811 		spin_lock_bh(lock);
812 		hlist_add_head_rcu(&ct->nat_bysource,
813 				   &nf_nat_bysource[srchash]);
814 		spin_unlock_bh(lock);
815 	}
816 
817 	/* It's done. */
818 	if (maniptype == NF_NAT_MANIP_DST)
819 		ct->status |= IPS_DST_NAT_DONE;
820 	else
821 		ct->status |= IPS_SRC_NAT_DONE;
822 
823 	return NF_ACCEPT;
824 }
825 EXPORT_SYMBOL(nf_nat_setup_info);
826 
827 static unsigned int
__nf_nat_alloc_null_binding(struct nf_conn * ct,enum nf_nat_manip_type manip)828 __nf_nat_alloc_null_binding(struct nf_conn *ct, enum nf_nat_manip_type manip)
829 {
830 	/* Force range to this IP; let proto decide mapping for
831 	 * per-proto parts (hence not IP_NAT_RANGE_PROTO_SPECIFIED).
832 	 * Use reply in case it's already been mangled (eg local packet).
833 	 */
834 	union nf_inet_addr ip =
835 		(manip == NF_NAT_MANIP_SRC ?
836 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3 :
837 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3);
838 	struct nf_nat_range2 range = {
839 		.flags		= NF_NAT_RANGE_MAP_IPS,
840 		.min_addr	= ip,
841 		.max_addr	= ip,
842 	};
843 	return nf_nat_setup_info(ct, &range, manip);
844 }
845 
846 unsigned int
nf_nat_alloc_null_binding(struct nf_conn * ct,unsigned int hooknum)847 nf_nat_alloc_null_binding(struct nf_conn *ct, unsigned int hooknum)
848 {
849 	return __nf_nat_alloc_null_binding(ct, HOOK2MANIP(hooknum));
850 }
851 EXPORT_SYMBOL_GPL(nf_nat_alloc_null_binding);
852 
853 /* Do packet manipulations according to nf_nat_setup_info. */
nf_nat_packet(struct nf_conn * ct,enum ip_conntrack_info ctinfo,unsigned int hooknum,struct sk_buff * skb)854 unsigned int nf_nat_packet(struct nf_conn *ct,
855 			   enum ip_conntrack_info ctinfo,
856 			   unsigned int hooknum,
857 			   struct sk_buff *skb)
858 {
859 	enum nf_nat_manip_type mtype = HOOK2MANIP(hooknum);
860 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
861 	unsigned int verdict = NF_ACCEPT;
862 	unsigned long statusbit;
863 
864 	if (mtype == NF_NAT_MANIP_SRC)
865 		statusbit = IPS_SRC_NAT;
866 	else
867 		statusbit = IPS_DST_NAT;
868 
869 	/* Invert if this is reply dir. */
870 	if (dir == IP_CT_DIR_REPLY)
871 		statusbit ^= IPS_NAT_MASK;
872 
873 	/* Non-atomic: these bits don't change. */
874 	if (ct->status & statusbit)
875 		verdict = nf_nat_manip_pkt(skb, ct, mtype, dir);
876 
877 	return verdict;
878 }
879 EXPORT_SYMBOL_GPL(nf_nat_packet);
880 
in_vrf_postrouting(const struct nf_hook_state * state)881 static bool in_vrf_postrouting(const struct nf_hook_state *state)
882 {
883 #if IS_ENABLED(CONFIG_NET_L3_MASTER_DEV)
884 	if (state->hook == NF_INET_POST_ROUTING &&
885 	    netif_is_l3_master(state->out))
886 		return true;
887 #endif
888 	return false;
889 }
890 
891 unsigned int
nf_nat_inet_fn(void * priv,struct sk_buff * skb,const struct nf_hook_state * state)892 nf_nat_inet_fn(void *priv, struct sk_buff *skb,
893 	       const struct nf_hook_state *state)
894 {
895 	struct nf_conn *ct;
896 	enum ip_conntrack_info ctinfo;
897 	struct nf_conn_nat *nat;
898 	/* maniptype == SRC for postrouting. */
899 	enum nf_nat_manip_type maniptype = HOOK2MANIP(state->hook);
900 
901 	ct = nf_ct_get(skb, &ctinfo);
902 	/* Can't track?  It's not due to stress, or conntrack would
903 	 * have dropped it.  Hence it's the user's responsibilty to
904 	 * packet filter it out, or implement conntrack/NAT for that
905 	 * protocol. 8) --RR
906 	 */
907 	if (!ct || in_vrf_postrouting(state))
908 		return NF_ACCEPT;
909 
910 	nat = nfct_nat(ct);
911 
912 	switch (ctinfo) {
913 	case IP_CT_RELATED:
914 	case IP_CT_RELATED_REPLY:
915 		/* Only ICMPs can be IP_CT_IS_REPLY.  Fallthrough */
916 	case IP_CT_NEW:
917 		/* Seen it before?  This can happen for loopback, retrans,
918 		 * or local packets.
919 		 */
920 		if (!nf_nat_initialized(ct, maniptype)) {
921 			struct nf_nat_lookup_hook_priv *lpriv = priv;
922 			struct nf_hook_entries *e = rcu_dereference(lpriv->entries);
923 			unsigned int ret;
924 			int i;
925 
926 			if (!e)
927 				goto null_bind;
928 
929 			for (i = 0; i < e->num_hook_entries; i++) {
930 				ret = e->hooks[i].hook(e->hooks[i].priv, skb,
931 						       state);
932 				if (ret != NF_ACCEPT)
933 					return ret;
934 				if (nf_nat_initialized(ct, maniptype))
935 					goto do_nat;
936 			}
937 null_bind:
938 			ret = nf_nat_alloc_null_binding(ct, state->hook);
939 			if (ret != NF_ACCEPT)
940 				return ret;
941 		} else {
942 			pr_debug("Already setup manip %s for ct %p (status bits 0x%lx)\n",
943 				 maniptype == NF_NAT_MANIP_SRC ? "SRC" : "DST",
944 				 ct, ct->status);
945 			if (nf_nat_oif_changed(state->hook, ctinfo, nat,
946 					       state->out))
947 				goto oif_changed;
948 		}
949 		break;
950 	default:
951 		/* ESTABLISHED */
952 		WARN_ON(ctinfo != IP_CT_ESTABLISHED &&
953 			ctinfo != IP_CT_ESTABLISHED_REPLY);
954 		if (nf_nat_oif_changed(state->hook, ctinfo, nat, state->out))
955 			goto oif_changed;
956 	}
957 do_nat:
958 	return nf_nat_packet(ct, ctinfo, state->hook, skb);
959 
960 oif_changed:
961 	nf_ct_kill_acct(ct, ctinfo, skb);
962 	return NF_DROP;
963 }
964 EXPORT_SYMBOL_GPL(nf_nat_inet_fn);
965 
966 struct nf_nat_proto_clean {
967 	u8	l3proto;
968 	u8	l4proto;
969 };
970 
971 /* kill conntracks with affected NAT section */
nf_nat_proto_remove(struct nf_conn * i,void * data)972 static int nf_nat_proto_remove(struct nf_conn *i, void *data)
973 {
974 	const struct nf_nat_proto_clean *clean = data;
975 
976 	if ((clean->l3proto && nf_ct_l3num(i) != clean->l3proto) ||
977 	    (clean->l4proto && nf_ct_protonum(i) != clean->l4proto))
978 		return 0;
979 
980 	return i->status & IPS_NAT_MASK ? 1 : 0;
981 }
982 
nf_nat_cleanup_conntrack(struct nf_conn * ct)983 static void nf_nat_cleanup_conntrack(struct nf_conn *ct)
984 {
985 	unsigned int h;
986 
987 	h = hash_by_src(nf_ct_net(ct), nf_ct_zone(ct), &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
988 	spin_lock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
989 	hlist_del_rcu(&ct->nat_bysource);
990 	spin_unlock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
991 }
992 
nf_nat_proto_clean(struct nf_conn * ct,void * data)993 static int nf_nat_proto_clean(struct nf_conn *ct, void *data)
994 {
995 	if (nf_nat_proto_remove(ct, data))
996 		return 1;
997 
998 	/* This module is being removed and conntrack has nat null binding.
999 	 * Remove it from bysource hash, as the table will be freed soon.
1000 	 *
1001 	 * Else, when the conntrack is destoyed, nf_nat_cleanup_conntrack()
1002 	 * will delete entry from already-freed table.
1003 	 */
1004 	if (test_and_clear_bit(IPS_SRC_NAT_DONE_BIT, &ct->status))
1005 		nf_nat_cleanup_conntrack(ct);
1006 
1007 	/* don't delete conntrack.  Although that would make things a lot
1008 	 * simpler, we'd end up flushing all conntracks on nat rmmod.
1009 	 */
1010 	return 0;
1011 }
1012 
1013 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1014 
1015 #include <linux/netfilter/nfnetlink.h>
1016 #include <linux/netfilter/nfnetlink_conntrack.h>
1017 
1018 static const struct nla_policy protonat_nla_policy[CTA_PROTONAT_MAX+1] = {
1019 	[CTA_PROTONAT_PORT_MIN]	= { .type = NLA_U16 },
1020 	[CTA_PROTONAT_PORT_MAX]	= { .type = NLA_U16 },
1021 };
1022 
nf_nat_l4proto_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1023 static int nf_nat_l4proto_nlattr_to_range(struct nlattr *tb[],
1024 					  struct nf_nat_range2 *range)
1025 {
1026 	if (tb[CTA_PROTONAT_PORT_MIN]) {
1027 		range->min_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MIN]);
1028 		range->max_proto.all = range->min_proto.all;
1029 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1030 	}
1031 	if (tb[CTA_PROTONAT_PORT_MAX]) {
1032 		range->max_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MAX]);
1033 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1034 	}
1035 	return 0;
1036 }
1037 
nfnetlink_parse_nat_proto(struct nlattr * attr,const struct nf_conn * ct,struct nf_nat_range2 * range)1038 static int nfnetlink_parse_nat_proto(struct nlattr *attr,
1039 				     const struct nf_conn *ct,
1040 				     struct nf_nat_range2 *range)
1041 {
1042 	struct nlattr *tb[CTA_PROTONAT_MAX+1];
1043 	int err;
1044 
1045 	err = nla_parse_nested_deprecated(tb, CTA_PROTONAT_MAX, attr,
1046 					  protonat_nla_policy, NULL);
1047 	if (err < 0)
1048 		return err;
1049 
1050 	return nf_nat_l4proto_nlattr_to_range(tb, range);
1051 }
1052 
1053 static const struct nla_policy nat_nla_policy[CTA_NAT_MAX+1] = {
1054 	[CTA_NAT_V4_MINIP]	= { .type = NLA_U32 },
1055 	[CTA_NAT_V4_MAXIP]	= { .type = NLA_U32 },
1056 	[CTA_NAT_V6_MINIP]	= { .len = sizeof(struct in6_addr) },
1057 	[CTA_NAT_V6_MAXIP]	= { .len = sizeof(struct in6_addr) },
1058 	[CTA_NAT_PROTO]		= { .type = NLA_NESTED },
1059 };
1060 
nf_nat_ipv4_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1061 static int nf_nat_ipv4_nlattr_to_range(struct nlattr *tb[],
1062 				       struct nf_nat_range2 *range)
1063 {
1064 	if (tb[CTA_NAT_V4_MINIP]) {
1065 		range->min_addr.ip = nla_get_be32(tb[CTA_NAT_V4_MINIP]);
1066 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1067 	}
1068 
1069 	range->max_addr.ip = nla_get_be32_default(tb[CTA_NAT_V4_MAXIP],
1070 						  range->min_addr.ip);
1071 
1072 	return 0;
1073 }
1074 
nf_nat_ipv6_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1075 static int nf_nat_ipv6_nlattr_to_range(struct nlattr *tb[],
1076 				       struct nf_nat_range2 *range)
1077 {
1078 	if (tb[CTA_NAT_V6_MINIP]) {
1079 		nla_memcpy(&range->min_addr.ip6, tb[CTA_NAT_V6_MINIP],
1080 			   sizeof(struct in6_addr));
1081 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1082 	}
1083 
1084 	if (tb[CTA_NAT_V6_MAXIP])
1085 		nla_memcpy(&range->max_addr.ip6, tb[CTA_NAT_V6_MAXIP],
1086 			   sizeof(struct in6_addr));
1087 	else
1088 		range->max_addr = range->min_addr;
1089 
1090 	return 0;
1091 }
1092 
1093 static int
nfnetlink_parse_nat(const struct nlattr * nat,const struct nf_conn * ct,struct nf_nat_range2 * range)1094 nfnetlink_parse_nat(const struct nlattr *nat,
1095 		    const struct nf_conn *ct, struct nf_nat_range2 *range)
1096 {
1097 	struct nlattr *tb[CTA_NAT_MAX+1];
1098 	int err;
1099 
1100 	memset(range, 0, sizeof(*range));
1101 
1102 	err = nla_parse_nested_deprecated(tb, CTA_NAT_MAX, nat,
1103 					  nat_nla_policy, NULL);
1104 	if (err < 0)
1105 		return err;
1106 
1107 	switch (nf_ct_l3num(ct)) {
1108 	case NFPROTO_IPV4:
1109 		err = nf_nat_ipv4_nlattr_to_range(tb, range);
1110 		break;
1111 	case NFPROTO_IPV6:
1112 		err = nf_nat_ipv6_nlattr_to_range(tb, range);
1113 		break;
1114 	default:
1115 		err = -EPROTONOSUPPORT;
1116 		break;
1117 	}
1118 
1119 	if (err)
1120 		return err;
1121 
1122 	if (!tb[CTA_NAT_PROTO])
1123 		return 0;
1124 
1125 	return nfnetlink_parse_nat_proto(tb[CTA_NAT_PROTO], ct, range);
1126 }
1127 
1128 /* This function is called under rcu_read_lock() */
1129 static int
nfnetlink_parse_nat_setup(struct nf_conn * ct,enum nf_nat_manip_type manip,const struct nlattr * attr)1130 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1131 			  enum nf_nat_manip_type manip,
1132 			  const struct nlattr *attr)
1133 {
1134 	struct nf_nat_range2 range;
1135 	int err;
1136 
1137 	/* Should not happen, restricted to creating new conntracks
1138 	 * via ctnetlink.
1139 	 */
1140 	if (WARN_ON_ONCE(nf_nat_initialized(ct, manip)))
1141 		return -EEXIST;
1142 
1143 	/* No NAT information has been passed, allocate the null-binding */
1144 	if (attr == NULL)
1145 		return __nf_nat_alloc_null_binding(ct, manip) == NF_DROP ? -ENOMEM : 0;
1146 
1147 	err = nfnetlink_parse_nat(attr, ct, &range);
1148 	if (err < 0)
1149 		return err;
1150 
1151 	return nf_nat_setup_info(ct, &range, manip) == NF_DROP ? -ENOMEM : 0;
1152 }
1153 #else
1154 static int
nfnetlink_parse_nat_setup(struct nf_conn * ct,enum nf_nat_manip_type manip,const struct nlattr * attr)1155 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1156 			  enum nf_nat_manip_type manip,
1157 			  const struct nlattr *attr)
1158 {
1159 	return -EOPNOTSUPP;
1160 }
1161 #endif
1162 
1163 static struct nf_ct_helper_expectfn follow_master_nat = {
1164 	.name		= "nat-follow-master",
1165 	.expectfn	= nf_nat_follow_master,
1166 };
1167 
nf_nat_register_fn(struct net * net,u8 pf,const struct nf_hook_ops * ops,const struct nf_hook_ops * orig_nat_ops,unsigned int ops_count)1168 int nf_nat_register_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1169 		       const struct nf_hook_ops *orig_nat_ops, unsigned int ops_count)
1170 {
1171 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1172 	struct nf_nat_hooks_net *nat_proto_net;
1173 	struct nf_nat_lookup_hook_priv *priv;
1174 	unsigned int hooknum = ops->hooknum;
1175 	struct nf_hook_ops *nat_ops;
1176 	int i, ret;
1177 
1178 #ifndef MODULE
1179 	/* If nf_nat_core is built-in and nf_nat_init() fails, dependent
1180 	 * modules like nft_chain_nat.ko may still call this function.
1181 	 * However, nat_net would be invalid, likely pointing to some other
1182 	 * per-net structure.
1183 	 */
1184 	if (WARN_ON_ONCE(!nf_nat_hook))
1185 		return -EOPNOTSUPP;
1186 #endif
1187 
1188 	if (WARN_ON_ONCE(pf >= ARRAY_SIZE(nat_net->nat_proto_net)))
1189 		return -EINVAL;
1190 
1191 	nat_proto_net = &nat_net->nat_proto_net[pf];
1192 
1193 	for (i = 0; i < ops_count; i++) {
1194 		if (orig_nat_ops[i].hooknum == hooknum) {
1195 			hooknum = i;
1196 			break;
1197 		}
1198 	}
1199 
1200 	if (WARN_ON_ONCE(i == ops_count))
1201 		return -EINVAL;
1202 
1203 	mutex_lock(&nf_nat_proto_mutex);
1204 	if (!nat_proto_net->nat_hook_ops) {
1205 		WARN_ON(nat_proto_net->users != 0);
1206 
1207 		nat_ops = kmemdup_array(orig_nat_ops, ops_count, sizeof(*orig_nat_ops), GFP_KERNEL);
1208 		if (!nat_ops) {
1209 			mutex_unlock(&nf_nat_proto_mutex);
1210 			return -ENOMEM;
1211 		}
1212 
1213 		for (i = 0; i < ops_count; i++) {
1214 			priv = kzalloc_obj(*priv);
1215 			if (priv) {
1216 				nat_ops[i].priv = priv;
1217 				continue;
1218 			}
1219 			mutex_unlock(&nf_nat_proto_mutex);
1220 			while (i)
1221 				kfree(nat_ops[--i].priv);
1222 			kfree(nat_ops);
1223 			return -ENOMEM;
1224 		}
1225 
1226 		ret = nf_register_net_hooks(net, nat_ops, ops_count);
1227 		if (ret < 0) {
1228 			mutex_unlock(&nf_nat_proto_mutex);
1229 			for (i = 0; i < ops_count; i++) {
1230 				priv = nat_ops[i].priv;
1231 				kfree_rcu(priv, rcu_head);
1232 			}
1233 			kfree_rcu(nat_ops, rcu);
1234 			return ret;
1235 		}
1236 
1237 		nat_proto_net->nat_hook_ops = nat_ops;
1238 	}
1239 
1240 	nat_ops = nat_proto_net->nat_hook_ops;
1241 	priv = nat_ops[hooknum].priv;
1242 	if (WARN_ON_ONCE(!priv)) {
1243 		mutex_unlock(&nf_nat_proto_mutex);
1244 		return -EOPNOTSUPP;
1245 	}
1246 
1247 	ret = nf_hook_entries_insert_raw(&priv->entries, ops);
1248 	if (ret == 0)
1249 		nat_proto_net->users++;
1250 
1251 	mutex_unlock(&nf_nat_proto_mutex);
1252 	return ret;
1253 }
1254 
nf_nat_unregister_fn(struct net * net,u8 pf,const struct nf_hook_ops * ops,unsigned int ops_count)1255 void nf_nat_unregister_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1256 			  unsigned int ops_count)
1257 {
1258 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1259 	struct nf_nat_hooks_net *nat_proto_net;
1260 	struct nf_nat_lookup_hook_priv *priv;
1261 	struct nf_hook_ops *nat_ops;
1262 	int hooknum = ops->hooknum;
1263 	int i;
1264 
1265 	if (pf >= ARRAY_SIZE(nat_net->nat_proto_net))
1266 		return;
1267 
1268 	nat_proto_net = &nat_net->nat_proto_net[pf];
1269 
1270 	mutex_lock(&nf_nat_proto_mutex);
1271 	if (WARN_ON(nat_proto_net->users == 0))
1272 		goto unlock;
1273 
1274 	nat_proto_net->users--;
1275 
1276 	nat_ops = nat_proto_net->nat_hook_ops;
1277 	for (i = 0; i < ops_count; i++) {
1278 		if (nat_ops[i].hooknum == hooknum) {
1279 			hooknum = i;
1280 			break;
1281 		}
1282 	}
1283 	if (WARN_ON_ONCE(i == ops_count))
1284 		goto unlock;
1285 	priv = nat_ops[hooknum].priv;
1286 	nf_hook_entries_delete_raw(&priv->entries, ops);
1287 
1288 	if (nat_proto_net->users == 0) {
1289 		nf_unregister_net_hooks(net, nat_ops, ops_count);
1290 
1291 		for (i = 0; i < ops_count; i++) {
1292 			priv = nat_ops[i].priv;
1293 			kfree_rcu(priv, rcu_head);
1294 		}
1295 
1296 		nat_proto_net->nat_hook_ops = NULL;
1297 		kfree_rcu(nat_ops, rcu);
1298 	}
1299 unlock:
1300 	mutex_unlock(&nf_nat_proto_mutex);
1301 }
1302 
1303 static struct pernet_operations nat_net_ops = {
1304 	.id = &nat_net_id,
1305 	.size = sizeof(struct nat_net),
1306 };
1307 
1308 static const struct nf_nat_hook nat_hook = {
1309 	.parse_nat_setup	= nfnetlink_parse_nat_setup,
1310 #ifdef CONFIG_XFRM
1311 	.decode_session		= __nf_nat_decode_session,
1312 #endif
1313 	.remove_nat_bysrc	= nf_nat_cleanup_conntrack,
1314 };
1315 
nf_nat_init(void)1316 static int __init nf_nat_init(void)
1317 {
1318 	int ret, i;
1319 
1320 	/* Leave them the same for the moment. */
1321 	nf_nat_htable_size = nf_conntrack_htable_size;
1322 	if (nf_nat_htable_size < CONNTRACK_LOCKS)
1323 		nf_nat_htable_size = CONNTRACK_LOCKS;
1324 
1325 	nf_nat_bysource = nf_ct_alloc_hashtable(&nf_nat_htable_size, 0);
1326 	if (!nf_nat_bysource)
1327 		return -ENOMEM;
1328 
1329 	for (i = 0; i < CONNTRACK_LOCKS; i++)
1330 		spin_lock_init(&nf_nat_locks[i]);
1331 
1332 	ret = register_pernet_subsys(&nat_net_ops);
1333 	if (ret < 0) {
1334 		kvfree(nf_nat_bysource);
1335 		return ret;
1336 	}
1337 
1338 	nf_ct_helper_expectfn_register(&follow_master_nat);
1339 
1340 	WARN_ON(nf_nat_hook != NULL);
1341 	RCU_INIT_POINTER(nf_nat_hook, &nat_hook);
1342 
1343 	ret = register_nf_nat_bpf();
1344 	if (ret < 0) {
1345 		RCU_INIT_POINTER(nf_nat_hook, NULL);
1346 		nf_ct_helper_expectfn_unregister(&follow_master_nat);
1347 		synchronize_net();
1348 		nf_ct_helper_expectfn_destroy(&follow_master_nat);
1349 		unregister_pernet_subsys(&nat_net_ops);
1350 		kvfree(nf_nat_bysource);
1351 	}
1352 
1353 	return ret;
1354 }
1355 
nf_nat_cleanup(void)1356 static void __exit nf_nat_cleanup(void)
1357 {
1358 	struct nf_nat_proto_clean clean = {};
1359 
1360 	nf_ct_iterate_destroy(nf_nat_proto_clean, &clean);
1361 
1362 	nf_ct_helper_expectfn_unregister(&follow_master_nat);
1363 	RCU_INIT_POINTER(nf_nat_hook, NULL);
1364 
1365 	synchronize_net();
1366 	nf_ct_helper_expectfn_destroy(&follow_master_nat);
1367 	kvfree(nf_nat_bysource);
1368 	unregister_pernet_subsys(&nat_net_ops);
1369 }
1370 
1371 MODULE_LICENSE("GPL");
1372 MODULE_DESCRIPTION("Network address translation core");
1373 
1374 module_init(nf_nat_init);
1375 module_exit(nf_nat_cleanup);
1376