TestKernelFilePermissions.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibCore/File.h>
  8. #include <LibTest/TestCase.h>
  9. #include <fcntl.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <sys/stat.h>
  14. #include <sys/types.h>
  15. #include <unistd.h>
  16. TEST_CASE(test_change_file_contents)
  17. {
  18. char path[] = "/tmp/suid.XXXXXX";
  19. auto fd = mkstemp(path);
  20. EXPECT(fd != -1);
  21. ftruncate(fd, 0);
  22. EXPECT(fchmod(fd, 06755) != -1);
  23. char buffer[8] {};
  24. write(fd, buffer, sizeof(buffer));
  25. struct stat s;
  26. EXPECT(fstat(fd, &s) != -1);
  27. close(fd);
  28. unlink(path);
  29. EXPECT(!(s.st_mode & S_ISUID));
  30. EXPECT(!(s.st_mode & S_ISGID));
  31. }
  32. TEST_CASE(test_change_file_ownership)
  33. {
  34. char path[] = "/tmp/suid.XXXXXX";
  35. auto fd = mkstemp(path);
  36. EXPECT(fd != -1);
  37. ftruncate(fd, 0);
  38. EXPECT(fchmod(fd, 06755) != -1);
  39. fchown(fd, getuid(), getgid());
  40. struct stat s;
  41. EXPECT(fstat(fd, &s) != -1);
  42. close(fd);
  43. unlink(path);
  44. EXPECT(!(s.st_mode & S_ISUID));
  45. EXPECT(!(s.st_mode & S_ISGID));
  46. }
  47. TEST_CASE(test_change_file_permissions)
  48. {
  49. char path[] = "/tmp/suid.XXXXXX";
  50. auto fd = mkstemp(path);
  51. EXPECT(fd != -1);
  52. ftruncate(fd, 0);
  53. EXPECT(fchmod(fd, 06755) != -1);
  54. fchmod(fd, 0755);
  55. struct stat s;
  56. EXPECT(fstat(fd, &s) != -1);
  57. close(fd);
  58. unlink(path);
  59. EXPECT(!(s.st_mode & S_ISUID));
  60. EXPECT(!(s.st_mode & S_ISGID));
  61. }
  62. TEST_CASE(test_change_file_location)
  63. {
  64. char path[] = "/tmp/suid.XXXXXX";
  65. auto fd = mkstemp(path);
  66. EXPECT(fd != -1);
  67. ftruncate(fd, 0);
  68. EXPECT(fchmod(fd, 06755) != -1);
  69. auto suid_path_or_error = Core::File::read_link(String::formatted("/proc/{}/fd/{}", getpid(), fd));
  70. EXPECT(!suid_path_or_error.is_error());
  71. auto suid_path = suid_path_or_error.release_value();
  72. EXPECT(suid_path.characters());
  73. auto new_path = String::formatted("{}.renamed", suid_path);
  74. rename(suid_path.characters(), new_path.characters());
  75. struct stat s;
  76. EXPECT(lstat(new_path.characters(), &s) != -1);
  77. close(fd);
  78. unlink(path);
  79. // Renamed file should retain set-uid/set-gid permissions
  80. EXPECT(s.st_mode & S_ISUID);
  81. EXPECT(s.st_mode & S_ISGID);
  82. unlink(new_path.characters());
  83. }