gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/prctl.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include <sys/prctl.h>
    16  #include <sys/ptrace.h>
    17  #include <sys/types.h>
    18  #include <sys/wait.h>
    19  #include <unistd.h>
    20  
    21  #include <string>
    22  
    23  #include "gtest/gtest.h"
    24  #include "absl/flags/flag.h"
    25  #include "test/util/capability_util.h"
    26  #include "test/util/cleanup.h"
    27  #include "test/util/multiprocess_util.h"
    28  #include "test/util/posix_error.h"
    29  #include "test/util/signal_util.h"
    30  #include "test/util/test_util.h"
    31  #include "test/util/thread_util.h"
    32  
    33  ABSL_FLAG(bool, prctl_no_new_privs_test_child, false,
    34            "If true, exit with the return value of prctl(PR_GET_NO_NEW_PRIVS) "
    35            "plus an offset (see test source).");
    36  
    37  namespace gvisor {
    38  namespace testing {
    39  
    40  namespace {
    41  
    42  #ifndef SUID_DUMP_DISABLE
    43  #define SUID_DUMP_DISABLE 0
    44  #endif /* SUID_DUMP_DISABLE */
    45  #ifndef SUID_DUMP_USER
    46  #define SUID_DUMP_USER 1
    47  #endif /* SUID_DUMP_USER */
    48  #ifndef SUID_DUMP_ROOT
    49  #define SUID_DUMP_ROOT 2
    50  #endif /* SUID_DUMP_ROOT */
    51  
    52  TEST(PrctlTest, NameInitialized) {
    53    const size_t name_length = 20;
    54    char name[name_length] = {};
    55    ASSERT_THAT(prctl(PR_GET_NAME, name), SyscallSucceeds());
    56    ASSERT_NE(std::string(name), "");
    57  }
    58  
    59  TEST(PrctlTest, SetNameLongName) {
    60    const size_t name_length = 20;
    61    const std::string long_name(name_length, 'A');
    62    ASSERT_THAT(prctl(PR_SET_NAME, long_name.c_str()), SyscallSucceeds());
    63    char truncated_name[name_length] = {};
    64    ASSERT_THAT(prctl(PR_GET_NAME, truncated_name), SyscallSucceeds());
    65    const size_t truncated_length = 15;
    66    ASSERT_EQ(long_name.substr(0, truncated_length), std::string(truncated_name));
    67  }
    68  
    69  TEST(PrctlTest, ChildProcessName) {
    70    constexpr size_t kMaxNameLength = 15;
    71  
    72    char parent_name[kMaxNameLength + 1] = {};
    73    memset(parent_name, 'a', kMaxNameLength);
    74  
    75    ASSERT_THAT(prctl(PR_SET_NAME, parent_name), SyscallSucceeds());
    76  
    77    pid_t child_pid = fork();
    78    TEST_PCHECK(child_pid >= 0);
    79    if (child_pid == 0) {
    80      char child_name[kMaxNameLength + 1] = {};
    81      TEST_PCHECK(prctl(PR_GET_NAME, child_name) >= 0);
    82      TEST_CHECK(memcmp(parent_name, child_name, sizeof(parent_name)) == 0);
    83      _exit(0);
    84    }
    85  
    86    int status;
    87    ASSERT_THAT(waitpid(child_pid, &status, 0),
    88                SyscallSucceedsWithValue(child_pid));
    89    EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)
    90        << "status =" << status;
    91  }
    92  
    93  // Offset added to exit code from test child to distinguish from other abnormal
    94  // exits.
    95  constexpr int kPrctlNoNewPrivsTestChildExitBase = 100;
    96  
    97  TEST(PrctlTest, NoNewPrivsPreservedAcrossCloneForkAndExecve) {
    98    // Check if no_new_privs is already set. If it is, we can still test that it's
    99    // preserved across clone/fork/execve, but we also expect it to still be set
   100    // at the end of the test. Otherwise, call prctl(PR_SET_NO_NEW_PRIVS) so as
   101    // not to contaminate the original thread.
   102    int no_new_privs;
   103    ASSERT_THAT(no_new_privs = prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   104                SyscallSucceeds());
   105    ScopedThread thread = ScopedThread([] {
   106      ASSERT_THAT(prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), SyscallSucceeds());
   107      EXPECT_THAT(prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   108                  SyscallSucceedsWithValue(1));
   109      ScopedThread threadInner = ScopedThread([] {
   110        EXPECT_THAT(prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   111                    SyscallSucceedsWithValue(1));
   112        // Note that these ASSERT_*s failing will only return from this thread,
   113        // but this is the intended behavior.
   114        pid_t child_pid = -1;
   115        int execve_errno = 0;
   116        auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(
   117            ForkAndExec("/proc/self/exe",
   118                        {"/proc/self/exe", "--prctl_no_new_privs_test_child"}, {},
   119                        nullptr, &child_pid, &execve_errno));
   120  
   121        ASSERT_GT(child_pid, 0);
   122        ASSERT_EQ(execve_errno, 0);
   123  
   124        int status = 0;
   125        ASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0),
   126                    SyscallSucceeds());
   127        ASSERT_TRUE(WIFEXITED(status));
   128        ASSERT_EQ(WEXITSTATUS(status), kPrctlNoNewPrivsTestChildExitBase + 1);
   129  
   130        EXPECT_THAT(prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   131                    SyscallSucceedsWithValue(1));
   132      });
   133      threadInner.Join();
   134      EXPECT_THAT(prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   135                  SyscallSucceedsWithValue(1));
   136    });
   137    thread.Join();
   138    EXPECT_THAT(prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0),
   139                SyscallSucceedsWithValue(no_new_privs));
   140  }
   141  
   142  TEST(PrctlTest, PDeathSig) {
   143    pid_t child_pid;
   144  
   145    // Make the new process' parent a separate thread since the parent death
   146    // signal fires when the parent *thread* exits.
   147    ScopedThread thread = ScopedThread([&] {
   148      child_pid = fork();
   149      TEST_CHECK(child_pid >= 0);
   150      if (child_pid == 0) {
   151        // In child process.
   152        TEST_CHECK(prctl(PR_SET_PDEATHSIG, SIGKILL) >= 0);
   153        int signo;
   154        TEST_CHECK(prctl(PR_GET_PDEATHSIG, &signo) >= 0);
   155        TEST_CHECK(signo == SIGKILL);
   156        // Enable tracing, then raise SIGSTOP and expect our parent to suppress
   157        // it.
   158        TEST_CHECK(ptrace(PTRACE_TRACEME, 0, 0, 0) >= 0);
   159        TEST_CHECK(raise(SIGSTOP) == 0);
   160        // Sleep until killed by our parent death signal. sleep(3) is
   161        // async-signal-safe, absl::SleepFor isn't.
   162        while (true) {
   163          sleep(10);
   164        }
   165      }
   166      // In parent process.
   167  
   168      // Wait for the child to send itself SIGSTOP and enter signal-delivery-stop.
   169      int status;
   170      ASSERT_THAT(waitpid(child_pid, &status, 0),
   171                  SyscallSucceedsWithValue(child_pid));
   172      EXPECT_TRUE(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP)
   173          << "status = " << status;
   174  
   175      // Suppress the SIGSTOP and detach from the child.
   176      ASSERT_THAT(ptrace(PTRACE_DETACH, child_pid, 0, 0), SyscallSucceeds());
   177    });
   178    thread.Join();
   179  
   180    // The child should have been killed by its parent death SIGKILL.
   181    int status;
   182    ASSERT_THAT(waitpid(child_pid, &status, 0),
   183                SyscallSucceedsWithValue(child_pid));
   184    EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL)
   185        << "status = " << status;
   186  }
   187  
   188  // This test is to validate that calling prctl with PR_SET_MM without the
   189  // CAP_SYS_RESOURCE returns EPERM.
   190  TEST(PrctlTest, InvalidPrSetMM) {
   191    // Drop capability to test below.
   192    AutoCapability cap(CAP_SYS_RESOURCE, false);
   193    ASSERT_THAT(prctl(PR_SET_MM, 0, 0, 0, 0), SyscallFailsWithErrno(EPERM));
   194  }
   195  
   196  // Sanity check that dumpability is remembered.
   197  TEST(PrctlTest, SetGetDumpability) {
   198    int before;
   199    ASSERT_THAT(before = prctl(PR_GET_DUMPABLE), SyscallSucceeds());
   200    auto cleanup = Cleanup([before] {
   201      ASSERT_THAT(prctl(PR_SET_DUMPABLE, before), SyscallSucceeds());
   202    });
   203  
   204    EXPECT_THAT(prctl(PR_SET_DUMPABLE, SUID_DUMP_DISABLE), SyscallSucceeds());
   205    EXPECT_THAT(prctl(PR_GET_DUMPABLE),
   206                SyscallSucceedsWithValue(SUID_DUMP_DISABLE));
   207  
   208    EXPECT_THAT(prctl(PR_SET_DUMPABLE, SUID_DUMP_USER), SyscallSucceeds());
   209    EXPECT_THAT(prctl(PR_GET_DUMPABLE), SyscallSucceedsWithValue(SUID_DUMP_USER));
   210  }
   211  
   212  // SUID_DUMP_ROOT cannot be set via PR_SET_DUMPABLE.
   213  TEST(PrctlTest, RootDumpability) {
   214    EXPECT_THAT(prctl(PR_SET_DUMPABLE, SUID_DUMP_ROOT),
   215                SyscallFailsWithErrno(EINVAL));
   216  }
   217  
   218  TEST(PrctlTest, SimpleSetGetChildSubreaper) {
   219    // Tasks start off not subreaper.
   220    int is_subreaper = 0;
   221    EXPECT_THAT(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper), SyscallSucceeds());
   222    EXPECT_EQ(is_subreaper, 0);
   223  
   224    // Set to 1.
   225    EXPECT_THAT(prctl(PR_SET_CHILD_SUBREAPER, 1), SyscallSucceeds());
   226    EXPECT_THAT(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper), SyscallSucceeds());
   227    EXPECT_EQ(is_subreaper, 1);
   228  
   229    // Set to something positive but not 1.
   230    EXPECT_THAT(prctl(PR_SET_CHILD_SUBREAPER, 42), SyscallSucceeds());
   231    // Get still returns 1.
   232    EXPECT_THAT(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper), SyscallSucceeds());
   233    EXPECT_EQ(is_subreaper, 1);
   234  
   235    // Set to something negative.
   236    EXPECT_THAT(prctl(PR_SET_CHILD_SUBREAPER, -42), SyscallSucceeds());
   237    // Get still returns 1.
   238    EXPECT_THAT(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper), SyscallSucceeds());
   239    EXPECT_EQ(is_subreaper, 1);
   240  }
   241  
   242  TEST(PrctlTest, ThreadsInheritChildSubreaperBit) {
   243    // Set child subreaper bit.
   244    ASSERT_THAT(prctl(PR_SET_CHILD_SUBREAPER, 1), SyscallSucceeds());
   245    ScopedThread thread([&] {
   246      int is_subreaper = 0;
   247      ASSERT_THAT(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper),
   248                  SyscallSucceeds());
   249      EXPECT_EQ(is_subreaper, 1);
   250    });
   251  }
   252  
   253  TEST(PrctlTest, ProcessesDoNotInheritChildSubreaperBit) {
   254    // Set child subreaper bit.
   255    ASSERT_THAT(prctl(PR_SET_CHILD_SUBREAPER, 1), SyscallSucceeds());
   256  
   257    const auto rest = [&] {
   258      int is_subreaper = 0;
   259      TEST_CHECK_SUCCESS(prctl(PR_GET_CHILD_SUBREAPER, &is_subreaper));
   260      TEST_CHECK(is_subreaper == 0);
   261    };
   262  
   263    EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));
   264  }
   265  
   266  static std::atomic<bool> got_sigchild;
   267  
   268  void sigchild_handler(int sig, siginfo_t* siginfo, void* arg) {
   269    got_sigchild = true;
   270  }
   271  
   272  TEST(PrctlTest, OrphansReparentedToSubreaper) {
   273    // Set the subreaper bit.
   274    ASSERT_THAT(prctl(PR_SET_CHILD_SUBREAPER, 1), SyscallSucceeds());
   275  
   276    // Set up a signal handler to listen for reparented children.
   277    struct sigaction sa = {};
   278    sa.sa_sigaction = sigchild_handler;
   279    sigfillset(&sa.sa_mask);
   280    auto const sig_cleanup =
   281        ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGCHLD, sa));
   282  
   283    // Execute the test_app zombie_test, which will create an orphaned process
   284    // and expect that it is reaped.
   285    constexpr char kTestApp[] = "test/cmd/test_app/test_app";
   286    const std::string path = RunfilePath(kTestApp);
   287    int execve_errno;
   288    pid_t pid;
   289    auto exec_cleanup = ASSERT_NO_ERRNO_AND_VALUE(
   290        ForkAndExec(path, {path, "zombie_test"}, {}, &pid, &execve_errno));
   291    ASSERT_EQ(execve_errno, 0);
   292  
   293    // Wait for 2 children: the process we just started, and the orphan that will
   294    // be reparented to us.
   295    for (int i = 0; i < 2; i++) {
   296      int status;
   297      int wait_pid;
   298      ASSERT_THAT(wait_pid = RetryEINTR(waitpid)(-1, &status, 0),
   299                  SyscallSucceeds());
   300      if (wait_pid == pid) {
   301        // Test app should have exited cleanly.
   302        EXPECT_EQ(status, 0);
   303      }
   304    }
   305  
   306    // We should have gotten a SIGCHILD for the reparented orphan.
   307    EXPECT_TRUE(got_sigchild);
   308  }
   309  
   310  }  // namespace
   311  
   312  }  // namespace testing
   313  }  // namespace gvisor
   314  
   315  int main(int argc, char** argv) {
   316    gvisor::testing::TestInit(&argc, &argv);
   317  
   318    if (absl::GetFlag(FLAGS_prctl_no_new_privs_test_child)) {
   319      exit(gvisor::testing::kPrctlNoNewPrivsTestChildExitBase +
   320           prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0));
   321    }
   322  
   323    return gvisor::testing::RunAllTests();
   324  }