• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter.  This is separated from,
3    but required by, the NAT layer; it can also be used by an iptables
4    extension. */
5 
6 /* (C) 1999-2001 Paul `Rusty' Russell
7  * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9  * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
10  */
11 
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/jhash.h>
25 #include <linux/siphash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
33 #include <linux/mm.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
36 #include <trace/hooks/net.h>
37 
38 #include <net/netfilter/nf_conntrack.h>
39 #include <net/netfilter/nf_conntrack_l4proto.h>
40 #include <net/netfilter/nf_conntrack_expect.h>
41 #include <net/netfilter/nf_conntrack_helper.h>
42 #include <net/netfilter/nf_conntrack_seqadj.h>
43 #include <net/netfilter/nf_conntrack_core.h>
44 #include <net/netfilter/nf_conntrack_extend.h>
45 #include <net/netfilter/nf_conntrack_acct.h>
46 #include <net/netfilter/nf_conntrack_ecache.h>
47 #include <net/netfilter/nf_conntrack_zones.h>
48 #include <net/netfilter/nf_conntrack_timestamp.h>
49 #include <net/netfilter/nf_conntrack_timeout.h>
50 #include <net/netfilter/nf_conntrack_labels.h>
51 #include <net/netfilter/nf_conntrack_synproxy.h>
52 #include <net/netfilter/nf_nat.h>
53 #include <net/netfilter/nf_nat_helper.h>
54 #include <net/netns/hash.h>
55 #include <net/ip.h>
56 
57 #include "nf_internals.h"
58 
59 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
60 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
61 
62 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
63 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
64 
65 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
66 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
67 
68 struct conntrack_gc_work {
69 	struct delayed_work	dwork;
70 	u32			next_bucket;
71 	bool			exiting;
72 	bool			early_drop;
73 };
74 
75 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
76 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
77 static __read_mostly bool nf_conntrack_locks_all;
78 
79 /* serialize hash resizes and nf_ct_iterate_cleanup */
80 static DEFINE_MUTEX(nf_conntrack_mutex);
81 
82 #define GC_SCAN_INTERVAL	(120u * HZ)
83 #define GC_SCAN_MAX_DURATION	msecs_to_jiffies(10)
84 
85 static struct conntrack_gc_work conntrack_gc_work;
86 
nf_conntrack_lock(spinlock_t * lock)87 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
88 {
89 	/* 1) Acquire the lock */
90 	spin_lock(lock);
91 
92 	/* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
93 	 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
94 	 */
95 	if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
96 		return;
97 
98 	/* fast path failed, unlock */
99 	spin_unlock(lock);
100 
101 	/* Slow path 1) get global lock */
102 	spin_lock(&nf_conntrack_locks_all_lock);
103 
104 	/* Slow path 2) get the lock we want */
105 	spin_lock(lock);
106 
107 	/* Slow path 3) release the global lock */
108 	spin_unlock(&nf_conntrack_locks_all_lock);
109 }
110 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
111 
nf_conntrack_double_unlock(unsigned int h1,unsigned int h2)112 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
113 {
114 	h1 %= CONNTRACK_LOCKS;
115 	h2 %= CONNTRACK_LOCKS;
116 	spin_unlock(&nf_conntrack_locks[h1]);
117 	if (h1 != h2)
118 		spin_unlock(&nf_conntrack_locks[h2]);
119 }
120 
121 /* return true if we need to recompute hashes (in case hash table was resized) */
nf_conntrack_double_lock(struct net * net,unsigned int h1,unsigned int h2,unsigned int sequence)122 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
123 				     unsigned int h2, unsigned int sequence)
124 {
125 	h1 %= CONNTRACK_LOCKS;
126 	h2 %= CONNTRACK_LOCKS;
127 	if (h1 <= h2) {
128 		nf_conntrack_lock(&nf_conntrack_locks[h1]);
129 		if (h1 != h2)
130 			spin_lock_nested(&nf_conntrack_locks[h2],
131 					 SINGLE_DEPTH_NESTING);
132 	} else {
133 		nf_conntrack_lock(&nf_conntrack_locks[h2]);
134 		spin_lock_nested(&nf_conntrack_locks[h1],
135 				 SINGLE_DEPTH_NESTING);
136 	}
137 	if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
138 		nf_conntrack_double_unlock(h1, h2);
139 		return true;
140 	}
141 	return false;
142 }
143 
nf_conntrack_all_lock(void)144 static void nf_conntrack_all_lock(void)
145 	__acquires(&nf_conntrack_locks_all_lock)
146 {
147 	int i;
148 
149 	spin_lock(&nf_conntrack_locks_all_lock);
150 
151 	nf_conntrack_locks_all = true;
152 
153 	for (i = 0; i < CONNTRACK_LOCKS; i++) {
154 		spin_lock(&nf_conntrack_locks[i]);
155 
156 		/* This spin_unlock provides the "release" to ensure that
157 		 * nf_conntrack_locks_all==true is visible to everyone that
158 		 * acquired spin_lock(&nf_conntrack_locks[]).
159 		 */
160 		spin_unlock(&nf_conntrack_locks[i]);
161 	}
162 }
163 
nf_conntrack_all_unlock(void)164 static void nf_conntrack_all_unlock(void)
165 	__releases(&nf_conntrack_locks_all_lock)
166 {
167 	/* All prior stores must be complete before we clear
168 	 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
169 	 * might observe the false value but not the entire
170 	 * critical section.
171 	 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
172 	 */
173 	smp_store_release(&nf_conntrack_locks_all, false);
174 	spin_unlock(&nf_conntrack_locks_all_lock);
175 }
176 
177 unsigned int nf_conntrack_htable_size __read_mostly;
178 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
179 
180 unsigned int nf_conntrack_max __read_mostly;
181 EXPORT_SYMBOL_GPL(nf_conntrack_max);
182 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
183 static unsigned int nf_conntrack_hash_rnd __read_mostly;
184 
hash_conntrack_raw(const struct nf_conntrack_tuple * tuple,const struct net * net)185 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
186 			      const struct net *net)
187 {
188 	unsigned int n;
189 	u32 seed;
190 
191 	get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
192 
193 	/* The direction must be ignored, so we hash everything up to the
194 	 * destination ports (which is a multiple of 4) and treat the last
195 	 * three bytes manually.
196 	 */
197 	seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
198 	n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
199 	return jhash2((u32 *)tuple, n, seed ^
200 		      (((__force __u16)tuple->dst.u.all << 16) |
201 		      tuple->dst.protonum));
202 }
203 
scale_hash(u32 hash)204 static u32 scale_hash(u32 hash)
205 {
206 	return reciprocal_scale(hash, nf_conntrack_htable_size);
207 }
208 
__hash_conntrack(const struct net * net,const struct nf_conntrack_tuple * tuple,unsigned int size)209 static u32 __hash_conntrack(const struct net *net,
210 			    const struct nf_conntrack_tuple *tuple,
211 			    unsigned int size)
212 {
213 	return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
214 }
215 
hash_conntrack(const struct net * net,const struct nf_conntrack_tuple * tuple)216 static u32 hash_conntrack(const struct net *net,
217 			  const struct nf_conntrack_tuple *tuple)
218 {
219 	return scale_hash(hash_conntrack_raw(tuple, net));
220 }
221 
nf_ct_get_tuple_ports(const struct sk_buff * skb,unsigned int dataoff,struct nf_conntrack_tuple * tuple)222 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
223 				  unsigned int dataoff,
224 				  struct nf_conntrack_tuple *tuple)
225 {	struct {
226 		__be16 sport;
227 		__be16 dport;
228 	} _inet_hdr, *inet_hdr;
229 
230 	/* Actually only need first 4 bytes to get ports. */
231 	inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
232 	if (!inet_hdr)
233 		return false;
234 
235 	tuple->src.u.udp.port = inet_hdr->sport;
236 	tuple->dst.u.udp.port = inet_hdr->dport;
237 	return true;
238 }
239 
240 static bool
nf_ct_get_tuple(const struct sk_buff * skb,unsigned int nhoff,unsigned int dataoff,u_int16_t l3num,u_int8_t protonum,struct net * net,struct nf_conntrack_tuple * tuple)241 nf_ct_get_tuple(const struct sk_buff *skb,
242 		unsigned int nhoff,
243 		unsigned int dataoff,
244 		u_int16_t l3num,
245 		u_int8_t protonum,
246 		struct net *net,
247 		struct nf_conntrack_tuple *tuple)
248 {
249 	unsigned int size;
250 	const __be32 *ap;
251 	__be32 _addrs[8];
252 
253 	memset(tuple, 0, sizeof(*tuple));
254 
255 	tuple->src.l3num = l3num;
256 	switch (l3num) {
257 	case NFPROTO_IPV4:
258 		nhoff += offsetof(struct iphdr, saddr);
259 		size = 2 * sizeof(__be32);
260 		break;
261 	case NFPROTO_IPV6:
262 		nhoff += offsetof(struct ipv6hdr, saddr);
263 		size = sizeof(_addrs);
264 		break;
265 	default:
266 		return true;
267 	}
268 
269 	ap = skb_header_pointer(skb, nhoff, size, _addrs);
270 	if (!ap)
271 		return false;
272 
273 	switch (l3num) {
274 	case NFPROTO_IPV4:
275 		tuple->src.u3.ip = ap[0];
276 		tuple->dst.u3.ip = ap[1];
277 		break;
278 	case NFPROTO_IPV6:
279 		memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
280 		memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
281 		break;
282 	}
283 
284 	tuple->dst.protonum = protonum;
285 	tuple->dst.dir = IP_CT_DIR_ORIGINAL;
286 
287 	switch (protonum) {
288 #if IS_ENABLED(CONFIG_IPV6)
289 	case IPPROTO_ICMPV6:
290 		return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
291 #endif
292 	case IPPROTO_ICMP:
293 		return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
294 #ifdef CONFIG_NF_CT_PROTO_GRE
295 	case IPPROTO_GRE:
296 		return gre_pkt_to_tuple(skb, dataoff, net, tuple);
297 #endif
298 	case IPPROTO_TCP:
299 	case IPPROTO_UDP: /* fallthrough */
300 		return nf_ct_get_tuple_ports(skb, dataoff, tuple);
301 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
302 	case IPPROTO_UDPLITE:
303 		return nf_ct_get_tuple_ports(skb, dataoff, tuple);
304 #endif
305 #ifdef CONFIG_NF_CT_PROTO_SCTP
306 	case IPPROTO_SCTP:
307 		return nf_ct_get_tuple_ports(skb, dataoff, tuple);
308 #endif
309 #ifdef CONFIG_NF_CT_PROTO_DCCP
310 	case IPPROTO_DCCP:
311 		return nf_ct_get_tuple_ports(skb, dataoff, tuple);
312 #endif
313 	default:
314 		break;
315 	}
316 
317 	return true;
318 }
319 
ipv4_get_l4proto(const struct sk_buff * skb,unsigned int nhoff,u_int8_t * protonum)320 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
321 			    u_int8_t *protonum)
322 {
323 	int dataoff = -1;
324 	const struct iphdr *iph;
325 	struct iphdr _iph;
326 
327 	iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
328 	if (!iph)
329 		return -1;
330 
331 	/* Conntrack defragments packets, we might still see fragments
332 	 * inside ICMP packets though.
333 	 */
334 	if (iph->frag_off & htons(IP_OFFSET))
335 		return -1;
336 
337 	dataoff = nhoff + (iph->ihl << 2);
338 	*protonum = iph->protocol;
339 
340 	/* Check bogus IP headers */
341 	if (dataoff > skb->len) {
342 		pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
343 			 nhoff, iph->ihl << 2, skb->len);
344 		return -1;
345 	}
346 	return dataoff;
347 }
348 
349 #if IS_ENABLED(CONFIG_IPV6)
ipv6_get_l4proto(const struct sk_buff * skb,unsigned int nhoff,u8 * protonum)350 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
351 			    u8 *protonum)
352 {
353 	int protoff = -1;
354 	unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
355 	__be16 frag_off;
356 	u8 nexthdr;
357 
358 	if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
359 			  &nexthdr, sizeof(nexthdr)) != 0) {
360 		pr_debug("can't get nexthdr\n");
361 		return -1;
362 	}
363 	protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
364 	/*
365 	 * (protoff == skb->len) means the packet has not data, just
366 	 * IPv6 and possibly extensions headers, but it is tracked anyway
367 	 */
368 	if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
369 		pr_debug("can't find proto in pkt\n");
370 		return -1;
371 	}
372 
373 	*protonum = nexthdr;
374 	return protoff;
375 }
376 #endif
377 
get_l4proto(const struct sk_buff * skb,unsigned int nhoff,u8 pf,u8 * l4num)378 static int get_l4proto(const struct sk_buff *skb,
379 		       unsigned int nhoff, u8 pf, u8 *l4num)
380 {
381 	switch (pf) {
382 	case NFPROTO_IPV4:
383 		return ipv4_get_l4proto(skb, nhoff, l4num);
384 #if IS_ENABLED(CONFIG_IPV6)
385 	case NFPROTO_IPV6:
386 		return ipv6_get_l4proto(skb, nhoff, l4num);
387 #endif
388 	default:
389 		*l4num = 0;
390 		break;
391 	}
392 	return -1;
393 }
394 
nf_ct_get_tuplepr(const struct sk_buff * skb,unsigned int nhoff,u_int16_t l3num,struct net * net,struct nf_conntrack_tuple * tuple)395 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
396 		       u_int16_t l3num,
397 		       struct net *net, struct nf_conntrack_tuple *tuple)
398 {
399 	u8 protonum;
400 	int protoff;
401 
402 	protoff = get_l4proto(skb, nhoff, l3num, &protonum);
403 	if (protoff <= 0)
404 		return false;
405 
406 	return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
407 }
408 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
409 
410 bool
nf_ct_invert_tuple(struct nf_conntrack_tuple * inverse,const struct nf_conntrack_tuple * orig)411 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
412 		   const struct nf_conntrack_tuple *orig)
413 {
414 	memset(inverse, 0, sizeof(*inverse));
415 
416 	inverse->src.l3num = orig->src.l3num;
417 
418 	switch (orig->src.l3num) {
419 	case NFPROTO_IPV4:
420 		inverse->src.u3.ip = orig->dst.u3.ip;
421 		inverse->dst.u3.ip = orig->src.u3.ip;
422 		break;
423 	case NFPROTO_IPV6:
424 		inverse->src.u3.in6 = orig->dst.u3.in6;
425 		inverse->dst.u3.in6 = orig->src.u3.in6;
426 		break;
427 	default:
428 		break;
429 	}
430 
431 	inverse->dst.dir = !orig->dst.dir;
432 
433 	inverse->dst.protonum = orig->dst.protonum;
434 
435 	switch (orig->dst.protonum) {
436 	case IPPROTO_ICMP:
437 		return nf_conntrack_invert_icmp_tuple(inverse, orig);
438 #if IS_ENABLED(CONFIG_IPV6)
439 	case IPPROTO_ICMPV6:
440 		return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
441 #endif
442 	}
443 
444 	inverse->src.u.all = orig->dst.u.all;
445 	inverse->dst.u.all = orig->src.u.all;
446 	return true;
447 }
448 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
449 
450 /* Generate a almost-unique pseudo-id for a given conntrack.
451  *
452  * intentionally doesn't re-use any of the seeds used for hash
453  * table location, we assume id gets exposed to userspace.
454  *
455  * Following nf_conn items do not change throughout lifetime
456  * of the nf_conn:
457  *
458  * 1. nf_conn address
459  * 2. nf_conn->master address (normally NULL)
460  * 3. the associated net namespace
461  * 4. the original direction tuple
462  */
nf_ct_get_id(const struct nf_conn * ct)463 u32 nf_ct_get_id(const struct nf_conn *ct)
464 {
465 	static __read_mostly siphash_key_t ct_id_seed;
466 	unsigned long a, b, c, d;
467 
468 	net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
469 
470 	a = (unsigned long)ct;
471 	b = (unsigned long)ct->master;
472 	c = (unsigned long)nf_ct_net(ct);
473 	d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
474 				   sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
475 				   &ct_id_seed);
476 #ifdef CONFIG_64BIT
477 	return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
478 #else
479 	return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
480 #endif
481 }
482 EXPORT_SYMBOL_GPL(nf_ct_get_id);
483 
484 static void
clean_from_lists(struct nf_conn * ct)485 clean_from_lists(struct nf_conn *ct)
486 {
487 	pr_debug("clean_from_lists(%p)\n", ct);
488 	hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
489 	hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
490 
491 	/* Destroy all pending expectations */
492 	nf_ct_remove_expectations(ct);
493 }
494 
495 /* must be called with local_bh_disable */
nf_ct_add_to_dying_list(struct nf_conn * ct)496 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
497 {
498 	struct ct_pcpu *pcpu;
499 
500 	/* add this conntrack to the (per cpu) dying list */
501 	ct->cpu = smp_processor_id();
502 	pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
503 
504 	spin_lock(&pcpu->lock);
505 	hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
506 			     &pcpu->dying);
507 	spin_unlock(&pcpu->lock);
508 }
509 
510 /* must be called with local_bh_disable */
nf_ct_add_to_unconfirmed_list(struct nf_conn * ct)511 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
512 {
513 	struct ct_pcpu *pcpu;
514 
515 	/* add this conntrack to the (per cpu) unconfirmed list */
516 	ct->cpu = smp_processor_id();
517 	pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
518 
519 	spin_lock(&pcpu->lock);
520 	hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
521 			     &pcpu->unconfirmed);
522 	spin_unlock(&pcpu->lock);
523 }
524 
525 /* must be called with local_bh_disable */
nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn * ct)526 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
527 {
528 	struct ct_pcpu *pcpu;
529 
530 	/* We overload first tuple to link into unconfirmed or dying list.*/
531 	pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
532 
533 	spin_lock(&pcpu->lock);
534 	BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
535 	hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
536 	spin_unlock(&pcpu->lock);
537 }
538 
539 #define NFCT_ALIGN(len)	(((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
540 
541 /* Released via destroy_conntrack() */
nf_ct_tmpl_alloc(struct net * net,const struct nf_conntrack_zone * zone,gfp_t flags)542 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
543 				 const struct nf_conntrack_zone *zone,
544 				 gfp_t flags)
545 {
546 	struct nf_conn *tmpl, *p;
547 
548 	if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
549 		tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
550 		if (!tmpl)
551 			return NULL;
552 
553 		p = tmpl;
554 		tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
555 		if (tmpl != p) {
556 			tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
557 			tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
558 		}
559 	} else {
560 		tmpl = kzalloc(sizeof(*tmpl), flags);
561 		if (!tmpl)
562 			return NULL;
563 	}
564 
565 	tmpl->status = IPS_TEMPLATE;
566 	write_pnet(&tmpl->ct_net, net);
567 	nf_ct_zone_add(tmpl, zone);
568 	atomic_set(&tmpl->ct_general.use, 0);
569 
570 	return tmpl;
571 }
572 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
573 
nf_ct_tmpl_free(struct nf_conn * tmpl)574 void nf_ct_tmpl_free(struct nf_conn *tmpl)
575 {
576 	nf_ct_ext_destroy(tmpl);
577 
578 	if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
579 		kfree((char *)tmpl - tmpl->proto.tmpl_padto);
580 	else
581 		kfree(tmpl);
582 }
583 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
584 
destroy_gre_conntrack(struct nf_conn * ct)585 static void destroy_gre_conntrack(struct nf_conn *ct)
586 {
587 #ifdef CONFIG_NF_CT_PROTO_GRE
588 	struct nf_conn *master = ct->master;
589 
590 	if (master)
591 		nf_ct_gre_keymap_destroy(master);
592 #endif
593 }
594 
595 static void
destroy_conntrack(struct nf_conntrack * nfct)596 destroy_conntrack(struct nf_conntrack *nfct)
597 {
598 	struct nf_conn *ct = (struct nf_conn *)nfct;
599 
600 	pr_debug("destroy_conntrack(%p)\n", ct);
601 	WARN_ON(atomic_read(&nfct->use) != 0);
602 
603 	if (unlikely(nf_ct_is_template(ct))) {
604 		nf_ct_tmpl_free(ct);
605 		return;
606 	}
607 
608 	if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
609 		destroy_gre_conntrack(ct);
610 
611 	local_bh_disable();
612 	/* Expectations will have been removed in clean_from_lists,
613 	 * except TFTP can create an expectation on the first packet,
614 	 * before connection is in the list, so we need to clean here,
615 	 * too.
616 	 */
617 	nf_ct_remove_expectations(ct);
618 
619 	nf_ct_del_from_dying_or_unconfirmed_list(ct);
620 
621 	local_bh_enable();
622 
623 	if (ct->master)
624 		nf_ct_put(ct->master);
625 
626 	pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
627 	nf_conntrack_free(ct);
628 }
629 
nf_ct_delete_from_lists(struct nf_conn * ct)630 static void nf_ct_delete_from_lists(struct nf_conn *ct)
631 {
632 	struct net *net = nf_ct_net(ct);
633 	unsigned int hash, reply_hash;
634 	unsigned int sequence;
635 
636 	nf_ct_helper_destroy(ct);
637 
638 	local_bh_disable();
639 	do {
640 		sequence = read_seqcount_begin(&nf_conntrack_generation);
641 		hash = hash_conntrack(net,
642 				      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
643 		reply_hash = hash_conntrack(net,
644 					   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
645 	} while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
646 
647 	clean_from_lists(ct);
648 	nf_conntrack_double_unlock(hash, reply_hash);
649 
650 	nf_ct_add_to_dying_list(ct);
651 
652 	local_bh_enable();
653 }
654 
nf_ct_delete(struct nf_conn * ct,u32 portid,int report)655 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
656 {
657 	struct nf_conn_tstamp *tstamp;
658 
659 	if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
660 		return false;
661 
662 	tstamp = nf_conn_tstamp_find(ct);
663 	if (tstamp) {
664 		s32 timeout = READ_ONCE(ct->timeout) - nfct_time_stamp;
665 
666 		tstamp->stop = ktime_get_real_ns();
667 		if (timeout < 0)
668 			tstamp->stop -= jiffies_to_nsecs(-timeout);
669 	}
670 
671 	if (nf_conntrack_event_report(IPCT_DESTROY, ct,
672 				    portid, report) < 0) {
673 		/* destroy event was not delivered. nf_ct_put will
674 		 * be done by event cache worker on redelivery.
675 		 */
676 		nf_ct_delete_from_lists(ct);
677 		nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
678 		return false;
679 	}
680 
681 	nf_conntrack_ecache_work(nf_ct_net(ct));
682 	nf_ct_delete_from_lists(ct);
683 	nf_ct_put(ct);
684 	return true;
685 }
686 EXPORT_SYMBOL_GPL(nf_ct_delete);
687 
688 static inline bool
nf_ct_key_equal(struct nf_conntrack_tuple_hash * h,const struct nf_conntrack_tuple * tuple,const struct nf_conntrack_zone * zone,const struct net * net)689 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
690 		const struct nf_conntrack_tuple *tuple,
691 		const struct nf_conntrack_zone *zone,
692 		const struct net *net)
693 {
694 	struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
695 
696 	/* A conntrack can be recreated with the equal tuple,
697 	 * so we need to check that the conntrack is confirmed
698 	 */
699 	return nf_ct_tuple_equal(tuple, &h->tuple) &&
700 	       nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
701 	       nf_ct_is_confirmed(ct) &&
702 	       net_eq(net, nf_ct_net(ct));
703 }
704 
705 static inline bool
nf_ct_match(const struct nf_conn * ct1,const struct nf_conn * ct2)706 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
707 {
708 	return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
709 				 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
710 	       nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
711 				 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
712 	       nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
713 	       nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
714 	       net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
715 }
716 
717 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
nf_ct_gc_expired(struct nf_conn * ct)718 static void nf_ct_gc_expired(struct nf_conn *ct)
719 {
720 	if (!atomic_inc_not_zero(&ct->ct_general.use))
721 		return;
722 
723 	if (nf_ct_should_gc(ct))
724 		nf_ct_kill(ct);
725 
726 	nf_ct_put(ct);
727 }
728 
729 /*
730  * Warning :
731  * - Caller must take a reference on returned object
732  *   and recheck nf_ct_tuple_equal(tuple, &h->tuple)
733  */
734 static struct nf_conntrack_tuple_hash *
____nf_conntrack_find(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * tuple,u32 hash)735 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
736 		      const struct nf_conntrack_tuple *tuple, u32 hash)
737 {
738 	struct nf_conntrack_tuple_hash *h;
739 	struct hlist_nulls_head *ct_hash;
740 	struct hlist_nulls_node *n;
741 	unsigned int bucket, hsize;
742 
743 begin:
744 	nf_conntrack_get_ht(&ct_hash, &hsize);
745 	bucket = reciprocal_scale(hash, hsize);
746 
747 	hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
748 		struct nf_conn *ct;
749 
750 		ct = nf_ct_tuplehash_to_ctrack(h);
751 		if (nf_ct_is_expired(ct)) {
752 			nf_ct_gc_expired(ct);
753 			continue;
754 		}
755 
756 		if (nf_ct_key_equal(h, tuple, zone, net))
757 			return h;
758 	}
759 	/*
760 	 * if the nulls value we got at the end of this lookup is
761 	 * not the expected one, we must restart lookup.
762 	 * We probably met an item that was moved to another chain.
763 	 */
764 	if (get_nulls_value(n) != bucket) {
765 		NF_CT_STAT_INC_ATOMIC(net, search_restart);
766 		goto begin;
767 	}
768 
769 	return NULL;
770 }
771 
772 /* Find a connection corresponding to a tuple. */
773 static struct nf_conntrack_tuple_hash *
__nf_conntrack_find_get(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * tuple,u32 hash)774 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
775 			const struct nf_conntrack_tuple *tuple, u32 hash)
776 {
777 	struct nf_conntrack_tuple_hash *h;
778 	struct nf_conn *ct;
779 
780 	rcu_read_lock();
781 
782 	h = ____nf_conntrack_find(net, zone, tuple, hash);
783 	if (h) {
784 		/* We have a candidate that matches the tuple we're interested
785 		 * in, try to obtain a reference and re-check tuple
786 		 */
787 		ct = nf_ct_tuplehash_to_ctrack(h);
788 		if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
789 			if (likely(nf_ct_key_equal(h, tuple, zone, net)))
790 				goto found;
791 
792 			/* TYPESAFE_BY_RCU recycled the candidate */
793 			nf_ct_put(ct);
794 		}
795 
796 		h = NULL;
797 	}
798 found:
799 	rcu_read_unlock();
800 
801 	return h;
802 }
803 
804 struct nf_conntrack_tuple_hash *
nf_conntrack_find_get(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * tuple)805 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
806 		      const struct nf_conntrack_tuple *tuple)
807 {
808 	return __nf_conntrack_find_get(net, zone, tuple,
809 				       hash_conntrack_raw(tuple, net));
810 }
811 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
812 
__nf_conntrack_hash_insert(struct nf_conn * ct,unsigned int hash,unsigned int reply_hash)813 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
814 				       unsigned int hash,
815 				       unsigned int reply_hash)
816 {
817 	hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
818 			   &nf_conntrack_hash[hash]);
819 	hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
820 			   &nf_conntrack_hash[reply_hash]);
821 }
822 
823 int
nf_conntrack_hash_check_insert(struct nf_conn * ct)824 nf_conntrack_hash_check_insert(struct nf_conn *ct)
825 {
826 	const struct nf_conntrack_zone *zone;
827 	struct net *net = nf_ct_net(ct);
828 	unsigned int hash, reply_hash;
829 	struct nf_conntrack_tuple_hash *h;
830 	struct hlist_nulls_node *n;
831 	unsigned int sequence;
832 
833 	zone = nf_ct_zone(ct);
834 
835 	local_bh_disable();
836 	do {
837 		sequence = read_seqcount_begin(&nf_conntrack_generation);
838 		hash = hash_conntrack(net,
839 				      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
840 		reply_hash = hash_conntrack(net,
841 					   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
842 	} while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
843 
844 	/* See if there's one in the list already, including reverse */
845 	hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
846 		if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
847 				    zone, net))
848 			goto out;
849 
850 	hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
851 		if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
852 				    zone, net))
853 			goto out;
854 
855 	smp_wmb();
856 	/* The caller holds a reference to this object */
857 	atomic_set(&ct->ct_general.use, 2);
858 	__nf_conntrack_hash_insert(ct, hash, reply_hash);
859 	nf_conntrack_double_unlock(hash, reply_hash);
860 	NF_CT_STAT_INC(net, insert);
861 	local_bh_enable();
862 	return 0;
863 
864 out:
865 	nf_conntrack_double_unlock(hash, reply_hash);
866 	local_bh_enable();
867 	return -EEXIST;
868 }
869 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
870 
nf_ct_acct_add(struct nf_conn * ct,u32 dir,unsigned int packets,unsigned int bytes)871 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
872 		    unsigned int bytes)
873 {
874 	struct nf_conn_acct *acct;
875 
876 	acct = nf_conn_acct_find(ct);
877 	if (acct) {
878 		struct nf_conn_counter *counter = acct->counter;
879 
880 		atomic64_add(packets, &counter[dir].packets);
881 		atomic64_add(bytes, &counter[dir].bytes);
882 	}
883 }
884 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
885 
nf_ct_acct_merge(struct nf_conn * ct,enum ip_conntrack_info ctinfo,const struct nf_conn * loser_ct)886 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
887 			     const struct nf_conn *loser_ct)
888 {
889 	struct nf_conn_acct *acct;
890 
891 	acct = nf_conn_acct_find(loser_ct);
892 	if (acct) {
893 		struct nf_conn_counter *counter = acct->counter;
894 		unsigned int bytes;
895 
896 		/* u32 should be fine since we must have seen one packet. */
897 		bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
898 		nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
899 	}
900 }
901 
__nf_conntrack_insert_prepare(struct nf_conn * ct)902 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
903 {
904 	struct nf_conn_tstamp *tstamp;
905 
906 	atomic_inc(&ct->ct_general.use);
907 	ct->status |= IPS_CONFIRMED;
908 
909 	/* set conntrack timestamp, if enabled. */
910 	tstamp = nf_conn_tstamp_find(ct);
911 	if (tstamp)
912 		tstamp->start = ktime_get_real_ns();
913 }
914 
915 /* caller must hold locks to prevent concurrent changes */
__nf_ct_resolve_clash(struct sk_buff * skb,struct nf_conntrack_tuple_hash * h)916 static int __nf_ct_resolve_clash(struct sk_buff *skb,
917 				 struct nf_conntrack_tuple_hash *h)
918 {
919 	/* This is the conntrack entry already in hashes that won race. */
920 	struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
921 	enum ip_conntrack_info ctinfo;
922 	struct nf_conn *loser_ct;
923 
924 	loser_ct = nf_ct_get(skb, &ctinfo);
925 
926 	if (nf_ct_is_dying(ct))
927 		return NF_DROP;
928 
929 	if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
930 	    nf_ct_match(ct, loser_ct)) {
931 		struct net *net = nf_ct_net(ct);
932 
933 		nf_conntrack_get(&ct->ct_general);
934 
935 		nf_ct_acct_merge(ct, ctinfo, loser_ct);
936 		nf_ct_add_to_dying_list(loser_ct);
937 		nf_conntrack_put(&loser_ct->ct_general);
938 		nf_ct_set(skb, ct, ctinfo);
939 
940 		NF_CT_STAT_INC(net, clash_resolve);
941 		return NF_ACCEPT;
942 	}
943 
944 	return NF_DROP;
945 }
946 
947 /**
948  * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
949  *
950  * @skb: skb that causes the collision
951  * @repl_idx: hash slot for reply direction
952  *
953  * Called when origin or reply direction had a clash.
954  * The skb can be handled without packet drop provided the reply direction
955  * is unique or there the existing entry has the identical tuple in both
956  * directions.
957  *
958  * Caller must hold conntrack table locks to prevent concurrent updates.
959  *
960  * Returns NF_DROP if the clash could not be handled.
961  */
nf_ct_resolve_clash_harder(struct sk_buff * skb,u32 repl_idx)962 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
963 {
964 	struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
965 	const struct nf_conntrack_zone *zone;
966 	struct nf_conntrack_tuple_hash *h;
967 	struct hlist_nulls_node *n;
968 	struct net *net;
969 
970 	zone = nf_ct_zone(loser_ct);
971 	net = nf_ct_net(loser_ct);
972 
973 	/* Reply direction must never result in a clash, unless both origin
974 	 * and reply tuples are identical.
975 	 */
976 	hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
977 		if (nf_ct_key_equal(h,
978 				    &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
979 				    zone, net))
980 			return __nf_ct_resolve_clash(skb, h);
981 	}
982 
983 	/* We want the clashing entry to go away real soon: 1 second timeout. */
984 	WRITE_ONCE(loser_ct->timeout, nfct_time_stamp + HZ);
985 
986 	/* IPS_NAT_CLASH removes the entry automatically on the first
987 	 * reply.  Also prevents UDP tracker from moving the entry to
988 	 * ASSURED state, i.e. the entry can always be evicted under
989 	 * pressure.
990 	 */
991 	loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
992 
993 	__nf_conntrack_insert_prepare(loser_ct);
994 
995 	/* fake add for ORIGINAL dir: we want lookups to only find the entry
996 	 * already in the table.  This also hides the clashing entry from
997 	 * ctnetlink iteration, i.e. conntrack -L won't show them.
998 	 */
999 	hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1000 
1001 	hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1002 				 &nf_conntrack_hash[repl_idx]);
1003 
1004 	NF_CT_STAT_INC(net, clash_resolve);
1005 	return NF_ACCEPT;
1006 }
1007 
1008 /**
1009  * nf_ct_resolve_clash - attempt to handle clash without packet drop
1010  *
1011  * @skb: skb that causes the clash
1012  * @h: tuplehash of the clashing entry already in table
1013  * @reply_hash: hash slot for reply direction
1014  *
1015  * A conntrack entry can be inserted to the connection tracking table
1016  * if there is no existing entry with an identical tuple.
1017  *
1018  * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1019  * to be dropped.  In case @skb is retransmitted, next conntrack lookup
1020  * will find the already-existing entry.
1021  *
1022  * The major problem with such packet drop is the extra delay added by
1023  * the packet loss -- it will take some time for a retransmit to occur
1024  * (or the sender to time out when waiting for a reply).
1025  *
1026  * This function attempts to handle the situation without packet drop.
1027  *
1028  * If @skb has no NAT transformation or if the colliding entries are
1029  * exactly the same, only the to-be-confirmed conntrack entry is discarded
1030  * and @skb is associated with the conntrack entry already in the table.
1031  *
1032  * Failing that, the new, unconfirmed conntrack is still added to the table
1033  * provided that the collision only occurs in the ORIGINAL direction.
1034  * The new entry will be added only in the non-clashing REPLY direction,
1035  * so packets in the ORIGINAL direction will continue to match the existing
1036  * entry.  The new entry will also have a fixed timeout so it expires --
1037  * due to the collision, it will only see reply traffic.
1038  *
1039  * Returns NF_DROP if the clash could not be resolved.
1040  */
1041 static __cold noinline int
nf_ct_resolve_clash(struct sk_buff * skb,struct nf_conntrack_tuple_hash * h,u32 reply_hash)1042 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1043 		    u32 reply_hash)
1044 {
1045 	/* This is the conntrack entry already in hashes that won race. */
1046 	struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1047 	const struct nf_conntrack_l4proto *l4proto;
1048 	enum ip_conntrack_info ctinfo;
1049 	struct nf_conn *loser_ct;
1050 	struct net *net;
1051 	int ret;
1052 
1053 	loser_ct = nf_ct_get(skb, &ctinfo);
1054 	net = nf_ct_net(loser_ct);
1055 
1056 	l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1057 	if (!l4proto->allow_clash)
1058 		goto drop;
1059 
1060 	ret = __nf_ct_resolve_clash(skb, h);
1061 	if (ret == NF_ACCEPT)
1062 		return ret;
1063 
1064 	ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1065 	if (ret == NF_ACCEPT)
1066 		return ret;
1067 
1068 drop:
1069 	nf_ct_add_to_dying_list(loser_ct);
1070 	NF_CT_STAT_INC(net, drop);
1071 	NF_CT_STAT_INC(net, insert_failed);
1072 	return NF_DROP;
1073 }
1074 
1075 /* Confirm a connection given skb; places it in hash table */
1076 int
__nf_conntrack_confirm(struct sk_buff * skb)1077 __nf_conntrack_confirm(struct sk_buff *skb)
1078 {
1079 	const struct nf_conntrack_zone *zone;
1080 	unsigned int hash, reply_hash;
1081 	struct nf_conntrack_tuple_hash *h;
1082 	struct nf_conn *ct;
1083 	struct nf_conn_help *help;
1084 	struct hlist_nulls_node *n;
1085 	enum ip_conntrack_info ctinfo;
1086 	struct net *net;
1087 	unsigned int sequence;
1088 	int ret = NF_DROP;
1089 
1090 	ct = nf_ct_get(skb, &ctinfo);
1091 	net = nf_ct_net(ct);
1092 
1093 	/* ipt_REJECT uses nf_conntrack_attach to attach related
1094 	   ICMP/TCP RST packets in other direction.  Actual packet
1095 	   which created connection will be IP_CT_NEW or for an
1096 	   expected connection, IP_CT_RELATED. */
1097 	if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1098 		return NF_ACCEPT;
1099 
1100 	zone = nf_ct_zone(ct);
1101 	local_bh_disable();
1102 
1103 	do {
1104 		sequence = read_seqcount_begin(&nf_conntrack_generation);
1105 		/* reuse the hash saved before */
1106 		hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1107 		hash = scale_hash(hash);
1108 		reply_hash = hash_conntrack(net,
1109 					   &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
1110 
1111 	} while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1112 
1113 	/* We're not in hash table, and we refuse to set up related
1114 	 * connections for unconfirmed conns.  But packet copies and
1115 	 * REJECT will give spurious warnings here.
1116 	 */
1117 
1118 	/* Another skb with the same unconfirmed conntrack may
1119 	 * win the race. This may happen for bridge(br_flood)
1120 	 * or broadcast/multicast packets do skb_clone with
1121 	 * unconfirmed conntrack.
1122 	 */
1123 	if (unlikely(nf_ct_is_confirmed(ct))) {
1124 		WARN_ON_ONCE(1);
1125 		nf_conntrack_double_unlock(hash, reply_hash);
1126 		local_bh_enable();
1127 		return NF_DROP;
1128 	}
1129 
1130 	pr_debug("Confirming conntrack %p\n", ct);
1131 	/* We have to check the DYING flag after unlink to prevent
1132 	 * a race against nf_ct_get_next_corpse() possibly called from
1133 	 * user context, else we insert an already 'dead' hash, blocking
1134 	 * further use of that particular connection -JM.
1135 	 */
1136 	nf_ct_del_from_dying_or_unconfirmed_list(ct);
1137 
1138 	if (unlikely(nf_ct_is_dying(ct))) {
1139 		nf_ct_add_to_dying_list(ct);
1140 		NF_CT_STAT_INC(net, insert_failed);
1141 		goto dying;
1142 	}
1143 
1144 	/* See if there's one in the list already, including reverse:
1145 	   NAT could have grabbed it without realizing, since we're
1146 	   not in the hash.  If there is, we lost race. */
1147 	hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
1148 		if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1149 				    zone, net))
1150 			goto out;
1151 
1152 	hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
1153 		if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1154 				    zone, net))
1155 			goto out;
1156 
1157 	/* Timer relative to confirmation time, not original
1158 	   setting time, otherwise we'd get timer wrap in
1159 	   weird delay cases. */
1160 	ct->timeout += nfct_time_stamp;
1161 
1162 	__nf_conntrack_insert_prepare(ct);
1163 
1164 	/* Since the lookup is lockless, hash insertion must be done after
1165 	 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1166 	 * guarantee that no other CPU can find the conntrack before the above
1167 	 * stores are visible.
1168 	 */
1169 	__nf_conntrack_hash_insert(ct, hash, reply_hash);
1170 	nf_conntrack_double_unlock(hash, reply_hash);
1171 	local_bh_enable();
1172 
1173 	help = nfct_help(ct);
1174 	if (help && help->helper)
1175 		nf_conntrack_event_cache(IPCT_HELPER, ct);
1176 
1177 	nf_conntrack_event_cache(master_ct(ct) ?
1178 				 IPCT_RELATED : IPCT_NEW, ct);
1179 	return NF_ACCEPT;
1180 
1181 out:
1182 	ret = nf_ct_resolve_clash(skb, h, reply_hash);
1183 dying:
1184 	nf_conntrack_double_unlock(hash, reply_hash);
1185 	local_bh_enable();
1186 	return ret;
1187 }
1188 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1189 
1190 /* Returns true if a connection correspondings to the tuple (required
1191    for NAT). */
1192 int
nf_conntrack_tuple_taken(const struct nf_conntrack_tuple * tuple,const struct nf_conn * ignored_conntrack)1193 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1194 			 const struct nf_conn *ignored_conntrack)
1195 {
1196 	struct net *net = nf_ct_net(ignored_conntrack);
1197 	const struct nf_conntrack_zone *zone;
1198 	struct nf_conntrack_tuple_hash *h;
1199 	struct hlist_nulls_head *ct_hash;
1200 	unsigned int hash, hsize;
1201 	struct hlist_nulls_node *n;
1202 	struct nf_conn *ct;
1203 
1204 	zone = nf_ct_zone(ignored_conntrack);
1205 
1206 	rcu_read_lock();
1207  begin:
1208 	nf_conntrack_get_ht(&ct_hash, &hsize);
1209 	hash = __hash_conntrack(net, tuple, hsize);
1210 
1211 	hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1212 		ct = nf_ct_tuplehash_to_ctrack(h);
1213 
1214 		if (ct == ignored_conntrack)
1215 			continue;
1216 
1217 		if (nf_ct_is_expired(ct)) {
1218 			nf_ct_gc_expired(ct);
1219 			continue;
1220 		}
1221 
1222 		if (nf_ct_key_equal(h, tuple, zone, net)) {
1223 			/* Tuple is taken already, so caller will need to find
1224 			 * a new source port to use.
1225 			 *
1226 			 * Only exception:
1227 			 * If the *original tuples* are identical, then both
1228 			 * conntracks refer to the same flow.
1229 			 * This is a rare situation, it can occur e.g. when
1230 			 * more than one UDP packet is sent from same socket
1231 			 * in different threads.
1232 			 *
1233 			 * Let nf_ct_resolve_clash() deal with this later.
1234 			 */
1235 			if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1236 					      &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1237 					      nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1238 				continue;
1239 
1240 			NF_CT_STAT_INC_ATOMIC(net, found);
1241 			rcu_read_unlock();
1242 			return 1;
1243 		}
1244 	}
1245 
1246 	if (get_nulls_value(n) != hash) {
1247 		NF_CT_STAT_INC_ATOMIC(net, search_restart);
1248 		goto begin;
1249 	}
1250 
1251 	rcu_read_unlock();
1252 
1253 	return 0;
1254 }
1255 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1256 
1257 #define NF_CT_EVICTION_RANGE	8
1258 
1259 /* There's a small race here where we may free a just-assured
1260    connection.  Too bad: we're in trouble anyway. */
early_drop_list(struct net * net,struct hlist_nulls_head * head)1261 static unsigned int early_drop_list(struct net *net,
1262 				    struct hlist_nulls_head *head)
1263 {
1264 	struct nf_conntrack_tuple_hash *h;
1265 	struct hlist_nulls_node *n;
1266 	unsigned int drops = 0;
1267 	struct nf_conn *tmp;
1268 
1269 	hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1270 		tmp = nf_ct_tuplehash_to_ctrack(h);
1271 
1272 		if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1273 			continue;
1274 
1275 		if (nf_ct_is_expired(tmp)) {
1276 			nf_ct_gc_expired(tmp);
1277 			continue;
1278 		}
1279 
1280 		if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1281 		    !net_eq(nf_ct_net(tmp), net) ||
1282 		    nf_ct_is_dying(tmp))
1283 			continue;
1284 
1285 		if (!atomic_inc_not_zero(&tmp->ct_general.use))
1286 			continue;
1287 
1288 		/* kill only if still in same netns -- might have moved due to
1289 		 * SLAB_TYPESAFE_BY_RCU rules.
1290 		 *
1291 		 * We steal the timer reference.  If that fails timer has
1292 		 * already fired or someone else deleted it. Just drop ref
1293 		 * and move to next entry.
1294 		 */
1295 		if (net_eq(nf_ct_net(tmp), net) &&
1296 		    nf_ct_is_confirmed(tmp) &&
1297 		    nf_ct_delete(tmp, 0, 0))
1298 			drops++;
1299 
1300 		nf_ct_put(tmp);
1301 	}
1302 
1303 	return drops;
1304 }
1305 
early_drop(struct net * net,unsigned int hash)1306 static noinline int early_drop(struct net *net, unsigned int hash)
1307 {
1308 	unsigned int i, bucket;
1309 
1310 	for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1311 		struct hlist_nulls_head *ct_hash;
1312 		unsigned int hsize, drops;
1313 
1314 		rcu_read_lock();
1315 		nf_conntrack_get_ht(&ct_hash, &hsize);
1316 		if (!i)
1317 			bucket = reciprocal_scale(hash, hsize);
1318 		else
1319 			bucket = (bucket + 1) % hsize;
1320 
1321 		drops = early_drop_list(net, &ct_hash[bucket]);
1322 		rcu_read_unlock();
1323 
1324 		if (drops) {
1325 			NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1326 			return true;
1327 		}
1328 	}
1329 
1330 	return false;
1331 }
1332 
gc_worker_skip_ct(const struct nf_conn * ct)1333 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1334 {
1335 	return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1336 }
1337 
gc_worker_can_early_drop(const struct nf_conn * ct)1338 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1339 {
1340 	const struct nf_conntrack_l4proto *l4proto;
1341 
1342 	if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1343 		return true;
1344 
1345 	l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1346 	if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1347 		return true;
1348 
1349 	return false;
1350 }
1351 
gc_worker(struct work_struct * work)1352 static void gc_worker(struct work_struct *work)
1353 {
1354 	unsigned long end_time = jiffies + GC_SCAN_MAX_DURATION;
1355 	unsigned int i, hashsz, nf_conntrack_max95 = 0;
1356 	unsigned long next_run = GC_SCAN_INTERVAL;
1357 	struct conntrack_gc_work *gc_work;
1358 	gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1359 
1360 	i = gc_work->next_bucket;
1361 	if (gc_work->early_drop)
1362 		nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1363 
1364 	do {
1365 		struct nf_conntrack_tuple_hash *h;
1366 		struct hlist_nulls_head *ct_hash;
1367 		struct hlist_nulls_node *n;
1368 		struct nf_conn *tmp;
1369 
1370 		rcu_read_lock();
1371 
1372 		nf_conntrack_get_ht(&ct_hash, &hashsz);
1373 		if (i >= hashsz) {
1374 			rcu_read_unlock();
1375 			break;
1376 		}
1377 
1378 		hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1379 			struct net *net;
1380 
1381 			tmp = nf_ct_tuplehash_to_ctrack(h);
1382 
1383 			if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1384 				nf_ct_offload_timeout(tmp);
1385 				continue;
1386 			}
1387 
1388 			if (nf_ct_is_expired(tmp)) {
1389 				nf_ct_gc_expired(tmp);
1390 				continue;
1391 			}
1392 
1393 			if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1394 				continue;
1395 
1396 			net = nf_ct_net(tmp);
1397 			if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1398 				continue;
1399 
1400 			/* need to take reference to avoid possible races */
1401 			if (!atomic_inc_not_zero(&tmp->ct_general.use))
1402 				continue;
1403 
1404 			if (gc_worker_skip_ct(tmp)) {
1405 				nf_ct_put(tmp);
1406 				continue;
1407 			}
1408 
1409 			if (gc_worker_can_early_drop(tmp))
1410 				nf_ct_kill(tmp);
1411 
1412 			nf_ct_put(tmp);
1413 		}
1414 
1415 		/* could check get_nulls_value() here and restart if ct
1416 		 * was moved to another chain.  But given gc is best-effort
1417 		 * we will just continue with next hash slot.
1418 		 */
1419 		rcu_read_unlock();
1420 		cond_resched();
1421 		i++;
1422 
1423 		if (time_after(jiffies, end_time) && i < hashsz) {
1424 			gc_work->next_bucket = i;
1425 			next_run = 0;
1426 			break;
1427 		}
1428 	} while (i < hashsz);
1429 
1430 	if (gc_work->exiting)
1431 		return;
1432 
1433 	/*
1434 	 * Eviction will normally happen from the packet path, and not
1435 	 * from this gc worker.
1436 	 *
1437 	 * This worker is only here to reap expired entries when system went
1438 	 * idle after a busy period.
1439 	 */
1440 	if (next_run) {
1441 		gc_work->early_drop = false;
1442 		gc_work->next_bucket = 0;
1443 	}
1444 	queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1445 }
1446 
conntrack_gc_work_init(struct conntrack_gc_work * gc_work)1447 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1448 {
1449 	INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1450 	gc_work->exiting = false;
1451 }
1452 
1453 static struct nf_conn *
__nf_conntrack_alloc(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * orig,const struct nf_conntrack_tuple * repl,gfp_t gfp,u32 hash)1454 __nf_conntrack_alloc(struct net *net,
1455 		     const struct nf_conntrack_zone *zone,
1456 		     const struct nf_conntrack_tuple *orig,
1457 		     const struct nf_conntrack_tuple *repl,
1458 		     gfp_t gfp, u32 hash)
1459 {
1460 	struct nf_conn *ct;
1461 
1462 	/* We don't want any race condition at early drop stage */
1463 	atomic_inc(&net->ct.count);
1464 
1465 	if (nf_conntrack_max &&
1466 	    unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1467 		if (!early_drop(net, hash)) {
1468 			if (!conntrack_gc_work.early_drop)
1469 				conntrack_gc_work.early_drop = true;
1470 			atomic_dec(&net->ct.count);
1471 			net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1472 			return ERR_PTR(-ENOMEM);
1473 		}
1474 	}
1475 
1476 	/*
1477 	 * Do not use kmem_cache_zalloc(), as this cache uses
1478 	 * SLAB_TYPESAFE_BY_RCU.
1479 	 */
1480 	ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1481 	if (ct == NULL)
1482 		goto out;
1483 
1484 	spin_lock_init(&ct->lock);
1485 	ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1486 	ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1487 	ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1488 	/* save hash for reusing when confirming */
1489 	*(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1490 	ct->status = 0;
1491 	WRITE_ONCE(ct->timeout, 0);
1492 	write_pnet(&ct->ct_net, net);
1493 	memset(&ct->__nfct_init_offset, 0,
1494 	       offsetof(struct nf_conn, proto) -
1495 	       offsetof(struct nf_conn, __nfct_init_offset));
1496 
1497 	nf_ct_zone_add(ct, zone);
1498 
1499 	/* Because we use RCU lookups, we set ct_general.use to zero before
1500 	 * this is inserted in any list.
1501 	 */
1502 	atomic_set(&ct->ct_general.use, 0);
1503 	return ct;
1504 out:
1505 	atomic_dec(&net->ct.count);
1506 	return ERR_PTR(-ENOMEM);
1507 }
1508 
nf_conntrack_alloc(struct net * net,const struct nf_conntrack_zone * zone,const struct nf_conntrack_tuple * orig,const struct nf_conntrack_tuple * repl,gfp_t gfp)1509 struct nf_conn *nf_conntrack_alloc(struct net *net,
1510 				   const struct nf_conntrack_zone *zone,
1511 				   const struct nf_conntrack_tuple *orig,
1512 				   const struct nf_conntrack_tuple *repl,
1513 				   gfp_t gfp)
1514 {
1515 	return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1516 }
1517 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1518 
nf_conntrack_free(struct nf_conn * ct)1519 void nf_conntrack_free(struct nf_conn *ct)
1520 {
1521 	struct net *net = nf_ct_net(ct);
1522 
1523 	/* A freed object has refcnt == 0, that's
1524 	 * the golden rule for SLAB_TYPESAFE_BY_RCU
1525 	 */
1526 	WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1527 
1528 	nf_ct_ext_destroy(ct);
1529 	kmem_cache_free(nf_conntrack_cachep, ct);
1530 	smp_mb__before_atomic();
1531 	atomic_dec(&net->ct.count);
1532 }
1533 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1534 
1535 
1536 /* Allocate a new conntrack: we return -ENOMEM if classification
1537    failed due to stress.  Otherwise it really is unclassifiable. */
1538 static noinline struct nf_conntrack_tuple_hash *
init_conntrack(struct net * net,struct nf_conn * tmpl,const struct nf_conntrack_tuple * tuple,struct sk_buff * skb,unsigned int dataoff,u32 hash)1539 init_conntrack(struct net *net, struct nf_conn *tmpl,
1540 	       const struct nf_conntrack_tuple *tuple,
1541 	       struct sk_buff *skb,
1542 	       unsigned int dataoff, u32 hash)
1543 {
1544 	struct nf_conn *ct;
1545 	struct nf_conn_help *help;
1546 	struct nf_conntrack_tuple repl_tuple;
1547 	struct nf_conntrack_ecache *ecache;
1548 	struct nf_conntrack_expect *exp = NULL;
1549 	const struct nf_conntrack_zone *zone;
1550 	struct nf_conn_timeout *timeout_ext;
1551 	struct nf_conntrack_zone tmp;
1552 
1553 	if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1554 		pr_debug("Can't invert tuple.\n");
1555 		return NULL;
1556 	}
1557 
1558 	zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1559 	ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1560 				  hash);
1561 	if (IS_ERR(ct))
1562 		return (struct nf_conntrack_tuple_hash *)ct;
1563 
1564 	if (!nf_ct_add_synproxy(ct, tmpl)) {
1565 		nf_conntrack_free(ct);
1566 		return ERR_PTR(-ENOMEM);
1567 	}
1568 
1569 	timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1570 
1571 	if (timeout_ext)
1572 		nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1573 				      GFP_ATOMIC);
1574 
1575 	nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1576 	nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1577 	nf_ct_labels_ext_add(ct);
1578 
1579 	ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1580 	nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1581 				 ecache ? ecache->expmask : 0,
1582 			     GFP_ATOMIC);
1583 
1584 	local_bh_disable();
1585 	if (net->ct.expect_count) {
1586 		spin_lock(&nf_conntrack_expect_lock);
1587 		exp = nf_ct_find_expectation(net, zone, tuple);
1588 		if (exp) {
1589 			pr_debug("expectation arrives ct=%p exp=%p\n",
1590 				 ct, exp);
1591 			/* Welcome, Mr. Bond.  We've been expecting you... */
1592 			__set_bit(IPS_EXPECTED_BIT, &ct->status);
1593 			/* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1594 			ct->master = exp->master;
1595 			if (exp->helper) {
1596 				help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1597 				if (help)
1598 					rcu_assign_pointer(help->helper, exp->helper);
1599 			}
1600 
1601 #ifdef CONFIG_NF_CONNTRACK_MARK
1602 			ct->mark = READ_ONCE(exp->master->mark);
1603 #endif
1604 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1605 			ct->secmark = exp->master->secmark;
1606 #endif
1607 			NF_CT_STAT_INC(net, expect_new);
1608 		}
1609 		spin_unlock(&nf_conntrack_expect_lock);
1610 	}
1611 	if (!exp)
1612 		__nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1613 
1614 	/* Now it is inserted into the unconfirmed list, bump refcount */
1615 	nf_conntrack_get(&ct->ct_general);
1616 	nf_ct_add_to_unconfirmed_list(ct);
1617 
1618 	local_bh_enable();
1619 
1620 	if (exp) {
1621 		if (exp->expectfn)
1622 			exp->expectfn(ct, exp);
1623 		nf_ct_expect_put(exp);
1624 	}
1625 
1626 	return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1627 }
1628 
1629 /* On success, returns 0, sets skb->_nfct | ctinfo */
1630 static int
resolve_normal_ct(struct nf_conn * tmpl,struct sk_buff * skb,unsigned int dataoff,u_int8_t protonum,const struct nf_hook_state * state)1631 resolve_normal_ct(struct nf_conn *tmpl,
1632 		  struct sk_buff *skb,
1633 		  unsigned int dataoff,
1634 		  u_int8_t protonum,
1635 		  const struct nf_hook_state *state)
1636 {
1637 	const struct nf_conntrack_zone *zone;
1638 	struct nf_conntrack_tuple tuple;
1639 	struct nf_conntrack_tuple_hash *h;
1640 	enum ip_conntrack_info ctinfo;
1641 	struct nf_conntrack_zone tmp;
1642 	struct nf_conn *ct;
1643 	u32 hash;
1644 
1645 	if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1646 			     dataoff, state->pf, protonum, state->net,
1647 			     &tuple)) {
1648 		pr_debug("Can't get tuple\n");
1649 		return 0;
1650 	}
1651 
1652 	/* look for tuple match */
1653 	zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1654 	hash = hash_conntrack_raw(&tuple, state->net);
1655 	h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1656 	if (!h) {
1657 		h = init_conntrack(state->net, tmpl, &tuple,
1658 				   skb, dataoff, hash);
1659 		if (!h)
1660 			return 0;
1661 		if (IS_ERR(h))
1662 			return PTR_ERR(h);
1663 	}
1664 	ct = nf_ct_tuplehash_to_ctrack(h);
1665 
1666 	/* It exists; we have (non-exclusive) reference. */
1667 	if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1668 		ctinfo = IP_CT_ESTABLISHED_REPLY;
1669 	} else {
1670 		/* Once we've had two way comms, always ESTABLISHED. */
1671 		if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1672 			pr_debug("normal packet for %p\n", ct);
1673 			ctinfo = IP_CT_ESTABLISHED;
1674 		} else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1675 			pr_debug("related packet for %p\n", ct);
1676 			ctinfo = IP_CT_RELATED;
1677 		} else {
1678 			pr_debug("new packet for %p\n", ct);
1679 			ctinfo = IP_CT_NEW;
1680 		}
1681 	}
1682 	nf_ct_set(skb, ct, ctinfo);
1683 	return 0;
1684 }
1685 
1686 /*
1687  * icmp packets need special treatment to handle error messages that are
1688  * related to a connection.
1689  *
1690  * Callers need to check if skb has a conntrack assigned when this
1691  * helper returns; in such case skb belongs to an already known connection.
1692  */
1693 static unsigned int __cold
nf_conntrack_handle_icmp(struct nf_conn * tmpl,struct sk_buff * skb,unsigned int dataoff,u8 protonum,const struct nf_hook_state * state)1694 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1695 			 struct sk_buff *skb,
1696 			 unsigned int dataoff,
1697 			 u8 protonum,
1698 			 const struct nf_hook_state *state)
1699 {
1700 	int ret;
1701 
1702 	if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1703 		ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1704 #if IS_ENABLED(CONFIG_IPV6)
1705 	else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1706 		ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1707 #endif
1708 	else
1709 		return NF_ACCEPT;
1710 
1711 	if (ret <= 0)
1712 		NF_CT_STAT_INC_ATOMIC(state->net, error);
1713 
1714 	return ret;
1715 }
1716 
generic_packet(struct nf_conn * ct,struct sk_buff * skb,enum ip_conntrack_info ctinfo)1717 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1718 			  enum ip_conntrack_info ctinfo)
1719 {
1720 	const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1721 
1722 	if (!timeout)
1723 		timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1724 
1725 	nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1726 	return NF_ACCEPT;
1727 }
1728 
1729 /* Returns verdict for packet, or -1 for invalid. */
nf_conntrack_handle_packet(struct nf_conn * ct,struct sk_buff * skb,unsigned int dataoff,enum ip_conntrack_info ctinfo,const struct nf_hook_state * state)1730 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1731 				      struct sk_buff *skb,
1732 				      unsigned int dataoff,
1733 				      enum ip_conntrack_info ctinfo,
1734 				      const struct nf_hook_state *state)
1735 {
1736 	switch (nf_ct_protonum(ct)) {
1737 	case IPPROTO_TCP:
1738 		return nf_conntrack_tcp_packet(ct, skb, dataoff,
1739 					       ctinfo, state);
1740 	case IPPROTO_UDP:
1741 		return nf_conntrack_udp_packet(ct, skb, dataoff,
1742 					       ctinfo, state);
1743 	case IPPROTO_ICMP:
1744 		return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1745 #if IS_ENABLED(CONFIG_IPV6)
1746 	case IPPROTO_ICMPV6:
1747 		return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1748 #endif
1749 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1750 	case IPPROTO_UDPLITE:
1751 		return nf_conntrack_udplite_packet(ct, skb, dataoff,
1752 						   ctinfo, state);
1753 #endif
1754 #ifdef CONFIG_NF_CT_PROTO_SCTP
1755 	case IPPROTO_SCTP:
1756 		return nf_conntrack_sctp_packet(ct, skb, dataoff,
1757 						ctinfo, state);
1758 #endif
1759 #ifdef CONFIG_NF_CT_PROTO_DCCP
1760 	case IPPROTO_DCCP:
1761 		return nf_conntrack_dccp_packet(ct, skb, dataoff,
1762 						ctinfo, state);
1763 #endif
1764 #ifdef CONFIG_NF_CT_PROTO_GRE
1765 	case IPPROTO_GRE:
1766 		return nf_conntrack_gre_packet(ct, skb, dataoff,
1767 					       ctinfo, state);
1768 #endif
1769 	}
1770 
1771 	return generic_packet(ct, skb, ctinfo);
1772 }
1773 
1774 unsigned int
nf_conntrack_in(struct sk_buff * skb,const struct nf_hook_state * state)1775 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1776 {
1777 	enum ip_conntrack_info ctinfo;
1778 	struct nf_conn *ct, *tmpl;
1779 	u_int8_t protonum;
1780 	int dataoff, ret;
1781 
1782 	tmpl = nf_ct_get(skb, &ctinfo);
1783 	if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1784 		/* Previously seen (loopback or untracked)?  Ignore. */
1785 		if ((tmpl && !nf_ct_is_template(tmpl)) ||
1786 		     ctinfo == IP_CT_UNTRACKED)
1787 			return NF_ACCEPT;
1788 		skb->_nfct = 0;
1789 	}
1790 
1791 	/* rcu_read_lock()ed by nf_hook_thresh */
1792 	dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1793 	if (dataoff <= 0) {
1794 		pr_debug("not prepared to track yet or error occurred\n");
1795 		NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1796 		ret = NF_ACCEPT;
1797 		goto out;
1798 	}
1799 
1800 	if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1801 		ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1802 					       protonum, state);
1803 		if (ret <= 0) {
1804 			ret = -ret;
1805 			goto out;
1806 		}
1807 		/* ICMP[v6] protocol trackers may assign one conntrack. */
1808 		if (skb->_nfct)
1809 			goto out;
1810 	}
1811 repeat:
1812 	ret = resolve_normal_ct(tmpl, skb, dataoff,
1813 				protonum, state);
1814 	if (ret < 0) {
1815 		/* Too stressed to deal. */
1816 		NF_CT_STAT_INC_ATOMIC(state->net, drop);
1817 		ret = NF_DROP;
1818 		goto out;
1819 	}
1820 
1821 	ct = nf_ct_get(skb, &ctinfo);
1822 	if (!ct) {
1823 		/* Not valid part of a connection */
1824 		NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1825 		ret = NF_ACCEPT;
1826 		goto out;
1827 	}
1828 
1829 	ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1830 	if (ret <= 0) {
1831 		/* Invalid: inverse of the return code tells
1832 		 * the netfilter core what to do */
1833 		pr_debug("nf_conntrack_in: Can't track with proto module\n");
1834 		nf_conntrack_put(&ct->ct_general);
1835 		skb->_nfct = 0;
1836 		/* Special case: TCP tracker reports an attempt to reopen a
1837 		 * closed/aborted connection. We have to go back and create a
1838 		 * fresh conntrack.
1839 		 */
1840 		if (ret == -NF_REPEAT)
1841 			goto repeat;
1842 
1843 		NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1844 		if (ret == -NF_DROP)
1845 			NF_CT_STAT_INC_ATOMIC(state->net, drop);
1846 
1847 		ret = -ret;
1848 		goto out;
1849 	}
1850 
1851 	if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1852 	    !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1853 		nf_conntrack_event_cache(IPCT_REPLY, ct);
1854 out:
1855 	if (tmpl)
1856 		nf_ct_put(tmpl);
1857 
1858 	return ret;
1859 }
1860 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1861 
1862 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1863    implicitly racy: see __nf_conntrack_confirm */
nf_conntrack_alter_reply(struct nf_conn * ct,const struct nf_conntrack_tuple * newreply)1864 void nf_conntrack_alter_reply(struct nf_conn *ct,
1865 			      const struct nf_conntrack_tuple *newreply)
1866 {
1867 	struct nf_conn_help *help = nfct_help(ct);
1868 
1869 	/* Should be unconfirmed, so not in hash table yet */
1870 	WARN_ON(nf_ct_is_confirmed(ct));
1871 
1872 	pr_debug("Altering reply tuple of %p to ", ct);
1873 	nf_ct_dump_tuple(newreply);
1874 
1875 	ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1876 	if (ct->master || (help && !hlist_empty(&help->expectations)))
1877 		return;
1878 
1879 	rcu_read_lock();
1880 	__nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1881 	rcu_read_unlock();
1882 }
1883 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1884 
1885 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
__nf_ct_refresh_acct(struct nf_conn * ct,enum ip_conntrack_info ctinfo,const struct sk_buff * skb,u32 extra_jiffies,bool do_acct)1886 void __nf_ct_refresh_acct(struct nf_conn *ct,
1887 			  enum ip_conntrack_info ctinfo,
1888 			  const struct sk_buff *skb,
1889 			  u32 extra_jiffies,
1890 			  bool do_acct)
1891 {
1892 	/* Only update if this is not a fixed timeout */
1893 	if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1894 		goto acct;
1895 
1896 	/* If not in hash table, timer will not be active yet */
1897 	if (nf_ct_is_confirmed(ct))
1898 		extra_jiffies += nfct_time_stamp;
1899 
1900 	if (READ_ONCE(ct->timeout) != extra_jiffies)
1901 		WRITE_ONCE(ct->timeout, extra_jiffies);
1902 acct:
1903 	if (do_acct)
1904 		nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1905 }
1906 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1907 
nf_ct_kill_acct(struct nf_conn * ct,enum ip_conntrack_info ctinfo,const struct sk_buff * skb)1908 bool nf_ct_kill_acct(struct nf_conn *ct,
1909 		     enum ip_conntrack_info ctinfo,
1910 		     const struct sk_buff *skb)
1911 {
1912 	nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1913 
1914 	return nf_ct_delete(ct, 0, 0);
1915 }
1916 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1917 
1918 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1919 
1920 #include <linux/netfilter/nfnetlink.h>
1921 #include <linux/netfilter/nfnetlink_conntrack.h>
1922 #include <linux/mutex.h>
1923 
1924 /* Generic function for tcp/udp/sctp/dccp and alike. */
nf_ct_port_tuple_to_nlattr(struct sk_buff * skb,const struct nf_conntrack_tuple * tuple)1925 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1926 			       const struct nf_conntrack_tuple *tuple)
1927 {
1928 	if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1929 	    nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1930 		goto nla_put_failure;
1931 	return 0;
1932 
1933 nla_put_failure:
1934 	return -1;
1935 }
1936 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1937 
1938 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1939 	[CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
1940 	[CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
1941 };
1942 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1943 
nf_ct_port_nlattr_to_tuple(struct nlattr * tb[],struct nf_conntrack_tuple * t,u_int32_t flags)1944 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1945 			       struct nf_conntrack_tuple *t,
1946 			       u_int32_t flags)
1947 {
1948 	if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
1949 		if (!tb[CTA_PROTO_SRC_PORT])
1950 			return -EINVAL;
1951 
1952 		t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1953 	}
1954 
1955 	if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
1956 		if (!tb[CTA_PROTO_DST_PORT])
1957 			return -EINVAL;
1958 
1959 		t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1960 	}
1961 
1962 	return 0;
1963 }
1964 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1965 
nf_ct_port_nlattr_tuple_size(void)1966 unsigned int nf_ct_port_nlattr_tuple_size(void)
1967 {
1968 	static unsigned int size __read_mostly;
1969 
1970 	if (!size)
1971 		size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1972 
1973 	return size;
1974 }
1975 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1976 #endif
1977 
1978 /* Used by ipt_REJECT and ip6t_REJECT. */
nf_conntrack_attach(struct sk_buff * nskb,const struct sk_buff * skb)1979 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1980 {
1981 	struct nf_conn *ct;
1982 	enum ip_conntrack_info ctinfo;
1983 
1984 	/* This ICMP is in reverse direction to the packet which caused it */
1985 	ct = nf_ct_get(skb, &ctinfo);
1986 	if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1987 		ctinfo = IP_CT_RELATED_REPLY;
1988 	else
1989 		ctinfo = IP_CT_RELATED;
1990 
1991 	/* Attach to new skbuff, and increment count */
1992 	nf_ct_set(nskb, ct, ctinfo);
1993 	nf_conntrack_get(skb_nfct(nskb));
1994 }
1995 
__nf_conntrack_update(struct net * net,struct sk_buff * skb,struct nf_conn * ct,enum ip_conntrack_info ctinfo)1996 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
1997 				 struct nf_conn *ct,
1998 				 enum ip_conntrack_info ctinfo)
1999 {
2000 	struct nf_conntrack_tuple_hash *h;
2001 	struct nf_conntrack_tuple tuple;
2002 	struct nf_nat_hook *nat_hook;
2003 	unsigned int status;
2004 	int dataoff;
2005 	u16 l3num;
2006 	u8 l4num;
2007 
2008 	l3num = nf_ct_l3num(ct);
2009 
2010 	dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2011 	if (dataoff <= 0)
2012 		return -1;
2013 
2014 	if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2015 			     l4num, net, &tuple))
2016 		return -1;
2017 
2018 	if (ct->status & IPS_SRC_NAT) {
2019 		memcpy(tuple.src.u3.all,
2020 		       ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2021 		       sizeof(tuple.src.u3.all));
2022 		tuple.src.u.all =
2023 			ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2024 	}
2025 
2026 	if (ct->status & IPS_DST_NAT) {
2027 		memcpy(tuple.dst.u3.all,
2028 		       ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2029 		       sizeof(tuple.dst.u3.all));
2030 		tuple.dst.u.all =
2031 			ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2032 	}
2033 
2034 	h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2035 	if (!h)
2036 		return 0;
2037 
2038 	/* Store status bits of the conntrack that is clashing to re-do NAT
2039 	 * mangling according to what it has been done already to this packet.
2040 	 */
2041 	status = ct->status;
2042 
2043 	nf_ct_put(ct);
2044 	ct = nf_ct_tuplehash_to_ctrack(h);
2045 	nf_ct_set(skb, ct, ctinfo);
2046 
2047 	nat_hook = rcu_dereference(nf_nat_hook);
2048 	if (!nat_hook)
2049 		return 0;
2050 
2051 	if (status & IPS_SRC_NAT &&
2052 	    nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2053 				IP_CT_DIR_ORIGINAL) == NF_DROP)
2054 		return -1;
2055 
2056 	if (status & IPS_DST_NAT &&
2057 	    nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2058 				IP_CT_DIR_ORIGINAL) == NF_DROP)
2059 		return -1;
2060 
2061 	return 0;
2062 }
2063 
2064 /* This packet is coming from userspace via nf_queue, complete the packet
2065  * processing after the helper invocation in nf_confirm().
2066  */
nf_confirm_cthelper(struct sk_buff * skb,struct nf_conn * ct,enum ip_conntrack_info ctinfo)2067 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2068 			       enum ip_conntrack_info ctinfo)
2069 {
2070 	const struct nf_conntrack_helper *helper;
2071 	const struct nf_conn_help *help;
2072 	int protoff;
2073 
2074 	help = nfct_help(ct);
2075 	if (!help)
2076 		return 0;
2077 
2078 	helper = rcu_dereference(help->helper);
2079 	if (!helper)
2080 		return 0;
2081 
2082 	if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2083 		return 0;
2084 
2085 	switch (nf_ct_l3num(ct)) {
2086 	case NFPROTO_IPV4:
2087 		protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2088 		break;
2089 #if IS_ENABLED(CONFIG_IPV6)
2090 	case NFPROTO_IPV6: {
2091 		__be16 frag_off;
2092 		u8 pnum;
2093 
2094 		pnum = ipv6_hdr(skb)->nexthdr;
2095 		protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2096 					   &frag_off);
2097 		if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2098 			return 0;
2099 		break;
2100 	}
2101 #endif
2102 	default:
2103 		return 0;
2104 	}
2105 
2106 	if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2107 	    !nf_is_loopback_packet(skb)) {
2108 		if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2109 			NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2110 			return -1;
2111 		}
2112 	}
2113 
2114 	/* We've seen it coming out the other side: confirm it */
2115 	return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2116 }
2117 
nf_conntrack_update(struct net * net,struct sk_buff * skb)2118 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2119 {
2120 	enum ip_conntrack_info ctinfo;
2121 	struct nf_conn *ct;
2122 	int err;
2123 
2124 	ct = nf_ct_get(skb, &ctinfo);
2125 	if (!ct)
2126 		return 0;
2127 
2128 	if (!nf_ct_is_confirmed(ct)) {
2129 		err = __nf_conntrack_update(net, skb, ct, ctinfo);
2130 		if (err < 0)
2131 			return err;
2132 
2133 		ct = nf_ct_get(skb, &ctinfo);
2134 	}
2135 
2136 	return nf_confirm_cthelper(skb, ct, ctinfo);
2137 }
2138 
nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple * dst_tuple,const struct sk_buff * skb)2139 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2140 				       const struct sk_buff *skb)
2141 {
2142 	const struct nf_conntrack_tuple *src_tuple;
2143 	const struct nf_conntrack_tuple_hash *hash;
2144 	struct nf_conntrack_tuple srctuple;
2145 	enum ip_conntrack_info ctinfo;
2146 	struct nf_conn *ct;
2147 
2148 	ct = nf_ct_get(skb, &ctinfo);
2149 	if (ct) {
2150 		src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2151 		memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2152 		return true;
2153 	}
2154 
2155 	if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2156 			       NFPROTO_IPV4, dev_net(skb->dev),
2157 			       &srctuple))
2158 		return false;
2159 
2160 	hash = nf_conntrack_find_get(dev_net(skb->dev),
2161 				     &nf_ct_zone_dflt,
2162 				     &srctuple);
2163 	if (!hash)
2164 		return false;
2165 
2166 	ct = nf_ct_tuplehash_to_ctrack(hash);
2167 	src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2168 	memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2169 	nf_ct_put(ct);
2170 
2171 	return true;
2172 }
2173 
2174 /* Bring out ya dead! */
2175 static struct nf_conn *
get_next_corpse(int (* iter)(struct nf_conn * i,void * data),void * data,unsigned int * bucket)2176 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2177 		void *data, unsigned int *bucket)
2178 {
2179 	struct nf_conntrack_tuple_hash *h;
2180 	struct nf_conn *ct;
2181 	struct hlist_nulls_node *n;
2182 	spinlock_t *lockp;
2183 
2184 	for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2185 		struct hlist_nulls_head *hslot = &nf_conntrack_hash[*bucket];
2186 
2187 		if (hlist_nulls_empty(hslot))
2188 			continue;
2189 
2190 		lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2191 		local_bh_disable();
2192 		nf_conntrack_lock(lockp);
2193 		hlist_nulls_for_each_entry(h, n, hslot, hnnode) {
2194 			if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2195 				continue;
2196 			/* All nf_conn objects are added to hash table twice, one
2197 			 * for original direction tuple, once for the reply tuple.
2198 			 *
2199 			 * Exception: In the IPS_NAT_CLASH case, only the reply
2200 			 * tuple is added (the original tuple already existed for
2201 			 * a different object).
2202 			 *
2203 			 * We only need to call the iterator once for each
2204 			 * conntrack, so we just use the 'reply' direction
2205 			 * tuple while iterating.
2206 			 */
2207 			ct = nf_ct_tuplehash_to_ctrack(h);
2208 			if (iter(ct, data))
2209 				goto found;
2210 		}
2211 		spin_unlock(lockp);
2212 		local_bh_enable();
2213 		cond_resched();
2214 	}
2215 
2216 	return NULL;
2217 found:
2218 	atomic_inc(&ct->ct_general.use);
2219 	spin_unlock(lockp);
2220 	local_bh_enable();
2221 	return ct;
2222 }
2223 
nf_ct_iterate_cleanup(int (* iter)(struct nf_conn * i,void * data),void * data,u32 portid,int report)2224 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2225 				  void *data, u32 portid, int report)
2226 {
2227 	unsigned int bucket = 0;
2228 	struct nf_conn *ct;
2229 
2230 	might_sleep();
2231 
2232 	mutex_lock(&nf_conntrack_mutex);
2233 	while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2234 		/* Time to push up daises... */
2235 
2236 		nf_ct_delete(ct, portid, report);
2237 		nf_ct_put(ct);
2238 		cond_resched();
2239 	}
2240 	mutex_unlock(&nf_conntrack_mutex);
2241 }
2242 
2243 struct iter_data {
2244 	int (*iter)(struct nf_conn *i, void *data);
2245 	void *data;
2246 	struct net *net;
2247 };
2248 
iter_net_only(struct nf_conn * i,void * data)2249 static int iter_net_only(struct nf_conn *i, void *data)
2250 {
2251 	struct iter_data *d = data;
2252 
2253 	if (!net_eq(d->net, nf_ct_net(i)))
2254 		return 0;
2255 
2256 	return d->iter(i, d->data);
2257 }
2258 
2259 static void
__nf_ct_unconfirmed_destroy(struct net * net)2260 __nf_ct_unconfirmed_destroy(struct net *net)
2261 {
2262 	int cpu;
2263 
2264 	for_each_possible_cpu(cpu) {
2265 		struct nf_conntrack_tuple_hash *h;
2266 		struct hlist_nulls_node *n;
2267 		struct ct_pcpu *pcpu;
2268 
2269 		pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2270 
2271 		spin_lock_bh(&pcpu->lock);
2272 		hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2273 			struct nf_conn *ct;
2274 
2275 			ct = nf_ct_tuplehash_to_ctrack(h);
2276 
2277 			/* we cannot call iter() on unconfirmed list, the
2278 			 * owning cpu can reallocate ct->ext at any time.
2279 			 */
2280 			set_bit(IPS_DYING_BIT, &ct->status);
2281 		}
2282 		spin_unlock_bh(&pcpu->lock);
2283 		cond_resched();
2284 	}
2285 }
2286 
nf_ct_unconfirmed_destroy(struct net * net)2287 void nf_ct_unconfirmed_destroy(struct net *net)
2288 {
2289 	might_sleep();
2290 
2291 	if (atomic_read(&net->ct.count) > 0) {
2292 		__nf_ct_unconfirmed_destroy(net);
2293 		nf_queue_nf_hook_drop(net);
2294 		synchronize_net();
2295 	}
2296 }
2297 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2298 
nf_ct_iterate_cleanup_net(struct net * net,int (* iter)(struct nf_conn * i,void * data),void * data,u32 portid,int report)2299 void nf_ct_iterate_cleanup_net(struct net *net,
2300 			       int (*iter)(struct nf_conn *i, void *data),
2301 			       void *data, u32 portid, int report)
2302 {
2303 	struct iter_data d;
2304 
2305 	might_sleep();
2306 
2307 	if (atomic_read(&net->ct.count) == 0)
2308 		return;
2309 
2310 	d.iter = iter;
2311 	d.data = data;
2312 	d.net = net;
2313 
2314 	nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2315 }
2316 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2317 
2318 /**
2319  * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2320  * @iter: callback to invoke for each conntrack
2321  * @data: data to pass to @iter
2322  *
2323  * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2324  * unconfirmed list as dying (so they will not be inserted into
2325  * main table).
2326  *
2327  * Can only be called in module exit path.
2328  */
2329 void
nf_ct_iterate_destroy(int (* iter)(struct nf_conn * i,void * data),void * data)2330 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2331 {
2332 	struct net *net;
2333 
2334 	down_read(&net_rwsem);
2335 	for_each_net(net) {
2336 		if (atomic_read(&net->ct.count) == 0)
2337 			continue;
2338 		__nf_ct_unconfirmed_destroy(net);
2339 		nf_queue_nf_hook_drop(net);
2340 	}
2341 	up_read(&net_rwsem);
2342 
2343 	/* Need to wait for netns cleanup worker to finish, if its
2344 	 * running -- it might have deleted a net namespace from
2345 	 * the global list, so our __nf_ct_unconfirmed_destroy() might
2346 	 * not have affected all namespaces.
2347 	 */
2348 	net_ns_barrier();
2349 
2350 	/* a conntrack could have been unlinked from unconfirmed list
2351 	 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2352 	 * This makes sure its inserted into conntrack table.
2353 	 */
2354 	synchronize_net();
2355 
2356 	nf_ct_iterate_cleanup(iter, data, 0, 0);
2357 }
2358 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2359 
kill_all(struct nf_conn * i,void * data)2360 static int kill_all(struct nf_conn *i, void *data)
2361 {
2362 	return net_eq(nf_ct_net(i), data);
2363 }
2364 
nf_conntrack_cleanup_start(void)2365 void nf_conntrack_cleanup_start(void)
2366 {
2367 	conntrack_gc_work.exiting = true;
2368 	RCU_INIT_POINTER(ip_ct_attach, NULL);
2369 }
2370 
nf_conntrack_cleanup_end(void)2371 void nf_conntrack_cleanup_end(void)
2372 {
2373 	RCU_INIT_POINTER(nf_ct_hook, NULL);
2374 	cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2375 	kvfree(nf_conntrack_hash);
2376 
2377 	nf_conntrack_proto_fini();
2378 	nf_conntrack_seqadj_fini();
2379 	nf_conntrack_labels_fini();
2380 	nf_conntrack_helper_fini();
2381 	nf_conntrack_timeout_fini();
2382 	nf_conntrack_ecache_fini();
2383 	nf_conntrack_tstamp_fini();
2384 	nf_conntrack_acct_fini();
2385 	nf_conntrack_expect_fini();
2386 
2387 	kmem_cache_destroy(nf_conntrack_cachep);
2388 }
2389 
2390 /*
2391  * Mishearing the voices in his head, our hero wonders how he's
2392  * supposed to kill the mall.
2393  */
nf_conntrack_cleanup_net(struct net * net)2394 void nf_conntrack_cleanup_net(struct net *net)
2395 {
2396 	LIST_HEAD(single);
2397 
2398 	list_add(&net->exit_list, &single);
2399 	nf_conntrack_cleanup_net_list(&single);
2400 }
2401 
nf_conntrack_cleanup_net_list(struct list_head * net_exit_list)2402 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2403 {
2404 	int busy;
2405 	struct net *net;
2406 
2407 	/*
2408 	 * This makes sure all current packets have passed through
2409 	 *  netfilter framework.  Roll on, two-stage module
2410 	 *  delete...
2411 	 */
2412 	synchronize_net();
2413 i_see_dead_people:
2414 	busy = 0;
2415 	list_for_each_entry(net, net_exit_list, exit_list) {
2416 		nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2417 		if (atomic_read(&net->ct.count) != 0)
2418 			busy = 1;
2419 	}
2420 	if (busy) {
2421 		schedule();
2422 		goto i_see_dead_people;
2423 	}
2424 
2425 	list_for_each_entry(net, net_exit_list, exit_list) {
2426 		nf_conntrack_proto_pernet_fini(net);
2427 		nf_conntrack_ecache_pernet_fini(net);
2428 		nf_conntrack_expect_pernet_fini(net);
2429 		free_percpu(net->ct.stat);
2430 		free_percpu(net->ct.pcpu_lists);
2431 	}
2432 }
2433 
nf_ct_alloc_hashtable(unsigned int * sizep,int nulls)2434 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2435 {
2436 	struct hlist_nulls_head *hash;
2437 	unsigned int nr_slots, i;
2438 
2439 	if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2440 		return NULL;
2441 
2442 	BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2443 	nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2444 
2445 	hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2446 
2447 	if (hash && nulls)
2448 		for (i = 0; i < nr_slots; i++)
2449 			INIT_HLIST_NULLS_HEAD(&hash[i], i);
2450 
2451 	return hash;
2452 }
2453 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2454 
nf_conntrack_hash_resize(unsigned int hashsize)2455 int nf_conntrack_hash_resize(unsigned int hashsize)
2456 {
2457 	int i, bucket;
2458 	unsigned int old_size;
2459 	struct hlist_nulls_head *hash, *old_hash;
2460 	struct nf_conntrack_tuple_hash *h;
2461 	struct nf_conn *ct;
2462 
2463 	if (!hashsize)
2464 		return -EINVAL;
2465 
2466 	hash = nf_ct_alloc_hashtable(&hashsize, 1);
2467 	if (!hash)
2468 		return -ENOMEM;
2469 
2470 	mutex_lock(&nf_conntrack_mutex);
2471 	old_size = nf_conntrack_htable_size;
2472 	if (old_size == hashsize) {
2473 		mutex_unlock(&nf_conntrack_mutex);
2474 		kvfree(hash);
2475 		return 0;
2476 	}
2477 
2478 	local_bh_disable();
2479 	nf_conntrack_all_lock();
2480 	write_seqcount_begin(&nf_conntrack_generation);
2481 
2482 	/* Lookups in the old hash might happen in parallel, which means we
2483 	 * might get false negatives during connection lookup. New connections
2484 	 * created because of a false negative won't make it into the hash
2485 	 * though since that required taking the locks.
2486 	 */
2487 
2488 	for (i = 0; i < nf_conntrack_htable_size; i++) {
2489 		while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2490 			h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2491 					      struct nf_conntrack_tuple_hash, hnnode);
2492 			ct = nf_ct_tuplehash_to_ctrack(h);
2493 			hlist_nulls_del_rcu(&h->hnnode);
2494 			bucket = __hash_conntrack(nf_ct_net(ct),
2495 						  &h->tuple, hashsize);
2496 			hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2497 		}
2498 	}
2499 	old_size = nf_conntrack_htable_size;
2500 	old_hash = nf_conntrack_hash;
2501 
2502 	nf_conntrack_hash = hash;
2503 	nf_conntrack_htable_size = hashsize;
2504 
2505 	write_seqcount_end(&nf_conntrack_generation);
2506 	nf_conntrack_all_unlock();
2507 	local_bh_enable();
2508 
2509 	mutex_unlock(&nf_conntrack_mutex);
2510 
2511 	synchronize_net();
2512 	kvfree(old_hash);
2513 	return 0;
2514 }
2515 
nf_conntrack_set_hashsize(const char * val,const struct kernel_param * kp)2516 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2517 {
2518 	unsigned int hashsize;
2519 	int rc;
2520 
2521 	if (current->nsproxy->net_ns != &init_net)
2522 		return -EOPNOTSUPP;
2523 
2524 	/* On boot, we can set this without any fancy locking. */
2525 	if (!nf_conntrack_hash)
2526 		return param_set_uint(val, kp);
2527 
2528 	rc = kstrtouint(val, 0, &hashsize);
2529 	if (rc)
2530 		return rc;
2531 
2532 	return nf_conntrack_hash_resize(hashsize);
2533 }
2534 
total_extension_size(void)2535 static __always_inline unsigned int total_extension_size(void)
2536 {
2537 	/* remember to add new extensions below */
2538 	BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2539 
2540 	return sizeof(struct nf_ct_ext) +
2541 	       sizeof(struct nf_conn_help)
2542 #if IS_ENABLED(CONFIG_NF_NAT)
2543 		+ sizeof(struct nf_conn_nat)
2544 #endif
2545 		+ sizeof(struct nf_conn_seqadj)
2546 		+ sizeof(struct nf_conn_acct)
2547 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2548 		+ sizeof(struct nf_conntrack_ecache)
2549 #endif
2550 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2551 		+ sizeof(struct nf_conn_tstamp)
2552 #endif
2553 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2554 		+ sizeof(struct nf_conn_timeout)
2555 #endif
2556 #ifdef CONFIG_NF_CONNTRACK_LABELS
2557 		+ sizeof(struct nf_conn_labels)
2558 #endif
2559 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2560 		+ sizeof(struct nf_conn_synproxy)
2561 #endif
2562 	;
2563 };
2564 
nf_conntrack_init_start(void)2565 int nf_conntrack_init_start(void)
2566 {
2567 	unsigned long nr_pages = totalram_pages();
2568 	int max_factor = 8;
2569 	int ret = -ENOMEM;
2570 	int i;
2571 
2572 	/* struct nf_ct_ext uses u8 to store offsets/size */
2573 	BUILD_BUG_ON(total_extension_size() > 255u);
2574 
2575 	seqcount_spinlock_init(&nf_conntrack_generation,
2576 			       &nf_conntrack_locks_all_lock);
2577 
2578 	for (i = 0; i < CONNTRACK_LOCKS; i++)
2579 		spin_lock_init(&nf_conntrack_locks[i]);
2580 
2581 	if (!nf_conntrack_htable_size) {
2582 		/* Idea from tcp.c: use 1/16384 of memory.
2583 		 * On i386: 32MB machine has 512 buckets.
2584 		 * >= 1GB machines have 16384 buckets.
2585 		 * >= 4GB machines have 65536 buckets.
2586 		 */
2587 		nf_conntrack_htable_size
2588 			= (((nr_pages << PAGE_SHIFT) / 16384)
2589 			   / sizeof(struct hlist_head));
2590 		if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2591 			nf_conntrack_htable_size = 65536;
2592 		else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2593 			nf_conntrack_htable_size = 16384;
2594 		if (nf_conntrack_htable_size < 32)
2595 			nf_conntrack_htable_size = 32;
2596 
2597 		/* Use a max. factor of four by default to get the same max as
2598 		 * with the old struct list_heads. When a table size is given
2599 		 * we use the old value of 8 to avoid reducing the max.
2600 		 * entries. */
2601 		max_factor = 4;
2602 	}
2603 
2604 	nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2605 	if (!nf_conntrack_hash)
2606 		return -ENOMEM;
2607 
2608 	nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2609 
2610 	nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2611 						sizeof(struct nf_conn),
2612 						NFCT_INFOMASK + 1,
2613 						SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2614 	if (!nf_conntrack_cachep)
2615 		goto err_cachep;
2616 
2617 	ret = nf_conntrack_expect_init();
2618 	if (ret < 0)
2619 		goto err_expect;
2620 
2621 	ret = nf_conntrack_acct_init();
2622 	if (ret < 0)
2623 		goto err_acct;
2624 
2625 	ret = nf_conntrack_tstamp_init();
2626 	if (ret < 0)
2627 		goto err_tstamp;
2628 
2629 	ret = nf_conntrack_ecache_init();
2630 	if (ret < 0)
2631 		goto err_ecache;
2632 
2633 	ret = nf_conntrack_timeout_init();
2634 	if (ret < 0)
2635 		goto err_timeout;
2636 
2637 	ret = nf_conntrack_helper_init();
2638 	if (ret < 0)
2639 		goto err_helper;
2640 
2641 	ret = nf_conntrack_labels_init();
2642 	if (ret < 0)
2643 		goto err_labels;
2644 
2645 	ret = nf_conntrack_seqadj_init();
2646 	if (ret < 0)
2647 		goto err_seqadj;
2648 
2649 	ret = nf_conntrack_proto_init();
2650 	if (ret < 0)
2651 		goto err_proto;
2652 
2653 	conntrack_gc_work_init(&conntrack_gc_work);
2654 	queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2655 
2656 	return 0;
2657 
2658 err_proto:
2659 	nf_conntrack_seqadj_fini();
2660 err_seqadj:
2661 	nf_conntrack_labels_fini();
2662 err_labels:
2663 	nf_conntrack_helper_fini();
2664 err_helper:
2665 	nf_conntrack_timeout_fini();
2666 err_timeout:
2667 	nf_conntrack_ecache_fini();
2668 err_ecache:
2669 	nf_conntrack_tstamp_fini();
2670 err_tstamp:
2671 	nf_conntrack_acct_fini();
2672 err_acct:
2673 	nf_conntrack_expect_fini();
2674 err_expect:
2675 	kmem_cache_destroy(nf_conntrack_cachep);
2676 err_cachep:
2677 	kvfree(nf_conntrack_hash);
2678 	return ret;
2679 }
2680 
2681 static struct nf_ct_hook nf_conntrack_hook = {
2682 	.update		= nf_conntrack_update,
2683 	.destroy	= destroy_conntrack,
2684 	.get_tuple_skb  = nf_conntrack_get_tuple_skb,
2685 };
2686 
nf_conntrack_init_end(void)2687 void nf_conntrack_init_end(void)
2688 {
2689 	/* For use by REJECT target */
2690 	RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2691 	RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2692 }
2693 
2694 /*
2695  * We need to use special "null" values, not used in hash table
2696  */
2697 #define UNCONFIRMED_NULLS_VAL	((1<<30)+0)
2698 #define DYING_NULLS_VAL		((1<<30)+1)
2699 
nf_conntrack_init_net(struct net * net)2700 int nf_conntrack_init_net(struct net *net)
2701 {
2702 	int ret = -ENOMEM;
2703 	int cpu;
2704 
2705 	BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2706 	BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2707 	atomic_set(&net->ct.count, 0);
2708 
2709 	net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2710 	if (!net->ct.pcpu_lists)
2711 		goto err_stat;
2712 
2713 	for_each_possible_cpu(cpu) {
2714 		struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2715 
2716 		spin_lock_init(&pcpu->lock);
2717 		INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2718 		INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2719 	}
2720 
2721 	net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2722 	if (!net->ct.stat)
2723 		goto err_pcpu_lists;
2724 
2725 	ret = nf_conntrack_expect_pernet_init(net);
2726 	if (ret < 0)
2727 		goto err_expect;
2728 
2729 	nf_conntrack_acct_pernet_init(net);
2730 	nf_conntrack_tstamp_pernet_init(net);
2731 	nf_conntrack_ecache_pernet_init(net);
2732 	nf_conntrack_helper_pernet_init(net);
2733 	nf_conntrack_proto_pernet_init(net);
2734 
2735 	return 0;
2736 
2737 err_expect:
2738 	free_percpu(net->ct.stat);
2739 err_pcpu_lists:
2740 	free_percpu(net->ct.pcpu_lists);
2741 err_stat:
2742 	return ret;
2743 }
2744