xt_quota.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * netfilter module to enforce network quotas
  4. *
  5. * Sam Johnston <samj@samj.net>
  6. */
  7. #include <linux/skbuff.h>
  8. #include <linux/slab.h>
  9. #include <linux/spinlock.h>
  10. #include <linux/netfilter/x_tables.h>
  11. #include <linux/netfilter/xt_quota.h>
  12. #include <linux/module.h>
  13. struct xt_quota_priv {
  14. spinlock_t lock;
  15. uint64_t quota;
  16. };
  17. MODULE_LICENSE("GPL");
  18. MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
  19. MODULE_DESCRIPTION("Xtables: countdown quota match");
  20. MODULE_ALIAS("ipt_quota");
  21. MODULE_ALIAS("ip6t_quota");
  22. static bool
  23. quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
  24. {
  25. struct xt_quota_info *q = (void *)par->matchinfo;
  26. struct xt_quota_priv *priv = q->master;
  27. bool ret = q->flags & XT_QUOTA_INVERT;
  28. spin_lock_bh(&priv->lock);
  29. if (priv->quota >= skb->len) {
  30. priv->quota -= skb->len;
  31. ret = !ret;
  32. } else {
  33. /* we do not allow even small packets from now on */
  34. priv->quota = 0;
  35. }
  36. spin_unlock_bh(&priv->lock);
  37. return ret;
  38. }
  39. static int quota_mt_check(const struct xt_mtchk_param *par)
  40. {
  41. struct xt_quota_info *q = par->matchinfo;
  42. if (q->flags & ~XT_QUOTA_MASK)
  43. return -EINVAL;
  44. q->master = kmalloc(sizeof(*q->master), GFP_KERNEL);
  45. if (q->master == NULL)
  46. return -ENOMEM;
  47. spin_lock_init(&q->master->lock);
  48. q->master->quota = q->quota;
  49. return 0;
  50. }
  51. static void quota_mt_destroy(const struct xt_mtdtor_param *par)
  52. {
  53. const struct xt_quota_info *q = par->matchinfo;
  54. kfree(q->master);
  55. }
  56. static struct xt_match quota_mt_reg __read_mostly = {
  57. .name = "quota",
  58. .revision = 0,
  59. .family = NFPROTO_UNSPEC,
  60. .match = quota_mt,
  61. .checkentry = quota_mt_check,
  62. .destroy = quota_mt_destroy,
  63. .matchsize = sizeof(struct xt_quota_info),
  64. .usersize = offsetof(struct xt_quota_info, master),
  65. .me = THIS_MODULE,
  66. };
  67. static int __init quota_mt_init(void)
  68. {
  69. return xt_register_match(&quota_mt_reg);
  70. }
  71. static void __exit quota_mt_exit(void)
  72. {
  73. xt_unregister_match(&quota_mt_reg);
  74. }
  75. module_init(quota_mt_init);
  76. module_exit(quota_mt_exit);