xt_hashlimit.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. #include <net/net_namespace.h>
  30. #include <net/netns/generic.h>
  31. #include <linux/netfilter/x_tables.h>
  32. #include <linux/netfilter_ipv4/ip_tables.h>
  33. #include <linux/netfilter_ipv6/ip6_tables.h>
  34. #include <linux/netfilter/xt_hashlimit.h>
  35. #include <linux/mutex.h>
  36. MODULE_LICENSE("GPL");
  37. MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
  38. MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
  39. MODULE_DESCRIPTION("Xtables: per hash-bucket rate-limit match");
  40. MODULE_ALIAS("ipt_hashlimit");
  41. MODULE_ALIAS("ip6t_hashlimit");
  42. struct hashlimit_net {
  43. struct hlist_head htables;
  44. struct proc_dir_entry *ipt_hashlimit;
  45. struct proc_dir_entry *ip6t_hashlimit;
  46. };
  47. static int hashlimit_net_id;
  48. static inline struct hashlimit_net *hashlimit_pernet(struct net *net)
  49. {
  50. return net_generic(net, hashlimit_net_id);
  51. }
  52. /* need to declare this at the top */
  53. static const struct file_operations dl_file_ops;
  54. /* hash table crap */
  55. struct dsthash_dst {
  56. union {
  57. struct {
  58. __be32 src;
  59. __be32 dst;
  60. } ip;
  61. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  62. struct {
  63. __be32 src[4];
  64. __be32 dst[4];
  65. } ip6;
  66. #endif
  67. };
  68. __be16 src_port;
  69. __be16 dst_port;
  70. };
  71. struct dsthash_ent {
  72. /* static / read-only parts in the beginning */
  73. struct hlist_node node;
  74. struct dsthash_dst dst;
  75. /* modified structure members in the end */
  76. spinlock_t lock;
  77. unsigned long expires; /* precalculated expiry time */
  78. struct {
  79. unsigned long prev; /* last modification */
  80. u_int32_t credit;
  81. u_int32_t credit_cap, cost;
  82. } rateinfo;
  83. struct rcu_head rcu;
  84. };
  85. struct xt_hashlimit_htable {
  86. struct hlist_node node; /* global list of all htables */
  87. int use;
  88. u_int8_t family;
  89. bool rnd_initialized;
  90. struct hashlimit_cfg1 cfg; /* config */
  91. /* used internally */
  92. spinlock_t lock; /* lock for list_head */
  93. u_int32_t rnd; /* random seed for hash */
  94. unsigned int count; /* number entries in table */
  95. struct delayed_work gc_work;
  96. /* seq_file stuff */
  97. struct proc_dir_entry *pde;
  98. const char *name;
  99. struct net *net;
  100. struct hlist_head hash[0]; /* hashtable itself */
  101. };
  102. static DEFINE_MUTEX(hashlimit_mutex); /* protects htables list */
  103. static struct kmem_cache *hashlimit_cachep __read_mostly;
  104. static inline bool dst_cmp(const struct dsthash_ent *ent,
  105. const struct dsthash_dst *b)
  106. {
  107. return !memcmp(&ent->dst, b, sizeof(ent->dst));
  108. }
  109. static u_int32_t
  110. hash_dst(const struct xt_hashlimit_htable *ht, const struct dsthash_dst *dst)
  111. {
  112. u_int32_t hash = jhash2((const u32 *)dst,
  113. sizeof(*dst)/sizeof(u32),
  114. ht->rnd);
  115. /*
  116. * Instead of returning hash % ht->cfg.size (implying a divide)
  117. * we return the high 32 bits of the (hash * ht->cfg.size) that will
  118. * give results between [0 and cfg.size-1] and same hash distribution,
  119. * but using a multiply, less expensive than a divide
  120. */
  121. return reciprocal_scale(hash, ht->cfg.size);
  122. }
  123. static struct dsthash_ent *
  124. dsthash_find(const struct xt_hashlimit_htable *ht,
  125. const struct dsthash_dst *dst)
  126. {
  127. struct dsthash_ent *ent;
  128. u_int32_t hash = hash_dst(ht, dst);
  129. if (!hlist_empty(&ht->hash[hash])) {
  130. hlist_for_each_entry_rcu(ent, &ht->hash[hash], node)
  131. if (dst_cmp(ent, dst)) {
  132. spin_lock(&ent->lock);
  133. return ent;
  134. }
  135. }
  136. return NULL;
  137. }
  138. /* allocate dsthash_ent, initialize dst, put in htable and lock it */
  139. static struct dsthash_ent *
  140. dsthash_alloc_init(struct xt_hashlimit_htable *ht,
  141. const struct dsthash_dst *dst, bool *race)
  142. {
  143. struct dsthash_ent *ent;
  144. spin_lock(&ht->lock);
  145. /* Two or more packets may race to create the same entry in the
  146. * hashtable, double check if this packet lost race.
  147. */
  148. ent = dsthash_find(ht, dst);
  149. if (ent != NULL) {
  150. spin_unlock(&ht->lock);
  151. *race = true;
  152. return ent;
  153. }
  154. /* initialize hash with random val at the time we allocate
  155. * the first hashtable entry */
  156. if (unlikely(!ht->rnd_initialized)) {
  157. get_random_bytes(&ht->rnd, sizeof(ht->rnd));
  158. ht->rnd_initialized = true;
  159. }
  160. if (ht->cfg.max && ht->count >= ht->cfg.max) {
  161. /* FIXME: do something. question is what.. */
  162. net_err_ratelimited("max count of %u reached\n", ht->cfg.max);
  163. ent = NULL;
  164. } else
  165. ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
  166. if (ent) {
  167. memcpy(&ent->dst, dst, sizeof(ent->dst));
  168. spin_lock_init(&ent->lock);
  169. spin_lock(&ent->lock);
  170. hlist_add_head_rcu(&ent->node, &ht->hash[hash_dst(ht, dst)]);
  171. ht->count++;
  172. }
  173. spin_unlock(&ht->lock);
  174. return ent;
  175. }
  176. static void dsthash_free_rcu(struct rcu_head *head)
  177. {
  178. struct dsthash_ent *ent = container_of(head, struct dsthash_ent, rcu);
  179. kmem_cache_free(hashlimit_cachep, ent);
  180. }
  181. static inline void
  182. dsthash_free(struct xt_hashlimit_htable *ht, struct dsthash_ent *ent)
  183. {
  184. hlist_del_rcu(&ent->node);
  185. call_rcu_bh(&ent->rcu, dsthash_free_rcu);
  186. ht->count--;
  187. }
  188. static void htable_gc(struct work_struct *work);
  189. static int htable_create(struct net *net, struct xt_hashlimit_mtinfo1 *minfo,
  190. u_int8_t family)
  191. {
  192. struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
  193. struct xt_hashlimit_htable *hinfo;
  194. unsigned int size;
  195. unsigned int i;
  196. if (minfo->cfg.size) {
  197. size = minfo->cfg.size;
  198. } else {
  199. size = (totalram_pages << PAGE_SHIFT) / 16384 /
  200. sizeof(struct list_head);
  201. if (totalram_pages > 1024 * 1024 * 1024 / PAGE_SIZE)
  202. size = 8192;
  203. if (size < 16)
  204. size = 16;
  205. }
  206. /* FIXME: don't use vmalloc() here or anywhere else -HW */
  207. hinfo = vmalloc(sizeof(struct xt_hashlimit_htable) +
  208. sizeof(struct list_head) * size);
  209. if (hinfo == NULL)
  210. return -ENOMEM;
  211. minfo->hinfo = hinfo;
  212. /* copy match config into hashtable config */
  213. memcpy(&hinfo->cfg, &minfo->cfg, sizeof(hinfo->cfg));
  214. hinfo->cfg.size = size;
  215. if (hinfo->cfg.max == 0)
  216. hinfo->cfg.max = 8 * hinfo->cfg.size;
  217. else if (hinfo->cfg.max < hinfo->cfg.size)
  218. hinfo->cfg.max = hinfo->cfg.size;
  219. for (i = 0; i < hinfo->cfg.size; i++)
  220. INIT_HLIST_HEAD(&hinfo->hash[i]);
  221. hinfo->use = 1;
  222. hinfo->count = 0;
  223. hinfo->family = family;
  224. hinfo->rnd_initialized = false;
  225. hinfo->name = kstrdup(minfo->name, GFP_KERNEL);
  226. if (!hinfo->name) {
  227. vfree(hinfo);
  228. return -ENOMEM;
  229. }
  230. spin_lock_init(&hinfo->lock);
  231. hinfo->pde = proc_create_data(minfo->name, 0,
  232. (family == NFPROTO_IPV4) ?
  233. hashlimit_net->ipt_hashlimit : hashlimit_net->ip6t_hashlimit,
  234. &dl_file_ops, hinfo);
  235. if (hinfo->pde == NULL) {
  236. kfree(hinfo->name);
  237. vfree(hinfo);
  238. return -ENOMEM;
  239. }
  240. hinfo->net = net;
  241. INIT_DEFERRABLE_WORK(&hinfo->gc_work, htable_gc);
  242. queue_delayed_work(system_power_efficient_wq, &hinfo->gc_work,
  243. msecs_to_jiffies(hinfo->cfg.gc_interval));
  244. hlist_add_head(&hinfo->node, &hashlimit_net->htables);
  245. return 0;
  246. }
  247. static bool select_all(const struct xt_hashlimit_htable *ht,
  248. const struct dsthash_ent *he)
  249. {
  250. return 1;
  251. }
  252. static bool select_gc(const struct xt_hashlimit_htable *ht,
  253. const struct dsthash_ent *he)
  254. {
  255. return time_after_eq(jiffies, he->expires);
  256. }
  257. static void htable_selective_cleanup(struct xt_hashlimit_htable *ht,
  258. bool (*select)(const struct xt_hashlimit_htable *ht,
  259. const struct dsthash_ent *he))
  260. {
  261. unsigned int i;
  262. for (i = 0; i < ht->cfg.size; i++) {
  263. struct dsthash_ent *dh;
  264. struct hlist_node *n;
  265. spin_lock_bh(&ht->lock);
  266. hlist_for_each_entry_safe(dh, n, &ht->hash[i], node) {
  267. if ((*select)(ht, dh))
  268. dsthash_free(ht, dh);
  269. }
  270. spin_unlock_bh(&ht->lock);
  271. cond_resched();
  272. }
  273. }
  274. static void htable_gc(struct work_struct *work)
  275. {
  276. struct xt_hashlimit_htable *ht;
  277. ht = container_of(work, struct xt_hashlimit_htable, gc_work.work);
  278. htable_selective_cleanup(ht, select_gc);
  279. queue_delayed_work(system_power_efficient_wq,
  280. &ht->gc_work, msecs_to_jiffies(ht->cfg.gc_interval));
  281. }
  282. static void htable_remove_proc_entry(struct xt_hashlimit_htable *hinfo)
  283. {
  284. struct hashlimit_net *hashlimit_net = hashlimit_pernet(hinfo->net);
  285. struct proc_dir_entry *parent;
  286. if (hinfo->family == NFPROTO_IPV4)
  287. parent = hashlimit_net->ipt_hashlimit;
  288. else
  289. parent = hashlimit_net->ip6t_hashlimit;
  290. if (parent != NULL)
  291. remove_proc_entry(hinfo->name, parent);
  292. }
  293. static void htable_destroy(struct xt_hashlimit_htable *hinfo)
  294. {
  295. cancel_delayed_work_sync(&hinfo->gc_work);
  296. htable_remove_proc_entry(hinfo);
  297. htable_selective_cleanup(hinfo, select_all);
  298. kfree(hinfo->name);
  299. vfree(hinfo);
  300. }
  301. static struct xt_hashlimit_htable *htable_find_get(struct net *net,
  302. const char *name,
  303. u_int8_t family)
  304. {
  305. struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
  306. struct xt_hashlimit_htable *hinfo;
  307. hlist_for_each_entry(hinfo, &hashlimit_net->htables, node) {
  308. if (!strcmp(name, hinfo->name) &&
  309. hinfo->family == family) {
  310. hinfo->use++;
  311. return hinfo;
  312. }
  313. }
  314. return NULL;
  315. }
  316. static void htable_put(struct xt_hashlimit_htable *hinfo)
  317. {
  318. mutex_lock(&hashlimit_mutex);
  319. if (--hinfo->use == 0) {
  320. hlist_del(&hinfo->node);
  321. htable_destroy(hinfo);
  322. }
  323. mutex_unlock(&hashlimit_mutex);
  324. }
  325. /* The algorithm used is the Simple Token Bucket Filter (TBF)
  326. * see net/sched/sch_tbf.c in the linux source tree
  327. */
  328. /* Rusty: This is my (non-mathematically-inclined) understanding of
  329. this algorithm. The `average rate' in jiffies becomes your initial
  330. amount of credit `credit' and the most credit you can ever have
  331. `credit_cap'. The `peak rate' becomes the cost of passing the
  332. test, `cost'.
  333. `prev' tracks the last packet hit: you gain one credit per jiffy.
  334. If you get credit balance more than this, the extra credit is
  335. discarded. Every time the match passes, you lose `cost' credits;
  336. if you don't have that many, the test fails.
  337. See Alexey's formal explanation in net/sched/sch_tbf.c.
  338. To get the maximum range, we multiply by this factor (ie. you get N
  339. credits per jiffy). We want to allow a rate as low as 1 per day
  340. (slowest userspace tool allows), which means
  341. CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
  342. */
  343. #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
  344. /* Repeated shift and or gives us all 1s, final shift and add 1 gives
  345. * us the power of 2 below the theoretical max, so GCC simply does a
  346. * shift. */
  347. #define _POW2_BELOW2(x) ((x)|((x)>>1))
  348. #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
  349. #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
  350. #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
  351. #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
  352. #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
  353. #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
  354. /* in byte mode, the lowest possible rate is one packet/second.
  355. * credit_cap is used as a counter that tells us how many times we can
  356. * refill the "credits available" counter when it becomes empty.
  357. */
  358. #define MAX_CPJ_BYTES (0xFFFFFFFF / HZ)
  359. #define CREDITS_PER_JIFFY_BYTES POW2_BELOW32(MAX_CPJ_BYTES)
  360. static u32 xt_hashlimit_len_to_chunks(u32 len)
  361. {
  362. return (len >> XT_HASHLIMIT_BYTE_SHIFT) + 1;
  363. }
  364. /* Precision saver. */
  365. static u32 user2credits(u32 user)
  366. {
  367. /* If multiplying would overflow... */
  368. if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY))
  369. /* Divide first. */
  370. return (user / XT_HASHLIMIT_SCALE) * HZ * CREDITS_PER_JIFFY;
  371. return (user * HZ * CREDITS_PER_JIFFY) / XT_HASHLIMIT_SCALE;
  372. }
  373. static u32 user2credits_byte(u32 user)
  374. {
  375. u64 us = user;
  376. us *= HZ * CREDITS_PER_JIFFY_BYTES;
  377. return (u32) (us >> 32);
  378. }
  379. static void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now, u32 mode)
  380. {
  381. unsigned long delta = now - dh->rateinfo.prev;
  382. u32 cap;
  383. if (delta == 0)
  384. return;
  385. dh->rateinfo.prev = now;
  386. if (mode & XT_HASHLIMIT_BYTES) {
  387. u32 tmp = dh->rateinfo.credit;
  388. dh->rateinfo.credit += CREDITS_PER_JIFFY_BYTES * delta;
  389. cap = CREDITS_PER_JIFFY_BYTES * HZ;
  390. if (tmp >= dh->rateinfo.credit) {/* overflow */
  391. dh->rateinfo.credit = cap;
  392. return;
  393. }
  394. } else {
  395. dh->rateinfo.credit += delta * CREDITS_PER_JIFFY;
  396. cap = dh->rateinfo.credit_cap;
  397. }
  398. if (dh->rateinfo.credit > cap)
  399. dh->rateinfo.credit = cap;
  400. }
  401. static void rateinfo_init(struct dsthash_ent *dh,
  402. struct xt_hashlimit_htable *hinfo)
  403. {
  404. dh->rateinfo.prev = jiffies;
  405. if (hinfo->cfg.mode & XT_HASHLIMIT_BYTES) {
  406. dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
  407. dh->rateinfo.cost = user2credits_byte(hinfo->cfg.avg);
  408. dh->rateinfo.credit_cap = hinfo->cfg.burst;
  409. } else {
  410. dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
  411. hinfo->cfg.burst);
  412. dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
  413. dh->rateinfo.credit_cap = dh->rateinfo.credit;
  414. }
  415. }
  416. static inline __be32 maskl(__be32 a, unsigned int l)
  417. {
  418. return l ? htonl(ntohl(a) & ~0 << (32 - l)) : 0;
  419. }
  420. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  421. static void hashlimit_ipv6_mask(__be32 *i, unsigned int p)
  422. {
  423. switch (p) {
  424. case 0 ... 31:
  425. i[0] = maskl(i[0], p);
  426. i[1] = i[2] = i[3] = 0;
  427. break;
  428. case 32 ... 63:
  429. i[1] = maskl(i[1], p - 32);
  430. i[2] = i[3] = 0;
  431. break;
  432. case 64 ... 95:
  433. i[2] = maskl(i[2], p - 64);
  434. i[3] = 0;
  435. break;
  436. case 96 ... 127:
  437. i[3] = maskl(i[3], p - 96);
  438. break;
  439. case 128:
  440. break;
  441. }
  442. }
  443. #endif
  444. static int
  445. hashlimit_init_dst(const struct xt_hashlimit_htable *hinfo,
  446. struct dsthash_dst *dst,
  447. const struct sk_buff *skb, unsigned int protoff)
  448. {
  449. __be16 _ports[2], *ports;
  450. u8 nexthdr;
  451. int poff;
  452. memset(dst, 0, sizeof(*dst));
  453. switch (hinfo->family) {
  454. case NFPROTO_IPV4:
  455. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
  456. dst->ip.dst = maskl(ip_hdr(skb)->daddr,
  457. hinfo->cfg.dstmask);
  458. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
  459. dst->ip.src = maskl(ip_hdr(skb)->saddr,
  460. hinfo->cfg.srcmask);
  461. if (!(hinfo->cfg.mode &
  462. (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
  463. return 0;
  464. nexthdr = ip_hdr(skb)->protocol;
  465. break;
  466. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  467. case NFPROTO_IPV6:
  468. {
  469. __be16 frag_off;
  470. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP) {
  471. memcpy(&dst->ip6.dst, &ipv6_hdr(skb)->daddr,
  472. sizeof(dst->ip6.dst));
  473. hashlimit_ipv6_mask(dst->ip6.dst, hinfo->cfg.dstmask);
  474. }
  475. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP) {
  476. memcpy(&dst->ip6.src, &ipv6_hdr(skb)->saddr,
  477. sizeof(dst->ip6.src));
  478. hashlimit_ipv6_mask(dst->ip6.src, hinfo->cfg.srcmask);
  479. }
  480. if (!(hinfo->cfg.mode &
  481. (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
  482. return 0;
  483. nexthdr = ipv6_hdr(skb)->nexthdr;
  484. protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr, &frag_off);
  485. if ((int)protoff < 0)
  486. return -1;
  487. break;
  488. }
  489. #endif
  490. default:
  491. BUG();
  492. return 0;
  493. }
  494. poff = proto_ports_offset(nexthdr);
  495. if (poff >= 0) {
  496. ports = skb_header_pointer(skb, protoff + poff, sizeof(_ports),
  497. &_ports);
  498. } else {
  499. _ports[0] = _ports[1] = 0;
  500. ports = _ports;
  501. }
  502. if (!ports)
  503. return -1;
  504. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SPT)
  505. dst->src_port = ports[0];
  506. if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DPT)
  507. dst->dst_port = ports[1];
  508. return 0;
  509. }
  510. static u32 hashlimit_byte_cost(unsigned int len, struct dsthash_ent *dh)
  511. {
  512. u64 tmp = xt_hashlimit_len_to_chunks(len);
  513. tmp = tmp * dh->rateinfo.cost;
  514. if (unlikely(tmp > CREDITS_PER_JIFFY_BYTES * HZ))
  515. tmp = CREDITS_PER_JIFFY_BYTES * HZ;
  516. if (dh->rateinfo.credit < tmp && dh->rateinfo.credit_cap) {
  517. dh->rateinfo.credit_cap--;
  518. dh->rateinfo.credit = CREDITS_PER_JIFFY_BYTES * HZ;
  519. }
  520. return (u32) tmp;
  521. }
  522. static bool
  523. hashlimit_mt(const struct sk_buff *skb, struct xt_action_param *par)
  524. {
  525. const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
  526. struct xt_hashlimit_htable *hinfo = info->hinfo;
  527. unsigned long now = jiffies;
  528. struct dsthash_ent *dh;
  529. struct dsthash_dst dst;
  530. bool race = false;
  531. u32 cost;
  532. if (hashlimit_init_dst(hinfo, &dst, skb, par->thoff) < 0)
  533. goto hotdrop;
  534. rcu_read_lock_bh();
  535. dh = dsthash_find(hinfo, &dst);
  536. if (dh == NULL) {
  537. dh = dsthash_alloc_init(hinfo, &dst, &race);
  538. if (dh == NULL) {
  539. rcu_read_unlock_bh();
  540. goto hotdrop;
  541. } else if (race) {
  542. /* Already got an entry, update expiration timeout */
  543. dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
  544. rateinfo_recalc(dh, now, hinfo->cfg.mode);
  545. } else {
  546. dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
  547. rateinfo_init(dh, hinfo);
  548. }
  549. } else {
  550. /* update expiration timeout */
  551. dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
  552. rateinfo_recalc(dh, now, hinfo->cfg.mode);
  553. }
  554. if (info->cfg.mode & XT_HASHLIMIT_BYTES)
  555. cost = hashlimit_byte_cost(skb->len, dh);
  556. else
  557. cost = dh->rateinfo.cost;
  558. if (dh->rateinfo.credit >= cost) {
  559. /* below the limit */
  560. dh->rateinfo.credit -= cost;
  561. spin_unlock(&dh->lock);
  562. rcu_read_unlock_bh();
  563. return !(info->cfg.mode & XT_HASHLIMIT_INVERT);
  564. }
  565. spin_unlock(&dh->lock);
  566. rcu_read_unlock_bh();
  567. /* default match is underlimit - so over the limit, we need to invert */
  568. return info->cfg.mode & XT_HASHLIMIT_INVERT;
  569. hotdrop:
  570. par->hotdrop = true;
  571. return false;
  572. }
  573. static int hashlimit_mt_check(const struct xt_mtchk_param *par)
  574. {
  575. struct net *net = par->net;
  576. struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
  577. int ret;
  578. if (info->cfg.gc_interval == 0 || info->cfg.expire == 0)
  579. return -EINVAL;
  580. ret = xt_check_proc_name(info->name, sizeof(info->name));
  581. if (ret)
  582. return ret;
  583. if (par->family == NFPROTO_IPV4) {
  584. if (info->cfg.srcmask > 32 || info->cfg.dstmask > 32)
  585. return -EINVAL;
  586. } else {
  587. if (info->cfg.srcmask > 128 || info->cfg.dstmask > 128)
  588. return -EINVAL;
  589. }
  590. if (info->cfg.mode & ~XT_HASHLIMIT_ALL) {
  591. pr_info("Unknown mode mask %X, kernel too old?\n",
  592. info->cfg.mode);
  593. return -EINVAL;
  594. }
  595. /* Check for overflow. */
  596. if (info->cfg.mode & XT_HASHLIMIT_BYTES) {
  597. if (user2credits_byte(info->cfg.avg) == 0) {
  598. pr_info("overflow, rate too high: %u\n", info->cfg.avg);
  599. return -EINVAL;
  600. }
  601. } else if (info->cfg.burst == 0 ||
  602. user2credits(info->cfg.avg * info->cfg.burst) <
  603. user2credits(info->cfg.avg)) {
  604. pr_info("overflow, try lower: %u/%u\n",
  605. info->cfg.avg, info->cfg.burst);
  606. return -ERANGE;
  607. }
  608. mutex_lock(&hashlimit_mutex);
  609. info->hinfo = htable_find_get(net, info->name, par->family);
  610. if (info->hinfo == NULL) {
  611. ret = htable_create(net, info, par->family);
  612. if (ret < 0) {
  613. mutex_unlock(&hashlimit_mutex);
  614. return ret;
  615. }
  616. }
  617. mutex_unlock(&hashlimit_mutex);
  618. return 0;
  619. }
  620. static void hashlimit_mt_destroy(const struct xt_mtdtor_param *par)
  621. {
  622. const struct xt_hashlimit_mtinfo1 *info = par->matchinfo;
  623. htable_put(info->hinfo);
  624. }
  625. static struct xt_match hashlimit_mt_reg[] __read_mostly = {
  626. {
  627. .name = "hashlimit",
  628. .revision = 1,
  629. .family = NFPROTO_IPV4,
  630. .match = hashlimit_mt,
  631. .matchsize = sizeof(struct xt_hashlimit_mtinfo1),
  632. .checkentry = hashlimit_mt_check,
  633. .destroy = hashlimit_mt_destroy,
  634. .me = THIS_MODULE,
  635. },
  636. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  637. {
  638. .name = "hashlimit",
  639. .revision = 1,
  640. .family = NFPROTO_IPV6,
  641. .match = hashlimit_mt,
  642. .matchsize = sizeof(struct xt_hashlimit_mtinfo1),
  643. .checkentry = hashlimit_mt_check,
  644. .destroy = hashlimit_mt_destroy,
  645. .me = THIS_MODULE,
  646. },
  647. #endif
  648. };
  649. /* PROC stuff */
  650. static void *dl_seq_start(struct seq_file *s, loff_t *pos)
  651. __acquires(htable->lock)
  652. {
  653. struct xt_hashlimit_htable *htable = s->private;
  654. unsigned int *bucket;
  655. spin_lock_bh(&htable->lock);
  656. if (*pos >= htable->cfg.size)
  657. return NULL;
  658. bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
  659. if (!bucket)
  660. return ERR_PTR(-ENOMEM);
  661. *bucket = *pos;
  662. return bucket;
  663. }
  664. static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
  665. {
  666. struct xt_hashlimit_htable *htable = s->private;
  667. unsigned int *bucket = (unsigned int *)v;
  668. *pos = ++(*bucket);
  669. if (*pos >= htable->cfg.size) {
  670. kfree(v);
  671. return NULL;
  672. }
  673. return bucket;
  674. }
  675. static void dl_seq_stop(struct seq_file *s, void *v)
  676. __releases(htable->lock)
  677. {
  678. struct xt_hashlimit_htable *htable = s->private;
  679. unsigned int *bucket = (unsigned int *)v;
  680. if (!IS_ERR(bucket))
  681. kfree(bucket);
  682. spin_unlock_bh(&htable->lock);
  683. }
  684. static int dl_seq_real_show(struct dsthash_ent *ent, u_int8_t family,
  685. struct seq_file *s)
  686. {
  687. const struct xt_hashlimit_htable *ht = s->private;
  688. spin_lock(&ent->lock);
  689. /* recalculate to show accurate numbers */
  690. rateinfo_recalc(ent, jiffies, ht->cfg.mode);
  691. switch (family) {
  692. case NFPROTO_IPV4:
  693. seq_printf(s, "%ld %pI4:%u->%pI4:%u %u %u %u\n",
  694. (long)(ent->expires - jiffies)/HZ,
  695. &ent->dst.ip.src,
  696. ntohs(ent->dst.src_port),
  697. &ent->dst.ip.dst,
  698. ntohs(ent->dst.dst_port),
  699. ent->rateinfo.credit, ent->rateinfo.credit_cap,
  700. ent->rateinfo.cost);
  701. break;
  702. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  703. case NFPROTO_IPV6:
  704. seq_printf(s, "%ld %pI6:%u->%pI6:%u %u %u %u\n",
  705. (long)(ent->expires - jiffies)/HZ,
  706. &ent->dst.ip6.src,
  707. ntohs(ent->dst.src_port),
  708. &ent->dst.ip6.dst,
  709. ntohs(ent->dst.dst_port),
  710. ent->rateinfo.credit, ent->rateinfo.credit_cap,
  711. ent->rateinfo.cost);
  712. break;
  713. #endif
  714. default:
  715. BUG();
  716. }
  717. spin_unlock(&ent->lock);
  718. return seq_has_overflowed(s);
  719. }
  720. static int dl_seq_show(struct seq_file *s, void *v)
  721. {
  722. struct xt_hashlimit_htable *htable = s->private;
  723. unsigned int *bucket = (unsigned int *)v;
  724. struct dsthash_ent *ent;
  725. if (!hlist_empty(&htable->hash[*bucket])) {
  726. hlist_for_each_entry(ent, &htable->hash[*bucket], node)
  727. if (dl_seq_real_show(ent, htable->family, s))
  728. return -1;
  729. }
  730. return 0;
  731. }
  732. static const struct seq_operations dl_seq_ops = {
  733. .start = dl_seq_start,
  734. .next = dl_seq_next,
  735. .stop = dl_seq_stop,
  736. .show = dl_seq_show
  737. };
  738. static int dl_proc_open(struct inode *inode, struct file *file)
  739. {
  740. int ret = seq_open(file, &dl_seq_ops);
  741. if (!ret) {
  742. struct seq_file *sf = file->private_data;
  743. sf->private = PDE_DATA(inode);
  744. }
  745. return ret;
  746. }
  747. static const struct file_operations dl_file_ops = {
  748. .owner = THIS_MODULE,
  749. .open = dl_proc_open,
  750. .read = seq_read,
  751. .llseek = seq_lseek,
  752. .release = seq_release
  753. };
  754. static int __net_init hashlimit_proc_net_init(struct net *net)
  755. {
  756. struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
  757. hashlimit_net->ipt_hashlimit = proc_mkdir("ipt_hashlimit", net->proc_net);
  758. if (!hashlimit_net->ipt_hashlimit)
  759. return -ENOMEM;
  760. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  761. hashlimit_net->ip6t_hashlimit = proc_mkdir("ip6t_hashlimit", net->proc_net);
  762. if (!hashlimit_net->ip6t_hashlimit) {
  763. remove_proc_entry("ipt_hashlimit", net->proc_net);
  764. return -ENOMEM;
  765. }
  766. #endif
  767. return 0;
  768. }
  769. static void __net_exit hashlimit_proc_net_exit(struct net *net)
  770. {
  771. struct xt_hashlimit_htable *hinfo;
  772. struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
  773. /* hashlimit_net_exit() is called before hashlimit_mt_destroy().
  774. * Make sure that the parent ipt_hashlimit and ip6t_hashlimit proc
  775. * entries is empty before trying to remove it.
  776. */
  777. mutex_lock(&hashlimit_mutex);
  778. hlist_for_each_entry(hinfo, &hashlimit_net->htables, node)
  779. htable_remove_proc_entry(hinfo);
  780. hashlimit_net->ipt_hashlimit = NULL;
  781. hashlimit_net->ip6t_hashlimit = NULL;
  782. mutex_unlock(&hashlimit_mutex);
  783. remove_proc_entry("ipt_hashlimit", net->proc_net);
  784. #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
  785. remove_proc_entry("ip6t_hashlimit", net->proc_net);
  786. #endif
  787. }
  788. static int __net_init hashlimit_net_init(struct net *net)
  789. {
  790. struct hashlimit_net *hashlimit_net = hashlimit_pernet(net);
  791. INIT_HLIST_HEAD(&hashlimit_net->htables);
  792. return hashlimit_proc_net_init(net);
  793. }
  794. static void __net_exit hashlimit_net_exit(struct net *net)
  795. {
  796. hashlimit_proc_net_exit(net);
  797. }
  798. static struct pernet_operations hashlimit_net_ops = {
  799. .init = hashlimit_net_init,
  800. .exit = hashlimit_net_exit,
  801. .id = &hashlimit_net_id,
  802. .size = sizeof(struct hashlimit_net),
  803. };
  804. static int __init hashlimit_mt_init(void)
  805. {
  806. int err;
  807. err = register_pernet_subsys(&hashlimit_net_ops);
  808. if (err < 0)
  809. return err;
  810. err = xt_register_matches(hashlimit_mt_reg,
  811. ARRAY_SIZE(hashlimit_mt_reg));
  812. if (err < 0)
  813. goto err1;
  814. err = -ENOMEM;
  815. hashlimit_cachep = kmem_cache_create("xt_hashlimit",
  816. sizeof(struct dsthash_ent), 0, 0,
  817. NULL);
  818. if (!hashlimit_cachep) {
  819. pr_warn("unable to create slab cache\n");
  820. goto err2;
  821. }
  822. return 0;
  823. err2:
  824. xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
  825. err1:
  826. unregister_pernet_subsys(&hashlimit_net_ops);
  827. return err;
  828. }
  829. static void __exit hashlimit_mt_exit(void)
  830. {
  831. xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
  832. unregister_pernet_subsys(&hashlimit_net_ops);
  833. rcu_barrier_bh();
  834. kmem_cache_destroy(hashlimit_cachep);
  835. }
  836. module_init(hashlimit_mt_init);
  837. module_exit(hashlimit_mt_exit);