xref: /openbmc/linux/net/netfilter/nf_nat_core.c (revision 44ad3baf1cca483e418b6aadf2d3994f69e0f16a)
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
677 		off = get_random_u16();
678 
679 	attempts = range_size;
680 	if (attempts > NF_NAT_MAX_ATTEMPTS)
681 		attempts = NF_NAT_MAX_ATTEMPTS;
682 
683 	/* We are in softirq; doing a search of the entire range risks
684 	 * soft lockup when all tuples are already used.
685 	 *
686 	 * If we can't find any free port from first offset, pick a new
687 	 * one and try again, with ever smaller search window.
688 	 */
689 another_round:
690 	for (i = 0; i < attempts; i++, off++) {
691 		*keyptr = htons(min + off % range_size);
692 		if (!nf_nat_used_tuple_harder(tuple, ct, attempts - i))
693 			return;
694 	}
695 
696 	if (attempts >= range_size || attempts < 16)
697 		return;
698 	attempts /= 2;
699 	off = get_random_u16();
700 	goto another_round;
701 }
702 
703 /* Manipulate the tuple into the range given. For NF_INET_POST_ROUTING,
704  * we change the source to map into the range. For NF_INET_PRE_ROUTING
705  * and NF_INET_LOCAL_OUT, we change the destination to map into the
706  * range. It might not be possible to get a unique tuple, but we try.
707  * At worst (or if we race), we will end up with a final duplicate in
708  * __nf_conntrack_confirm and drop the packet. */
709 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)710 get_unique_tuple(struct nf_conntrack_tuple *tuple,
711 		 const struct nf_conntrack_tuple *orig_tuple,
712 		 const struct nf_nat_range2 *range,
713 		 struct nf_conn *ct,
714 		 enum nf_nat_manip_type maniptype)
715 {
716 	const struct nf_conntrack_zone *zone;
717 	struct net *net = nf_ct_net(ct);
718 
719 	zone = nf_ct_zone(ct);
720 
721 	/* 1) If this srcip/proto/src-proto-part is currently mapped,
722 	 * and that same mapping gives a unique tuple within the given
723 	 * range, use that.
724 	 *
725 	 * This is only required for source (ie. NAT/masq) mappings.
726 	 * So far, we don't do local source mappings, so multiple
727 	 * manips not an issue.
728 	 */
729 	if (maniptype == NF_NAT_MANIP_SRC &&
730 	    !(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
731 		/* try the original tuple first */
732 		if (nf_in_range(orig_tuple, range)) {
733 			if (!nf_nat_used_tuple_new(orig_tuple, ct)) {
734 				*tuple = *orig_tuple;
735 				return;
736 			}
737 		} else if (find_appropriate_src(net, zone,
738 						orig_tuple, tuple, range)) {
739 			pr_debug("get_unique_tuple: Found current src map\n");
740 			if (!nf_nat_used_tuple(tuple, ct))
741 				return;
742 		}
743 	}
744 
745 	/* 2) Select the least-used IP/proto combination in the given range */
746 	*tuple = *orig_tuple;
747 	find_best_ips_proto(zone, tuple, range, ct, maniptype);
748 
749 	/* 3) The per-protocol part of the manip is made to map into
750 	 * the range to make a unique tuple.
751 	 */
752 
753 	/* Only bother mapping if it's not already in range and unique */
754 	if (!(range->flags & NF_NAT_RANGE_PROTO_RANDOM_ALL)) {
755 		if (range->flags & NF_NAT_RANGE_PROTO_SPECIFIED) {
756 			if (!(range->flags & NF_NAT_RANGE_PROTO_OFFSET) &&
757 			    l4proto_in_range(tuple, maniptype,
758 					     &range->min_proto,
759 					     &range->max_proto) &&
760 			    (range->min_proto.all == range->max_proto.all ||
761 			     !nf_nat_used_tuple(tuple, ct)))
762 				return;
763 		} else if (!nf_nat_used_tuple(tuple, ct)) {
764 			return;
765 		}
766 	}
767 
768 	/* Last chance: get protocol to try to obtain unique tuple. */
769 	nf_nat_l4proto_unique_tuple(tuple, range, maniptype, ct);
770 }
771 
nf_ct_nat_ext_add(struct nf_conn * ct)772 struct nf_conn_nat *nf_ct_nat_ext_add(struct nf_conn *ct)
773 {
774 	struct nf_conn_nat *nat = nfct_nat(ct);
775 	if (nat)
776 		return nat;
777 
778 	if (!nf_ct_is_confirmed(ct))
779 		nat = nf_ct_ext_add(ct, NF_CT_EXT_NAT, GFP_ATOMIC);
780 
781 	return nat;
782 }
783 EXPORT_SYMBOL_GPL(nf_ct_nat_ext_add);
784 
785 unsigned int
nf_nat_setup_info(struct nf_conn * ct,const struct nf_nat_range2 * range,enum nf_nat_manip_type maniptype)786 nf_nat_setup_info(struct nf_conn *ct,
787 		  const struct nf_nat_range2 *range,
788 		  enum nf_nat_manip_type maniptype)
789 {
790 	struct net *net = nf_ct_net(ct);
791 	struct nf_conntrack_tuple curr_tuple, new_tuple;
792 
793 	/* Can't setup nat info for confirmed ct. */
794 	if (nf_ct_is_confirmed(ct))
795 		return NF_ACCEPT;
796 
797 	WARN_ON(maniptype != NF_NAT_MANIP_SRC &&
798 		maniptype != NF_NAT_MANIP_DST);
799 
800 	if (WARN_ON(nf_nat_initialized(ct, maniptype)))
801 		return NF_DROP;
802 
803 	/* What we've got will look like inverse of reply. Normally
804 	 * this is what is in the conntrack, except for prior
805 	 * manipulations (future optimization: if num_manips == 0,
806 	 * orig_tp = ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple)
807 	 */
808 	nf_ct_invert_tuple(&curr_tuple,
809 			   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
810 
811 	get_unique_tuple(&new_tuple, &curr_tuple, range, ct, maniptype);
812 
813 	if (!nf_ct_tuple_equal(&new_tuple, &curr_tuple)) {
814 		struct nf_conntrack_tuple reply;
815 
816 		/* Alter conntrack table so will recognize replies. */
817 		nf_ct_invert_tuple(&reply, &new_tuple);
818 		nf_conntrack_alter_reply(ct, &reply);
819 
820 		/* Non-atomic: we own this at the moment. */
821 		if (maniptype == NF_NAT_MANIP_SRC)
822 			ct->status |= IPS_SRC_NAT;
823 		else
824 			ct->status |= IPS_DST_NAT;
825 
826 		if (nfct_help(ct) && !nfct_seqadj(ct))
827 			if (!nfct_seqadj_ext_add(ct))
828 				return NF_DROP;
829 	}
830 
831 	if (maniptype == NF_NAT_MANIP_SRC) {
832 		unsigned int srchash;
833 		spinlock_t *lock;
834 
835 		srchash = hash_by_src(net, nf_ct_zone(ct),
836 				      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
837 		lock = &nf_nat_locks[srchash % CONNTRACK_LOCKS];
838 		spin_lock_bh(lock);
839 		hlist_add_head_rcu(&ct->nat_bysource,
840 				   &nf_nat_bysource[srchash]);
841 		spin_unlock_bh(lock);
842 	}
843 
844 	/* It's done. */
845 	if (maniptype == NF_NAT_MANIP_DST)
846 		ct->status |= IPS_DST_NAT_DONE;
847 	else
848 		ct->status |= IPS_SRC_NAT_DONE;
849 
850 	return NF_ACCEPT;
851 }
852 EXPORT_SYMBOL(nf_nat_setup_info);
853 
854 static unsigned int
__nf_nat_alloc_null_binding(struct nf_conn * ct,enum nf_nat_manip_type manip)855 __nf_nat_alloc_null_binding(struct nf_conn *ct, enum nf_nat_manip_type manip)
856 {
857 	/* Force range to this IP; let proto decide mapping for
858 	 * per-proto parts (hence not IP_NAT_RANGE_PROTO_SPECIFIED).
859 	 * Use reply in case it's already been mangled (eg local packet).
860 	 */
861 	union nf_inet_addr ip =
862 		(manip == NF_NAT_MANIP_SRC ?
863 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3 :
864 		ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3);
865 	struct nf_nat_range2 range = {
866 		.flags		= NF_NAT_RANGE_MAP_IPS,
867 		.min_addr	= ip,
868 		.max_addr	= ip,
869 	};
870 	return nf_nat_setup_info(ct, &range, manip);
871 }
872 
873 unsigned int
nf_nat_alloc_null_binding(struct nf_conn * ct,unsigned int hooknum)874 nf_nat_alloc_null_binding(struct nf_conn *ct, unsigned int hooknum)
875 {
876 	return __nf_nat_alloc_null_binding(ct, HOOK2MANIP(hooknum));
877 }
878 EXPORT_SYMBOL_GPL(nf_nat_alloc_null_binding);
879 
880 /* 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)881 unsigned int nf_nat_packet(struct nf_conn *ct,
882 			   enum ip_conntrack_info ctinfo,
883 			   unsigned int hooknum,
884 			   struct sk_buff *skb)
885 {
886 	enum nf_nat_manip_type mtype = HOOK2MANIP(hooknum);
887 	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
888 	unsigned int verdict = NF_ACCEPT;
889 	unsigned long statusbit;
890 
891 	if (mtype == NF_NAT_MANIP_SRC)
892 		statusbit = IPS_SRC_NAT;
893 	else
894 		statusbit = IPS_DST_NAT;
895 
896 	/* Invert if this is reply dir. */
897 	if (dir == IP_CT_DIR_REPLY)
898 		statusbit ^= IPS_NAT_MASK;
899 
900 	/* Non-atomic: these bits don't change. */
901 	if (ct->status & statusbit)
902 		verdict = nf_nat_manip_pkt(skb, ct, mtype, dir);
903 
904 	return verdict;
905 }
906 EXPORT_SYMBOL_GPL(nf_nat_packet);
907 
in_vrf_postrouting(const struct nf_hook_state * state)908 static bool in_vrf_postrouting(const struct nf_hook_state *state)
909 {
910 #if IS_ENABLED(CONFIG_NET_L3_MASTER_DEV)
911 	if (state->hook == NF_INET_POST_ROUTING &&
912 	    netif_is_l3_master(state->out))
913 		return true;
914 #endif
915 	return false;
916 }
917 
918 unsigned int
nf_nat_inet_fn(void * priv,struct sk_buff * skb,const struct nf_hook_state * state)919 nf_nat_inet_fn(void *priv, struct sk_buff *skb,
920 	       const struct nf_hook_state *state)
921 {
922 	struct nf_conn *ct;
923 	enum ip_conntrack_info ctinfo;
924 	struct nf_conn_nat *nat;
925 	/* maniptype == SRC for postrouting. */
926 	enum nf_nat_manip_type maniptype = HOOK2MANIP(state->hook);
927 
928 	ct = nf_ct_get(skb, &ctinfo);
929 	/* Can't track?  It's not due to stress, or conntrack would
930 	 * have dropped it.  Hence it's the user's responsibilty to
931 	 * packet filter it out, or implement conntrack/NAT for that
932 	 * protocol. 8) --RR
933 	 */
934 	if (!ct || in_vrf_postrouting(state))
935 		return NF_ACCEPT;
936 
937 	nat = nfct_nat(ct);
938 
939 	switch (ctinfo) {
940 	case IP_CT_RELATED:
941 	case IP_CT_RELATED_REPLY:
942 		/* Only ICMPs can be IP_CT_IS_REPLY.  Fallthrough */
943 	case IP_CT_NEW:
944 		/* Seen it before?  This can happen for loopback, retrans,
945 		 * or local packets.
946 		 */
947 		if (!nf_nat_initialized(ct, maniptype)) {
948 			struct nf_nat_lookup_hook_priv *lpriv = priv;
949 			struct nf_hook_entries *e = rcu_dereference(lpriv->entries);
950 			unsigned int ret;
951 			int i;
952 
953 			if (!e)
954 				goto null_bind;
955 
956 			for (i = 0; i < e->num_hook_entries; i++) {
957 				ret = e->hooks[i].hook(e->hooks[i].priv, skb,
958 						       state);
959 				if (ret != NF_ACCEPT)
960 					return ret;
961 				if (nf_nat_initialized(ct, maniptype))
962 					goto do_nat;
963 			}
964 null_bind:
965 			ret = nf_nat_alloc_null_binding(ct, state->hook);
966 			if (ret != NF_ACCEPT)
967 				return ret;
968 		} else {
969 			pr_debug("Already setup manip %s for ct %p (status bits 0x%lx)\n",
970 				 maniptype == NF_NAT_MANIP_SRC ? "SRC" : "DST",
971 				 ct, ct->status);
972 			if (nf_nat_oif_changed(state->hook, ctinfo, nat,
973 					       state->out))
974 				goto oif_changed;
975 		}
976 		break;
977 	default:
978 		/* ESTABLISHED */
979 		WARN_ON(ctinfo != IP_CT_ESTABLISHED &&
980 			ctinfo != IP_CT_ESTABLISHED_REPLY);
981 		if (nf_nat_oif_changed(state->hook, ctinfo, nat, state->out))
982 			goto oif_changed;
983 	}
984 do_nat:
985 	return nf_nat_packet(ct, ctinfo, state->hook, skb);
986 
987 oif_changed:
988 	nf_ct_kill_acct(ct, ctinfo, skb);
989 	return NF_DROP;
990 }
991 EXPORT_SYMBOL_GPL(nf_nat_inet_fn);
992 
993 struct nf_nat_proto_clean {
994 	u8	l3proto;
995 	u8	l4proto;
996 };
997 
998 /* kill conntracks with affected NAT section */
nf_nat_proto_remove(struct nf_conn * i,void * data)999 static int nf_nat_proto_remove(struct nf_conn *i, void *data)
1000 {
1001 	const struct nf_nat_proto_clean *clean = data;
1002 
1003 	if ((clean->l3proto && nf_ct_l3num(i) != clean->l3proto) ||
1004 	    (clean->l4proto && nf_ct_protonum(i) != clean->l4proto))
1005 		return 0;
1006 
1007 	return i->status & IPS_NAT_MASK ? 1 : 0;
1008 }
1009 
nf_nat_cleanup_conntrack(struct nf_conn * ct)1010 static void nf_nat_cleanup_conntrack(struct nf_conn *ct)
1011 {
1012 	unsigned int h;
1013 
1014 	h = hash_by_src(nf_ct_net(ct), nf_ct_zone(ct), &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
1015 	spin_lock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
1016 	hlist_del_rcu(&ct->nat_bysource);
1017 	spin_unlock_bh(&nf_nat_locks[h % CONNTRACK_LOCKS]);
1018 }
1019 
nf_nat_proto_clean(struct nf_conn * ct,void * data)1020 static int nf_nat_proto_clean(struct nf_conn *ct, void *data)
1021 {
1022 	if (nf_nat_proto_remove(ct, data))
1023 		return 1;
1024 
1025 	/* This module is being removed and conntrack has nat null binding.
1026 	 * Remove it from bysource hash, as the table will be freed soon.
1027 	 *
1028 	 * Else, when the conntrack is destoyed, nf_nat_cleanup_conntrack()
1029 	 * will delete entry from already-freed table.
1030 	 */
1031 	if (test_and_clear_bit(IPS_SRC_NAT_DONE_BIT, &ct->status))
1032 		nf_nat_cleanup_conntrack(ct);
1033 
1034 	/* don't delete conntrack.  Although that would make things a lot
1035 	 * simpler, we'd end up flushing all conntracks on nat rmmod.
1036 	 */
1037 	return 0;
1038 }
1039 
1040 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1041 
1042 #include <linux/netfilter/nfnetlink.h>
1043 #include <linux/netfilter/nfnetlink_conntrack.h>
1044 
1045 static const struct nla_policy protonat_nla_policy[CTA_PROTONAT_MAX+1] = {
1046 	[CTA_PROTONAT_PORT_MIN]	= { .type = NLA_U16 },
1047 	[CTA_PROTONAT_PORT_MAX]	= { .type = NLA_U16 },
1048 };
1049 
nf_nat_l4proto_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1050 static int nf_nat_l4proto_nlattr_to_range(struct nlattr *tb[],
1051 					  struct nf_nat_range2 *range)
1052 {
1053 	if (tb[CTA_PROTONAT_PORT_MIN]) {
1054 		range->min_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MIN]);
1055 		range->max_proto.all = range->min_proto.all;
1056 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1057 	}
1058 	if (tb[CTA_PROTONAT_PORT_MAX]) {
1059 		range->max_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MAX]);
1060 		range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1061 	}
1062 	return 0;
1063 }
1064 
nfnetlink_parse_nat_proto(struct nlattr * attr,const struct nf_conn * ct,struct nf_nat_range2 * range)1065 static int nfnetlink_parse_nat_proto(struct nlattr *attr,
1066 				     const struct nf_conn *ct,
1067 				     struct nf_nat_range2 *range)
1068 {
1069 	struct nlattr *tb[CTA_PROTONAT_MAX+1];
1070 	int err;
1071 
1072 	err = nla_parse_nested_deprecated(tb, CTA_PROTONAT_MAX, attr,
1073 					  protonat_nla_policy, NULL);
1074 	if (err < 0)
1075 		return err;
1076 
1077 	return nf_nat_l4proto_nlattr_to_range(tb, range);
1078 }
1079 
1080 static const struct nla_policy nat_nla_policy[CTA_NAT_MAX+1] = {
1081 	[CTA_NAT_V4_MINIP]	= { .type = NLA_U32 },
1082 	[CTA_NAT_V4_MAXIP]	= { .type = NLA_U32 },
1083 	[CTA_NAT_V6_MINIP]	= { .len = sizeof(struct in6_addr) },
1084 	[CTA_NAT_V6_MAXIP]	= { .len = sizeof(struct in6_addr) },
1085 	[CTA_NAT_PROTO]		= { .type = NLA_NESTED },
1086 };
1087 
nf_nat_ipv4_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1088 static int nf_nat_ipv4_nlattr_to_range(struct nlattr *tb[],
1089 				       struct nf_nat_range2 *range)
1090 {
1091 	if (tb[CTA_NAT_V4_MINIP]) {
1092 		range->min_addr.ip = nla_get_be32(tb[CTA_NAT_V4_MINIP]);
1093 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1094 	}
1095 
1096 	if (tb[CTA_NAT_V4_MAXIP])
1097 		range->max_addr.ip = nla_get_be32(tb[CTA_NAT_V4_MAXIP]);
1098 	else
1099 		range->max_addr.ip = range->min_addr.ip;
1100 
1101 	return 0;
1102 }
1103 
nf_nat_ipv6_nlattr_to_range(struct nlattr * tb[],struct nf_nat_range2 * range)1104 static int nf_nat_ipv6_nlattr_to_range(struct nlattr *tb[],
1105 				       struct nf_nat_range2 *range)
1106 {
1107 	if (tb[CTA_NAT_V6_MINIP]) {
1108 		nla_memcpy(&range->min_addr.ip6, tb[CTA_NAT_V6_MINIP],
1109 			   sizeof(struct in6_addr));
1110 		range->flags |= NF_NAT_RANGE_MAP_IPS;
1111 	}
1112 
1113 	if (tb[CTA_NAT_V6_MAXIP])
1114 		nla_memcpy(&range->max_addr.ip6, tb[CTA_NAT_V6_MAXIP],
1115 			   sizeof(struct in6_addr));
1116 	else
1117 		range->max_addr = range->min_addr;
1118 
1119 	return 0;
1120 }
1121 
1122 static int
nfnetlink_parse_nat(const struct nlattr * nat,const struct nf_conn * ct,struct nf_nat_range2 * range)1123 nfnetlink_parse_nat(const struct nlattr *nat,
1124 		    const struct nf_conn *ct, struct nf_nat_range2 *range)
1125 {
1126 	struct nlattr *tb[CTA_NAT_MAX+1];
1127 	int err;
1128 
1129 	memset(range, 0, sizeof(*range));
1130 
1131 	err = nla_parse_nested_deprecated(tb, CTA_NAT_MAX, nat,
1132 					  nat_nla_policy, NULL);
1133 	if (err < 0)
1134 		return err;
1135 
1136 	switch (nf_ct_l3num(ct)) {
1137 	case NFPROTO_IPV4:
1138 		err = nf_nat_ipv4_nlattr_to_range(tb, range);
1139 		break;
1140 	case NFPROTO_IPV6:
1141 		err = nf_nat_ipv6_nlattr_to_range(tb, range);
1142 		break;
1143 	default:
1144 		err = -EPROTONOSUPPORT;
1145 		break;
1146 	}
1147 
1148 	if (err)
1149 		return err;
1150 
1151 	if (!tb[CTA_NAT_PROTO])
1152 		return 0;
1153 
1154 	return nfnetlink_parse_nat_proto(tb[CTA_NAT_PROTO], ct, range);
1155 }
1156 
1157 /* This function is called under rcu_read_lock() */
1158 static int
nfnetlink_parse_nat_setup(struct nf_conn * ct,enum nf_nat_manip_type manip,const struct nlattr * attr)1159 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1160 			  enum nf_nat_manip_type manip,
1161 			  const struct nlattr *attr)
1162 {
1163 	struct nf_nat_range2 range;
1164 	int err;
1165 
1166 	/* Should not happen, restricted to creating new conntracks
1167 	 * via ctnetlink.
1168 	 */
1169 	if (WARN_ON_ONCE(nf_nat_initialized(ct, manip)))
1170 		return -EEXIST;
1171 
1172 	/* No NAT information has been passed, allocate the null-binding */
1173 	if (attr == NULL)
1174 		return __nf_nat_alloc_null_binding(ct, manip) == NF_DROP ? -ENOMEM : 0;
1175 
1176 	err = nfnetlink_parse_nat(attr, ct, &range);
1177 	if (err < 0)
1178 		return err;
1179 
1180 	return nf_nat_setup_info(ct, &range, manip) == NF_DROP ? -ENOMEM : 0;
1181 }
1182 #else
1183 static int
nfnetlink_parse_nat_setup(struct nf_conn * ct,enum nf_nat_manip_type manip,const struct nlattr * attr)1184 nfnetlink_parse_nat_setup(struct nf_conn *ct,
1185 			  enum nf_nat_manip_type manip,
1186 			  const struct nlattr *attr)
1187 {
1188 	return -EOPNOTSUPP;
1189 }
1190 #endif
1191 
1192 static struct nf_ct_helper_expectfn follow_master_nat = {
1193 	.name		= "nat-follow-master",
1194 	.expectfn	= nf_nat_follow_master,
1195 };
1196 
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)1197 int nf_nat_register_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1198 		       const struct nf_hook_ops *orig_nat_ops, unsigned int ops_count)
1199 {
1200 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1201 	struct nf_nat_hooks_net *nat_proto_net;
1202 	struct nf_nat_lookup_hook_priv *priv;
1203 	unsigned int hooknum = ops->hooknum;
1204 	struct nf_hook_ops *nat_ops;
1205 	int i, ret;
1206 
1207 	if (WARN_ON_ONCE(pf >= ARRAY_SIZE(nat_net->nat_proto_net)))
1208 		return -EINVAL;
1209 
1210 	nat_proto_net = &nat_net->nat_proto_net[pf];
1211 
1212 	for (i = 0; i < ops_count; i++) {
1213 		if (orig_nat_ops[i].hooknum == hooknum) {
1214 			hooknum = i;
1215 			break;
1216 		}
1217 	}
1218 
1219 	if (WARN_ON_ONCE(i == ops_count))
1220 		return -EINVAL;
1221 
1222 	mutex_lock(&nf_nat_proto_mutex);
1223 	if (!nat_proto_net->nat_hook_ops) {
1224 		WARN_ON(nat_proto_net->users != 0);
1225 
1226 		nat_ops = kmemdup(orig_nat_ops, sizeof(*orig_nat_ops) * ops_count, GFP_KERNEL);
1227 		if (!nat_ops) {
1228 			mutex_unlock(&nf_nat_proto_mutex);
1229 			return -ENOMEM;
1230 		}
1231 
1232 		for (i = 0; i < ops_count; i++) {
1233 			priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1234 			if (priv) {
1235 				nat_ops[i].priv = priv;
1236 				continue;
1237 			}
1238 			mutex_unlock(&nf_nat_proto_mutex);
1239 			while (i)
1240 				kfree(nat_ops[--i].priv);
1241 			kfree(nat_ops);
1242 			return -ENOMEM;
1243 		}
1244 
1245 		ret = nf_register_net_hooks(net, nat_ops, ops_count);
1246 		if (ret < 0) {
1247 			mutex_unlock(&nf_nat_proto_mutex);
1248 			for (i = 0; i < ops_count; i++)
1249 				kfree(nat_ops[i].priv);
1250 			kfree(nat_ops);
1251 			return ret;
1252 		}
1253 
1254 		nat_proto_net->nat_hook_ops = nat_ops;
1255 	}
1256 
1257 	nat_ops = nat_proto_net->nat_hook_ops;
1258 	priv = nat_ops[hooknum].priv;
1259 	if (WARN_ON_ONCE(!priv)) {
1260 		mutex_unlock(&nf_nat_proto_mutex);
1261 		return -EOPNOTSUPP;
1262 	}
1263 
1264 	ret = nf_hook_entries_insert_raw(&priv->entries, ops);
1265 	if (ret == 0)
1266 		nat_proto_net->users++;
1267 
1268 	mutex_unlock(&nf_nat_proto_mutex);
1269 	return ret;
1270 }
1271 
nf_nat_unregister_fn(struct net * net,u8 pf,const struct nf_hook_ops * ops,unsigned int ops_count)1272 void nf_nat_unregister_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops,
1273 			  unsigned int ops_count)
1274 {
1275 	struct nat_net *nat_net = net_generic(net, nat_net_id);
1276 	struct nf_nat_hooks_net *nat_proto_net;
1277 	struct nf_nat_lookup_hook_priv *priv;
1278 	struct nf_hook_ops *nat_ops;
1279 	int hooknum = ops->hooknum;
1280 	int i;
1281 
1282 	if (pf >= ARRAY_SIZE(nat_net->nat_proto_net))
1283 		return;
1284 
1285 	nat_proto_net = &nat_net->nat_proto_net[pf];
1286 
1287 	mutex_lock(&nf_nat_proto_mutex);
1288 	if (WARN_ON(nat_proto_net->users == 0))
1289 		goto unlock;
1290 
1291 	nat_proto_net->users--;
1292 
1293 	nat_ops = nat_proto_net->nat_hook_ops;
1294 	for (i = 0; i < ops_count; i++) {
1295 		if (nat_ops[i].hooknum == hooknum) {
1296 			hooknum = i;
1297 			break;
1298 		}
1299 	}
1300 	if (WARN_ON_ONCE(i == ops_count))
1301 		goto unlock;
1302 	priv = nat_ops[hooknum].priv;
1303 	nf_hook_entries_delete_raw(&priv->entries, ops);
1304 
1305 	if (nat_proto_net->users == 0) {
1306 		nf_unregister_net_hooks(net, nat_ops, ops_count);
1307 
1308 		for (i = 0; i < ops_count; i++) {
1309 			priv = nat_ops[i].priv;
1310 			kfree_rcu(priv, rcu_head);
1311 		}
1312 
1313 		nat_proto_net->nat_hook_ops = NULL;
1314 		kfree(nat_ops);
1315 	}
1316 unlock:
1317 	mutex_unlock(&nf_nat_proto_mutex);
1318 }
1319 
1320 static struct pernet_operations nat_net_ops = {
1321 	.id = &nat_net_id,
1322 	.size = sizeof(struct nat_net),
1323 };
1324 
1325 static const struct nf_nat_hook nat_hook = {
1326 	.parse_nat_setup	= nfnetlink_parse_nat_setup,
1327 #ifdef CONFIG_XFRM
1328 	.decode_session		= __nf_nat_decode_session,
1329 #endif
1330 	.manip_pkt		= nf_nat_manip_pkt,
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 
1389 module_init(nf_nat_init);
1390 module_exit(nf_nat_cleanup);
1391