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