test_dev_cgroup.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <errno.h>
  11. #include <assert.h>
  12. #include <sys/time.h>
  13. #include <linux/bpf.h>
  14. #include <bpf/bpf.h>
  15. #include <bpf/libbpf.h>
  16. #include "cgroup_helpers.h"
  17. #include "bpf_rlimit.h"
  18. #define DEV_CGROUP_PROG "./dev_cgroup.o"
  19. #define TEST_CGROUP "/test-bpf-based-device-cgroup/"
  20. int main(int argc, char **argv)
  21. {
  22. struct bpf_object *obj;
  23. int error = EXIT_FAILURE;
  24. int prog_fd, cgroup_fd;
  25. __u32 prog_cnt;
  26. if (bpf_prog_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE,
  27. &obj, &prog_fd)) {
  28. printf("Failed to load DEV_CGROUP program\n");
  29. goto out;
  30. }
  31. if (setup_cgroup_environment()) {
  32. printf("Failed to load DEV_CGROUP program\n");
  33. goto err;
  34. }
  35. /* Create a cgroup, get fd, and join it */
  36. cgroup_fd = create_and_get_cgroup(TEST_CGROUP);
  37. if (!cgroup_fd) {
  38. printf("Failed to create test cgroup\n");
  39. goto err;
  40. }
  41. if (join_cgroup(TEST_CGROUP)) {
  42. printf("Failed to join cgroup\n");
  43. goto err;
  44. }
  45. /* Attach bpf program */
  46. if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) {
  47. printf("Failed to attach DEV_CGROUP program");
  48. goto err;
  49. }
  50. if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL,
  51. &prog_cnt)) {
  52. printf("Failed to query attached programs");
  53. goto err;
  54. }
  55. /* All operations with /dev/zero and and /dev/urandom are allowed,
  56. * everything else is forbidden.
  57. */
  58. assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
  59. assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
  60. assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
  61. /* /dev/zero is whitelisted */
  62. assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
  63. assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
  64. assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
  65. assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
  66. /* src is allowed, target is forbidden */
  67. assert(system("dd if=/dev/urandom of=/dev/full count=64"));
  68. /* src is forbidden, target is allowed */
  69. assert(system("dd if=/dev/random of=/dev/zero count=64"));
  70. error = 0;
  71. printf("test_dev_cgroup:PASS\n");
  72. err:
  73. cleanup_cgroup_environment();
  74. out:
  75. return error;
  76. }