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