validate_cap.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <cap-ng.h>
  3. #include <linux/capability.h>
  4. #include <stdbool.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <sys/prctl.h>
  8. #include <sys/auxv.h>
  9. #include "../kselftest.h"
  10. #ifndef PR_CAP_AMBIENT
  11. #define PR_CAP_AMBIENT 47
  12. # define PR_CAP_AMBIENT_IS_SET 1
  13. # define PR_CAP_AMBIENT_RAISE 2
  14. # define PR_CAP_AMBIENT_LOWER 3
  15. # define PR_CAP_AMBIENT_CLEAR_ALL 4
  16. #endif
  17. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 19)
  18. # define HAVE_GETAUXVAL
  19. #endif
  20. static bool bool_arg(char **argv, int i)
  21. {
  22. if (!strcmp(argv[i], "0"))
  23. return false;
  24. else if (!strcmp(argv[i], "1"))
  25. return true;
  26. else {
  27. ksft_exit_fail_msg("wrong argv[%d]\n", i);
  28. return false;
  29. }
  30. }
  31. int main(int argc, char **argv)
  32. {
  33. const char *atsec = "";
  34. /*
  35. * Be careful just in case a setgid or setcapped copy of this
  36. * helper gets out.
  37. */
  38. if (argc != 5)
  39. ksft_exit_fail_msg("wrong argc\n");
  40. #ifdef HAVE_GETAUXVAL
  41. if (getauxval(AT_SECURE))
  42. atsec = " (AT_SECURE is set)";
  43. else
  44. atsec = " (AT_SECURE is not set)";
  45. #endif
  46. capng_get_caps_process();
  47. if (capng_have_capability(CAPNG_EFFECTIVE, CAP_NET_BIND_SERVICE) != bool_arg(argv, 1)) {
  48. ksft_print_msg("Wrong effective state%s\n", atsec);
  49. return 1;
  50. }
  51. if (capng_have_capability(CAPNG_PERMITTED, CAP_NET_BIND_SERVICE) != bool_arg(argv, 2)) {
  52. ksft_print_msg("Wrong permitted state%s\n", atsec);
  53. return 1;
  54. }
  55. if (capng_have_capability(CAPNG_INHERITABLE, CAP_NET_BIND_SERVICE) != bool_arg(argv, 3)) {
  56. ksft_print_msg("Wrong inheritable state%s\n", atsec);
  57. return 1;
  58. }
  59. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_BIND_SERVICE, 0, 0, 0) != bool_arg(argv, 4)) {
  60. ksft_print_msg("Wrong ambient state%s\n", atsec);
  61. return 1;
  62. }
  63. ksft_print_msg("%s: Capabilities after execve were correct\n",
  64. "validate_cap:");
  65. return 0;
  66. }