xt_hashlimit.c 29 KB

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