xt_quota.c 1.9 KB

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