dev_cgroup.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Copyright (c) 2017 Facebook
  2. *
  3. * This program is free software; you can redistribute it and/or
  4. * modify it under the terms of version 2 of the GNU General Public
  5. * License as published by the Free Software Foundation.
  6. */
  7. #include <linux/bpf.h>
  8. #include <linux/version.h>
  9. #include "bpf_helpers.h"
  10. SEC("cgroup/dev")
  11. int bpf_prog1(struct bpf_cgroup_dev_ctx *ctx)
  12. {
  13. short type = ctx->access_type & 0xFFFF;
  14. #ifdef DEBUG
  15. short access = ctx->access_type >> 16;
  16. char fmt[] = " %d:%d \n";
  17. switch (type) {
  18. case BPF_DEVCG_DEV_BLOCK:
  19. fmt[0] = 'b';
  20. break;
  21. case BPF_DEVCG_DEV_CHAR:
  22. fmt[0] = 'c';
  23. break;
  24. default:
  25. fmt[0] = '?';
  26. break;
  27. }
  28. if (access & BPF_DEVCG_ACC_READ)
  29. fmt[8] = 'r';
  30. if (access & BPF_DEVCG_ACC_WRITE)
  31. fmt[9] = 'w';
  32. if (access & BPF_DEVCG_ACC_MKNOD)
  33. fmt[10] = 'm';
  34. bpf_trace_printk(fmt, sizeof(fmt), ctx->major, ctx->minor);
  35. #endif
  36. /* Allow access to /dev/zero and /dev/random.
  37. * Forbid everything else.
  38. */
  39. if (ctx->major != 1 || type != BPF_DEVCG_DEV_CHAR)
  40. return 0;
  41. switch (ctx->minor) {
  42. case 5: /* 1:5 /dev/zero */
  43. case 9: /* 1:9 /dev/urandom */
  44. return 1;
  45. }
  46. return 0;
  47. }
  48. char _license[] SEC("license") = "GPL";
  49. __u32 _version SEC("version") = LINUX_VERSION_CODE;