validate_cap.c 1.7 KB

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