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