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
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>
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
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>
33 #include <linux/nsproxy.h>
34 #include <linux/rculist_nulls.h>
36 #include <net/netfilter/nf_conntrack.h>
37 #include <net/netfilter/nf_conntrack_l4proto.h>
38 #include <net/netfilter/nf_conntrack_expect.h>
39 #include <net/netfilter/nf_conntrack_helper.h>
40 #include <net/netfilter/nf_conntrack_seqadj.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>
55 #include "nf_internals.h"
57 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks
[CONNTRACK_LOCKS
];
58 EXPORT_SYMBOL_GPL(nf_conntrack_locks
);
60 __cacheline_aligned_in_smp
DEFINE_SPINLOCK(nf_conntrack_expect_lock
);
61 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock
);
63 struct hlist_nulls_head
*nf_conntrack_hash __read_mostly
;
64 EXPORT_SYMBOL_GPL(nf_conntrack_hash
);
66 struct conntrack_gc_work
{
67 struct delayed_work dwork
;
73 static __read_mostly
struct kmem_cache
*nf_conntrack_cachep
;
74 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock
);
75 static __read_mostly
bool nf_conntrack_locks_all
;
77 /* serialize hash resizes and nf_ct_iterate_cleanup */
78 static DEFINE_MUTEX(nf_conntrack_mutex
);
80 #define GC_SCAN_INTERVAL (120u * HZ)
81 #define GC_SCAN_MAX_DURATION msecs_to_jiffies(10)
83 #define MIN_CHAINLEN 8u
84 #define MAX_CHAINLEN (32u - MIN_CHAINLEN)
86 static struct conntrack_gc_work conntrack_gc_work
;
88 void nf_conntrack_lock(spinlock_t
*lock
) __acquires(lock
)
90 /* 1) Acquire the lock */
93 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
94 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
96 if (likely(smp_load_acquire(&nf_conntrack_locks_all
) == false))
99 /* fast path failed, unlock */
102 /* Slow path 1) get global lock */
103 spin_lock(&nf_conntrack_locks_all_lock
);
105 /* Slow path 2) get the lock we want */
108 /* Slow path 3) release the global lock */
109 spin_unlock(&nf_conntrack_locks_all_lock
);
111 EXPORT_SYMBOL_GPL(nf_conntrack_lock
);
113 static void nf_conntrack_double_unlock(unsigned int h1
, unsigned int h2
)
115 h1
%= CONNTRACK_LOCKS
;
116 h2
%= CONNTRACK_LOCKS
;
117 spin_unlock(&nf_conntrack_locks
[h1
]);
119 spin_unlock(&nf_conntrack_locks
[h2
]);
122 /* return true if we need to recompute hashes (in case hash table was resized) */
123 static bool nf_conntrack_double_lock(struct net
*net
, unsigned int h1
,
124 unsigned int h2
, unsigned int sequence
)
126 h1
%= CONNTRACK_LOCKS
;
127 h2
%= CONNTRACK_LOCKS
;
129 nf_conntrack_lock(&nf_conntrack_locks
[h1
]);
131 spin_lock_nested(&nf_conntrack_locks
[h2
],
132 SINGLE_DEPTH_NESTING
);
134 nf_conntrack_lock(&nf_conntrack_locks
[h2
]);
135 spin_lock_nested(&nf_conntrack_locks
[h1
],
136 SINGLE_DEPTH_NESTING
);
138 if (read_seqcount_retry(&nf_conntrack_generation
, sequence
)) {
139 nf_conntrack_double_unlock(h1
, h2
);
145 static void nf_conntrack_all_lock(void)
146 __acquires(&nf_conntrack_locks_all_lock
)
150 spin_lock(&nf_conntrack_locks_all_lock
);
152 /* For nf_contrack_locks_all, only the latest time when another
153 * CPU will see an update is controlled, by the "release" of the
155 * The earliest time is not controlled, an thus KCSAN could detect
156 * a race when nf_conntract_lock() reads the variable.
157 * WRITE_ONCE() is used to ensure the compiler will not
158 * optimize the write.
160 WRITE_ONCE(nf_conntrack_locks_all
, true);
162 for (i
= 0; i
< CONNTRACK_LOCKS
; i
++) {
163 spin_lock(&nf_conntrack_locks
[i
]);
165 /* This spin_unlock provides the "release" to ensure that
166 * nf_conntrack_locks_all==true is visible to everyone that
167 * acquired spin_lock(&nf_conntrack_locks[]).
169 spin_unlock(&nf_conntrack_locks
[i
]);
173 static void nf_conntrack_all_unlock(void)
174 __releases(&nf_conntrack_locks_all_lock
)
176 /* All prior stores must be complete before we clear
177 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
178 * might observe the false value but not the entire
180 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
182 smp_store_release(&nf_conntrack_locks_all
, false);
183 spin_unlock(&nf_conntrack_locks_all_lock
);
186 unsigned int nf_conntrack_htable_size __read_mostly
;
187 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size
);
189 unsigned int nf_conntrack_max __read_mostly
;
190 EXPORT_SYMBOL_GPL(nf_conntrack_max
);
191 seqcount_spinlock_t nf_conntrack_generation __read_mostly
;
192 static siphash_key_t nf_conntrack_hash_rnd __read_mostly
;
194 static u32
hash_conntrack_raw(const struct nf_conntrack_tuple
*tuple
,
196 const struct net
*net
)
199 struct nf_conntrack_man src
;
200 union nf_inet_addr dst_addr
;
205 } __aligned(SIPHASH_ALIGNMENT
) combined
;
207 get_random_once(&nf_conntrack_hash_rnd
, sizeof(nf_conntrack_hash_rnd
));
209 memset(&combined
, 0, sizeof(combined
));
211 /* The direction must be ignored, so handle usable members manually. */
212 combined
.src
= tuple
->src
;
213 combined
.dst_addr
= tuple
->dst
.u3
;
214 combined
.zone
= zoneid
;
215 combined
.net_mix
= net_hash_mix(net
);
216 combined
.dport
= (__force __u16
)tuple
->dst
.u
.all
;
217 combined
.proto
= tuple
->dst
.protonum
;
219 return (u32
)siphash(&combined
, sizeof(combined
), &nf_conntrack_hash_rnd
);
222 static u32
scale_hash(u32 hash
)
224 return reciprocal_scale(hash
, nf_conntrack_htable_size
);
227 static u32
__hash_conntrack(const struct net
*net
,
228 const struct nf_conntrack_tuple
*tuple
,
232 return reciprocal_scale(hash_conntrack_raw(tuple
, zoneid
, net
), size
);
235 static u32
hash_conntrack(const struct net
*net
,
236 const struct nf_conntrack_tuple
*tuple
,
239 return scale_hash(hash_conntrack_raw(tuple
, zoneid
, net
));
242 static bool nf_ct_get_tuple_ports(const struct sk_buff
*skb
,
243 unsigned int dataoff
,
244 struct nf_conntrack_tuple
*tuple
)
248 } _inet_hdr
, *inet_hdr
;
250 /* Actually only need first 4 bytes to get ports. */
251 inet_hdr
= skb_header_pointer(skb
, dataoff
, sizeof(_inet_hdr
), &_inet_hdr
);
255 tuple
->src
.u
.udp
.port
= inet_hdr
->sport
;
256 tuple
->dst
.u
.udp
.port
= inet_hdr
->dport
;
261 nf_ct_get_tuple(const struct sk_buff
*skb
,
263 unsigned int dataoff
,
267 struct nf_conntrack_tuple
*tuple
)
273 memset(tuple
, 0, sizeof(*tuple
));
275 tuple
->src
.l3num
= l3num
;
278 nhoff
+= offsetof(struct iphdr
, saddr
);
279 size
= 2 * sizeof(__be32
);
282 nhoff
+= offsetof(struct ipv6hdr
, saddr
);
283 size
= sizeof(_addrs
);
289 ap
= skb_header_pointer(skb
, nhoff
, size
, _addrs
);
295 tuple
->src
.u3
.ip
= ap
[0];
296 tuple
->dst
.u3
.ip
= ap
[1];
299 memcpy(tuple
->src
.u3
.ip6
, ap
, sizeof(tuple
->src
.u3
.ip6
));
300 memcpy(tuple
->dst
.u3
.ip6
, ap
+ 4, sizeof(tuple
->dst
.u3
.ip6
));
304 tuple
->dst
.protonum
= protonum
;
305 tuple
->dst
.dir
= IP_CT_DIR_ORIGINAL
;
308 #if IS_ENABLED(CONFIG_IPV6)
310 return icmpv6_pkt_to_tuple(skb
, dataoff
, net
, tuple
);
313 return icmp_pkt_to_tuple(skb
, dataoff
, net
, tuple
);
314 #ifdef CONFIG_NF_CT_PROTO_GRE
316 return gre_pkt_to_tuple(skb
, dataoff
, net
, tuple
);
319 case IPPROTO_UDP
: /* fallthrough */
320 return nf_ct_get_tuple_ports(skb
, dataoff
, tuple
);
321 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
322 case IPPROTO_UDPLITE
:
323 return nf_ct_get_tuple_ports(skb
, dataoff
, tuple
);
325 #ifdef CONFIG_NF_CT_PROTO_SCTP
327 return nf_ct_get_tuple_ports(skb
, dataoff
, tuple
);
329 #ifdef CONFIG_NF_CT_PROTO_DCCP
331 return nf_ct_get_tuple_ports(skb
, dataoff
, tuple
);
340 static int ipv4_get_l4proto(const struct sk_buff
*skb
, unsigned int nhoff
,
344 const struct iphdr
*iph
;
347 iph
= skb_header_pointer(skb
, nhoff
, sizeof(_iph
), &_iph
);
351 /* Conntrack defragments packets, we might still see fragments
352 * inside ICMP packets though.
354 if (iph
->frag_off
& htons(IP_OFFSET
))
357 dataoff
= nhoff
+ (iph
->ihl
<< 2);
358 *protonum
= iph
->protocol
;
360 /* Check bogus IP headers */
361 if (dataoff
> skb
->len
) {
362 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
363 nhoff
, iph
->ihl
<< 2, skb
->len
);
369 #if IS_ENABLED(CONFIG_IPV6)
370 static int ipv6_get_l4proto(const struct sk_buff
*skb
, unsigned int nhoff
,
374 unsigned int extoff
= nhoff
+ sizeof(struct ipv6hdr
);
378 if (skb_copy_bits(skb
, nhoff
+ offsetof(struct ipv6hdr
, nexthdr
),
379 &nexthdr
, sizeof(nexthdr
)) != 0) {
380 pr_debug("can't get nexthdr\n");
383 protoff
= ipv6_skip_exthdr(skb
, extoff
, &nexthdr
, &frag_off
);
385 * (protoff == skb->len) means the packet has not data, just
386 * IPv6 and possibly extensions headers, but it is tracked anyway
388 if (protoff
< 0 || (frag_off
& htons(~0x7)) != 0) {
389 pr_debug("can't find proto in pkt\n");
398 static int get_l4proto(const struct sk_buff
*skb
,
399 unsigned int nhoff
, u8 pf
, u8
*l4num
)
403 return ipv4_get_l4proto(skb
, nhoff
, l4num
);
404 #if IS_ENABLED(CONFIG_IPV6)
406 return ipv6_get_l4proto(skb
, nhoff
, l4num
);
415 bool nf_ct_get_tuplepr(const struct sk_buff
*skb
, unsigned int nhoff
,
417 struct net
*net
, struct nf_conntrack_tuple
*tuple
)
422 protoff
= get_l4proto(skb
, nhoff
, l3num
, &protonum
);
426 return nf_ct_get_tuple(skb
, nhoff
, protoff
, l3num
, protonum
, net
, tuple
);
428 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr
);
431 nf_ct_invert_tuple(struct nf_conntrack_tuple
*inverse
,
432 const struct nf_conntrack_tuple
*orig
)
434 memset(inverse
, 0, sizeof(*inverse
));
436 inverse
->src
.l3num
= orig
->src
.l3num
;
438 switch (orig
->src
.l3num
) {
440 inverse
->src
.u3
.ip
= orig
->dst
.u3
.ip
;
441 inverse
->dst
.u3
.ip
= orig
->src
.u3
.ip
;
444 inverse
->src
.u3
.in6
= orig
->dst
.u3
.in6
;
445 inverse
->dst
.u3
.in6
= orig
->src
.u3
.in6
;
451 inverse
->dst
.dir
= !orig
->dst
.dir
;
453 inverse
->dst
.protonum
= orig
->dst
.protonum
;
455 switch (orig
->dst
.protonum
) {
457 return nf_conntrack_invert_icmp_tuple(inverse
, orig
);
458 #if IS_ENABLED(CONFIG_IPV6)
460 return nf_conntrack_invert_icmpv6_tuple(inverse
, orig
);
464 inverse
->src
.u
.all
= orig
->dst
.u
.all
;
465 inverse
->dst
.u
.all
= orig
->src
.u
.all
;
468 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple
);
470 /* Generate a almost-unique pseudo-id for a given conntrack.
472 * intentionally doesn't re-use any of the seeds used for hash
473 * table location, we assume id gets exposed to userspace.
475 * Following nf_conn items do not change throughout lifetime
479 * 2. nf_conn->master address (normally NULL)
480 * 3. the associated net namespace
481 * 4. the original direction tuple
483 u32
nf_ct_get_id(const struct nf_conn
*ct
)
485 static __read_mostly siphash_key_t ct_id_seed
;
486 unsigned long a
, b
, c
, d
;
488 net_get_random_once(&ct_id_seed
, sizeof(ct_id_seed
));
490 a
= (unsigned long)ct
;
491 b
= (unsigned long)ct
->master
;
492 c
= (unsigned long)nf_ct_net(ct
);
493 d
= (unsigned long)siphash(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
494 sizeof(ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
),
497 return siphash_4u64((u64
)a
, (u64
)b
, (u64
)c
, (u64
)d
, &ct_id_seed
);
499 return siphash_4u32((u32
)a
, (u32
)b
, (u32
)c
, (u32
)d
, &ct_id_seed
);
502 EXPORT_SYMBOL_GPL(nf_ct_get_id
);
505 clean_from_lists(struct nf_conn
*ct
)
507 pr_debug("clean_from_lists(%p)\n", ct
);
508 hlist_nulls_del_rcu(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
);
509 hlist_nulls_del_rcu(&ct
->tuplehash
[IP_CT_DIR_REPLY
].hnnode
);
511 /* Destroy all pending expectations */
512 nf_ct_remove_expectations(ct
);
515 /* must be called with local_bh_disable */
516 static void nf_ct_add_to_dying_list(struct nf_conn
*ct
)
518 struct ct_pcpu
*pcpu
;
520 /* add this conntrack to the (per cpu) dying list */
521 ct
->cpu
= smp_processor_id();
522 pcpu
= per_cpu_ptr(nf_ct_net(ct
)->ct
.pcpu_lists
, ct
->cpu
);
524 spin_lock(&pcpu
->lock
);
525 hlist_nulls_add_head(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
,
527 spin_unlock(&pcpu
->lock
);
530 /* must be called with local_bh_disable */
531 static void nf_ct_add_to_unconfirmed_list(struct nf_conn
*ct
)
533 struct ct_pcpu
*pcpu
;
535 /* add this conntrack to the (per cpu) unconfirmed list */
536 ct
->cpu
= smp_processor_id();
537 pcpu
= per_cpu_ptr(nf_ct_net(ct
)->ct
.pcpu_lists
, ct
->cpu
);
539 spin_lock(&pcpu
->lock
);
540 hlist_nulls_add_head(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
,
542 spin_unlock(&pcpu
->lock
);
545 /* must be called with local_bh_disable */
546 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn
*ct
)
548 struct ct_pcpu
*pcpu
;
550 /* We overload first tuple to link into unconfirmed or dying list.*/
551 pcpu
= per_cpu_ptr(nf_ct_net(ct
)->ct
.pcpu_lists
, ct
->cpu
);
553 spin_lock(&pcpu
->lock
);
554 BUG_ON(hlist_nulls_unhashed(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
));
555 hlist_nulls_del_rcu(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
);
556 spin_unlock(&pcpu
->lock
);
559 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
561 /* Released via destroy_conntrack() */
562 struct nf_conn
*nf_ct_tmpl_alloc(struct net
*net
,
563 const struct nf_conntrack_zone
*zone
,
566 struct nf_conn
*tmpl
, *p
;
568 if (ARCH_KMALLOC_MINALIGN
<= NFCT_INFOMASK
) {
569 tmpl
= kzalloc(sizeof(*tmpl
) + NFCT_INFOMASK
, flags
);
574 tmpl
= (struct nf_conn
*)NFCT_ALIGN((unsigned long)p
);
576 tmpl
= (struct nf_conn
*)NFCT_ALIGN((unsigned long)p
);
577 tmpl
->proto
.tmpl_padto
= (char *)tmpl
- (char *)p
;
580 tmpl
= kzalloc(sizeof(*tmpl
), flags
);
585 tmpl
->status
= IPS_TEMPLATE
;
586 write_pnet(&tmpl
->ct_net
, net
);
587 nf_ct_zone_add(tmpl
, zone
);
588 atomic_set(&tmpl
->ct_general
.use
, 0);
592 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc
);
594 void nf_ct_tmpl_free(struct nf_conn
*tmpl
)
596 nf_ct_ext_destroy(tmpl
);
598 if (ARCH_KMALLOC_MINALIGN
<= NFCT_INFOMASK
)
599 kfree((char *)tmpl
- tmpl
->proto
.tmpl_padto
);
603 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free
);
605 static void destroy_gre_conntrack(struct nf_conn
*ct
)
607 #ifdef CONFIG_NF_CT_PROTO_GRE
608 struct nf_conn
*master
= ct
->master
;
611 nf_ct_gre_keymap_destroy(master
);
616 destroy_conntrack(struct nf_conntrack
*nfct
)
618 struct nf_conn
*ct
= (struct nf_conn
*)nfct
;
620 pr_debug("destroy_conntrack(%p)\n", ct
);
621 WARN_ON(atomic_read(&nfct
->use
) != 0);
623 if (unlikely(nf_ct_is_template(ct
))) {
628 if (unlikely(nf_ct_protonum(ct
) == IPPROTO_GRE
))
629 destroy_gre_conntrack(ct
);
632 /* Expectations will have been removed in clean_from_lists,
633 * except TFTP can create an expectation on the first packet,
634 * before connection is in the list, so we need to clean here,
637 nf_ct_remove_expectations(ct
);
639 nf_ct_del_from_dying_or_unconfirmed_list(ct
);
644 nf_ct_put(ct
->master
);
646 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct
);
647 nf_conntrack_free(ct
);
650 static void nf_ct_delete_from_lists(struct nf_conn
*ct
)
652 struct net
*net
= nf_ct_net(ct
);
653 unsigned int hash
, reply_hash
;
654 unsigned int sequence
;
656 nf_ct_helper_destroy(ct
);
660 sequence
= read_seqcount_begin(&nf_conntrack_generation
);
661 hash
= hash_conntrack(net
,
662 &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
663 nf_ct_zone_id(nf_ct_zone(ct
), IP_CT_DIR_ORIGINAL
));
664 reply_hash
= hash_conntrack(net
,
665 &ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
666 nf_ct_zone_id(nf_ct_zone(ct
), IP_CT_DIR_REPLY
));
667 } while (nf_conntrack_double_lock(net
, hash
, reply_hash
, sequence
));
669 clean_from_lists(ct
);
670 nf_conntrack_double_unlock(hash
, reply_hash
);
672 nf_ct_add_to_dying_list(ct
);
677 bool nf_ct_delete(struct nf_conn
*ct
, u32 portid
, int report
)
679 struct nf_conn_tstamp
*tstamp
;
682 if (test_and_set_bit(IPS_DYING_BIT
, &ct
->status
))
685 tstamp
= nf_conn_tstamp_find(ct
);
687 s32 timeout
= READ_ONCE(ct
->timeout
) - nfct_time_stamp
;
689 tstamp
->stop
= ktime_get_real_ns();
691 tstamp
->stop
-= jiffies_to_nsecs(-timeout
);
694 if (nf_conntrack_event_report(IPCT_DESTROY
, ct
,
695 portid
, report
) < 0) {
696 /* destroy event was not delivered. nf_ct_put will
697 * be done by event cache worker on redelivery.
699 nf_ct_delete_from_lists(ct
);
700 nf_conntrack_ecache_work(nf_ct_net(ct
), NFCT_ECACHE_DESTROY_FAIL
);
705 if (nf_conntrack_ecache_dwork_pending(net
))
706 nf_conntrack_ecache_work(net
, NFCT_ECACHE_DESTROY_SENT
);
707 nf_ct_delete_from_lists(ct
);
711 EXPORT_SYMBOL_GPL(nf_ct_delete
);
714 nf_ct_key_equal(struct nf_conntrack_tuple_hash
*h
,
715 const struct nf_conntrack_tuple
*tuple
,
716 const struct nf_conntrack_zone
*zone
,
717 const struct net
*net
)
719 struct nf_conn
*ct
= nf_ct_tuplehash_to_ctrack(h
);
721 /* A conntrack can be recreated with the equal tuple,
722 * so we need to check that the conntrack is confirmed
724 return nf_ct_tuple_equal(tuple
, &h
->tuple
) &&
725 nf_ct_zone_equal(ct
, zone
, NF_CT_DIRECTION(h
)) &&
726 nf_ct_is_confirmed(ct
) &&
727 net_eq(net
, nf_ct_net(ct
));
731 nf_ct_match(const struct nf_conn
*ct1
, const struct nf_conn
*ct2
)
733 return nf_ct_tuple_equal(&ct1
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
734 &ct2
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
) &&
735 nf_ct_tuple_equal(&ct1
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
736 &ct2
->tuplehash
[IP_CT_DIR_REPLY
].tuple
) &&
737 nf_ct_zone_equal(ct1
, nf_ct_zone(ct2
), IP_CT_DIR_ORIGINAL
) &&
738 nf_ct_zone_equal(ct1
, nf_ct_zone(ct2
), IP_CT_DIR_REPLY
) &&
739 net_eq(nf_ct_net(ct1
), nf_ct_net(ct2
));
742 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
743 static void nf_ct_gc_expired(struct nf_conn
*ct
)
745 if (!atomic_inc_not_zero(&ct
->ct_general
.use
))
748 if (nf_ct_should_gc(ct
))
756 * - Caller must take a reference on returned object
757 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
759 static struct nf_conntrack_tuple_hash
*
760 ____nf_conntrack_find(struct net
*net
, const struct nf_conntrack_zone
*zone
,
761 const struct nf_conntrack_tuple
*tuple
, u32 hash
)
763 struct nf_conntrack_tuple_hash
*h
;
764 struct hlist_nulls_head
*ct_hash
;
765 struct hlist_nulls_node
*n
;
766 unsigned int bucket
, hsize
;
769 nf_conntrack_get_ht(&ct_hash
, &hsize
);
770 bucket
= reciprocal_scale(hash
, hsize
);
772 hlist_nulls_for_each_entry_rcu(h
, n
, &ct_hash
[bucket
], hnnode
) {
775 ct
= nf_ct_tuplehash_to_ctrack(h
);
776 if (nf_ct_is_expired(ct
)) {
777 nf_ct_gc_expired(ct
);
781 if (nf_ct_key_equal(h
, tuple
, zone
, net
))
785 * if the nulls value we got at the end of this lookup is
786 * not the expected one, we must restart lookup.
787 * We probably met an item that was moved to another chain.
789 if (get_nulls_value(n
) != bucket
) {
790 NF_CT_STAT_INC_ATOMIC(net
, search_restart
);
797 /* Find a connection corresponding to a tuple. */
798 static struct nf_conntrack_tuple_hash
*
799 __nf_conntrack_find_get(struct net
*net
, const struct nf_conntrack_zone
*zone
,
800 const struct nf_conntrack_tuple
*tuple
, u32 hash
)
802 struct nf_conntrack_tuple_hash
*h
;
807 h
= ____nf_conntrack_find(net
, zone
, tuple
, hash
);
809 /* We have a candidate that matches the tuple we're interested
810 * in, try to obtain a reference and re-check tuple
812 ct
= nf_ct_tuplehash_to_ctrack(h
);
813 if (likely(atomic_inc_not_zero(&ct
->ct_general
.use
))) {
814 if (likely(nf_ct_key_equal(h
, tuple
, zone
, net
)))
817 /* TYPESAFE_BY_RCU recycled the candidate */
829 struct nf_conntrack_tuple_hash
*
830 nf_conntrack_find_get(struct net
*net
, const struct nf_conntrack_zone
*zone
,
831 const struct nf_conntrack_tuple
*tuple
)
833 unsigned int rid
, zone_id
= nf_ct_zone_id(zone
, IP_CT_DIR_ORIGINAL
);
834 struct nf_conntrack_tuple_hash
*thash
;
836 thash
= __nf_conntrack_find_get(net
, zone
, tuple
,
837 hash_conntrack_raw(tuple
, zone_id
, net
));
842 rid
= nf_ct_zone_id(zone
, IP_CT_DIR_REPLY
);
844 return __nf_conntrack_find_get(net
, zone
, tuple
,
845 hash_conntrack_raw(tuple
, rid
, net
));
848 EXPORT_SYMBOL_GPL(nf_conntrack_find_get
);
850 static void __nf_conntrack_hash_insert(struct nf_conn
*ct
,
852 unsigned int reply_hash
)
854 hlist_nulls_add_head_rcu(&ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
,
855 &nf_conntrack_hash
[hash
]);
856 hlist_nulls_add_head_rcu(&ct
->tuplehash
[IP_CT_DIR_REPLY
].hnnode
,
857 &nf_conntrack_hash
[reply_hash
]);
861 nf_conntrack_hash_check_insert(struct nf_conn
*ct
)
863 const struct nf_conntrack_zone
*zone
;
864 struct net
*net
= nf_ct_net(ct
);
865 unsigned int hash
, reply_hash
;
866 struct nf_conntrack_tuple_hash
*h
;
867 struct hlist_nulls_node
*n
;
868 unsigned int max_chainlen
;
869 unsigned int chainlen
= 0;
870 unsigned int sequence
;
873 zone
= nf_ct_zone(ct
);
877 sequence
= read_seqcount_begin(&nf_conntrack_generation
);
878 hash
= hash_conntrack(net
,
879 &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
880 nf_ct_zone_id(nf_ct_zone(ct
), IP_CT_DIR_ORIGINAL
));
881 reply_hash
= hash_conntrack(net
,
882 &ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
883 nf_ct_zone_id(nf_ct_zone(ct
), IP_CT_DIR_REPLY
));
884 } while (nf_conntrack_double_lock(net
, hash
, reply_hash
, sequence
));
886 max_chainlen
= MIN_CHAINLEN
+ prandom_u32_max(MAX_CHAINLEN
);
888 /* See if there's one in the list already, including reverse */
889 hlist_nulls_for_each_entry(h
, n
, &nf_conntrack_hash
[hash
], hnnode
) {
890 if (nf_ct_key_equal(h
, &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
894 if (chainlen
++ > max_chainlen
)
900 hlist_nulls_for_each_entry(h
, n
, &nf_conntrack_hash
[reply_hash
], hnnode
) {
901 if (nf_ct_key_equal(h
, &ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
904 if (chainlen
++ > max_chainlen
)
909 /* The caller holds a reference to this object */
910 atomic_set(&ct
->ct_general
.use
, 2);
911 __nf_conntrack_hash_insert(ct
, hash
, reply_hash
);
912 nf_conntrack_double_unlock(hash
, reply_hash
);
913 NF_CT_STAT_INC(net
, insert
);
917 NF_CT_STAT_INC(net
, chaintoolong
);
920 nf_conntrack_double_unlock(hash
, reply_hash
);
924 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert
);
926 void nf_ct_acct_add(struct nf_conn
*ct
, u32 dir
, unsigned int packets
,
929 struct nf_conn_acct
*acct
;
931 acct
= nf_conn_acct_find(ct
);
933 struct nf_conn_counter
*counter
= acct
->counter
;
935 atomic64_add(packets
, &counter
[dir
].packets
);
936 atomic64_add(bytes
, &counter
[dir
].bytes
);
939 EXPORT_SYMBOL_GPL(nf_ct_acct_add
);
941 static void nf_ct_acct_merge(struct nf_conn
*ct
, enum ip_conntrack_info ctinfo
,
942 const struct nf_conn
*loser_ct
)
944 struct nf_conn_acct
*acct
;
946 acct
= nf_conn_acct_find(loser_ct
);
948 struct nf_conn_counter
*counter
= acct
->counter
;
951 /* u32 should be fine since we must have seen one packet. */
952 bytes
= atomic64_read(&counter
[CTINFO2DIR(ctinfo
)].bytes
);
953 nf_ct_acct_update(ct
, CTINFO2DIR(ctinfo
), bytes
);
957 static void __nf_conntrack_insert_prepare(struct nf_conn
*ct
)
959 struct nf_conn_tstamp
*tstamp
;
961 atomic_inc(&ct
->ct_general
.use
);
962 ct
->status
|= IPS_CONFIRMED
;
964 /* set conntrack timestamp, if enabled. */
965 tstamp
= nf_conn_tstamp_find(ct
);
967 tstamp
->start
= ktime_get_real_ns();
970 /* caller must hold locks to prevent concurrent changes */
971 static int __nf_ct_resolve_clash(struct sk_buff
*skb
,
972 struct nf_conntrack_tuple_hash
*h
)
974 /* This is the conntrack entry already in hashes that won race. */
975 struct nf_conn
*ct
= nf_ct_tuplehash_to_ctrack(h
);
976 enum ip_conntrack_info ctinfo
;
977 struct nf_conn
*loser_ct
;
979 loser_ct
= nf_ct_get(skb
, &ctinfo
);
981 if (nf_ct_is_dying(ct
))
984 if (((ct
->status
& IPS_NAT_DONE_MASK
) == 0) ||
985 nf_ct_match(ct
, loser_ct
)) {
986 struct net
*net
= nf_ct_net(ct
);
988 nf_conntrack_get(&ct
->ct_general
);
990 nf_ct_acct_merge(ct
, ctinfo
, loser_ct
);
991 nf_ct_add_to_dying_list(loser_ct
);
992 nf_conntrack_put(&loser_ct
->ct_general
);
993 nf_ct_set(skb
, ct
, ctinfo
);
995 NF_CT_STAT_INC(net
, clash_resolve
);
1003 * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
1005 * @skb: skb that causes the collision
1006 * @repl_idx: hash slot for reply direction
1008 * Called when origin or reply direction had a clash.
1009 * The skb can be handled without packet drop provided the reply direction
1010 * is unique or there the existing entry has the identical tuple in both
1013 * Caller must hold conntrack table locks to prevent concurrent updates.
1015 * Returns NF_DROP if the clash could not be handled.
1017 static int nf_ct_resolve_clash_harder(struct sk_buff
*skb
, u32 repl_idx
)
1019 struct nf_conn
*loser_ct
= (struct nf_conn
*)skb_nfct(skb
);
1020 const struct nf_conntrack_zone
*zone
;
1021 struct nf_conntrack_tuple_hash
*h
;
1022 struct hlist_nulls_node
*n
;
1025 zone
= nf_ct_zone(loser_ct
);
1026 net
= nf_ct_net(loser_ct
);
1028 /* Reply direction must never result in a clash, unless both origin
1029 * and reply tuples are identical.
1031 hlist_nulls_for_each_entry(h
, n
, &nf_conntrack_hash
[repl_idx
], hnnode
) {
1032 if (nf_ct_key_equal(h
,
1033 &loser_ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
1035 return __nf_ct_resolve_clash(skb
, h
);
1038 /* We want the clashing entry to go away real soon: 1 second timeout. */
1039 WRITE_ONCE(loser_ct
->timeout
, nfct_time_stamp
+ HZ
);
1041 /* IPS_NAT_CLASH removes the entry automatically on the first
1042 * reply. Also prevents UDP tracker from moving the entry to
1043 * ASSURED state, i.e. the entry can always be evicted under
1046 loser_ct
->status
|= IPS_FIXED_TIMEOUT
| IPS_NAT_CLASH
;
1048 __nf_conntrack_insert_prepare(loser_ct
);
1050 /* fake add for ORIGINAL dir: we want lookups to only find the entry
1051 * already in the table. This also hides the clashing entry from
1052 * ctnetlink iteration, i.e. conntrack -L won't show them.
1054 hlist_nulls_add_fake(&loser_ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
);
1056 hlist_nulls_add_head_rcu(&loser_ct
->tuplehash
[IP_CT_DIR_REPLY
].hnnode
,
1057 &nf_conntrack_hash
[repl_idx
]);
1059 NF_CT_STAT_INC(net
, clash_resolve
);
1064 * nf_ct_resolve_clash - attempt to handle clash without packet drop
1066 * @skb: skb that causes the clash
1067 * @h: tuplehash of the clashing entry already in table
1068 * @reply_hash: hash slot for reply direction
1070 * A conntrack entry can be inserted to the connection tracking table
1071 * if there is no existing entry with an identical tuple.
1073 * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1074 * to be dropped. In case @skb is retransmitted, next conntrack lookup
1075 * will find the already-existing entry.
1077 * The major problem with such packet drop is the extra delay added by
1078 * the packet loss -- it will take some time for a retransmit to occur
1079 * (or the sender to time out when waiting for a reply).
1081 * This function attempts to handle the situation without packet drop.
1083 * If @skb has no NAT transformation or if the colliding entries are
1084 * exactly the same, only the to-be-confirmed conntrack entry is discarded
1085 * and @skb is associated with the conntrack entry already in the table.
1087 * Failing that, the new, unconfirmed conntrack is still added to the table
1088 * provided that the collision only occurs in the ORIGINAL direction.
1089 * The new entry will be added only in the non-clashing REPLY direction,
1090 * so packets in the ORIGINAL direction will continue to match the existing
1091 * entry. The new entry will also have a fixed timeout so it expires --
1092 * due to the collision, it will only see reply traffic.
1094 * Returns NF_DROP if the clash could not be resolved.
1096 static __cold noinline
int
1097 nf_ct_resolve_clash(struct sk_buff
*skb
, struct nf_conntrack_tuple_hash
*h
,
1100 /* This is the conntrack entry already in hashes that won race. */
1101 struct nf_conn
*ct
= nf_ct_tuplehash_to_ctrack(h
);
1102 const struct nf_conntrack_l4proto
*l4proto
;
1103 enum ip_conntrack_info ctinfo
;
1104 struct nf_conn
*loser_ct
;
1108 loser_ct
= nf_ct_get(skb
, &ctinfo
);
1109 net
= nf_ct_net(loser_ct
);
1111 l4proto
= nf_ct_l4proto_find(nf_ct_protonum(ct
));
1112 if (!l4proto
->allow_clash
)
1115 ret
= __nf_ct_resolve_clash(skb
, h
);
1116 if (ret
== NF_ACCEPT
)
1119 ret
= nf_ct_resolve_clash_harder(skb
, reply_hash
);
1120 if (ret
== NF_ACCEPT
)
1124 nf_ct_add_to_dying_list(loser_ct
);
1125 NF_CT_STAT_INC(net
, drop
);
1126 NF_CT_STAT_INC(net
, insert_failed
);
1130 /* Confirm a connection given skb; places it in hash table */
1132 __nf_conntrack_confirm(struct sk_buff
*skb
)
1134 unsigned int chainlen
= 0, sequence
, max_chainlen
;
1135 const struct nf_conntrack_zone
*zone
;
1136 unsigned int hash
, reply_hash
;
1137 struct nf_conntrack_tuple_hash
*h
;
1139 struct nf_conn_help
*help
;
1140 struct hlist_nulls_node
*n
;
1141 enum ip_conntrack_info ctinfo
;
1145 ct
= nf_ct_get(skb
, &ctinfo
);
1146 net
= nf_ct_net(ct
);
1148 /* ipt_REJECT uses nf_conntrack_attach to attach related
1149 ICMP/TCP RST packets in other direction. Actual packet
1150 which created connection will be IP_CT_NEW or for an
1151 expected connection, IP_CT_RELATED. */
1152 if (CTINFO2DIR(ctinfo
) != IP_CT_DIR_ORIGINAL
)
1155 zone
= nf_ct_zone(ct
);
1159 sequence
= read_seqcount_begin(&nf_conntrack_generation
);
1160 /* reuse the hash saved before */
1161 hash
= *(unsigned long *)&ct
->tuplehash
[IP_CT_DIR_REPLY
].hnnode
.pprev
;
1162 hash
= scale_hash(hash
);
1163 reply_hash
= hash_conntrack(net
,
1164 &ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
1165 nf_ct_zone_id(nf_ct_zone(ct
), IP_CT_DIR_REPLY
));
1166 } while (nf_conntrack_double_lock(net
, hash
, reply_hash
, sequence
));
1168 /* We're not in hash table, and we refuse to set up related
1169 * connections for unconfirmed conns. But packet copies and
1170 * REJECT will give spurious warnings here.
1173 /* Another skb with the same unconfirmed conntrack may
1174 * win the race. This may happen for bridge(br_flood)
1175 * or broadcast/multicast packets do skb_clone with
1176 * unconfirmed conntrack.
1178 if (unlikely(nf_ct_is_confirmed(ct
))) {
1180 nf_conntrack_double_unlock(hash
, reply_hash
);
1185 pr_debug("Confirming conntrack %p\n", ct
);
1186 /* We have to check the DYING flag after unlink to prevent
1187 * a race against nf_ct_get_next_corpse() possibly called from
1188 * user context, else we insert an already 'dead' hash, blocking
1189 * further use of that particular connection -JM.
1191 nf_ct_del_from_dying_or_unconfirmed_list(ct
);
1193 if (unlikely(nf_ct_is_dying(ct
))) {
1194 nf_ct_add_to_dying_list(ct
);
1195 NF_CT_STAT_INC(net
, insert_failed
);
1199 max_chainlen
= MIN_CHAINLEN
+ prandom_u32_max(MAX_CHAINLEN
);
1200 /* See if there's one in the list already, including reverse:
1201 NAT could have grabbed it without realizing, since we're
1202 not in the hash. If there is, we lost race. */
1203 hlist_nulls_for_each_entry(h
, n
, &nf_conntrack_hash
[hash
], hnnode
) {
1204 if (nf_ct_key_equal(h
, &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
1207 if (chainlen
++ > max_chainlen
)
1212 hlist_nulls_for_each_entry(h
, n
, &nf_conntrack_hash
[reply_hash
], hnnode
) {
1213 if (nf_ct_key_equal(h
, &ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
,
1216 if (chainlen
++ > max_chainlen
) {
1218 nf_ct_add_to_dying_list(ct
);
1219 NF_CT_STAT_INC(net
, chaintoolong
);
1220 NF_CT_STAT_INC(net
, insert_failed
);
1226 /* Timer relative to confirmation time, not original
1227 setting time, otherwise we'd get timer wrap in
1228 weird delay cases. */
1229 ct
->timeout
+= nfct_time_stamp
;
1231 __nf_conntrack_insert_prepare(ct
);
1233 /* Since the lookup is lockless, hash insertion must be done after
1234 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1235 * guarantee that no other CPU can find the conntrack before the above
1236 * stores are visible.
1238 __nf_conntrack_hash_insert(ct
, hash
, reply_hash
);
1239 nf_conntrack_double_unlock(hash
, reply_hash
);
1242 help
= nfct_help(ct
);
1243 if (help
&& help
->helper
)
1244 nf_conntrack_event_cache(IPCT_HELPER
, ct
);
1246 nf_conntrack_event_cache(master_ct(ct
) ?
1247 IPCT_RELATED
: IPCT_NEW
, ct
);
1251 ret
= nf_ct_resolve_clash(skb
, h
, reply_hash
);
1253 nf_conntrack_double_unlock(hash
, reply_hash
);
1257 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm
);
1259 /* Returns true if a connection correspondings to the tuple (required
1262 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple
*tuple
,
1263 const struct nf_conn
*ignored_conntrack
)
1265 struct net
*net
= nf_ct_net(ignored_conntrack
);
1266 const struct nf_conntrack_zone
*zone
;
1267 struct nf_conntrack_tuple_hash
*h
;
1268 struct hlist_nulls_head
*ct_hash
;
1269 unsigned int hash
, hsize
;
1270 struct hlist_nulls_node
*n
;
1273 zone
= nf_ct_zone(ignored_conntrack
);
1277 nf_conntrack_get_ht(&ct_hash
, &hsize
);
1278 hash
= __hash_conntrack(net
, tuple
, nf_ct_zone_id(zone
, IP_CT_DIR_REPLY
), hsize
);
1280 hlist_nulls_for_each_entry_rcu(h
, n
, &ct_hash
[hash
], hnnode
) {
1281 ct
= nf_ct_tuplehash_to_ctrack(h
);
1283 if (ct
== ignored_conntrack
)
1286 if (nf_ct_is_expired(ct
)) {
1287 nf_ct_gc_expired(ct
);
1291 if (nf_ct_key_equal(h
, tuple
, zone
, net
)) {
1292 /* Tuple is taken already, so caller will need to find
1293 * a new source port to use.
1296 * If the *original tuples* are identical, then both
1297 * conntracks refer to the same flow.
1298 * This is a rare situation, it can occur e.g. when
1299 * more than one UDP packet is sent from same socket
1300 * in different threads.
1302 * Let nf_ct_resolve_clash() deal with this later.
1304 if (nf_ct_tuple_equal(&ignored_conntrack
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
,
1305 &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
) &&
1306 nf_ct_zone_equal(ct
, zone
, IP_CT_DIR_ORIGINAL
))
1309 NF_CT_STAT_INC_ATOMIC(net
, found
);
1315 if (get_nulls_value(n
) != hash
) {
1316 NF_CT_STAT_INC_ATOMIC(net
, search_restart
);
1324 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken
);
1326 #define NF_CT_EVICTION_RANGE 8
1328 /* There's a small race here where we may free a just-assured
1329 connection. Too bad: we're in trouble anyway. */
1330 static unsigned int early_drop_list(struct net
*net
,
1331 struct hlist_nulls_head
*head
)
1333 struct nf_conntrack_tuple_hash
*h
;
1334 struct hlist_nulls_node
*n
;
1335 unsigned int drops
= 0;
1336 struct nf_conn
*tmp
;
1338 hlist_nulls_for_each_entry_rcu(h
, n
, head
, hnnode
) {
1339 tmp
= nf_ct_tuplehash_to_ctrack(h
);
1341 if (test_bit(IPS_OFFLOAD_BIT
, &tmp
->status
))
1344 if (nf_ct_is_expired(tmp
)) {
1345 nf_ct_gc_expired(tmp
);
1349 if (test_bit(IPS_ASSURED_BIT
, &tmp
->status
) ||
1350 !net_eq(nf_ct_net(tmp
), net
) ||
1351 nf_ct_is_dying(tmp
))
1354 if (!atomic_inc_not_zero(&tmp
->ct_general
.use
))
1357 /* kill only if still in same netns -- might have moved due to
1358 * SLAB_TYPESAFE_BY_RCU rules.
1360 * We steal the timer reference. If that fails timer has
1361 * already fired or someone else deleted it. Just drop ref
1362 * and move to next entry.
1364 if (net_eq(nf_ct_net(tmp
), net
) &&
1365 nf_ct_is_confirmed(tmp
) &&
1366 nf_ct_delete(tmp
, 0, 0))
1375 static noinline
int early_drop(struct net
*net
, unsigned int hash
)
1377 unsigned int i
, bucket
;
1379 for (i
= 0; i
< NF_CT_EVICTION_RANGE
; i
++) {
1380 struct hlist_nulls_head
*ct_hash
;
1381 unsigned int hsize
, drops
;
1384 nf_conntrack_get_ht(&ct_hash
, &hsize
);
1386 bucket
= reciprocal_scale(hash
, hsize
);
1388 bucket
= (bucket
+ 1) % hsize
;
1390 drops
= early_drop_list(net
, &ct_hash
[bucket
]);
1394 NF_CT_STAT_ADD_ATOMIC(net
, early_drop
, drops
);
1402 static bool gc_worker_skip_ct(const struct nf_conn
*ct
)
1404 return !nf_ct_is_confirmed(ct
) || nf_ct_is_dying(ct
);
1407 static bool gc_worker_can_early_drop(const struct nf_conn
*ct
)
1409 const struct nf_conntrack_l4proto
*l4proto
;
1411 if (!test_bit(IPS_ASSURED_BIT
, &ct
->status
))
1414 l4proto
= nf_ct_l4proto_find(nf_ct_protonum(ct
));
1415 if (l4proto
->can_early_drop
&& l4proto
->can_early_drop(ct
))
1421 static void gc_worker(struct work_struct
*work
)
1423 unsigned long end_time
= jiffies
+ GC_SCAN_MAX_DURATION
;
1424 unsigned int i
, hashsz
, nf_conntrack_max95
= 0;
1425 unsigned long next_run
= GC_SCAN_INTERVAL
;
1426 struct conntrack_gc_work
*gc_work
;
1427 gc_work
= container_of(work
, struct conntrack_gc_work
, dwork
.work
);
1429 i
= gc_work
->next_bucket
;
1430 if (gc_work
->early_drop
)
1431 nf_conntrack_max95
= nf_conntrack_max
/ 100u * 95u;
1434 struct nf_conntrack_tuple_hash
*h
;
1435 struct hlist_nulls_head
*ct_hash
;
1436 struct hlist_nulls_node
*n
;
1437 struct nf_conn
*tmp
;
1441 nf_conntrack_get_ht(&ct_hash
, &hashsz
);
1447 hlist_nulls_for_each_entry_rcu(h
, n
, &ct_hash
[i
], hnnode
) {
1448 struct nf_conntrack_net
*cnet
;
1451 tmp
= nf_ct_tuplehash_to_ctrack(h
);
1453 if (test_bit(IPS_OFFLOAD_BIT
, &tmp
->status
)) {
1454 nf_ct_offload_timeout(tmp
);
1458 if (nf_ct_is_expired(tmp
)) {
1459 nf_ct_gc_expired(tmp
);
1463 if (nf_conntrack_max95
== 0 || gc_worker_skip_ct(tmp
))
1466 net
= nf_ct_net(tmp
);
1467 cnet
= nf_ct_pernet(net
);
1468 if (atomic_read(&cnet
->count
) < nf_conntrack_max95
)
1471 /* need to take reference to avoid possible races */
1472 if (!atomic_inc_not_zero(&tmp
->ct_general
.use
))
1475 if (gc_worker_skip_ct(tmp
)) {
1480 if (gc_worker_can_early_drop(tmp
))
1486 /* could check get_nulls_value() here and restart if ct
1487 * was moved to another chain. But given gc is best-effort
1488 * we will just continue with next hash slot.
1494 if (time_after(jiffies
, end_time
) && i
< hashsz
) {
1495 gc_work
->next_bucket
= i
;
1499 } while (i
< hashsz
);
1501 if (gc_work
->exiting
)
1505 * Eviction will normally happen from the packet path, and not
1506 * from this gc worker.
1508 * This worker is only here to reap expired entries when system went
1509 * idle after a busy period.
1512 gc_work
->early_drop
= false;
1513 gc_work
->next_bucket
= 0;
1515 queue_delayed_work(system_power_efficient_wq
, &gc_work
->dwork
, next_run
);
1518 static void conntrack_gc_work_init(struct conntrack_gc_work
*gc_work
)
1520 INIT_DEFERRABLE_WORK(&gc_work
->dwork
, gc_worker
);
1521 gc_work
->exiting
= false;
1524 static struct nf_conn
*
1525 __nf_conntrack_alloc(struct net
*net
,
1526 const struct nf_conntrack_zone
*zone
,
1527 const struct nf_conntrack_tuple
*orig
,
1528 const struct nf_conntrack_tuple
*repl
,
1529 gfp_t gfp
, u32 hash
)
1531 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
1532 unsigned int ct_count
;
1535 /* We don't want any race condition at early drop stage */
1536 ct_count
= atomic_inc_return(&cnet
->count
);
1538 if (nf_conntrack_max
&& unlikely(ct_count
> nf_conntrack_max
)) {
1539 if (!early_drop(net
, hash
)) {
1540 if (!conntrack_gc_work
.early_drop
)
1541 conntrack_gc_work
.early_drop
= true;
1542 atomic_dec(&cnet
->count
);
1543 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1544 return ERR_PTR(-ENOMEM
);
1549 * Do not use kmem_cache_zalloc(), as this cache uses
1550 * SLAB_TYPESAFE_BY_RCU.
1552 ct
= kmem_cache_alloc(nf_conntrack_cachep
, gfp
);
1556 spin_lock_init(&ct
->lock
);
1557 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
= *orig
;
1558 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].hnnode
.pprev
= NULL
;
1559 ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
= *repl
;
1560 /* save hash for reusing when confirming */
1561 *(unsigned long *)(&ct
->tuplehash
[IP_CT_DIR_REPLY
].hnnode
.pprev
) = hash
;
1563 WRITE_ONCE(ct
->timeout
, 0);
1564 write_pnet(&ct
->ct_net
, net
);
1565 memset(&ct
->__nfct_init_offset
, 0,
1566 offsetof(struct nf_conn
, proto
) -
1567 offsetof(struct nf_conn
, __nfct_init_offset
));
1569 nf_ct_zone_add(ct
, zone
);
1571 /* Because we use RCU lookups, we set ct_general.use to zero before
1572 * this is inserted in any list.
1574 atomic_set(&ct
->ct_general
.use
, 0);
1577 atomic_dec(&cnet
->count
);
1578 return ERR_PTR(-ENOMEM
);
1581 struct nf_conn
*nf_conntrack_alloc(struct net
*net
,
1582 const struct nf_conntrack_zone
*zone
,
1583 const struct nf_conntrack_tuple
*orig
,
1584 const struct nf_conntrack_tuple
*repl
,
1587 return __nf_conntrack_alloc(net
, zone
, orig
, repl
, gfp
, 0);
1589 EXPORT_SYMBOL_GPL(nf_conntrack_alloc
);
1591 void nf_conntrack_free(struct nf_conn
*ct
)
1593 struct net
*net
= nf_ct_net(ct
);
1594 struct nf_conntrack_net
*cnet
;
1596 /* A freed object has refcnt == 0, that's
1597 * the golden rule for SLAB_TYPESAFE_BY_RCU
1599 WARN_ON(atomic_read(&ct
->ct_general
.use
) != 0);
1601 nf_ct_ext_destroy(ct
);
1602 kmem_cache_free(nf_conntrack_cachep
, ct
);
1603 cnet
= nf_ct_pernet(net
);
1605 smp_mb__before_atomic();
1606 atomic_dec(&cnet
->count
);
1608 EXPORT_SYMBOL_GPL(nf_conntrack_free
);
1611 /* Allocate a new conntrack: we return -ENOMEM if classification
1612 failed due to stress. Otherwise it really is unclassifiable. */
1613 static noinline
struct nf_conntrack_tuple_hash
*
1614 init_conntrack(struct net
*net
, struct nf_conn
*tmpl
,
1615 const struct nf_conntrack_tuple
*tuple
,
1616 struct sk_buff
*skb
,
1617 unsigned int dataoff
, u32 hash
)
1620 struct nf_conn_help
*help
;
1621 struct nf_conntrack_tuple repl_tuple
;
1622 struct nf_conntrack_ecache
*ecache
;
1623 struct nf_conntrack_expect
*exp
= NULL
;
1624 const struct nf_conntrack_zone
*zone
;
1625 struct nf_conn_timeout
*timeout_ext
;
1626 struct nf_conntrack_zone tmp
;
1627 struct nf_conntrack_net
*cnet
;
1629 if (!nf_ct_invert_tuple(&repl_tuple
, tuple
)) {
1630 pr_debug("Can't invert tuple.\n");
1634 zone
= nf_ct_zone_tmpl(tmpl
, skb
, &tmp
);
1635 ct
= __nf_conntrack_alloc(net
, zone
, tuple
, &repl_tuple
, GFP_ATOMIC
,
1638 return (struct nf_conntrack_tuple_hash
*)ct
;
1640 if (!nf_ct_add_synproxy(ct
, tmpl
)) {
1641 nf_conntrack_free(ct
);
1642 return ERR_PTR(-ENOMEM
);
1645 timeout_ext
= tmpl
? nf_ct_timeout_find(tmpl
) : NULL
;
1648 nf_ct_timeout_ext_add(ct
, rcu_dereference(timeout_ext
->timeout
),
1651 nf_ct_acct_ext_add(ct
, GFP_ATOMIC
);
1652 nf_ct_tstamp_ext_add(ct
, GFP_ATOMIC
);
1653 nf_ct_labels_ext_add(ct
);
1655 ecache
= tmpl
? nf_ct_ecache_find(tmpl
) : NULL
;
1656 nf_ct_ecache_ext_add(ct
, ecache
? ecache
->ctmask
: 0,
1657 ecache
? ecache
->expmask
: 0,
1661 cnet
= nf_ct_pernet(net
);
1662 if (cnet
->expect_count
) {
1663 spin_lock(&nf_conntrack_expect_lock
);
1664 exp
= nf_ct_find_expectation(net
, zone
, tuple
);
1666 pr_debug("expectation arrives ct=%p exp=%p\n",
1668 /* Welcome, Mr. Bond. We've been expecting you... */
1669 __set_bit(IPS_EXPECTED_BIT
, &ct
->status
);
1670 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1671 ct
->master
= exp
->master
;
1673 help
= nf_ct_helper_ext_add(ct
, GFP_ATOMIC
);
1675 rcu_assign_pointer(help
->helper
, exp
->helper
);
1678 #ifdef CONFIG_NF_CONNTRACK_MARK
1679 ct
->mark
= exp
->master
->mark
;
1681 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1682 ct
->secmark
= exp
->master
->secmark
;
1684 NF_CT_STAT_INC(net
, expect_new
);
1686 spin_unlock(&nf_conntrack_expect_lock
);
1689 __nf_ct_try_assign_helper(ct
, tmpl
, GFP_ATOMIC
);
1691 /* Now it is inserted into the unconfirmed list, bump refcount */
1692 nf_conntrack_get(&ct
->ct_general
);
1693 nf_ct_add_to_unconfirmed_list(ct
);
1699 exp
->expectfn(ct
, exp
);
1700 nf_ct_expect_put(exp
);
1703 return &ct
->tuplehash
[IP_CT_DIR_ORIGINAL
];
1706 /* On success, returns 0, sets skb->_nfct | ctinfo */
1708 resolve_normal_ct(struct nf_conn
*tmpl
,
1709 struct sk_buff
*skb
,
1710 unsigned int dataoff
,
1712 const struct nf_hook_state
*state
)
1714 const struct nf_conntrack_zone
*zone
;
1715 struct nf_conntrack_tuple tuple
;
1716 struct nf_conntrack_tuple_hash
*h
;
1717 enum ip_conntrack_info ctinfo
;
1718 struct nf_conntrack_zone tmp
;
1719 u32 hash
, zone_id
, rid
;
1722 if (!nf_ct_get_tuple(skb
, skb_network_offset(skb
),
1723 dataoff
, state
->pf
, protonum
, state
->net
,
1725 pr_debug("Can't get tuple\n");
1729 /* look for tuple match */
1730 zone
= nf_ct_zone_tmpl(tmpl
, skb
, &tmp
);
1732 zone_id
= nf_ct_zone_id(zone
, IP_CT_DIR_ORIGINAL
);
1733 hash
= hash_conntrack_raw(&tuple
, zone_id
, state
->net
);
1734 h
= __nf_conntrack_find_get(state
->net
, zone
, &tuple
, hash
);
1737 rid
= nf_ct_zone_id(zone
, IP_CT_DIR_REPLY
);
1738 if (zone_id
!= rid
) {
1739 u32 tmp
= hash_conntrack_raw(&tuple
, rid
, state
->net
);
1741 h
= __nf_conntrack_find_get(state
->net
, zone
, &tuple
, tmp
);
1746 h
= init_conntrack(state
->net
, tmpl
, &tuple
,
1747 skb
, dataoff
, hash
);
1753 ct
= nf_ct_tuplehash_to_ctrack(h
);
1755 /* It exists; we have (non-exclusive) reference. */
1756 if (NF_CT_DIRECTION(h
) == IP_CT_DIR_REPLY
) {
1757 ctinfo
= IP_CT_ESTABLISHED_REPLY
;
1759 /* Once we've had two way comms, always ESTABLISHED. */
1760 if (test_bit(IPS_SEEN_REPLY_BIT
, &ct
->status
)) {
1761 pr_debug("normal packet for %p\n", ct
);
1762 ctinfo
= IP_CT_ESTABLISHED
;
1763 } else if (test_bit(IPS_EXPECTED_BIT
, &ct
->status
)) {
1764 pr_debug("related packet for %p\n", ct
);
1765 ctinfo
= IP_CT_RELATED
;
1767 pr_debug("new packet for %p\n", ct
);
1771 nf_ct_set(skb
, ct
, ctinfo
);
1776 * icmp packets need special treatment to handle error messages that are
1777 * related to a connection.
1779 * Callers need to check if skb has a conntrack assigned when this
1780 * helper returns; in such case skb belongs to an already known connection.
1782 static unsigned int __cold
1783 nf_conntrack_handle_icmp(struct nf_conn
*tmpl
,
1784 struct sk_buff
*skb
,
1785 unsigned int dataoff
,
1787 const struct nf_hook_state
*state
)
1791 if (state
->pf
== NFPROTO_IPV4
&& protonum
== IPPROTO_ICMP
)
1792 ret
= nf_conntrack_icmpv4_error(tmpl
, skb
, dataoff
, state
);
1793 #if IS_ENABLED(CONFIG_IPV6)
1794 else if (state
->pf
== NFPROTO_IPV6
&& protonum
== IPPROTO_ICMPV6
)
1795 ret
= nf_conntrack_icmpv6_error(tmpl
, skb
, dataoff
, state
);
1801 NF_CT_STAT_INC_ATOMIC(state
->net
, error
);
1806 static int generic_packet(struct nf_conn
*ct
, struct sk_buff
*skb
,
1807 enum ip_conntrack_info ctinfo
)
1809 const unsigned int *timeout
= nf_ct_timeout_lookup(ct
);
1812 timeout
= &nf_generic_pernet(nf_ct_net(ct
))->timeout
;
1814 nf_ct_refresh_acct(ct
, ctinfo
, skb
, *timeout
);
1818 /* Returns verdict for packet, or -1 for invalid. */
1819 static int nf_conntrack_handle_packet(struct nf_conn
*ct
,
1820 struct sk_buff
*skb
,
1821 unsigned int dataoff
,
1822 enum ip_conntrack_info ctinfo
,
1823 const struct nf_hook_state
*state
)
1825 switch (nf_ct_protonum(ct
)) {
1827 return nf_conntrack_tcp_packet(ct
, skb
, dataoff
,
1830 return nf_conntrack_udp_packet(ct
, skb
, dataoff
,
1833 return nf_conntrack_icmp_packet(ct
, skb
, ctinfo
, state
);
1834 #if IS_ENABLED(CONFIG_IPV6)
1835 case IPPROTO_ICMPV6
:
1836 return nf_conntrack_icmpv6_packet(ct
, skb
, ctinfo
, state
);
1838 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1839 case IPPROTO_UDPLITE
:
1840 return nf_conntrack_udplite_packet(ct
, skb
, dataoff
,
1843 #ifdef CONFIG_NF_CT_PROTO_SCTP
1845 return nf_conntrack_sctp_packet(ct
, skb
, dataoff
,
1848 #ifdef CONFIG_NF_CT_PROTO_DCCP
1850 return nf_conntrack_dccp_packet(ct
, skb
, dataoff
,
1853 #ifdef CONFIG_NF_CT_PROTO_GRE
1855 return nf_conntrack_gre_packet(ct
, skb
, dataoff
,
1860 return generic_packet(ct
, skb
, ctinfo
);
1864 nf_conntrack_in(struct sk_buff
*skb
, const struct nf_hook_state
*state
)
1866 enum ip_conntrack_info ctinfo
;
1867 struct nf_conn
*ct
, *tmpl
;
1871 tmpl
= nf_ct_get(skb
, &ctinfo
);
1872 if (tmpl
|| ctinfo
== IP_CT_UNTRACKED
) {
1873 /* Previously seen (loopback or untracked)? Ignore. */
1874 if ((tmpl
&& !nf_ct_is_template(tmpl
)) ||
1875 ctinfo
== IP_CT_UNTRACKED
)
1880 /* rcu_read_lock()ed by nf_hook_thresh */
1881 dataoff
= get_l4proto(skb
, skb_network_offset(skb
), state
->pf
, &protonum
);
1883 pr_debug("not prepared to track yet or error occurred\n");
1884 NF_CT_STAT_INC_ATOMIC(state
->net
, invalid
);
1889 if (protonum
== IPPROTO_ICMP
|| protonum
== IPPROTO_ICMPV6
) {
1890 ret
= nf_conntrack_handle_icmp(tmpl
, skb
, dataoff
,
1896 /* ICMP[v6] protocol trackers may assign one conntrack. */
1901 ret
= resolve_normal_ct(tmpl
, skb
, dataoff
,
1904 /* Too stressed to deal. */
1905 NF_CT_STAT_INC_ATOMIC(state
->net
, drop
);
1910 ct
= nf_ct_get(skb
, &ctinfo
);
1912 /* Not valid part of a connection */
1913 NF_CT_STAT_INC_ATOMIC(state
->net
, invalid
);
1918 ret
= nf_conntrack_handle_packet(ct
, skb
, dataoff
, ctinfo
, state
);
1920 /* Invalid: inverse of the return code tells
1921 * the netfilter core what to do */
1922 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1923 nf_conntrack_put(&ct
->ct_general
);
1925 NF_CT_STAT_INC_ATOMIC(state
->net
, invalid
);
1926 if (ret
== -NF_DROP
)
1927 NF_CT_STAT_INC_ATOMIC(state
->net
, drop
);
1928 /* Special case: TCP tracker reports an attempt to reopen a
1929 * closed/aborted connection. We have to go back and create a
1932 if (ret
== -NF_REPEAT
)
1938 if (ctinfo
== IP_CT_ESTABLISHED_REPLY
&&
1939 !test_and_set_bit(IPS_SEEN_REPLY_BIT
, &ct
->status
))
1940 nf_conntrack_event_cache(IPCT_REPLY
, ct
);
1947 EXPORT_SYMBOL_GPL(nf_conntrack_in
);
1949 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1950 implicitly racy: see __nf_conntrack_confirm */
1951 void nf_conntrack_alter_reply(struct nf_conn
*ct
,
1952 const struct nf_conntrack_tuple
*newreply
)
1954 struct nf_conn_help
*help
= nfct_help(ct
);
1956 /* Should be unconfirmed, so not in hash table yet */
1957 WARN_ON(nf_ct_is_confirmed(ct
));
1959 pr_debug("Altering reply tuple of %p to ", ct
);
1960 nf_ct_dump_tuple(newreply
);
1962 ct
->tuplehash
[IP_CT_DIR_REPLY
].tuple
= *newreply
;
1963 if (ct
->master
|| (help
&& !hlist_empty(&help
->expectations
)))
1967 __nf_ct_try_assign_helper(ct
, NULL
, GFP_ATOMIC
);
1970 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply
);
1972 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1973 void __nf_ct_refresh_acct(struct nf_conn
*ct
,
1974 enum ip_conntrack_info ctinfo
,
1975 const struct sk_buff
*skb
,
1979 /* Only update if this is not a fixed timeout */
1980 if (test_bit(IPS_FIXED_TIMEOUT_BIT
, &ct
->status
))
1983 /* If not in hash table, timer will not be active yet */
1984 if (nf_ct_is_confirmed(ct
))
1985 extra_jiffies
+= nfct_time_stamp
;
1987 if (READ_ONCE(ct
->timeout
) != extra_jiffies
)
1988 WRITE_ONCE(ct
->timeout
, extra_jiffies
);
1991 nf_ct_acct_update(ct
, CTINFO2DIR(ctinfo
), skb
->len
);
1993 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct
);
1995 bool nf_ct_kill_acct(struct nf_conn
*ct
,
1996 enum ip_conntrack_info ctinfo
,
1997 const struct sk_buff
*skb
)
1999 nf_ct_acct_update(ct
, CTINFO2DIR(ctinfo
), skb
->len
);
2001 return nf_ct_delete(ct
, 0, 0);
2003 EXPORT_SYMBOL_GPL(nf_ct_kill_acct
);
2005 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
2007 #include <linux/netfilter/nfnetlink.h>
2008 #include <linux/netfilter/nfnetlink_conntrack.h>
2009 #include <linux/mutex.h>
2011 /* Generic function for tcp/udp/sctp/dccp and alike. */
2012 int nf_ct_port_tuple_to_nlattr(struct sk_buff
*skb
,
2013 const struct nf_conntrack_tuple
*tuple
)
2015 if (nla_put_be16(skb
, CTA_PROTO_SRC_PORT
, tuple
->src
.u
.tcp
.port
) ||
2016 nla_put_be16(skb
, CTA_PROTO_DST_PORT
, tuple
->dst
.u
.tcp
.port
))
2017 goto nla_put_failure
;
2023 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr
);
2025 const struct nla_policy nf_ct_port_nla_policy
[CTA_PROTO_MAX
+1] = {
2026 [CTA_PROTO_SRC_PORT
] = { .type
= NLA_U16
},
2027 [CTA_PROTO_DST_PORT
] = { .type
= NLA_U16
},
2029 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy
);
2031 int nf_ct_port_nlattr_to_tuple(struct nlattr
*tb
[],
2032 struct nf_conntrack_tuple
*t
,
2035 if (flags
& CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT
)) {
2036 if (!tb
[CTA_PROTO_SRC_PORT
])
2039 t
->src
.u
.tcp
.port
= nla_get_be16(tb
[CTA_PROTO_SRC_PORT
]);
2042 if (flags
& CTA_FILTER_FLAG(CTA_PROTO_DST_PORT
)) {
2043 if (!tb
[CTA_PROTO_DST_PORT
])
2046 t
->dst
.u
.tcp
.port
= nla_get_be16(tb
[CTA_PROTO_DST_PORT
]);
2051 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple
);
2053 unsigned int nf_ct_port_nlattr_tuple_size(void)
2055 static unsigned int size __read_mostly
;
2058 size
= nla_policy_len(nf_ct_port_nla_policy
, CTA_PROTO_MAX
+ 1);
2062 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size
);
2065 /* Used by ipt_REJECT and ip6t_REJECT. */
2066 static void nf_conntrack_attach(struct sk_buff
*nskb
, const struct sk_buff
*skb
)
2069 enum ip_conntrack_info ctinfo
;
2071 /* This ICMP is in reverse direction to the packet which caused it */
2072 ct
= nf_ct_get(skb
, &ctinfo
);
2073 if (CTINFO2DIR(ctinfo
) == IP_CT_DIR_ORIGINAL
)
2074 ctinfo
= IP_CT_RELATED_REPLY
;
2076 ctinfo
= IP_CT_RELATED
;
2078 /* Attach to new skbuff, and increment count */
2079 nf_ct_set(nskb
, ct
, ctinfo
);
2080 nf_conntrack_get(skb_nfct(nskb
));
2083 static int __nf_conntrack_update(struct net
*net
, struct sk_buff
*skb
,
2085 enum ip_conntrack_info ctinfo
)
2087 struct nf_conntrack_tuple_hash
*h
;
2088 struct nf_conntrack_tuple tuple
;
2089 struct nf_nat_hook
*nat_hook
;
2090 unsigned int status
;
2095 l3num
= nf_ct_l3num(ct
);
2097 dataoff
= get_l4proto(skb
, skb_network_offset(skb
), l3num
, &l4num
);
2101 if (!nf_ct_get_tuple(skb
, skb_network_offset(skb
), dataoff
, l3num
,
2102 l4num
, net
, &tuple
))
2105 if (ct
->status
& IPS_SRC_NAT
) {
2106 memcpy(tuple
.src
.u3
.all
,
2107 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
.src
.u3
.all
,
2108 sizeof(tuple
.src
.u3
.all
));
2110 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
.src
.u
.all
;
2113 if (ct
->status
& IPS_DST_NAT
) {
2114 memcpy(tuple
.dst
.u3
.all
,
2115 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
.dst
.u3
.all
,
2116 sizeof(tuple
.dst
.u3
.all
));
2118 ct
->tuplehash
[IP_CT_DIR_ORIGINAL
].tuple
.dst
.u
.all
;
2121 h
= nf_conntrack_find_get(net
, nf_ct_zone(ct
), &tuple
);
2125 /* Store status bits of the conntrack that is clashing to re-do NAT
2126 * mangling according to what it has been done already to this packet.
2128 status
= ct
->status
;
2131 ct
= nf_ct_tuplehash_to_ctrack(h
);
2132 nf_ct_set(skb
, ct
, ctinfo
);
2134 nat_hook
= rcu_dereference(nf_nat_hook
);
2138 if (status
& IPS_SRC_NAT
&&
2139 nat_hook
->manip_pkt(skb
, ct
, NF_NAT_MANIP_SRC
,
2140 IP_CT_DIR_ORIGINAL
) == NF_DROP
)
2143 if (status
& IPS_DST_NAT
&&
2144 nat_hook
->manip_pkt(skb
, ct
, NF_NAT_MANIP_DST
,
2145 IP_CT_DIR_ORIGINAL
) == NF_DROP
)
2151 /* This packet is coming from userspace via nf_queue, complete the packet
2152 * processing after the helper invocation in nf_confirm().
2154 static int nf_confirm_cthelper(struct sk_buff
*skb
, struct nf_conn
*ct
,
2155 enum ip_conntrack_info ctinfo
)
2157 const struct nf_conntrack_helper
*helper
;
2158 const struct nf_conn_help
*help
;
2161 help
= nfct_help(ct
);
2165 helper
= rcu_dereference(help
->helper
);
2166 if (!(helper
->flags
& NF_CT_HELPER_F_USERSPACE
))
2169 switch (nf_ct_l3num(ct
)) {
2171 protoff
= skb_network_offset(skb
) + ip_hdrlen(skb
);
2173 #if IS_ENABLED(CONFIG_IPV6)
2174 case NFPROTO_IPV6
: {
2178 pnum
= ipv6_hdr(skb
)->nexthdr
;
2179 protoff
= ipv6_skip_exthdr(skb
, sizeof(struct ipv6hdr
), &pnum
,
2181 if (protoff
< 0 || (frag_off
& htons(~0x7)) != 0)
2190 if (test_bit(IPS_SEQ_ADJUST_BIT
, &ct
->status
) &&
2191 !nf_is_loopback_packet(skb
)) {
2192 if (!nf_ct_seq_adjust(skb
, ct
, ctinfo
, protoff
)) {
2193 NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct
), drop
);
2198 /* We've seen it coming out the other side: confirm it */
2199 return nf_conntrack_confirm(skb
) == NF_DROP
? - 1 : 0;
2202 static int nf_conntrack_update(struct net
*net
, struct sk_buff
*skb
)
2204 enum ip_conntrack_info ctinfo
;
2208 ct
= nf_ct_get(skb
, &ctinfo
);
2212 if (!nf_ct_is_confirmed(ct
)) {
2213 err
= __nf_conntrack_update(net
, skb
, ct
, ctinfo
);
2217 ct
= nf_ct_get(skb
, &ctinfo
);
2220 return nf_confirm_cthelper(skb
, ct
, ctinfo
);
2223 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple
*dst_tuple
,
2224 const struct sk_buff
*skb
)
2226 const struct nf_conntrack_tuple
*src_tuple
;
2227 const struct nf_conntrack_tuple_hash
*hash
;
2228 struct nf_conntrack_tuple srctuple
;
2229 enum ip_conntrack_info ctinfo
;
2232 ct
= nf_ct_get(skb
, &ctinfo
);
2234 src_tuple
= nf_ct_tuple(ct
, CTINFO2DIR(ctinfo
));
2235 memcpy(dst_tuple
, src_tuple
, sizeof(*dst_tuple
));
2239 if (!nf_ct_get_tuplepr(skb
, skb_network_offset(skb
),
2240 NFPROTO_IPV4
, dev_net(skb
->dev
),
2244 hash
= nf_conntrack_find_get(dev_net(skb
->dev
),
2250 ct
= nf_ct_tuplehash_to_ctrack(hash
);
2251 src_tuple
= nf_ct_tuple(ct
, !hash
->tuple
.dst
.dir
);
2252 memcpy(dst_tuple
, src_tuple
, sizeof(*dst_tuple
));
2258 /* Bring out ya dead! */
2259 static struct nf_conn
*
2260 get_next_corpse(int (*iter
)(struct nf_conn
*i
, void *data
),
2261 void *data
, unsigned int *bucket
)
2263 struct nf_conntrack_tuple_hash
*h
;
2265 struct hlist_nulls_node
*n
;
2268 for (; *bucket
< nf_conntrack_htable_size
; (*bucket
)++) {
2269 struct hlist_nulls_head
*hslot
= &nf_conntrack_hash
[*bucket
];
2271 if (hlist_nulls_empty(hslot
))
2274 lockp
= &nf_conntrack_locks
[*bucket
% CONNTRACK_LOCKS
];
2276 nf_conntrack_lock(lockp
);
2277 hlist_nulls_for_each_entry(h
, n
, hslot
, hnnode
) {
2278 if (NF_CT_DIRECTION(h
) != IP_CT_DIR_REPLY
)
2280 /* All nf_conn objects are added to hash table twice, one
2281 * for original direction tuple, once for the reply tuple.
2283 * Exception: In the IPS_NAT_CLASH case, only the reply
2284 * tuple is added (the original tuple already existed for
2285 * a different object).
2287 * We only need to call the iterator once for each
2288 * conntrack, so we just use the 'reply' direction
2289 * tuple while iterating.
2291 ct
= nf_ct_tuplehash_to_ctrack(h
);
2302 atomic_inc(&ct
->ct_general
.use
);
2308 static void nf_ct_iterate_cleanup(int (*iter
)(struct nf_conn
*i
, void *data
),
2309 void *data
, u32 portid
, int report
)
2311 unsigned int bucket
= 0;
2316 mutex_lock(&nf_conntrack_mutex
);
2317 while ((ct
= get_next_corpse(iter
, data
, &bucket
)) != NULL
) {
2318 /* Time to push up daises... */
2320 nf_ct_delete(ct
, portid
, report
);
2324 mutex_unlock(&nf_conntrack_mutex
);
2328 int (*iter
)(struct nf_conn
*i
, void *data
);
2333 static int iter_net_only(struct nf_conn
*i
, void *data
)
2335 struct iter_data
*d
= data
;
2337 if (!net_eq(d
->net
, nf_ct_net(i
)))
2340 return d
->iter(i
, d
->data
);
2344 __nf_ct_unconfirmed_destroy(struct net
*net
)
2348 for_each_possible_cpu(cpu
) {
2349 struct nf_conntrack_tuple_hash
*h
;
2350 struct hlist_nulls_node
*n
;
2351 struct ct_pcpu
*pcpu
;
2353 pcpu
= per_cpu_ptr(net
->ct
.pcpu_lists
, cpu
);
2355 spin_lock_bh(&pcpu
->lock
);
2356 hlist_nulls_for_each_entry(h
, n
, &pcpu
->unconfirmed
, hnnode
) {
2359 ct
= nf_ct_tuplehash_to_ctrack(h
);
2361 /* we cannot call iter() on unconfirmed list, the
2362 * owning cpu can reallocate ct->ext at any time.
2364 set_bit(IPS_DYING_BIT
, &ct
->status
);
2366 spin_unlock_bh(&pcpu
->lock
);
2371 void nf_ct_unconfirmed_destroy(struct net
*net
)
2373 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
2377 if (atomic_read(&cnet
->count
) > 0) {
2378 __nf_ct_unconfirmed_destroy(net
);
2379 nf_queue_nf_hook_drop(net
);
2383 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy
);
2385 void nf_ct_iterate_cleanup_net(struct net
*net
,
2386 int (*iter
)(struct nf_conn
*i
, void *data
),
2387 void *data
, u32 portid
, int report
)
2389 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
2394 if (atomic_read(&cnet
->count
) == 0)
2401 nf_ct_iterate_cleanup(iter_net_only
, &d
, portid
, report
);
2403 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net
);
2406 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2407 * @iter: callback to invoke for each conntrack
2408 * @data: data to pass to @iter
2410 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2411 * unconfirmed list as dying (so they will not be inserted into
2414 * Can only be called in module exit path.
2417 nf_ct_iterate_destroy(int (*iter
)(struct nf_conn
*i
, void *data
), void *data
)
2421 down_read(&net_rwsem
);
2423 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
2425 if (atomic_read(&cnet
->count
) == 0)
2427 __nf_ct_unconfirmed_destroy(net
);
2428 nf_queue_nf_hook_drop(net
);
2430 up_read(&net_rwsem
);
2432 /* Need to wait for netns cleanup worker to finish, if its
2433 * running -- it might have deleted a net namespace from
2434 * the global list, so our __nf_ct_unconfirmed_destroy() might
2435 * not have affected all namespaces.
2439 /* a conntrack could have been unlinked from unconfirmed list
2440 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2441 * This makes sure its inserted into conntrack table.
2445 nf_ct_iterate_cleanup(iter
, data
, 0, 0);
2447 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy
);
2449 static int kill_all(struct nf_conn
*i
, void *data
)
2451 return net_eq(nf_ct_net(i
), data
);
2454 void nf_conntrack_cleanup_start(void)
2456 conntrack_gc_work
.exiting
= true;
2457 RCU_INIT_POINTER(ip_ct_attach
, NULL
);
2460 void nf_conntrack_cleanup_end(void)
2462 RCU_INIT_POINTER(nf_ct_hook
, NULL
);
2463 cancel_delayed_work_sync(&conntrack_gc_work
.dwork
);
2464 kvfree(nf_conntrack_hash
);
2466 nf_conntrack_proto_fini();
2467 nf_conntrack_seqadj_fini();
2468 nf_conntrack_labels_fini();
2469 nf_conntrack_helper_fini();
2470 nf_conntrack_timeout_fini();
2471 nf_conntrack_ecache_fini();
2472 nf_conntrack_tstamp_fini();
2473 nf_conntrack_acct_fini();
2474 nf_conntrack_expect_fini();
2476 kmem_cache_destroy(nf_conntrack_cachep
);
2480 * Mishearing the voices in his head, our hero wonders how he's
2481 * supposed to kill the mall.
2483 void nf_conntrack_cleanup_net(struct net
*net
)
2487 list_add(&net
->exit_list
, &single
);
2488 nf_conntrack_cleanup_net_list(&single
);
2491 void nf_conntrack_cleanup_net_list(struct list_head
*net_exit_list
)
2497 * This makes sure all current packets have passed through
2498 * netfilter framework. Roll on, two-stage module
2504 list_for_each_entry(net
, net_exit_list
, exit_list
) {
2505 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
2507 nf_ct_iterate_cleanup(kill_all
, net
, 0, 0);
2508 if (atomic_read(&cnet
->count
) != 0)
2513 goto i_see_dead_people
;
2516 list_for_each_entry(net
, net_exit_list
, exit_list
) {
2517 nf_conntrack_ecache_pernet_fini(net
);
2518 nf_conntrack_expect_pernet_fini(net
);
2519 free_percpu(net
->ct
.stat
);
2520 free_percpu(net
->ct
.pcpu_lists
);
2524 void *nf_ct_alloc_hashtable(unsigned int *sizep
, int nulls
)
2526 struct hlist_nulls_head
*hash
;
2527 unsigned int nr_slots
, i
;
2529 if (*sizep
> (UINT_MAX
/ sizeof(struct hlist_nulls_head
)))
2532 BUILD_BUG_ON(sizeof(struct hlist_nulls_head
) != sizeof(struct hlist_head
));
2533 nr_slots
= *sizep
= roundup(*sizep
, PAGE_SIZE
/ sizeof(struct hlist_nulls_head
));
2535 hash
= kvcalloc(nr_slots
, sizeof(struct hlist_nulls_head
), GFP_KERNEL
);
2538 for (i
= 0; i
< nr_slots
; i
++)
2539 INIT_HLIST_NULLS_HEAD(&hash
[i
], i
);
2543 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable
);
2545 int nf_conntrack_hash_resize(unsigned int hashsize
)
2548 unsigned int old_size
;
2549 struct hlist_nulls_head
*hash
, *old_hash
;
2550 struct nf_conntrack_tuple_hash
*h
;
2556 hash
= nf_ct_alloc_hashtable(&hashsize
, 1);
2560 mutex_lock(&nf_conntrack_mutex
);
2561 old_size
= nf_conntrack_htable_size
;
2562 if (old_size
== hashsize
) {
2563 mutex_unlock(&nf_conntrack_mutex
);
2569 nf_conntrack_all_lock();
2570 write_seqcount_begin(&nf_conntrack_generation
);
2572 /* Lookups in the old hash might happen in parallel, which means we
2573 * might get false negatives during connection lookup. New connections
2574 * created because of a false negative won't make it into the hash
2575 * though since that required taking the locks.
2578 for (i
= 0; i
< nf_conntrack_htable_size
; i
++) {
2579 while (!hlist_nulls_empty(&nf_conntrack_hash
[i
])) {
2580 unsigned int zone_id
;
2582 h
= hlist_nulls_entry(nf_conntrack_hash
[i
].first
,
2583 struct nf_conntrack_tuple_hash
, hnnode
);
2584 ct
= nf_ct_tuplehash_to_ctrack(h
);
2585 hlist_nulls_del_rcu(&h
->hnnode
);
2587 zone_id
= nf_ct_zone_id(nf_ct_zone(ct
), NF_CT_DIRECTION(h
));
2588 bucket
= __hash_conntrack(nf_ct_net(ct
),
2589 &h
->tuple
, zone_id
, hashsize
);
2590 hlist_nulls_add_head_rcu(&h
->hnnode
, &hash
[bucket
]);
2593 old_size
= nf_conntrack_htable_size
;
2594 old_hash
= nf_conntrack_hash
;
2596 nf_conntrack_hash
= hash
;
2597 nf_conntrack_htable_size
= hashsize
;
2599 write_seqcount_end(&nf_conntrack_generation
);
2600 nf_conntrack_all_unlock();
2603 mutex_unlock(&nf_conntrack_mutex
);
2610 int nf_conntrack_set_hashsize(const char *val
, const struct kernel_param
*kp
)
2612 unsigned int hashsize
;
2615 if (current
->nsproxy
->net_ns
!= &init_net
)
2618 /* On boot, we can set this without any fancy locking. */
2619 if (!nf_conntrack_hash
)
2620 return param_set_uint(val
, kp
);
2622 rc
= kstrtouint(val
, 0, &hashsize
);
2626 return nf_conntrack_hash_resize(hashsize
);
2629 static __always_inline
unsigned int total_extension_size(void)
2631 /* remember to add new extensions below */
2632 BUILD_BUG_ON(NF_CT_EXT_NUM
> 9);
2634 return sizeof(struct nf_ct_ext
) +
2635 sizeof(struct nf_conn_help
)
2636 #if IS_ENABLED(CONFIG_NF_NAT)
2637 + sizeof(struct nf_conn_nat
)
2639 + sizeof(struct nf_conn_seqadj
)
2640 + sizeof(struct nf_conn_acct
)
2641 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2642 + sizeof(struct nf_conntrack_ecache
)
2644 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2645 + sizeof(struct nf_conn_tstamp
)
2647 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2648 + sizeof(struct nf_conn_timeout
)
2650 #ifdef CONFIG_NF_CONNTRACK_LABELS
2651 + sizeof(struct nf_conn_labels
)
2653 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2654 + sizeof(struct nf_conn_synproxy
)
2659 int nf_conntrack_init_start(void)
2661 unsigned long nr_pages
= totalram_pages();
2666 /* struct nf_ct_ext uses u8 to store offsets/size */
2667 BUILD_BUG_ON(total_extension_size() > 255u);
2669 seqcount_spinlock_init(&nf_conntrack_generation
,
2670 &nf_conntrack_locks_all_lock
);
2672 for (i
= 0; i
< CONNTRACK_LOCKS
; i
++)
2673 spin_lock_init(&nf_conntrack_locks
[i
]);
2675 if (!nf_conntrack_htable_size
) {
2676 nf_conntrack_htable_size
2677 = (((nr_pages
<< PAGE_SHIFT
) / 16384)
2678 / sizeof(struct hlist_head
));
2679 if (BITS_PER_LONG
>= 64 &&
2680 nr_pages
> (4 * (1024 * 1024 * 1024 / PAGE_SIZE
)))
2681 nf_conntrack_htable_size
= 262144;
2682 else if (nr_pages
> (1024 * 1024 * 1024 / PAGE_SIZE
))
2683 nf_conntrack_htable_size
= 65536;
2685 if (nf_conntrack_htable_size
< 1024)
2686 nf_conntrack_htable_size
= 1024;
2687 /* Use a max. factor of one by default to keep the average
2688 * hash chain length at 2 entries. Each entry has to be added
2689 * twice (once for original direction, once for reply).
2690 * When a table size is given we use the old value of 8 to
2691 * avoid implicit reduction of the max entries setting.
2696 nf_conntrack_hash
= nf_ct_alloc_hashtable(&nf_conntrack_htable_size
, 1);
2697 if (!nf_conntrack_hash
)
2700 nf_conntrack_max
= max_factor
* nf_conntrack_htable_size
;
2702 nf_conntrack_cachep
= kmem_cache_create("nf_conntrack",
2703 sizeof(struct nf_conn
),
2705 SLAB_TYPESAFE_BY_RCU
| SLAB_HWCACHE_ALIGN
, NULL
);
2706 if (!nf_conntrack_cachep
)
2709 ret
= nf_conntrack_expect_init();
2713 ret
= nf_conntrack_acct_init();
2717 ret
= nf_conntrack_tstamp_init();
2721 ret
= nf_conntrack_ecache_init();
2725 ret
= nf_conntrack_timeout_init();
2729 ret
= nf_conntrack_helper_init();
2733 ret
= nf_conntrack_labels_init();
2737 ret
= nf_conntrack_seqadj_init();
2741 ret
= nf_conntrack_proto_init();
2745 conntrack_gc_work_init(&conntrack_gc_work
);
2746 queue_delayed_work(system_power_efficient_wq
, &conntrack_gc_work
.dwork
, HZ
);
2751 nf_conntrack_seqadj_fini();
2753 nf_conntrack_labels_fini();
2755 nf_conntrack_helper_fini();
2757 nf_conntrack_timeout_fini();
2759 nf_conntrack_ecache_fini();
2761 nf_conntrack_tstamp_fini();
2763 nf_conntrack_acct_fini();
2765 nf_conntrack_expect_fini();
2767 kmem_cache_destroy(nf_conntrack_cachep
);
2769 kvfree(nf_conntrack_hash
);
2773 static struct nf_ct_hook nf_conntrack_hook
= {
2774 .update
= nf_conntrack_update
,
2775 .destroy
= destroy_conntrack
,
2776 .get_tuple_skb
= nf_conntrack_get_tuple_skb
,
2779 void nf_conntrack_init_end(void)
2781 /* For use by REJECT target */
2782 RCU_INIT_POINTER(ip_ct_attach
, nf_conntrack_attach
);
2783 RCU_INIT_POINTER(nf_ct_hook
, &nf_conntrack_hook
);
2787 * We need to use special "null" values, not used in hash table
2789 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2790 #define DYING_NULLS_VAL ((1<<30)+1)
2792 int nf_conntrack_init_net(struct net
*net
)
2794 struct nf_conntrack_net
*cnet
= nf_ct_pernet(net
);
2798 BUILD_BUG_ON(IP_CT_UNTRACKED
== IP_CT_NUMBER
);
2799 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS
);
2800 atomic_set(&cnet
->count
, 0);
2802 net
->ct
.pcpu_lists
= alloc_percpu(struct ct_pcpu
);
2803 if (!net
->ct
.pcpu_lists
)
2806 for_each_possible_cpu(cpu
) {
2807 struct ct_pcpu
*pcpu
= per_cpu_ptr(net
->ct
.pcpu_lists
, cpu
);
2809 spin_lock_init(&pcpu
->lock
);
2810 INIT_HLIST_NULLS_HEAD(&pcpu
->unconfirmed
, UNCONFIRMED_NULLS_VAL
);
2811 INIT_HLIST_NULLS_HEAD(&pcpu
->dying
, DYING_NULLS_VAL
);
2814 net
->ct
.stat
= alloc_percpu(struct ip_conntrack_stat
);
2816 goto err_pcpu_lists
;
2818 ret
= nf_conntrack_expect_pernet_init(net
);
2822 nf_conntrack_acct_pernet_init(net
);
2823 nf_conntrack_tstamp_pernet_init(net
);
2824 nf_conntrack_ecache_pernet_init(net
);
2825 nf_conntrack_helper_pernet_init(net
);
2826 nf_conntrack_proto_pernet_init(net
);
2831 free_percpu(net
->ct
.stat
);
2833 free_percpu(net
->ct
.pcpu_lists
);