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