xref: /src/tests/sys/capsicum/procdesc.cc (revision fba81b33aabff74ad03d5f9f9663c176cf060fa6)
1 // Tests for the process descriptor API for Linux.
2 #include <sys/types.h>
3 #include <sys/resource.h>
4 #include <sys/select.h>
5 #include <sys/socket.h>
6 #include <sys/stat.h>
7 #include <sys/time.h>
8 #include <sys/wait.h>
9 #include <fcntl.h>
10 #include <poll.h>
11 #include <pthread.h>
12 #include <signal.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 
16 #include <iomanip>
17 #include <map>
18 
19 #include "capsicum.h"
20 #include "syscalls.h"
21 #include "capsicum-test.h"
22 
23 //------------------------------------------------
24 // Utilities for the tests.
25 
pdwait4_(int pd,int * status,int options,struct rusage * ru)26 static pid_t pdwait4_(int pd, int *status, int options, struct rusage *ru) {
27 #ifdef HAVE_PDWAIT4
28   return pdwait4(pd, status, options, ru);
29 #else
30   // Simulate pdwait4() with wait4(pdgetpid()); this won't work in capability mode.
31   pid_t pid = -1;
32   int rc = pdgetpid(pd, &pid);
33   if (rc < 0) {
34     return rc;
35   }
36   return wait4(pid, status, options, ru);
37 #endif
38 }
39 
print_rusage(FILE * f,struct rusage * ru)40 static void print_rusage(FILE *f, struct rusage *ru) {
41   fprintf(f, "  User CPU time=%ld.%06ld\n", (long)ru->ru_utime.tv_sec, (long)ru->ru_utime.tv_usec);
42   fprintf(f, "  System CPU time=%ld.%06ld\n", (long)ru->ru_stime.tv_sec, (long)ru->ru_stime.tv_usec);
43   fprintf(f, "  Max RSS=%ld\n", ru->ru_maxrss);
44 }
45 
print_stat(FILE * f,const struct stat * stat)46 static void print_stat(FILE *f, const struct stat *stat) {
47   fprintf(f,
48           "{ .st_dev=%ld, st_ino=%ld, st_mode=%04o, st_nlink=%ld, st_uid=%d, st_gid=%d,\n"
49           "  .st_rdev=%ld, .st_size=%ld, st_blksize=%ld, .st_block=%ld,\n  "
50           ".st_birthtime=%ld, "
51           ".st_atime=%ld, .st_mtime=%ld, .st_ctime=%ld}\n",
52           (long)stat->st_dev, (long)stat->st_ino, stat->st_mode,
53           (long)stat->st_nlink, stat->st_uid, stat->st_gid,
54           (long)stat->st_rdev, (long)stat->st_size, (long)stat->st_blksize,
55           (long)stat->st_blocks,
56           (long)stat->st_birthtime,
57           (long)stat->st_atime, (long)stat->st_mtime, (long)stat->st_ctime);
58 }
59 
60 static volatile sig_atomic_t had_signal[NSIG];
clear_had_signals()61 void clear_had_signals() {
62   memset(const_cast<sig_atomic_t *>(had_signal), 0, sizeof(had_signal));
63 }
handle_signal(int x)64 static void handle_signal(int x) {
65   had_signal[x] = true;
66 }
67 
68 // Check that the given child process terminates as expected.
CheckChildFinished(pid_t pid,bool signaled=false)69 void CheckChildFinished(pid_t pid, bool signaled=false) {
70   // Wait for the child to finish.
71   int rc;
72   int status = 0;
73   do {
74     rc = waitpid(pid, &status, 0);
75     if (rc < 0) {
76       fprintf(stderr, "Warning: waitpid error %s (%d)\n", strerror(errno), errno);
77       ADD_FAILURE() << "Failed to wait for child";
78       break;
79     } else if (rc == pid) {
80       break;
81     }
82   } while (true);
83   EXPECT_EQ(pid, rc);
84   if (rc == pid) {
85     if (signaled) {
86       EXPECT_TRUE(WIFSIGNALED(status));
87     } else {
88       EXPECT_TRUE(WIFEXITED(status)) << std::hex << status;
89       EXPECT_EQ(0, WEXITSTATUS(status));
90     }
91   }
92 }
93 
94 //------------------------------------------------
95 // Basic tests of process descriptor functionality
96 
TEST(Pdfork,Simple)97 TEST(Pdfork, Simple) {
98   int pd = -1;
99   int pipefds[2];
100   pid_t parent = getpid_();
101   EXPECT_OK(pipe(pipefds));
102   int pid = pdfork(&pd, 0);
103   EXPECT_OK(pid);
104   if (pid == 0) {
105     // Child: check pid values.
106     EXPECT_EQ(-1, pd);
107     EXPECT_NE(parent, getpid_());
108     EXPECT_EQ(parent, getppid());
109     close(pipefds[0]);
110     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
111     if (verbose) fprintf(stderr, "Child waiting for exit message\n");
112     // Terminate once the parent has completed the checks
113     AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
114     exit(testing::Test::HasFailure());
115   }
116   close(pipefds[1]);
117   // Ensure the child has started.
118   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
119 
120   EXPECT_NE(-1, pd);
121   EXPECT_PID_ALIVE(pid);
122   int pid_got;
123   EXPECT_OK(pdgetpid(pd, &pid_got));
124   EXPECT_EQ(pid, pid_got);
125 
126   // Tell the child to exit and wait until it is a zombie.
127   SEND_INT_MESSAGE(pipefds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
128   // EXPECT_PID_ZOMBIE waits for up to ~500ms, that should be enough time for
129   // the child to exit successfully.
130   EXPECT_PID_ZOMBIE(pid);
131   close(pipefds[0]);
132 
133   // Wait for the the child.
134   int status;
135   struct rusage ru;
136   memset(&ru, 0, sizeof(ru));
137   int waitrc = pdwait4_(pd, &status, 0, &ru);
138   EXPECT_EQ(pid, waitrc);
139   if (verbose) {
140     fprintf(stderr, "For pd %d pid %d:\n", pd, pid);
141     print_rusage(stderr, &ru);
142   }
143   EXPECT_PID_GONE(pid);
144 
145   // Can only pdwait4(pd) once (as initial call reaps zombie).
146   memset(&ru, 0, sizeof(ru));
147   EXPECT_EQ(-1, pdwait4_(pd, &status, 0, &ru));
148   EXPECT_EQ(ECHILD, errno);
149 
150   EXPECT_OK(close(pd));
151 }
152 
TEST(Pdfork,InvalidFlag)153 TEST(Pdfork, InvalidFlag) {
154   int pd = -1;
155   int pid = pdfork(&pd, PD_DAEMON<<5);
156   if (pid == 0) {
157     exit(1);
158   }
159   EXPECT_EQ(-1, pid);
160   EXPECT_EQ(EINVAL, errno);
161   if (pid > 0) waitpid(pid, NULL, 0);
162 }
163 
TEST(Pdfork,TimeCheck)164 TEST(Pdfork, TimeCheck) {
165   time_t now = time(NULL);  // seconds since epoch
166   EXPECT_NE(-1, now);
167   if (verbose) fprintf(stderr, "Calling pdfork around %ld\n", (long)(long)now);
168 
169   int pd = -1;
170   pid_t pid = pdfork(&pd, 0);
171   EXPECT_OK(pid);
172   if (pid == 0) {
173     // Child: check we didn't get a valid process descriptor then exit.
174     EXPECT_EQ(-1, pdgetpid(pd, &pid));
175     EXPECT_EQ(EBADF, errno);
176     exit(HasFailure());
177   }
178 
179   // Parent process. Ensure that [acm]times have been set correctly.
180   struct stat stat;
181   memset(&stat, 0, sizeof(stat));
182   EXPECT_OK(fstat(pd, &stat));
183   if (verbose) print_stat(stderr, &stat);
184 
185   EXPECT_GE(now, stat.st_birthtime);
186   EXPECT_EQ(stat.st_birthtime, stat.st_atime);
187   EXPECT_LT((now - stat.st_atime), 2);
188   EXPECT_EQ(stat.st_atime, stat.st_ctime);
189   EXPECT_EQ(stat.st_ctime, stat.st_mtime);
190 
191   // Wait for the child to finish.
192   pid_t pd_pid = -1;
193   EXPECT_OK(pdgetpid(pd, &pd_pid));
194   EXPECT_EQ(pid, pd_pid);
195   CheckChildFinished(pid);
196 }
197 
TEST(Pdfork,UseDescriptor)198 TEST(Pdfork, UseDescriptor) {
199   int pd = -1;
200   pid_t pid = pdfork(&pd, 0);
201   EXPECT_OK(pid);
202   if (pid == 0) {
203     // Child: immediately exit
204     exit(0);
205   }
206   CheckChildFinished(pid);
207 }
208 
TEST(Pdfork,NonProcessDescriptor)209 TEST(Pdfork, NonProcessDescriptor) {
210   int fd = open("/etc/passwd", O_RDONLY);
211   EXPECT_OK(fd);
212   // pd*() operations should fail on a non-process descriptor.
213   EXPECT_EQ(-1, pdkill(fd, SIGUSR1));
214   int status;
215   EXPECT_EQ(-1, pdwait4_(fd, &status, 0, NULL));
216   pid_t pid;
217   EXPECT_EQ(-1, pdgetpid(fd, &pid));
218   close(fd);
219 }
220 
SubThreadMain(void * arg)221 static void *SubThreadMain(void *arg) {
222   // Notify the main thread that we have started
223   if (verbose) fprintf(stderr, "      subthread started: pipe=%p\n", arg);
224   SEND_INT_MESSAGE((int)(intptr_t)arg, MSG_CHILD_STARTED);
225   while (true) {
226     if (verbose) fprintf(stderr, "      subthread: \"I aten't dead\"\n");
227     usleep(100000);
228   }
229   return NULL;
230 }
231 
ThreadMain(void *)232 static void *ThreadMain(void *) {
233   int pd;
234   int pipefds[2];
235   EXPECT_EQ(0, pipe(pipefds));
236   pid_t child = pdfork(&pd, 0);
237   if (child == 0) {
238     close(pipefds[0]);
239     // Child: start a subthread then loop.
240     pthread_t child_subthread;
241     // Wait for the subthread startup using another pipe.
242     int thread_pipefds[2];
243     EXPECT_EQ(0, pipe(thread_pipefds));
244     EXPECT_OK(pthread_create(&child_subthread, NULL, SubThreadMain,
245                              (void *)(intptr_t)thread_pipefds[0]));
246     if (verbose) {
247       fprintf(stderr, "    pdforked process %d: waiting for subthread.\n",
248               getpid());
249     }
250     AWAIT_INT_MESSAGE(thread_pipefds[1], MSG_CHILD_STARTED);
251     close(thread_pipefds[0]);
252     close(thread_pipefds[1]);
253     // Child: Notify parent that all threads have started
254     if (verbose) fprintf(stderr, "    pdforked process %d: subthread started\n", getpid());
255     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
256     while (true) {
257       if (verbose) fprintf(stderr, "    pdforked process %d: \"I aten't dead\"\n", getpid());
258       usleep(100000);
259     }
260     exit(0);
261   }
262   if (verbose) fprintf(stderr, "  thread generated pd %d\n", pd);
263   close(pipefds[1]);
264   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
265   if (verbose) fprintf(stderr, "[%d] got child startup message\n", getpid_());
266 
267   // Pass the process descriptor back to the main thread.
268   return reinterpret_cast<void *>(pd);
269 }
270 
TEST(Pdfork,FromThread)271 TEST(Pdfork, FromThread) {
272   // Fire off a new thread to do all of the creation work.
273   pthread_t child_thread;
274   EXPECT_OK(pthread_create(&child_thread, NULL, ThreadMain, NULL));
275   void *data;
276   EXPECT_OK(pthread_join(child_thread, &data));
277   int pd = reinterpret_cast<intptr_t>(data);
278   if (verbose) fprintf(stderr, "retrieved pd %d from terminated thread\n", pd);
279 
280   // Kill and reap.
281   pid_t pid;
282   EXPECT_OK(pdgetpid(pd, &pid));
283   EXPECT_OK(pdkill(pd, SIGKILL));
284   int status;
285   EXPECT_EQ(pid, pdwait4_(pd, &status, 0, NULL));
286   EXPECT_TRUE(WIFSIGNALED(status));
287 }
288 
289 //------------------------------------------------
290 // More complicated tests.
291 
292 
293 // Test fixture that pdfork()s off a child process, which terminates
294 // when it receives anything on a pipe.
295 class PipePdforkBase : public ::testing::Test {
296  public:
PipePdforkBase(int pdfork_flags)297   PipePdforkBase(int pdfork_flags) : pd_(-1), pid_(-1) {
298     clear_had_signals();
299     int pipes[2];
300     EXPECT_OK(pipe(pipes));
301     pipe_ = pipes[1];
302     int parent = getpid_();
303     if (verbose) fprintf(stderr, "[%d] about to pdfork()\n", getpid_());
304     int rc = pdfork(&pd_, pdfork_flags);
305     EXPECT_OK(rc);
306     if (rc == 0) {
307       // Child process: blocking-read an int from the pipe then exit with that value.
308       EXPECT_NE(parent, getpid_());
309       EXPECT_EQ(parent, getppid());
310       if (verbose) fprintf(stderr, "  [%d] child of %d waiting for value on pipe\n", getpid_(), getppid());
311       read(pipes[0], &rc, sizeof(rc));
312       if (verbose) fprintf(stderr, "  [%d] got value %d on pipe, exiting\n", getpid_(), rc);
313       exit(rc);
314     }
315     pid_ = rc;
316     usleep(100);  // ensure the child has a chance to run
317   }
~PipePdforkBase()318   ~PipePdforkBase() {
319     // Terminate by any means necessary.
320     if (pd_ > 0) {
321       pdkill(pd_, SIGKILL);
322       close(pd_);
323     }
324     if (pid_ > 0) {
325       kill(pid_, SIGKILL);
326       waitpid(pid_, NULL, WNOHANG);
327     }
328     // Check signal expectations.
329     EXPECT_FALSE(had_signal[SIGCHLD]);
330   }
TerminateChild()331   int TerminateChild() {
332     // Tell the child to exit.
333     int zero = 0;
334     if (verbose) fprintf(stderr, "[%d] write 0 to pipe\n", getpid_());
335     return write(pipe_, &zero, sizeof(zero));
336   }
337  protected:
338   int pd_;
339   int pipe_;
340   pid_t pid_;
341 };
342 
343 class PipePdfork : public PipePdforkBase {
344  public:
PipePdfork()345   PipePdfork() : PipePdforkBase(0) {}
346 };
347 
348 class PipePdforkDaemon : public PipePdforkBase {
349  public:
PipePdforkDaemon()350   PipePdforkDaemon() : PipePdforkBase(PD_DAEMON) {}
351 };
352 
353 // Can we poll a process descriptor?
TEST_F(PipePdfork,Poll)354 TEST_F(PipePdfork, Poll) {
355   // Poll the process descriptor, nothing happening.
356   struct pollfd fdp;
357   fdp.fd = pd_;
358   fdp.events = POLLIN | POLLERR | POLLHUP;
359   fdp.revents = 0;
360   EXPECT_EQ(0, poll(&fdp, 1, 0));
361 
362   TerminateChild();
363 
364   // Poll again, should have activity on the process descriptor.
365   EXPECT_EQ(1, poll(&fdp, 1, 2000));
366   EXPECT_TRUE(fdp.revents & POLLHUP);
367 
368   // Poll a third time, still have POLLHUP.
369   fdp.revents = 0;
370   EXPECT_EQ(1, poll(&fdp, 1, 0));
371   EXPECT_TRUE(fdp.revents & POLLHUP);
372 }
373 
374 // Can multiple processes poll on the same descriptor?
TEST_F(PipePdfork,PollMultiple)375 TEST_F(PipePdfork, PollMultiple) {
376   int pipefds[2];
377   EXPECT_EQ(0, pipe(pipefds));
378   int child = fork();
379   EXPECT_OK(child);
380   if (child == 0) {
381     close(pipefds[0]);
382     // Child: wait for parent to acknowledge startup
383     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
384     // Child: wait for two messages from the parent and the forked process
385     // before telling the other process to terminate.
386     if (verbose) fprintf(stderr, "[%d] waiting for read 1\n", getpid_());
387     AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
388     if (verbose) fprintf(stderr, "[%d] waiting for read 2\n", getpid_());
389     AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
390     TerminateChild();
391     if (verbose) fprintf(stderr, "[%d] about to exit\n", getpid_());
392     exit(testing::Test::HasFailure());
393   }
394   close(pipefds[1]);
395   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
396   if (verbose) fprintf(stderr, "[%d] got child startup message\n", getpid_());
397   // Fork again
398   int doppel = fork();
399   EXPECT_OK(doppel);
400   // We now have:
401   //   pid A: main process, here
402   //   |--pid B: pdfork()ed process, blocked on read()
403   //   |--pid C: fork()ed process, in read() above
404   //   +--pid D: doppel process, here
405 
406   // Both A and D execute the following code.
407   // First, check no activity on the process descriptor yet.
408   struct pollfd fdp;
409   fdp.fd = pd_;
410   fdp.events = POLLIN | POLLERR | POLLHUP;
411   fdp.revents = 0;
412   EXPECT_EQ(0, poll(&fdp, 1, 0));
413 
414   // Both A and D ask C to exit, allowing it to do so.
415   if (verbose) fprintf(stderr, "[%d] telling child to exit\n", getpid_());
416   SEND_INT_MESSAGE(pipefds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
417   close(pipefds[0]);
418 
419   // Now, wait (indefinitely) for activity on the process descriptor.
420   // We expect:
421   //  - pid C will finish its two read() calls, write to the pipe and exit.
422   //  - pid B will unblock from read(), and exit
423   //  - this will generate an event on the process descriptor...
424   //  - ...in both process A and process D.
425   if (verbose) fprintf(stderr, "[%d] waiting for child to exit\n", getpid_());
426   EXPECT_EQ(1, poll(&fdp, 1, 2000));
427   EXPECT_TRUE(fdp.revents & POLLHUP);
428 
429   if (doppel == 0) {
430     // Child: process D exits.
431     exit(0);
432   } else {
433     // Parent: wait on process D.
434     int rc = 0;
435     waitpid(doppel, &rc, 0);
436     EXPECT_TRUE(WIFEXITED(rc));
437     EXPECT_EQ(0, WEXITSTATUS(rc));
438     // Also wait on process B.
439     CheckChildFinished(child);
440   }
441 }
442 
443 // Check that exit status/rusage for a dead pdfork()ed child can be retrieved
444 // via any process descriptor, multiple times.
TEST_F(PipePdfork,MultipleRetrieveExitStatus)445 TEST_F(PipePdfork, MultipleRetrieveExitStatus) {
446   EXPECT_PID_ALIVE(pid_);
447   int pd_copy = dup(pd_);
448   EXPECT_LT(0, TerminateChild());
449 
450   int status;
451   struct rusage ru;
452   memset(&ru, 0, sizeof(ru));
453   int waitrc = pdwait4_(pd_copy, &status, 0, &ru);
454   EXPECT_EQ(pid_, waitrc);
455   if (verbose) {
456     fprintf(stderr, "For pd %d -> pid %d:\n", pd_, pid_);
457     print_rusage(stderr, &ru);
458   }
459   EXPECT_PID_GONE(pid_);
460 
461 #ifdef NOTYET
462   // Child has been reaped, so original process descriptor dangles but
463   // still has access to rusage information.
464   memset(&ru, 0, sizeof(ru));
465   EXPECT_EQ(0, pdwait4_(pd_, &status, 0, &ru));
466 #endif
467   close(pd_copy);
468 }
469 
TEST_F(PipePdfork,ChildExit)470 TEST_F(PipePdfork, ChildExit) {
471   EXPECT_PID_ALIVE(pid_);
472   EXPECT_LT(0, TerminateChild());
473   EXPECT_PID_DEAD(pid_);
474 
475   int status;
476   int rc = pdwait4_(pd_, &status, 0, NULL);
477   EXPECT_OK(rc);
478   EXPECT_EQ(pid_, rc);
479   pid_ = 0;
480 }
481 
482 // Closing a normal process descriptor terminates the underlying process.
TEST_F(PipePdfork,Close)483 TEST_F(PipePdfork, Close) {
484   sighandler_t original = signal(SIGCHLD, handle_signal);
485   EXPECT_PID_ALIVE(pid_);
486   int status;
487   EXPECT_EQ(0, waitpid(pid_, &status, WNOHANG));
488 
489   EXPECT_OK(close(pd_));
490   pd_ = -1;
491   EXPECT_FALSE(had_signal[SIGCHLD]);
492   EXPECT_PID_DEAD(pid_);
493 
494 #ifdef __FreeBSD__
495   EXPECT_EQ(-1, waitpid(pid_, NULL, 0));
496   EXPECT_EQ(errno, ECHILD);
497 #else
498   // Having closed the process descriptor means that pdwait4(pd) now doesn't work.
499   int rc = pdwait4_(pd_, &status, 0, NULL);
500   EXPECT_EQ(-1, rc);
501   EXPECT_EQ(EBADF, errno);
502 
503   // Closing all process descriptors means the the child can only be reaped via pid.
504   EXPECT_EQ(pid_, waitpid(pid_, &status, WNOHANG));
505 #endif
506   signal(SIGCHLD, original);
507 }
508 
TEST_F(PipePdfork,CloseLast)509 TEST_F(PipePdfork, CloseLast) {
510   sighandler_t original = signal(SIGCHLD, handle_signal);
511   // Child should only die when last process descriptor is closed.
512   EXPECT_PID_ALIVE(pid_);
513   int pd_other = dup(pd_);
514 
515   EXPECT_OK(close(pd_));
516   pd_ = -1;
517 
518   EXPECT_PID_ALIVE(pid_);
519   int status;
520   EXPECT_EQ(0, waitpid(pid_, &status, WNOHANG));
521 
522   // Can no longer pdwait4() the closed process descriptor...
523   EXPECT_EQ(-1, pdwait4_(pd_, &status, WNOHANG, NULL));
524   EXPECT_EQ(EBADF, errno);
525   // ...but can pdwait4() the still-open process descriptor.
526   errno = 0;
527   EXPECT_EQ(0, pdwait4_(pd_other, &status, WNOHANG, NULL));
528   EXPECT_EQ(0, errno);
529 
530   EXPECT_OK(close(pd_other));
531   EXPECT_PID_DEAD(pid_);
532 
533   EXPECT_FALSE(had_signal[SIGCHLD]);
534   signal(SIGCHLD, original);
535 }
536 
FORK_TEST(Pdfork,OtherUserIfRoot)537 FORK_TEST(Pdfork, OtherUserIfRoot) {
538   GTEST_SKIP_IF_NOT_ROOT();
539   int pd;
540   int status;
541   pid_t pid = pdfork(&pd, 0);
542   EXPECT_OK(pid);
543   if (pid == 0) {
544     // Child process: loop forever.
545     while (true) usleep(100000);
546   }
547   usleep(100);
548 
549   // Now that the second process has been pdfork()ed, change euid.
550   ASSERT_NE(0u, other_uid) << "other_uid not initialized correctly, "
551                               "please pass the -u <uid> flag.";
552   EXPECT_EQ(0, setuid(other_uid));
553   EXPECT_EQ(other_uid, getuid());
554   if (verbose) fprintf(stderr, "uid=%d euid=%d\n", getuid(), geteuid());
555 
556   // Fail to kill child with normal PID operation.
557   EXPECT_EQ(-1, kill(pid, SIGKILL));
558   EXPECT_EQ(EPERM, errno);
559   EXPECT_PID_ALIVE(pid);
560 
561   // Ideally, we should be able to send signals via a process descriptor even
562   // if it's owned by another user, but this is not implementated on FreeBSD.
563 #ifdef __FreeBSD__
564   // On FreeBSD, pdkill() still performs all the same checks that kill() does
565   // and therefore cannot be used to send a signal to a process with another
566   // UID unless we are root.
567   EXPECT_SYSCALL_FAIL(EBADF, pdkill(pid, SIGKILL));
568   EXPECT_PID_ALIVE(pid);
569   // However, the process will be killed when we close the process descriptor.
570   EXPECT_OK(close(pd));
571   EXPECT_PID_GONE(pid);
572   // Can't pdwait4() after close() since close() reparents the child to a reaper (init)
573   EXPECT_SYSCALL_FAIL(EBADF, pdwait4_(pd, &status, WNOHANG, NULL));
574 #else
575   // Sending a signal with pdkill() should be permitted though.
576   EXPECT_OK(pdkill(pd, SIGKILL));
577   EXPECT_PID_ZOMBIE(pid);
578 
579   int rc = pdwait4_(pd, &status, WNOHANG, NULL);
580   EXPECT_OK(rc);
581   EXPECT_EQ(pid, rc);
582   EXPECT_TRUE(WIFSIGNALED(status));
583 #endif
584 }
585 
TEST_F(PipePdfork,WaitPidThenPd)586 TEST_F(PipePdfork, WaitPidThenPd) {
587   TerminateChild();
588   int status;
589   // If we waitpid(pid) first...
590   int rc = waitpid(pid_, &status, 0);
591   EXPECT_OK(rc);
592   EXPECT_EQ(pid_, rc);
593 
594 #ifdef NOTYET
595   // ...the zombie is reaped but we can still subsequently pdwait4(pd).
596   EXPECT_EQ(0, pdwait4_(pd_, &status, 0, NULL));
597 #endif
598 }
599 
TEST_F(PipePdfork,WaitPdThenPid)600 TEST_F(PipePdfork, WaitPdThenPid) {
601   TerminateChild();
602   int status;
603   // If we pdwait4(pd) first...
604   int rc = pdwait4_(pd_, &status, 0, NULL);
605   EXPECT_OK(rc);
606   EXPECT_EQ(pid_, rc);
607 
608   // ...the zombie is reaped and cannot subsequently waitpid(pid).
609   EXPECT_EQ(-1, waitpid(pid_, &status, 0));
610   EXPECT_EQ(ECHILD, errno);
611 }
612 
613 // Setting PD_DAEMON prevents close() from killing the child.
TEST_F(PipePdforkDaemon,Close)614 TEST_F(PipePdforkDaemon, Close) {
615   EXPECT_OK(close(pd_));
616   pd_ = -1;
617   EXPECT_PID_ALIVE(pid_);
618 
619   // Can still explicitly kill it via the pid.
620   if (pid_ > 0) {
621     EXPECT_OK(kill(pid_, SIGKILL));
622     EXPECT_PID_DEAD(pid_);
623   }
624 }
625 
TestPdkill(pid_t pid,int pd)626 static void TestPdkill(pid_t pid, int pd) {
627   EXPECT_PID_ALIVE(pid);
628   // SIGCONT is ignored by default.
629   EXPECT_OK(pdkill(pd, SIGCONT));
630   EXPECT_PID_ALIVE(pid);
631 
632   // SIGINT isn't
633   EXPECT_OK(pdkill(pd, SIGINT));
634   EXPECT_PID_DEAD(pid);
635 
636   // pdkill() on zombie is no-op.
637   errno = 0;
638   EXPECT_EQ(0, pdkill(pd, SIGINT));
639   EXPECT_EQ(0, errno);
640 
641   // pdkill() on reaped process gives -ESRCH.
642   CheckChildFinished(pid, true);
643   EXPECT_EQ(-1, pdkill(pd, SIGINT));
644   EXPECT_EQ(ESRCH, errno);
645 }
646 
TEST_F(PipePdfork,Pdkill)647 TEST_F(PipePdfork, Pdkill) {
648   TestPdkill(pid_, pd_);
649 }
650 
TEST_F(PipePdforkDaemon,Pdkill)651 TEST_F(PipePdforkDaemon, Pdkill) {
652   TestPdkill(pid_, pd_);
653 }
654 
TEST(Pdfork,PdkillOtherSignal)655 TEST(Pdfork, PdkillOtherSignal) {
656   int pd = -1;
657   int pipefds[2];
658   EXPECT_EQ(0, pipe(pipefds));
659   int pid = pdfork(&pd, 0);
660   EXPECT_OK(pid);
661   if (pid == 0) {
662     // Child: tell the parent that we have started before entering the loop,
663     // and importantly only do so once we have registered the SIGUSR1 handler.
664     close(pipefds[0]);
665     clear_had_signals();
666     signal(SIGUSR1, handle_signal);
667     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
668     // Child: watch for SIGUSR1 forever.
669     while (!had_signal[SIGUSR1]) {
670       usleep(100000);
671     }
672     exit(123);
673   }
674   // Wait for child to start
675   close(pipefds[1]);
676   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
677   close(pipefds[0]);
678 
679   // Send an invalid signal.
680   EXPECT_EQ(-1, pdkill(pd, 0xFFFF));
681   EXPECT_EQ(EINVAL, errno);
682 
683   // Send an expected SIGUSR1 to the pdfork()ed child.
684   EXPECT_PID_ALIVE(pid);
685   pdkill(pd, SIGUSR1);
686   EXPECT_PID_DEAD(pid);
687 
688   // Child's exit status confirms whether it received the signal.
689   int status;
690   int rc = waitpid(pid, &status, 0);
691   EXPECT_OK(rc);
692   EXPECT_EQ(pid, rc);
693   EXPECT_TRUE(WIFEXITED(status)) << "status: 0x" << std::hex << status;
694   EXPECT_EQ(123, WEXITSTATUS(status));
695 }
696 
PdforkParentDeath(int pdfork_flags)697 pid_t PdforkParentDeath(int pdfork_flags) {
698   // Set up:
699   //   pid A: main process, here
700   //   +--pid B: fork()ed process, starts a child process with pdfork() then
701   //             waits for parent to send a shutdown message.
702   //      +--pid C: pdfork()ed process, looping forever
703   int sock_fds[2];
704   EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
705   if (verbose) fprintf(stderr, "[%d] parent about to fork()...\n", getpid_());
706   pid_t child = fork();
707   EXPECT_OK(child);
708   if (child == 0) {
709     int pd;
710     if (verbose) fprintf(stderr, "  [%d] child about to pdfork()...\n", getpid_());
711     int pipefds[2]; // for startup notification
712     EXPECT_OK(pipe(pipefds));
713     pid_t grandchild = pdfork(&pd, pdfork_flags);
714     if (grandchild == 0) {
715       close(pipefds[0]);
716       pid_t grandchildPid = getpid_();
717       EXPECT_EQ(sizeof(grandchildPid), (size_t)write(pipefds[1], &grandchildPid, sizeof(grandchildPid)));
718       while (true) {
719         if (verbose) fprintf(stderr, "    [%d] grandchild: \"I aten't dead\"\n", grandchildPid);
720         sleep(1);
721       }
722     }
723     close(pipefds[1]);
724     if (verbose) fprintf(stderr, "  [%d] pdfork()ed grandchild %d, sending ID to parent\n", getpid_(), grandchild);
725     // Wait for grandchild to start.
726     pid_t grandchild2;
727     EXPECT_EQ(sizeof(grandchild2), (size_t)read(pipefds[0], &grandchild2, sizeof(grandchild2)));
728     EXPECT_EQ(grandchild, grandchild2) << "received invalid grandchild pid";
729     if (verbose) fprintf(stderr, "  [%d] grandchild %d has started successfully\n", getpid_(), grandchild);
730     close(pipefds[0]);
731 
732     // Send grandchild pid to parent.
733     EXPECT_EQ(sizeof(grandchild), (size_t)write(sock_fds[1], &grandchild, sizeof(grandchild)));
734     if (verbose) fprintf(stderr, "  [%d] sent grandchild pid %d to parent\n", getpid_(), grandchild);
735     // Wait for parent to acknowledge the message.
736     AWAIT_INT_MESSAGE(sock_fds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
737     if (verbose) fprintf(stderr, "  [%d] parent acknowledged grandchild pid %d\n", getpid_(), grandchild);
738     if (verbose) fprintf(stderr, "  [%d] child terminating\n", getpid_());
739     exit(testing::Test::HasFailure());
740   }
741   if (verbose) fprintf(stderr, "[%d] fork()ed child is %d\n", getpid_(), child);
742   pid_t grandchild;
743   read(sock_fds[0], &grandchild, sizeof(grandchild));
744   if (verbose) fprintf(stderr, "[%d] received grandchild id %d\n", getpid_(), grandchild);
745   EXPECT_PID_ALIVE(child);
746   EXPECT_PID_ALIVE(grandchild);
747   // Tell child to exit.
748   if (verbose) fprintf(stderr, "[%d] telling child %d to exit\n", getpid_(), child);
749   SEND_INT_MESSAGE(sock_fds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
750   // Child dies, closing its process descriptor for the grandchild.
751   EXPECT_PID_DEAD(child);
752   CheckChildFinished(child);
753   return grandchild;
754 }
755 
TEST(Pdfork,Bagpuss)756 TEST(Pdfork, Bagpuss) {
757   // "And of course when Bagpuss goes to sleep, all his friends go to sleep too"
758   pid_t grandchild = PdforkParentDeath(0);
759   // By default: child death => closed process descriptor => grandchild death.
760   EXPECT_PID_DEAD(grandchild);
761 }
762 
TEST(Pdfork,BagpussDaemon)763 TEST(Pdfork, BagpussDaemon) {
764   pid_t grandchild = PdforkParentDeath(PD_DAEMON);
765   // With PD_DAEMON: child death => closed process descriptor => no effect on grandchild.
766   EXPECT_PID_ALIVE(grandchild);
767   if (grandchild > 0) {
768     EXPECT_OK(kill(grandchild, SIGKILL));
769   }
770 }
771 
772 // The exit of a pdfork()ed process should not generate SIGCHLD.
TEST_F(PipePdfork,NoSigchld)773 TEST_F(PipePdfork, NoSigchld) {
774   clear_had_signals();
775   sighandler_t original = signal(SIGCHLD, handle_signal);
776   TerminateChild();
777   int rc = 0;
778   // Can waitpid() for the specific pid of the pdfork()ed child.
779   EXPECT_EQ(pid_, waitpid(pid_, &rc, 0));
780   EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
781   EXPECT_FALSE(had_signal[SIGCHLD]);
782   signal(SIGCHLD, original);
783 }
784 
785 // The exit of a pdfork()ed process whose process descriptors have
786 // all been closed should generate SIGCHLD.  The child process needs
787 // PD_DAEMON to survive the closure of the process descriptors.
TEST_F(PipePdforkDaemon,NoPDSigchld)788 TEST_F(PipePdforkDaemon, NoPDSigchld) {
789   clear_had_signals();
790   sighandler_t original = signal(SIGCHLD, handle_signal);
791 
792   EXPECT_OK(close(pd_));
793   TerminateChild();
794 #ifdef __FreeBSD__
795   EXPECT_EQ(-1, waitpid(pid_, NULL, 0));
796   EXPECT_EQ(errno, ECHILD);
797 #else
798   int rc = 0;
799   // Can waitpid() for the specific pid of the pdfork()ed child.
800   EXPECT_EQ(pid_, waitpid(pid_, &rc, 0));
801   EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
802 #endif
803   EXPECT_FALSE(had_signal[SIGCHLD]);
804   signal(SIGCHLD, original);
805 }
806 
TEST_F(PipePdfork,ModeBits)807 TEST_F(PipePdfork, ModeBits) {
808   // Owner rwx bits indicate liveness of child
809   struct stat stat;
810   memset(&stat, 0, sizeof(stat));
811   EXPECT_OK(fstat(pd_, &stat));
812   if (verbose) print_stat(stderr, &stat);
813   EXPECT_EQ(S_IRWXU, (long)(stat.st_mode & S_IRWXU));
814 
815   TerminateChild();
816   usleep(100000);
817 
818   memset(&stat, 0, sizeof(stat));
819   EXPECT_OK(fstat(pd_, &stat));
820   if (verbose) print_stat(stderr, &stat);
821   EXPECT_EQ(0, (int)(stat.st_mode & S_IRWXU));
822 }
823 
TEST_F(PipePdfork,WildcardWait)824 TEST_F(PipePdfork, WildcardWait) {
825   TerminateChild();
826   EXPECT_PID_ZOMBIE(pid_);  // Ensure child is truly dead.
827 
828   // Wildcard waitpid(-1) should not see the pdfork()ed child because
829   // there is still a process descriptor for it.
830   int rc;
831   EXPECT_EQ(-1, waitpid(-1, &rc, WNOHANG));
832   EXPECT_EQ(ECHILD, errno);
833 
834   EXPECT_OK(close(pd_));
835   pd_ = -1;
836 }
837 
FORK_TEST(Pdfork,Pdkill)838 FORK_TEST(Pdfork, Pdkill) {
839   clear_had_signals();
840   int pd;
841   int pipefds[2];
842   EXPECT_OK(pipe(pipefds));
843   pid_t pid = pdfork(&pd, 0);
844   EXPECT_OK(pid);
845 
846   if (pid == 0) {
847     // Child: set a SIGINT handler, notify the parent and sleep.
848     close(pipefds[0]);
849     clear_had_signals();
850     signal(SIGINT, handle_signal);
851     if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
852     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
853     if (verbose) fprintf(stderr, "[%d] child about to sleep(10)\n", getpid_());
854     // Note: we could receive the SIGINT just before sleep(), so we use a loop
855     // with a short delay instead of one long sleep().
856     for (int i = 0; i < 50 && !had_signal[SIGINT]; i++) {
857       usleep(100000);
858     }
859     if (verbose) fprintf(stderr, "[%d] child slept, had[SIGINT]=%d\n",
860                          getpid_(), (int)had_signal[SIGINT]);
861     // Return non-zero if we didn't see SIGINT.
862     exit(had_signal[SIGINT] ? 0 : 99);
863   }
864 
865   // Parent: get child's PID.
866   pid_t pd_pid;
867   EXPECT_OK(pdgetpid(pd, &pd_pid));
868   EXPECT_EQ(pid, pd_pid);
869 
870   // Interrupt the child once it's registered the SIGINT handler.
871   close(pipefds[1]);
872   if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
873   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
874   EXPECT_OK(pdkill(pd, SIGINT));
875   if (verbose) fprintf(stderr, "[%d] sent SIGINT\n", getpid_());
876 
877   // Make sure the child finished properly (caught signal then exited).
878   CheckChildFinished(pid);
879 }
880 
FORK_TEST(Pdfork,PdkillSignal)881 FORK_TEST(Pdfork, PdkillSignal) {
882   int pd;
883   int pipefds[2];
884   EXPECT_OK(pipe(pipefds));
885   pid_t pid = pdfork(&pd, 0);
886   EXPECT_OK(pid);
887 
888   if (pid == 0) {
889     close(pipefds[0]);
890     if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
891     SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
892     // Child: wait for shutdown message. No SIGINT handler. The message should
893     // never be received, since SIGINT should terminate the process.
894     if (verbose) fprintf(stderr, "[%d] child about to read()\n", getpid_());
895     AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
896     fprintf(stderr, "[%d] child read() returned unexpectedly\n", getpid_());
897     exit(99);
898   }
899   // Wait for child to start before signalling.
900   if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
901   close(pipefds[1]);
902   AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
903   // Kill the child (as it doesn't handle SIGINT).
904   if (verbose) fprintf(stderr, "[%d] sending SIGINT\n", getpid_());
905   EXPECT_OK(pdkill(pd, SIGINT));
906 
907   // Make sure the child finished properly (terminated by signal).
908   CheckChildFinished(pid, true);
909 }
910 
911 //------------------------------------------------
912 // Test interactions with other parts of Capsicum:
913 //  - capability mode
914 //  - capabilities
915 
FORK_TEST(Pdfork,DaemonUnrestricted)916 FORK_TEST(Pdfork, DaemonUnrestricted) {
917   EXPECT_OK(cap_enter());
918   int fd;
919 
920   // Capability mode leaves pdfork() available, with and without flag.
921   int rc;
922   rc = pdfork(&fd, PD_DAEMON);
923   EXPECT_OK(rc);
924   if (rc == 0) {
925     // Child: immediately terminate.
926     exit(0);
927   }
928 
929   rc = pdfork(&fd, 0);
930   EXPECT_OK(rc);
931   if (rc == 0) {
932     // Child: immediately terminate.
933     exit(0);
934   }
935 }
936 
TEST(Pdfork,MissingRights)937 TEST(Pdfork, MissingRights) {
938   pid_t parent = getpid_();
939   int pd = -1;
940   pid_t pid = pdfork(&pd, 0);
941   EXPECT_OK(pid);
942   if (pid == 0) {
943     // Child: loop forever.
944     EXPECT_NE(parent, getpid_());
945     while (true) sleep(1);
946   }
947   // Create two capabilities from the process descriptor.
948   cap_rights_t r_ro;
949   cap_rights_init(&r_ro, CAP_READ, CAP_LOOKUP);
950   int cap_incapable = dup(pd);
951   EXPECT_OK(cap_incapable);
952   EXPECT_OK(cap_rights_limit(cap_incapable, &r_ro));
953   cap_rights_t r_pdall;
954   cap_rights_init(&r_pdall, CAP_PDGETPID, CAP_PDWAIT, CAP_PDKILL);
955   int cap_capable = dup(pd);
956   EXPECT_OK(cap_capable);
957   EXPECT_OK(cap_rights_limit(cap_capable, &r_pdall));
958 
959   pid_t other_pid;
960   EXPECT_NOTCAPABLE(pdgetpid(cap_incapable, &other_pid));
961   EXPECT_NOTCAPABLE(pdkill(cap_incapable, SIGINT));
962   int status;
963   EXPECT_NOTCAPABLE(pdwait4_(cap_incapable, &status, 0, NULL));
964 
965   EXPECT_OK(pdgetpid(cap_capable, &other_pid));
966   EXPECT_EQ(pid, other_pid);
967   EXPECT_OK(pdkill(cap_capable, SIGINT));
968   int rc = pdwait4_(pd, &status, 0, NULL);
969   EXPECT_OK(rc);
970   EXPECT_EQ(pid, rc);
971 }
972 
973 
974 //------------------------------------------------
975 // Passing process descriptors between processes.
976 
TEST_F(PipePdfork,PassProcessDescriptor)977 TEST_F(PipePdfork, PassProcessDescriptor) {
978   int sock_fds[2];
979   EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
980 
981   struct msghdr mh;
982   mh.msg_name = NULL;  // No address needed
983   mh.msg_namelen = 0;
984   char buffer1[1024];
985   struct iovec iov[1];
986   iov[0].iov_base = buffer1;
987   iov[0].iov_len = sizeof(buffer1);
988   mh.msg_iov = iov;
989   mh.msg_iovlen = 1;
990   char buffer2[1024];
991   mh.msg_control = buffer2;
992   mh.msg_controllen = sizeof(buffer2);
993   struct cmsghdr *cmptr;
994 
995   if (verbose) fprintf(stderr, "[%d] about to fork()\n", getpid_());
996   pid_t child2 = fork();
997   if (child2 == 0) {
998     // Child: close our copy of the original process descriptor.
999     close(pd_);
1000     SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_STARTED);
1001     // Child: wait to receive process descriptor over socket
1002     if (verbose) fprintf(stderr, "  [%d] child of %d waiting for process descriptor on socket\n", getpid_(), getppid());
1003     int rc = recvmsg(sock_fds[0], &mh, 0);
1004     EXPECT_OK(rc);
1005     EXPECT_LE(CMSG_LEN(sizeof(int)), mh.msg_controllen);
1006     cmptr = CMSG_FIRSTHDR(&mh);
1007     int pd = *(int*)CMSG_DATA(cmptr);
1008     EXPECT_EQ(CMSG_LEN(sizeof(int)), cmptr->cmsg_len);
1009     cmptr = CMSG_NXTHDR(&mh, cmptr);
1010     EXPECT_TRUE(cmptr == NULL);
1011     if (verbose) fprintf(stderr, "  [%d] got process descriptor %d on socket\n", getpid_(), pd);
1012     SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_FD_RECEIVED);
1013 
1014     // Child: confirm we can do pd*() operations on the process descriptor
1015     pid_t other;
1016     EXPECT_OK(pdgetpid(pd, &other));
1017     if (verbose) fprintf(stderr, "  [%d] process descriptor %d is pid %d\n", getpid_(), pd, other);
1018 
1019     // Wait until the parent has closed the process descriptor.
1020     AWAIT_INT_MESSAGE(sock_fds[0], MSG_PARENT_CLOSED_FD);
1021 
1022     if (verbose) fprintf(stderr, "  [%d] close process descriptor %d\n", getpid_(), pd);
1023     close(pd);
1024 
1025     // Last process descriptor closed, expect death
1026     EXPECT_PID_DEAD(other);
1027 
1028     exit(HasFailure());
1029   }
1030   // Wait until the child has started.
1031   AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_STARTED);
1032 
1033   // Send the process descriptor over the pipe to the sub-process
1034   mh.msg_controllen = CMSG_LEN(sizeof(int));
1035   cmptr = CMSG_FIRSTHDR(&mh);
1036   cmptr->cmsg_level = SOL_SOCKET;
1037   cmptr->cmsg_type = SCM_RIGHTS;
1038   cmptr->cmsg_len = CMSG_LEN(sizeof(int));
1039   *(int *)CMSG_DATA(cmptr) = pd_;
1040   buffer1[0] = 0;
1041   iov[0].iov_len = 1;
1042   if (verbose) fprintf(stderr, "[%d] send process descriptor %d on socket\n", getpid_(), pd_);
1043   int rc = sendmsg(sock_fds[1], &mh, 0);
1044   EXPECT_OK(rc);
1045   // Wait until the child has received the process descriptor.
1046   AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_FD_RECEIVED);
1047 
1048   if (verbose) fprintf(stderr, "[%d] close process descriptor %d\n", getpid_(), pd_);
1049   close(pd_);  // Not last open process descriptor
1050   SEND_INT_MESSAGE(sock_fds[1], MSG_PARENT_CLOSED_FD);
1051 
1052   // wait for child2
1053   int status;
1054   EXPECT_EQ(child2, waitpid(child2, &status, 0));
1055   rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1056   EXPECT_EQ(0, rc);
1057 
1058   // confirm death all round
1059   EXPECT_PID_DEAD(child2);
1060   EXPECT_PID_DEAD(pid_);
1061 }
1062