GNU Linux-libre 4.9.337-gnu1
[releases.git] / net / netfilter / xt_hashlimit.c
1 /*
2  *      xt_hashlimit - Netfilter module to limit the number of packets per time
3  *      separately for each hashbucket (sourceip/sourceport/dstip/dstport)
4  *
5  *      (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
6  *      (C) 2006-2012 Patrick McHardy <kaber@trash.net>
7  *      Copyright © CC Computer Consultants GmbH, 2007 - 2008
8  *
9  * Development of this code was funded by Astaro AG, http://www.astaro.com/
10  */
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/module.h>
13 #include <linux/spinlock.h>
14 #include <linux/random.h>
15 #include <linux/jhash.h>
16 #include <linux/slab.h>
17 #include <linux/vmalloc.h>
18 #include <linux/proc_fs.h>
19 #include <linux/seq_file.h>
20 #include <linux/list.h>
21 #include <linux/skbuff.h>
22 #include <linux/mm.h>
23 #include <linux/in.h>
24 #include <linux/ip.h>
25 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
26 #include <linux/ipv6.h>
27 #include <net/ipv6.h>
28 #endif
29
30 #include <net/net_namespace.h>
31 #include <net/netns/generic.h>
32
33 #include <linux/netfilter/x_tables.h>
34 #include <linux/netfilter_ipv4/ip_tables.h>
35 #include <linux/netfilter_ipv6/ip6_tables.h>
36 #include <linux/netfilter/xt_hashlimit.h>
37 #include <linux/mutex.h>
38
39 MODULE_LICENSE("GPL");
40 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
41 MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
42 MODULE_DESCRIPTION("Xtables: per hash-bucket rate-limit match");
43 MODULE_ALIAS("ipt_hashlimit");
44 MODULE_ALIAS("ip6t_hashlimit");
45
46 struct hashlimit_net {
47         struct hlist_head       htables;
48         struct proc_dir_entry   *ipt_hashlimit;
49         struct proc_dir_entry   *ip6t_hashlimit;
50 };
51
52 static int hashlimit_net_id;
53 static inline struct hashlimit_net *hashlimit_pernet(struct net *net)
54 {
55         return net_generic(net, hashlimit_net_id);
56 }
57
58 /* need to declare this at the top */
59 static const struct file_operations dl_file_ops_v1;
60 static const struct file_operations dl_file_ops;
61
62 /* hash table crap */
63 struct dsthash_dst {
64         union {
65                 struct {
66                         __be32 src;
67                         __be32 dst;
68                 } ip;
69 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
70                 struct {
71                         __be32 src[4];
72                         __be32 dst[4];
73                 } ip6;
74 #endif
75         };
76         __be16 src_port;
77         __be16 dst_port;
78 };
79
80 struct dsthash_ent {
81         /* static / read-only parts in the beginning */
82         struct hlist_node node;
83         struct dsthash_dst dst;
84
85         /* modified structure members in the end */
86         spinlock_t lock;
87         unsigned long expires;          /* precalculated expiry time */
88         struct {
89                 unsigned long prev;     /* last modification */
90                 u_int64_t credit;
91                 u_int64_t credit_cap, cost;
92         } rateinfo;
93         struct rcu_head rcu;
94 };
95
96 struct xt_hashlimit_htable {
97         struct hlist_node node;         /* global list of all htables */
98         int use;
99         u_int8_t family;
100         bool rnd_initialized;
101
102         struct hashlimit_cfg2 cfg;      /* config */
103
104         /* used internally */
105         spinlock_t lock;                /* lock for list_head */
106         u_int32_t rnd;                  /* random seed for hash */
107         unsigned int count;             /* number entries in table */
108         struct delayed_work gc_work;
109
110         /* seq_file stuff */
111         struct proc_dir_entry *pde;
112         const char *name;
113         struct net *net;
114
115         struct hlist_head hash[0];      /* hashtable itself */
116 };
117
118 static int
119 cfg_copy(struct hashlimit_cfg2 *to, void *from, int revision)
120 {
121         if (revision == 1) {
122                 struct hashlimit_cfg1 *cfg = (struct hashlimit_cfg1 *)from;
123
124                 to->mode = cfg->mode;
125                 to->avg = cfg->avg;
126                 to->burst = cfg->burst;
127                 to->size = cfg->size;
128                 to->max = cfg->max;
129                 to->gc_interval = cfg->gc_interval;
130                 to->expire = cfg->expire;
131                 to->srcmask = cfg->srcmask;
132                 to->dstmask = cfg->dstmask;
133         } else if (revision == 2) {
134                 memcpy(to, from, sizeof(struct hashlimit_cfg2));
135         } else {
136                 return -EINVAL;
137         }
138
139         return 0;
140 }
141
142 static DEFINE_MUTEX(hashlimit_mutex);   /* protects htables list */
143 static struct kmem_cache *hashlimit_cachep __read_mostly;
144
145 static inline bool dst_cmp(const struct dsthash_ent *ent,
146                            const struct dsthash_dst *b)
147 {
148         return !memcmp(&ent->dst, b, sizeof(ent->dst));
149 }
150
151 static u_int32_t
152 hash_dst(const struct xt_hashlimit_htable *ht, const struct dsthash_dst *dst)
153 {
154         u_int32_t hash = jhash2((const u32 *)dst,
155                                 sizeof(*dst)/sizeof(u32),
156                                 ht->rnd);
157         /*
158          * Instead of returning hash % ht->cfg.size (implying a divide)
159          * we return the high 32 bits of the (hash * ht->cfg.size) that will
160          * give results between [0 and cfg.size-1] and same hash distribution,
161          * but using a multiply, less expensive than a divide
162          */
163         return reciprocal_scale(hash, ht->cfg.size);
164 }
165
166 static struct dsthash_ent *
167 dsthash_find(const struct xt_hashlimit_htable *ht,
168              const struct dsthash_dst *dst)
169 {
170         struct dsthash_ent *ent;
171         u_int32_t hash = hash_dst(ht, dst);
172
173         if (!hlist_empty(&ht->hash[hash])) {
174                 hlist_for_each_entry_rcu(ent, &ht->hash[hash], node)
175                         if (dst_cmp(ent, dst)) {
176                                 spin_lock(&ent->lock);
177                                 return ent;
178                         }
179         }
180         return NULL;
181 }
182
183 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
184 static struct dsthash_ent *
185 dsthash_alloc_init(struct xt_hashlimit_htable *ht,
186                    const struct dsthash_dst *dst, bool *race)
187 {
188         struct dsthash_ent *ent;
189
190         spin_lock(&ht->lock);
191
192         /* Two or more packets may race to create the same entry in the
193          * hashtable, double check if this packet lost race.
194          */
195         ent = dsthash_find(ht, dst);
196         if (ent != NULL) {
197                 spin_unlock(&ht->lock);
198                 *race = true;
199                 return ent;
200         }
201
202         /* initialize hash with random val at the time we allocate
203          * the first hashtable entry */
204         if (unlikely(!ht->rnd_initialized)) {
205                 get_random_bytes(&ht->rnd, sizeof(ht->rnd));
206                 ht->rnd_initialized = true;
207         }
208
209         if (ht->cfg.max && ht->count >= ht->cfg.max) {
210                 /* FIXME: do something. question is what.. */
211                 net_err_ratelimited("max count of %u reached\n", ht->cfg.max);
212                 ent = NULL;
213         } else
214                 ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
215         if (ent) {
216                 memcpy(&ent->dst, dst, sizeof(ent->dst));
217                 spin_lock_init(&ent->lock);
218
219                 spin_lock(&ent->lock);
220                 hlist_add_head_rcu(&ent->node, &ht->hash[hash_dst(ht, dst)]);
221                 ht->count++;
222         }
223         spin_unlock(&ht->lock);
224         return ent;
225 }
226
227 static void dsthash_free_rcu(struct rcu_head *head)
228 {
229         struct dsthash_ent *ent = container_of(head, struct dsthash_ent, rcu);
230
231         kmem_cache_free(hashlimit_cachep, ent);
232 }
233
234 static inline void
235 dsthash_free(struct xt_hashlimit_htable *ht, struct dsthash_ent *ent)
236 {
237         hlist_del_rcu(&ent->node);
238         call_rcu_bh(&ent->rcu, dsthash_free_rcu);
239         ht->count--;
240 }
241 static void htable_gc(struct work_struct *work);
242
243 static int htable_create(struct net *net, struct hashlimit_cfg2 *cfg,
244                          const char *name, u_int8_t family,
245                          struct xt_hashlimit_htable **out_hinfo,
246                          int revision)
247 {
248         struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
249         struct xt_hashlimit_htable *hinfo;
250         unsigned int size, i;
251         int ret;
252
253         if (cfg->size) {
254                 size = cfg->size;
255         } else {
256                 size = (totalram_pages << PAGE_SHIFT) / 16384 /
257                        sizeof(struct list_head);
258                 if (totalram_pages > 1024 * 1024 * 1024 / PAGE_SIZE)
259                         size = 8192;
260                 if (size < 16)
261                         size = 16;
262         }
263         /* FIXME: don't use vmalloc() here or anywhere else -HW */
264         hinfo = vmalloc(sizeof(struct xt_hashlimit_htable) +
265                         sizeof(struct list_head) * size);
266         if (hinfo == NULL)
267                 return -ENOMEM;
268         *out_hinfo = hinfo;
269
270         /* copy match config into hashtable config */
271         ret = cfg_copy(&hinfo->cfg, (void *)cfg, 2);
272
273         if (ret)
274                 return ret;
275
276         hinfo->cfg.size = size;
277         if (hinfo->cfg.max == 0)
278                 hinfo->cfg.max = 8 * hinfo->cfg.size;
279         else if (hinfo->cfg.max < hinfo->cfg.size)
280                 hinfo->cfg.max = hinfo->cfg.size;
281
282         for (i = 0; i < hinfo->cfg.size; i++)
283                 INIT_HLIST_HEAD(&hinfo->hash[i]);
284
285         hinfo->use = 1;
286         hinfo->count = 0;
287         hinfo->family = family;
288         hinfo->rnd_initialized = false;
289         hinfo->name = kstrdup(name, GFP_KERNEL);
290         if (!hinfo->name) {
291                 vfree(hinfo);
292                 return -ENOMEM;
293         }
294         spin_lock_init(&hinfo->lock);
295
296         hinfo->pde = proc_create_data(name, 0,
297                 (family == NFPROTO_IPV4) ?
298                 hashlimit_net->ipt_hashlimit : hashlimit_net->ip6t_hashlimit,
299                 (revision == 1) ? &dl_file_ops_v1 : &dl_file_ops,
300                 hinfo);
301         if (hinfo->pde == NULL) {
302                 kfree(hinfo->name);
303                 vfree(hinfo);
304                 return -ENOMEM;
305         }
306         hinfo->net = net;
307
308         INIT_DEFERRABLE_WORK(&hinfo->gc_work, htable_gc);
309         queue_delayed_work(system_power_efficient_wq, &hinfo->gc_work,
310                            msecs_to_jiffies(hinfo->cfg.gc_interval));
311
312         hlist_add_head(&hinfo->node, &hashlimit_net->htables);
313
314         return 0;
315 }
316
317 static bool select_all(const struct xt_hashlimit_htable *ht,
318                        const struct dsthash_ent *he)
319 {
320         return 1;
321 }
322
323 static bool select_gc(const struct xt_hashlimit_htable *ht,
324                       const struct dsthash_ent *he)
325 {
326         return time_after_eq(jiffies, he->expires);
327 }
328
329 static void htable_selective_cleanup(struct xt_hashlimit_htable *ht,
330                         bool (*select)(const struct xt_hashlimit_htable *ht,
331                                       const struct dsthash_ent *he))
332 {
333         unsigned int i;
334
335         for (i = 0; i < ht->cfg.size; i++) {
336                 struct dsthash_ent *dh;
337                 struct hlist_node *n;
338
339                 spin_lock_bh(&ht->lock);
340                 hlist_for_each_entry_safe(dh, n, &ht->hash[i], node) {
341                         if ((*select)(ht, dh))
342                                 dsthash_free(ht, dh);
343                 }
344                 spin_unlock_bh(&ht->lock);
345                 cond_resched();
346         }
347 }
348
349 static void htable_gc(struct work_struct *work)
350 {
351         struct xt_hashlimit_htable *ht;
352
353         ht = container_of(work, struct xt_hashlimit_htable, gc_work.work);
354
355         htable_selective_cleanup(ht, select_gc);
356
357         queue_delayed_work(system_power_efficient_wq,
358                            &ht->gc_work, msecs_to_jiffies(ht->cfg.gc_interval));
359 }
360
361 static void htable_remove_proc_entry(struct xt_hashlimit_htable *hinfo)
362 {
363         struct hashlimit_net *hashlimit_net = hashlimit_pernet(hinfo->net);
364         struct proc_dir_entry *parent;
365
366         if (hinfo->family == NFPROTO_IPV4)
367                 parent = hashlimit_net->ipt_hashlimit;
368         else
369                 parent = hashlimit_net->ip6t_hashlimit;
370
371         if (parent != NULL)
372                 remove_proc_entry(hinfo->name, parent);
373 }
374
375 static void htable_destroy(struct xt_hashlimit_htable *hinfo)
376 {
377         cancel_delayed_work_sync(&hinfo->gc_work);
378         htable_remove_proc_entry(hinfo);
379         htable_selective_cleanup(hinfo, select_all);
380         kfree(hinfo->name);
381         vfree(hinfo);
382 }
383
384 static struct xt_hashlimit_htable *htable_find_get(struct net *net,
385                                                    const char *name,
386                                                    u_int8_t family)
387 {
388         struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
389         struct xt_hashlimit_htable *hinfo;
390
391         hlist_for_each_entry(hinfo, &hashlimit_net->htables, node) {
392                 if (!strcmp(name, hinfo->name) &&
393                     hinfo->family == family) {
394                         hinfo->use++;
395                         return hinfo;
396                 }
397         }
398         return NULL;
399 }
400
401 static void htable_put(struct xt_hashlimit_htable *hinfo)
402 {
403         mutex_lock(&hashlimit_mutex);
404         if (--hinfo->use == 0) {
405                 hlist_del(&hinfo->node);
406                 htable_destroy(hinfo);
407         }
408         mutex_unlock(&hashlimit_mutex);
409 }
410
411 /* The algorithm used is the Simple Token Bucket Filter (TBF)
412  * see net/sched/sch_tbf.c in the linux source tree
413  */
414
415 /* Rusty: This is my (non-mathematically-inclined) understanding of
416    this algorithm.  The `average rate' in jiffies becomes your initial
417    amount of credit `credit' and the most credit you can ever have
418    `credit_cap'.  The `peak rate' becomes the cost of passing the
419    test, `cost'.
420
421    `prev' tracks the last packet hit: you gain one credit per jiffy.
422    If you get credit balance more than this, the extra credit is
423    discarded.  Every time the match passes, you lose `cost' credits;
424    if you don't have that many, the test fails.
425
426    See Alexey's formal explanation in net/sched/sch_tbf.c.
427
428    To get the maximum range, we multiply by this factor (ie. you get N
429    credits per jiffy).  We want to allow a rate as low as 1 per day
430    (slowest userspace tool allows), which means
431    CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
432 */
433 #define MAX_CPJ_v1 (0xFFFFFFFF / (HZ*60*60*24))
434 #define MAX_CPJ (0xFFFFFFFFFFFFFFFFULL / (HZ*60*60*24))
435
436 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
437  * us the power of 2 below the theoretical max, so GCC simply does a
438  * shift. */
439 #define _POW2_BELOW2(x) ((x)|((x)>>1))
440 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
441 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
442 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
443 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
444 #define _POW2_BELOW64(x) (_POW2_BELOW32(x)|_POW2_BELOW32((x)>>32))
445 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
446 #define POW2_BELOW64(x) ((_POW2_BELOW64(x)>>1) + 1)
447
448 #define CREDITS_PER_JIFFY POW2_BELOW64(MAX_CPJ)
449 #define CREDITS_PER_JIFFY_v1 POW2_BELOW32(MAX_CPJ_v1)
450
451 /* in byte mode, the lowest possible rate is one packet/second.
452  * credit_cap is used as a counter that tells us how many times we can
453  * refill the "credits available" counter when it becomes empty.
454  */
455 #define MAX_CPJ_BYTES (0xFFFFFFFF / HZ)
456 #define CREDITS_PER_JIFFY_BYTES POW2_BELOW32(MAX_CPJ_BYTES)
457
458 static u32 xt_hashlimit_len_to_chunks(u32 len)
459 {
460         return (len >> XT_HASHLIMIT_BYTE_SHIFT) + 1;
461 }
462
463 /* Precision saver. */
464 static u64 user2credits(u64 user, int revision)
465 {
466         if (revision == 1) {
467                 /* If multiplying would overflow... */
468                 if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY_v1))
469                         /* Divide first. */
470                         return div64_u64(user, XT_HASHLIMIT_SCALE)
471                                 * HZ * CREDITS_PER_JIFFY_v1;
472
473                 return div64_u64(user * HZ * CREDITS_PER_JIFFY_v1,
474                                  XT_HASHLIMIT_SCALE);
475         } else {
476                 if (user > 0xFFFFFFFFFFFFFFFFULL / (HZ*CREDITS_PER_JIFFY))
477                         return div64_u64(user, XT_HASHLIMIT_SCALE_v2)
478                                 * HZ * CREDITS_PER_JIFFY;
479
480                 return div64_u64(user * HZ * CREDITS_PER_JIFFY,
481                                  XT_HASHLIMIT_SCALE_v2);
482         }
483 }
484
485 static u32 user2credits_byte(u32 user)
486 {
487         u64 us = user;
488         us *= HZ * CREDITS_PER_JIFFY_BYTES;
489         return (u32) (us >> 32);
490 }
491
492 static void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now,
493                             u32 mode, int revision)
494 {
495         unsigned long delta = now - dh->rateinfo.prev;
496         u64 cap, cpj;
497
498         if (delta == 0)
499                 return;
500
501         dh->rateinfo.prev = now;
502
503         if (mode & XT_HASHLIMIT_BYTES) {
504                 u64 tmp = dh->rateinfo.credit;
505                 dh->rateinfo.credit += CREDITS_PER_JIFFY_BYTES * delta;
506                 cap = CREDITS_PER_JIFFY_BYTES * HZ;
507                 if (tmp >= dh->rateinfo.credit) {/* overflow */
508                         dh->rateinfo.credit = cap;
509                         return;
510                 }
511         } else {
512                 cpj = (revision == 1) ?
513                         CREDITS_PER_JIFFY_v1 : CREDITS_PER_JIFFY;
514                 dh->rateinfo.credit += delta * cpj;
515                 cap = dh->rateinfo.credit_cap;
516         }
517         if (dh->rateinfo.credit > cap)
518                 dh->rateinfo.credit = cap;
519 }
520
521 static void rateinfo_init(struct dsthash_ent *dh,
522                           struct xt_hashlimit_htable *hinfo, int revision)
523 {
524         dh->rateinfo.prev = jiffies;
525         if (hinfo->cfg.mode & XT_HASHLIMIT_BYTES) {
526                 dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
527                 dh->rateinfo.cost = user2credits_byte(hinfo->cfg.avg);
528                 dh->rateinfo.credit_cap = hinfo->cfg.burst;
529         } else {
530                 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
531                                                    hinfo->cfg.burst, revision);
532                 dh->rateinfo.cost = user2credits(hinfo->cfg.avg, revision);
533                 dh->rateinfo.credit_cap = dh->rateinfo.credit;
534         }
535 }
536
537 static inline __be32 maskl(__be32 a, unsigned int l)
538 {
539         return l ? htonl(ntohl(a) & ~0 << (32 - l)) : 0;
540 }
541
542 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
543 static void hashlimit_ipv6_mask(__be32 *i, unsigned int p)
544 {
545         switch (p) {
546         case 0 ... 31:
547                 i[0] = maskl(i[0], p);
548                 i[1] = i[2] = i[3] = 0;
549                 break;
550         case 32 ... 63:
551                 i[1] = maskl(i[1], p - 32);
552                 i[2] = i[3] = 0;
553                 break;
554         case 64 ... 95:
555                 i[2] = maskl(i[2], p - 64);
556                 i[3] = 0;
557                 break;
558         case 96 ... 127:
559                 i[3] = maskl(i[3], p - 96);
560                 break;
561         case 128:
562                 break;
563         }
564 }
565 #endif
566
567 static int
568 hashlimit_init_dst(const struct xt_hashlimit_htable *hinfo,
569                    struct dsthash_dst *dst,
570                    const struct sk_buff *skb, unsigned int protoff)
571 {
572         __be16 _ports[2], *ports;
573         u8 nexthdr;
574         int poff;
575
576         memset(dst, 0, sizeof(*dst));
577
578         switch (hinfo->family) {
579         case NFPROTO_IPV4:
580                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
581                         dst->ip.dst = maskl(ip_hdr(skb)->daddr,
582                                       hinfo->cfg.dstmask);
583                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
584                         dst->ip.src = maskl(ip_hdr(skb)->saddr,
585                                       hinfo->cfg.srcmask);
586
587                 if (!(hinfo->cfg.mode &
588                       (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
589                         return 0;
590                 nexthdr = ip_hdr(skb)->protocol;
591                 break;
592 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
593         case NFPROTO_IPV6:
594         {
595                 __be16 frag_off;
596
597                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP) {
598                         memcpy(&dst->ip6.dst, &ipv6_hdr(skb)->daddr,
599                                sizeof(dst->ip6.dst));
600                         hashlimit_ipv6_mask(dst->ip6.dst, hinfo->cfg.dstmask);
601                 }
602                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP) {
603                         memcpy(&dst->ip6.src, &ipv6_hdr(skb)->saddr,
604                                sizeof(dst->ip6.src));
605                         hashlimit_ipv6_mask(dst->ip6.src, hinfo->cfg.srcmask);
606                 }
607
608                 if (!(hinfo->cfg.mode &
609                       (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
610                         return 0;
611                 nexthdr = ipv6_hdr(skb)->nexthdr;
612                 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr, &frag_off);
613                 if ((int)protoff < 0)
614                         return -1;
615                 break;
616         }
617 #endif
618         default:
619                 BUG();
620                 return 0;
621         }
622
623         poff = proto_ports_offset(nexthdr);
624         if (poff >= 0) {
625                 ports = skb_header_pointer(skb, protoff + poff, sizeof(_ports),
626                                            &_ports);
627         } else {
628                 _ports[0] = _ports[1] = 0;
629                 ports = _ports;
630         }
631         if (!ports)
632                 return -1;
633         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SPT)
634                 dst->src_port = ports[0];
635         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DPT)
636                 dst->dst_port = ports[1];
637         return 0;
638 }
639
640 static u32 hashlimit_byte_cost(unsigned int len, struct dsthash_ent *dh)
641 {
642         u64 tmp = xt_hashlimit_len_to_chunks(len);
643         tmp = tmp * dh->rateinfo.cost;
644
645         if (unlikely(tmp > CREDITS_PER_JIFFY_BYTES * HZ))
646                 tmp = CREDITS_PER_JIFFY_BYTES * HZ;
647
648         if (dh->rateinfo.credit < tmp && dh->rateinfo.credit_cap) {
649                 dh->rateinfo.credit_cap--;
650                 dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
651         }
652         return (u32) tmp;
653 }
654
655 static bool
656 hashlimit_mt_common(const struct sk_buff *skb, struct xt_action_param *par,
657                     struct xt_hashlimit_htable *hinfo,
658                     const struct hashlimit_cfg2 *cfg, int revision)
659 {
660         unsigned long now = jiffies;
661         struct dsthash_ent *dh;
662         struct dsthash_dst dst;
663         bool race = false;
664         u64 cost;
665
666         if (hashlimit_init_dst(hinfo, &dst, skb, par->thoff) < 0)
667                 goto hotdrop;
668
669         rcu_read_lock_bh();
670         dh = dsthash_find(hinfo, &dst);
671         if (dh == NULL) {
672                 dh = dsthash_alloc_init(hinfo, &dst, &race);
673                 if (dh == NULL) {
674                         rcu_read_unlock_bh();
675                         goto hotdrop;
676                 } else if (race) {
677                         /* Already got an entry, update expiration timeout */
678                         dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
679                         rateinfo_recalc(dh, now, hinfo->cfg.mode, revision);
680                 } else {
681                         dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
682                         rateinfo_init(dh, hinfo, revision);
683                 }
684         } else {
685                 /* update expiration timeout */
686                 dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
687                 rateinfo_recalc(dh, now, hinfo->cfg.mode, revision);
688         }
689
690         if (cfg->mode & XT_HASHLIMIT_BYTES)
691                 cost = hashlimit_byte_cost(skb->len, dh);
692         else
693                 cost = dh->rateinfo.cost;
694
695         if (dh->rateinfo.credit >= cost) {
696                 /* below the limit */
697                 dh->rateinfo.credit -= cost;
698                 spin_unlock(&dh->lock);
699                 rcu_read_unlock_bh();
700                 return !(cfg->mode & XT_HASHLIMIT_INVERT);
701         }
702
703         spin_unlock(&dh->lock);
704         rcu_read_unlock_bh();
705         /* default match is underlimit - so over the limit, we need to invert */
706         return cfg->mode & XT_HASHLIMIT_INVERT;
707
708  hotdrop:
709         par->hotdrop = true;
710         return false;
711 }
712
713 static bool
714 hashlimit_mt_v1(const struct sk_buff *skb, struct xt_action_param *par)
715 {
716         const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
717         struct xt_hashlimit_htable *hinfo = info->hinfo;
718         struct hashlimit_cfg2 cfg = {};
719         int ret;
720
721         ret = cfg_copy(&cfg, (void *)&info->cfg, 1);
722
723         if (ret)
724                 return ret;
725
726         return hashlimit_mt_common(skb, par, hinfo, &cfg, 1);
727 }
728
729 static bool
730 hashlimit_mt(const struct sk_buff *skb, struct xt_action_param *par)
731 {
732         const struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
733         struct xt_hashlimit_htable *hinfo = info->hinfo;
734
735         return hashlimit_mt_common(skb, par, hinfo, &info->cfg, 2);
736 }
737
738 #define HASHLIMIT_MAX_SIZE 1048576
739
740 static int hashlimit_mt_check_common(const struct xt_mtchk_param *par,
741                                      struct xt_hashlimit_htable **hinfo,
742                                      struct hashlimit_cfg2 *cfg,
743                                      const char *name, int revision)
744 {
745         struct net *net = par->net;
746         int ret;
747
748         if (cfg->gc_interval == 0 || cfg->expire == 0)
749                 return -EINVAL;
750         if (cfg->size > HASHLIMIT_MAX_SIZE) {
751                 cfg->size = HASHLIMIT_MAX_SIZE;
752                 pr_info_ratelimited("size too large, truncated to %u\n", cfg->size);
753         }
754         if (cfg->max > HASHLIMIT_MAX_SIZE) {
755                 cfg->max = HASHLIMIT_MAX_SIZE;
756                 pr_info_ratelimited("max too large, truncated to %u\n", cfg->max);
757         }
758         if (par->family == NFPROTO_IPV4) {
759                 if (cfg->srcmask > 32 || cfg->dstmask > 32)
760                         return -EINVAL;
761         } else {
762                 if (cfg->srcmask > 128 || cfg->dstmask > 128)
763                         return -EINVAL;
764         }
765
766         if (cfg->mode & ~XT_HASHLIMIT_ALL) {
767                 pr_info("Unknown mode mask %X, kernel too old?\n",
768                                                 cfg->mode);
769                 return -EINVAL;
770         }
771
772         /* Check for overflow. */
773         if (cfg->mode & XT_HASHLIMIT_BYTES) {
774                 if (user2credits_byte(cfg->avg) == 0) {
775                         pr_info("overflow, rate too high: %llu\n", cfg->avg);
776                         return -EINVAL;
777                 }
778         } else if (cfg->burst == 0 ||
779                     user2credits(cfg->avg * cfg->burst, revision) <
780                     user2credits(cfg->avg, revision)) {
781                         pr_info("overflow, try lower: %llu/%llu\n",
782                                 cfg->avg, cfg->burst);
783                         return -ERANGE;
784         }
785
786         mutex_lock(&hashlimit_mutex);
787         *hinfo = htable_find_get(net, name, par->family);
788         if (*hinfo == NULL) {
789                 ret = htable_create(net, cfg, name, par->family,
790                                     hinfo, revision);
791                 if (ret < 0) {
792                         mutex_unlock(&hashlimit_mutex);
793                         return ret;
794                 }
795         }
796         mutex_unlock(&hashlimit_mutex);
797
798         return 0;
799 }
800
801 static int hashlimit_mt_check_v1(const struct xt_mtchk_param *par)
802 {
803         struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
804         struct hashlimit_cfg2 cfg = {};
805         int ret;
806
807         ret = xt_check_proc_name(info->name, sizeof(info->name));
808         if (ret)
809                 return ret;
810
811         ret = cfg_copy(&cfg, (void *)&info->cfg, 1);
812
813         if (ret)
814                 return ret;
815
816         return hashlimit_mt_check_common(par, &info->hinfo,
817                                          &cfg, info->name, 1);
818 }
819
820 static int hashlimit_mt_check(const struct xt_mtchk_param *par)
821 {
822         struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
823         int ret;
824
825         ret = xt_check_proc_name(info->name, sizeof(info->name));
826         if (ret)
827                 return ret;
828
829         return hashlimit_mt_check_common(par, &info->hinfo, &info->cfg,
830                                          info->name, 2);
831 }
832
833 static void hashlimit_mt_destroy_v1(const struct xt_mtdtor_param *par)
834 {
835         const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
836
837         htable_put(info->hinfo);
838 }
839
840 static void hashlimit_mt_destroy(const struct xt_mtdtor_param *par)
841 {
842         const struct xt_hashlimit_mtinfo2 *info = par->matchinfo;
843
844         htable_put(info->hinfo);
845 }
846
847 static struct xt_match hashlimit_mt_reg[] __read_mostly = {
848         {
849                 .name           = "hashlimit",
850                 .revision       = 1,
851                 .family         = NFPROTO_IPV4,
852                 .match          = hashlimit_mt_v1,
853                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
854                 .checkentry     = hashlimit_mt_check_v1,
855                 .destroy        = hashlimit_mt_destroy_v1,
856                 .me             = THIS_MODULE,
857         },
858         {
859                 .name           = "hashlimit",
860                 .revision       = 2,
861                 .family         = NFPROTO_IPV4,
862                 .match          = hashlimit_mt,
863                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo2),
864                 .checkentry     = hashlimit_mt_check,
865                 .destroy        = hashlimit_mt_destroy,
866                 .me             = THIS_MODULE,
867         },
868 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
869         {
870                 .name           = "hashlimit",
871                 .revision       = 1,
872                 .family         = NFPROTO_IPV6,
873                 .match          = hashlimit_mt_v1,
874                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
875                 .checkentry     = hashlimit_mt_check_v1,
876                 .destroy        = hashlimit_mt_destroy_v1,
877                 .me             = THIS_MODULE,
878         },
879         {
880                 .name           = "hashlimit",
881                 .revision       = 2,
882                 .family         = NFPROTO_IPV6,
883                 .match          = hashlimit_mt,
884                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo2),
885                 .checkentry     = hashlimit_mt_check,
886                 .destroy        = hashlimit_mt_destroy,
887                 .me             = THIS_MODULE,
888         },
889 #endif
890 };
891
892 /* PROC stuff */
893 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
894         __acquires(htable->lock)
895 {
896         struct xt_hashlimit_htable *htable = s->private;
897         unsigned int *bucket;
898
899         spin_lock_bh(&htable->lock);
900         if (*pos >= htable->cfg.size)
901                 return NULL;
902
903         bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
904         if (!bucket)
905                 return ERR_PTR(-ENOMEM);
906
907         *bucket = *pos;
908         return bucket;
909 }
910
911 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
912 {
913         struct xt_hashlimit_htable *htable = s->private;
914         unsigned int *bucket = (unsigned int *)v;
915
916         *pos = ++(*bucket);
917         if (*pos >= htable->cfg.size) {
918                 kfree(v);
919                 return NULL;
920         }
921         return bucket;
922 }
923
924 static void dl_seq_stop(struct seq_file *s, void *v)
925         __releases(htable->lock)
926 {
927         struct xt_hashlimit_htable *htable = s->private;
928         unsigned int *bucket = (unsigned int *)v;
929
930         if (!IS_ERR(bucket))
931                 kfree(bucket);
932         spin_unlock_bh(&htable->lock);
933 }
934
935 static void dl_seq_print(struct dsthash_ent *ent, u_int8_t family,
936                          struct seq_file *s)
937 {
938         switch (family) {
939         case NFPROTO_IPV4:
940                 seq_printf(s, "%ld %pI4:%u->%pI4:%u %llu %llu %llu\n",
941                            (long)(ent->expires - jiffies)/HZ,
942                            &ent->dst.ip.src,
943                            ntohs(ent->dst.src_port),
944                            &ent->dst.ip.dst,
945                            ntohs(ent->dst.dst_port),
946                            ent->rateinfo.credit, ent->rateinfo.credit_cap,
947                            ent->rateinfo.cost);
948                 break;
949 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
950         case NFPROTO_IPV6:
951                 seq_printf(s, "%ld %pI6:%u->%pI6:%u %llu %llu %llu\n",
952                            (long)(ent->expires - jiffies)/HZ,
953                            &ent->dst.ip6.src,
954                            ntohs(ent->dst.src_port),
955                            &ent->dst.ip6.dst,
956                            ntohs(ent->dst.dst_port),
957                            ent->rateinfo.credit, ent->rateinfo.credit_cap,
958                            ent->rateinfo.cost);
959                 break;
960 #endif
961         default:
962                 BUG();
963         }
964 }
965
966 static int dl_seq_real_show_v1(struct dsthash_ent *ent, u_int8_t family,
967                                struct seq_file *s)
968 {
969         const struct xt_hashlimit_htable *ht = s->private;
970
971         spin_lock(&ent->lock);
972         /* recalculate to show accurate numbers */
973         rateinfo_recalc(ent, jiffies, ht->cfg.mode, 1);
974
975         dl_seq_print(ent, family, s);
976
977         spin_unlock(&ent->lock);
978         return seq_has_overflowed(s);
979 }
980
981 static int dl_seq_real_show(struct dsthash_ent *ent, u_int8_t family,
982                             struct seq_file *s)
983 {
984         const struct xt_hashlimit_htable *ht = s->private;
985
986         spin_lock(&ent->lock);
987         /* recalculate to show accurate numbers */
988         rateinfo_recalc(ent, jiffies, ht->cfg.mode, 2);
989
990         dl_seq_print(ent, family, s);
991
992         spin_unlock(&ent->lock);
993         return seq_has_overflowed(s);
994 }
995
996 static int dl_seq_show_v1(struct seq_file *s, void *v)
997 {
998         struct xt_hashlimit_htable *htable = s->private;
999         unsigned int *bucket = (unsigned int *)v;
1000         struct dsthash_ent *ent;
1001
1002         if (!hlist_empty(&htable->hash[*bucket])) {
1003                 hlist_for_each_entry(ent, &htable->hash[*bucket], node)
1004                         if (dl_seq_real_show_v1(ent, htable->family, s))
1005                                 return -1;
1006         }
1007         return 0;
1008 }
1009
1010 static int dl_seq_show(struct seq_file *s, void *v)
1011 {
1012         struct xt_hashlimit_htable *htable = s->private;
1013         unsigned int *bucket = (unsigned int *)v;
1014         struct dsthash_ent *ent;
1015
1016         if (!hlist_empty(&htable->hash[*bucket])) {
1017                 hlist_for_each_entry(ent, &htable->hash[*bucket], node)
1018                         if (dl_seq_real_show(ent, htable->family, s))
1019                                 return -1;
1020         }
1021         return 0;
1022 }
1023
1024 static const struct seq_operations dl_seq_ops_v1 = {
1025         .start = dl_seq_start,
1026         .next  = dl_seq_next,
1027         .stop  = dl_seq_stop,
1028         .show  = dl_seq_show_v1
1029 };
1030
1031 static const struct seq_operations dl_seq_ops = {
1032         .start = dl_seq_start,
1033         .next  = dl_seq_next,
1034         .stop  = dl_seq_stop,
1035         .show  = dl_seq_show
1036 };
1037
1038 static int dl_proc_open_v1(struct inode *inode, struct file *file)
1039 {
1040         int ret = seq_open(file, &dl_seq_ops_v1);
1041
1042         if (!ret) {
1043                 struct seq_file *sf = file->private_data;
1044                 sf->private = PDE_DATA(inode);
1045         }
1046         return ret;
1047 }
1048
1049 static int dl_proc_open(struct inode *inode, struct file *file)
1050 {
1051         int ret = seq_open(file, &dl_seq_ops);
1052
1053         if (!ret) {
1054                 struct seq_file *sf = file->private_data;
1055
1056                 sf->private = PDE_DATA(inode);
1057         }
1058         return ret;
1059 }
1060
1061 static const struct file_operations dl_file_ops_v1 = {
1062         .owner   = THIS_MODULE,
1063         .open    = dl_proc_open_v1,
1064         .read    = seq_read,
1065         .llseek  = seq_lseek,
1066         .release = seq_release
1067 };
1068
1069 static const struct file_operations dl_file_ops = {
1070         .owner   = THIS_MODULE,
1071         .open    = dl_proc_open,
1072         .read    = seq_read,
1073         .llseek  = seq_lseek,
1074         .release = seq_release
1075 };
1076
1077 static int __net_init hashlimit_proc_net_init(struct net *net)
1078 {
1079         struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1080
1081         hashlimit_net->ipt_hashlimit = proc_mkdir("ipt_hashlimit", net->proc_net);
1082         if (!hashlimit_net->ipt_hashlimit)
1083                 return -ENOMEM;
1084 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1085         hashlimit_net->ip6t_hashlimit = proc_mkdir("ip6t_hashlimit", net->proc_net);
1086         if (!hashlimit_net->ip6t_hashlimit) {
1087                 remove_proc_entry("ipt_hashlimit", net->proc_net);
1088                 return -ENOMEM;
1089         }
1090 #endif
1091         return 0;
1092 }
1093
1094 static void __net_exit hashlimit_proc_net_exit(struct net *net)
1095 {
1096         struct xt_hashlimit_htable *hinfo;
1097         struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1098
1099         /* hashlimit_net_exit() is called before hashlimit_mt_destroy().
1100          * Make sure that the parent ipt_hashlimit and ip6t_hashlimit proc
1101          * entries is empty before trying to remove it.
1102          */
1103         mutex_lock(&hashlimit_mutex);
1104         hlist_for_each_entry(hinfo, &hashlimit_net->htables, node)
1105                 htable_remove_proc_entry(hinfo);
1106         hashlimit_net->ipt_hashlimit = NULL;
1107         hashlimit_net->ip6t_hashlimit = NULL;
1108         mutex_unlock(&hashlimit_mutex);
1109
1110         remove_proc_entry("ipt_hashlimit", net->proc_net);
1111 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
1112         remove_proc_entry("ip6t_hashlimit", net->proc_net);
1113 #endif
1114 }
1115
1116 static int __net_init hashlimit_net_init(struct net *net)
1117 {
1118         struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
1119
1120         INIT_HLIST_HEAD(&hashlimit_net->htables);
1121         return hashlimit_proc_net_init(net);
1122 }
1123
1124 static void __net_exit hashlimit_net_exit(struct net *net)
1125 {
1126         hashlimit_proc_net_exit(net);
1127 }
1128
1129 static struct pernet_operations hashlimit_net_ops = {
1130         .init   = hashlimit_net_init,
1131         .exit   = hashlimit_net_exit,
1132         .id     = &hashlimit_net_id,
1133         .size   = sizeof(struct hashlimit_net),
1134 };
1135
1136 static int __init hashlimit_mt_init(void)
1137 {
1138         int err;
1139
1140         err = register_pernet_subsys(&hashlimit_net_ops);
1141         if (err < 0)
1142                 return err;
1143         err = xt_register_matches(hashlimit_mt_reg,
1144               ARRAY_SIZE(hashlimit_mt_reg));
1145         if (err < 0)
1146                 goto err1;
1147
1148         err = -ENOMEM;
1149         hashlimit_cachep = kmem_cache_create("xt_hashlimit",
1150                                             sizeof(struct dsthash_ent), 0, 0,
1151                                             NULL);
1152         if (!hashlimit_cachep) {
1153                 pr_warn("unable to create slab cache\n");
1154                 goto err2;
1155         }
1156         return 0;
1157
1158 err2:
1159         xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1160 err1:
1161         unregister_pernet_subsys(&hashlimit_net_ops);
1162         return err;
1163
1164 }
1165
1166 static void __exit hashlimit_mt_exit(void)
1167 {
1168         xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1169         unregister_pernet_subsys(&hashlimit_net_ops);
1170
1171         rcu_barrier_bh();
1172         kmem_cache_destroy(hashlimit_cachep);
1173 }
1174
1175 module_init(hashlimit_mt_init);
1176 module_exit(hashlimit_mt_exit);