xt_bpf.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Xtables module to match packets using a BPF filter.
  2. * Copyright 2013 Google Inc.
  3. * Written by Willem de Bruijn <willemb@google.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2 as
  7. * published by the Free Software Foundation.
  8. */
  9. #include <linux/module.h>
  10. #include <linux/skbuff.h>
  11. #include <linux/filter.h>
  12. #include <linux/netfilter/xt_bpf.h>
  13. #include <linux/netfilter/x_tables.h>
  14. MODULE_AUTHOR("Willem de Bruijn <willemb@google.com>");
  15. MODULE_DESCRIPTION("Xtables: BPF filter match");
  16. MODULE_LICENSE("GPL");
  17. MODULE_ALIAS("ipt_bpf");
  18. MODULE_ALIAS("ip6t_bpf");
  19. static int bpf_mt_check(const struct xt_mtchk_param *par)
  20. {
  21. struct xt_bpf_info *info = par->matchinfo;
  22. struct sock_fprog_kern program;
  23. program.len = info->bpf_program_num_elem;
  24. program.filter = info->bpf_program;
  25. if (bpf_prog_create(&info->filter, &program)) {
  26. pr_info("bpf: check failed: parse error\n");
  27. return -EINVAL;
  28. }
  29. return 0;
  30. }
  31. static bool bpf_mt(const struct sk_buff *skb, struct xt_action_param *par)
  32. {
  33. const struct xt_bpf_info *info = par->matchinfo;
  34. return BPF_PROG_RUN(info->filter, skb);
  35. }
  36. static void bpf_mt_destroy(const struct xt_mtdtor_param *par)
  37. {
  38. const struct xt_bpf_info *info = par->matchinfo;
  39. bpf_prog_destroy(info->filter);
  40. }
  41. static struct xt_match bpf_mt_reg __read_mostly = {
  42. .name = "bpf",
  43. .revision = 0,
  44. .family = NFPROTO_UNSPEC,
  45. .checkentry = bpf_mt_check,
  46. .match = bpf_mt,
  47. .destroy = bpf_mt_destroy,
  48. .matchsize = sizeof(struct xt_bpf_info),
  49. .me = THIS_MODULE,
  50. };
  51. static int __init bpf_mt_init(void)
  52. {
  53. return xt_register_match(&bpf_mt_reg);
  54. }
  55. static void __exit bpf_mt_exit(void)
  56. {
  57. xt_unregister_match(&bpf_mt_reg);
  58. }
  59. module_init(bpf_mt_init);
  60. module_exit(bpf_mt_exit);