bpf_lsm.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2020 Google LLC.
  4. */
  5. #include <linux/filter.h>
  6. #include <linux/bpf.h>
  7. #include <linux/btf.h>
  8. #include <linux/lsm_hooks.h>
  9. #include <linux/bpf_lsm.h>
  10. #include <linux/kallsyms.h>
  11. #include <linux/bpf_verifier.h>
  12. #include <net/bpf_sk_storage.h>
  13. #include <linux/bpf_local_storage.h>
  14. #include <linux/btf_ids.h>
  15. /* For every LSM hook that allows attachment of BPF programs, declare a nop
  16. * function where a BPF program can be attached.
  17. */
  18. #define LSM_HOOK(RET, DEFAULT, NAME, ...) \
  19. noinline RET bpf_lsm_##NAME(__VA_ARGS__) \
  20. { \
  21. return DEFAULT; \
  22. }
  23. #include <linux/lsm_hook_defs.h>
  24. #undef LSM_HOOK
  25. #define LSM_HOOK(RET, DEFAULT, NAME, ...) BTF_ID(func, bpf_lsm_##NAME)
  26. BTF_SET_START(bpf_lsm_hooks)
  27. #include <linux/lsm_hook_defs.h>
  28. #undef LSM_HOOK
  29. BTF_SET_END(bpf_lsm_hooks)
  30. int bpf_lsm_verify_prog(struct bpf_verifier_log *vlog,
  31. const struct bpf_prog *prog)
  32. {
  33. if (!prog->gpl_compatible) {
  34. bpf_log(vlog,
  35. "LSM programs must have a GPL compatible license\n");
  36. return -EINVAL;
  37. }
  38. if (!btf_id_set_contains(&bpf_lsm_hooks, prog->aux->attach_btf_id)) {
  39. bpf_log(vlog, "attach_btf_id %u points to wrong type name %s\n",
  40. prog->aux->attach_btf_id, prog->aux->attach_func_name);
  41. return -EINVAL;
  42. }
  43. return 0;
  44. }
  45. static const struct bpf_func_proto *
  46. bpf_lsm_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
  47. {
  48. switch (func_id) {
  49. case BPF_FUNC_inode_storage_get:
  50. return &bpf_inode_storage_get_proto;
  51. case BPF_FUNC_inode_storage_delete:
  52. return &bpf_inode_storage_delete_proto;
  53. case BPF_FUNC_sk_storage_get:
  54. return &bpf_sk_storage_get_proto;
  55. case BPF_FUNC_sk_storage_delete:
  56. return &bpf_sk_storage_delete_proto;
  57. default:
  58. return tracing_prog_func_proto(func_id, prog);
  59. }
  60. }
  61. const struct bpf_prog_ops lsm_prog_ops = {
  62. };
  63. const struct bpf_verifier_ops lsm_verifier_ops = {
  64. .get_func_proto = bpf_lsm_func_proto,
  65. .is_valid_access = btf_ctx_access,
  66. };