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 #elif defined(HAVE_PDWAIT)
30 struct __wrusage wr;
31 int rc;
32 pid_t pid = -1;
33
34 options |= WEXITED | WTRAPPED;
35 rc = pdwait(pd, status, options, &wr, NULL);
36 if (rc == 0) {
37 if (ru != NULL)
38 *ru = wr.wru_self;
39 rc = pdgetpid(pd, &pid);
40 if (rc == 0)
41 return pid;
42 }
43 return -1;
44 #else
45 // Simulate pdwait4() with wait4(pdgetpid()); this won't work in capability mode.
46 pid_t pid = -1;
47 int rc = pdgetpid(pd, &pid);
48 if (rc < 0) {
49 return rc;
50 }
51 return wait4(pid, status, options, ru);
52 #endif
53 }
54
print_rusage(FILE * f,struct rusage * ru)55 static void print_rusage(FILE *f, struct rusage *ru) {
56 fprintf(f, " User CPU time=%ld.%06ld\n", (long)ru->ru_utime.tv_sec, (long)ru->ru_utime.tv_usec);
57 fprintf(f, " System CPU time=%ld.%06ld\n", (long)ru->ru_stime.tv_sec, (long)ru->ru_stime.tv_usec);
58 fprintf(f, " Max RSS=%ld\n", ru->ru_maxrss);
59 }
60
print_stat(FILE * f,const struct stat * stat)61 static void print_stat(FILE *f, const struct stat *stat) {
62 fprintf(f,
63 "{ .st_dev=%ld, st_ino=%ld, st_mode=%04o, st_nlink=%ld, st_uid=%d, st_gid=%d,\n"
64 " .st_rdev=%ld, .st_size=%ld, st_blksize=%ld, .st_block=%ld,\n "
65 ".st_birthtime=%ld, "
66 ".st_atime=%ld, .st_mtime=%ld, .st_ctime=%ld}\n",
67 (long)stat->st_dev, (long)stat->st_ino, stat->st_mode,
68 (long)stat->st_nlink, stat->st_uid, stat->st_gid,
69 (long)stat->st_rdev, (long)stat->st_size, (long)stat->st_blksize,
70 (long)stat->st_blocks,
71 (long)stat->st_birthtime,
72 (long)stat->st_atime, (long)stat->st_mtime, (long)stat->st_ctime);
73 }
74
75 static volatile sig_atomic_t had_signal[NSIG];
clear_had_signals()76 void clear_had_signals() {
77 memset(const_cast<sig_atomic_t *>(had_signal), 0, sizeof(had_signal));
78 }
handle_signal(int x)79 static void handle_signal(int x) {
80 had_signal[x] = true;
81 }
82
83 // Check that the given child process terminates as expected.
CheckChildFinished(pid_t pid,bool signaled=false)84 void CheckChildFinished(pid_t pid, bool signaled=false) {
85 // Wait for the child to finish.
86 int rc;
87 int status = 0;
88 do {
89 rc = waitpid(pid, &status, 0);
90 if (rc < 0) {
91 fprintf(stderr, "Warning: waitpid error %s (%d)\n", strerror(errno), errno);
92 ADD_FAILURE() << "Failed to wait for child";
93 break;
94 } else if (rc == pid) {
95 break;
96 }
97 } while (true);
98 EXPECT_EQ(pid, rc);
99 if (rc == pid) {
100 if (signaled) {
101 EXPECT_TRUE(WIFSIGNALED(status));
102 } else {
103 EXPECT_TRUE(WIFEXITED(status)) << std::hex << status;
104 EXPECT_EQ(0, WEXITSTATUS(status));
105 }
106 }
107 }
108
109 //------------------------------------------------
110 // Basic tests of process descriptor functionality
111
TEST(Pdfork,Simple)112 TEST(Pdfork, Simple) {
113 int pd = -1;
114 int pipefds[2];
115 pid_t parent = getpid_();
116 EXPECT_OK(pipe(pipefds));
117 int pid = pdfork(&pd, 0);
118 EXPECT_OK(pid);
119 if (pid == 0) {
120 // Child: check pid values.
121 EXPECT_EQ(-1, pd);
122 EXPECT_NE(parent, getpid_());
123 EXPECT_EQ(parent, getppid());
124 close(pipefds[0]);
125 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
126 if (verbose) fprintf(stderr, "Child waiting for exit message\n");
127 // Terminate once the parent has completed the checks
128 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
129 exit(testing::Test::HasFailure());
130 }
131 close(pipefds[1]);
132 // Ensure the child has started.
133 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
134
135 EXPECT_NE(-1, pd);
136 EXPECT_PID_ALIVE(pid);
137 int pid_got;
138 EXPECT_OK(pdgetpid(pd, &pid_got));
139 EXPECT_EQ(pid, pid_got);
140
141 // Tell the child to exit and wait until it is a zombie.
142 SEND_INT_MESSAGE(pipefds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
143 // EXPECT_PID_ZOMBIE waits for up to ~500ms, that should be enough time for
144 // the child to exit successfully.
145 EXPECT_PID_ZOMBIE(pid);
146 close(pipefds[0]);
147
148 // Wait for the the child.
149 int status;
150 struct rusage ru;
151 memset(&ru, 0, sizeof(ru));
152 int waitrc = pdwait4_(pd, &status, 0, &ru);
153 EXPECT_EQ(pid, waitrc);
154 if (verbose) {
155 fprintf(stderr, "For pd %d pid %d:\n", pd, pid);
156 print_rusage(stderr, &ru);
157 }
158
159 // Can pdwait4(pd) as much as wanted.
160 memset(&ru, 0, sizeof(ru));
161 EXPECT_EQ(pid, pdwait4_(pd, &status, 0, &ru));
162
163 /* Reap */
164 EXPECT_EQ(pid, waitpid(pid, &status, WEXITED));
165 EXPECT_OK(close(pd));
166 EXPECT_PID_GONE(pid);
167 }
168
TEST(Pdfork,InvalidFlag)169 TEST(Pdfork, InvalidFlag) {
170 int pd = -1;
171 int pid = pdfork(&pd, PD_DAEMON<<5);
172 if (pid == 0) {
173 exit(1);
174 }
175 EXPECT_EQ(-1, pid);
176 EXPECT_EQ(EINVAL, errno);
177 if (pid > 0) waitpid(pid, NULL, 0);
178 }
179
TEST(Pdfork,TimeCheck)180 TEST(Pdfork, TimeCheck) {
181 time_t now = time(NULL); // seconds since epoch
182 EXPECT_NE(-1, now);
183 if (verbose) fprintf(stderr, "Calling pdfork around %ld\n", (long)(long)now);
184
185 int pd = -1;
186 pid_t pid = pdfork(&pd, 0);
187 EXPECT_OK(pid);
188 if (pid == 0) {
189 // Child: check we didn't get a valid process descriptor then exit.
190 EXPECT_EQ(-1, pdgetpid(pd, &pid));
191 EXPECT_EQ(EBADF, errno);
192 exit(HasFailure());
193 }
194
195 // Parent process. Ensure that [acm]times have been set correctly.
196 struct stat stat;
197 memset(&stat, 0, sizeof(stat));
198 EXPECT_OK(fstat(pd, &stat));
199 if (verbose) print_stat(stderr, &stat);
200
201 EXPECT_GE(now, stat.st_birthtime);
202 EXPECT_EQ(stat.st_birthtime, stat.st_atime);
203 EXPECT_LT((now - stat.st_atime), 2);
204 EXPECT_EQ(stat.st_atime, stat.st_ctime);
205 EXPECT_EQ(stat.st_ctime, stat.st_mtime);
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
TEST(Pdfork,UseDescriptor)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
TEST(Pdfork,NonProcessDescriptor)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
SubThreadMain(void * arg)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
ThreadMain(void *)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
TEST(Pdfork,FromThread)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:
PipePdforkBase(int pdfork_flags)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 }
~PipePdforkBase()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, WNOHANG);
343 }
344 // Check signal expectations.
345 //EXPECT_FALSE(had_signal[SIGCHLD]);
346 }
TerminateChild()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:
PipePdfork()361 PipePdfork() : PipePdforkBase(0) {}
362 };
363
364 class PipePdforkDaemon : public PipePdforkBase {
365 public:
PipePdforkDaemon()366 PipePdforkDaemon() : PipePdforkBase(PD_DAEMON) {}
367 };
368
369 // Can we poll a process descriptor?
TEST_F(PipePdfork,Poll)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?
TEST_F(PipePdfork,PollMultiple)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, 0);
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.
TEST_F(PipePdfork,MultipleRetrieveExitStatus)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
476 // Child has been reaped, so original process descriptor dangles but
477 // still has access to rusage information.
478 memset(&ru, 0, sizeof(ru));
479 EXPECT_EQ(pid_, pdwait4_(pd_, &status, 0, &ru));
480 close(pd_copy);
481 close(pd_);
482 waitpid(pid_, &status, 0);
483 EXPECT_PID_GONE(pid_);
484 }
485
TEST_F(PipePdfork,ChildExit)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 // Closing a normal process descriptor terminates the underlying process.
TEST_F(PipePdfork,Close)499 TEST_F(PipePdfork, Close) {
500 sighandler_t original = signal(SIGCHLD, handle_signal);
501 EXPECT_PID_ALIVE(pid_);
502 int status;
503 EXPECT_EQ(0, waitpid(pid_, &status, WNOHANG));
504
505 EXPECT_OK(close(pd_));
506 pd_ = -1;
507 EXPECT_FALSE(had_signal[SIGCHLD]);
508 EXPECT_PID_DEAD(pid_);
509
510 #ifdef __FreeBSD__
511 EXPECT_EQ(pid_, waitpid(pid_, NULL, 0));
512 #else
513 // Having closed the process descriptor means that pdwait4(pd) now doesn't work.
514 int rc = pdwait4_(pd_, &status, 0, NULL);
515 EXPECT_EQ(-1, rc);
516 EXPECT_EQ(EBADF, errno);
517
518 // Closing all process descriptors means the the child can only be reaped via pid.
519 EXPECT_EQ(pid_, waitpid(pid_, &status, WNOHANG));
520 #endif
521 signal(SIGCHLD, original);
522 }
523
TEST_F(PipePdfork,CloseLast)524 TEST_F(PipePdfork, CloseLast) {
525 sighandler_t original = signal(SIGCHLD, handle_signal);
526 // Child should only die when last process descriptor is closed.
527 EXPECT_PID_ALIVE(pid_);
528 int pd_other = dup(pd_);
529
530 EXPECT_OK(close(pd_));
531 pd_ = -1;
532
533 EXPECT_PID_ALIVE(pid_);
534 int status;
535 EXPECT_EQ(0, waitpid(pid_, &status, WNOHANG));
536
537 // Can no longer pdwait4() the closed process descriptor...
538 EXPECT_EQ(-1, pdwait4_(pd_, &status, WNOHANG, NULL));
539 EXPECT_EQ(EBADF, errno);
540 // ...but can pdwait4() the still-open process descriptor.
541 errno = 0;
542 EXPECT_EQ(-1, pdwait4_(pd_other, &status, WNOHANG, NULL));
543 // process not yet exited
544 EXPECT_EQ(EWOULDBLOCK, errno);
545
546 EXPECT_OK(close(pd_other));
547 EXPECT_EQ(0, waitpid(pid_, &status, WNOHANG));
548 EXPECT_PID_DEAD(pid_);
549
550 EXPECT_TRUE(had_signal[SIGCHLD]);
551 signal(SIGCHLD, original);
552 }
553
FORK_TEST(Pdfork,OtherUserIfRoot)554 FORK_TEST(Pdfork, OtherUserIfRoot) {
555 GTEST_SKIP_IF_NOT_ROOT();
556 int pd;
557 int status;
558 pid_t pid = pdfork(&pd, 0);
559 EXPECT_OK(pid);
560 if (pid == 0) {
561 // Child process: loop forever.
562 while (true) usleep(100000);
563 }
564 usleep(100);
565
566 // Now that the second process has been pdfork()ed, change euid.
567 ASSERT_NE(0u, other_uid) << "other_uid not initialized correctly, "
568 "please pass the -u <uid> flag.";
569 EXPECT_EQ(0, setuid(other_uid));
570 EXPECT_EQ(other_uid, getuid());
571 if (verbose) fprintf(stderr, "uid=%d euid=%d\n", getuid(), geteuid());
572
573 // Fail to kill child with normal PID operation.
574 EXPECT_EQ(-1, kill(pid, SIGKILL));
575 EXPECT_EQ(EPERM, errno);
576 EXPECT_PID_ALIVE(pid);
577
578 // Ideally, we should be able to send signals via a process descriptor even
579 // if it's owned by another user, but this is not implementated on FreeBSD.
580 // Sending a signal with pdkill() should be permitted though.
581 EXPECT_EQ(-1, pdkill(pd, SIGKILL));
582 EXPECT_EQ(EPERM, errno);
583
584 int rc = pdwait4_(pd, &status, WNOHANG, NULL);
585 EXPECT_EQ(-1, rc);
586 EXPECT_EQ(EWOULDBLOCK, errno);
587 }
588
TEST_F(PipePdfork,WaitPidThenPd)589 TEST_F(PipePdfork, WaitPidThenPd) {
590 TerminateChild();
591 int status;
592 // If we waitpid(pid) first...
593 int rc = waitpid(pid_, &status, 0);
594 EXPECT_OK(rc);
595 EXPECT_EQ(pid_, rc);
596
597 #ifdef NOTYET
598 // ...the zombie is reaped but we can still subsequently pdwait4(pd).
599 EXPECT_EQ(0, pdwait4_(pd_, &status, 0, NULL));
600 #endif
601 }
602
TEST_F(PipePdfork,WaitPdThenPid)603 TEST_F(PipePdfork, WaitPdThenPid) {
604 TerminateChild();
605 int status;
606 // If we pdwait4(pd) first...
607 int rc = pdwait4_(pd_, &status, 0, NULL);
608 EXPECT_OK(rc);
609 EXPECT_EQ(pid_, rc);
610
611 EXPECT_EQ(pid_, waitpid(pid_, &status, 0));
612 }
613
614 // Setting PD_DAEMON prevents close() from killing the child.
TEST_F(PipePdforkDaemon,Close)615 TEST_F(PipePdforkDaemon, Close) {
616 EXPECT_OK(close(pd_));
617 pd_ = -1;
618 EXPECT_PID_ALIVE(pid_);
619
620 // Can still explicitly kill it via the pid.
621 if (pid_ > 0) {
622 EXPECT_OK(kill(pid_, SIGKILL));
623 EXPECT_PID_DEAD(pid_);
624 }
625 }
626
TestPdkill(pid_t pid,int pd)627 static void TestPdkill(pid_t pid, int pd) {
628 EXPECT_PID_ALIVE(pid);
629 // SIGCONT is ignored by default.
630 EXPECT_OK(pdkill(pd, SIGCONT));
631 EXPECT_PID_ALIVE(pid);
632
633 // SIGINT isn't
634 EXPECT_OK(pdkill(pd, SIGINT));
635 EXPECT_PID_DEAD(pid);
636
637 // pdkill() on zombie is no-op.
638 errno = 0;
639 EXPECT_EQ(0, pdkill(pd, SIGINT));
640 EXPECT_EQ(0, errno);
641 }
642
TEST_F(PipePdfork,Pdkill)643 TEST_F(PipePdfork, Pdkill) {
644 TestPdkill(pid_, pd_);
645 }
646
TEST_F(PipePdforkDaemon,Pdkill)647 TEST_F(PipePdforkDaemon, Pdkill) {
648 TestPdkill(pid_, pd_);
649 }
650
TEST(Pdfork,PdkillOtherSignal)651 TEST(Pdfork, PdkillOtherSignal) {
652 int pd = -1;
653 int pipefds[2];
654 EXPECT_EQ(0, pipe(pipefds));
655 int pid = pdfork(&pd, 0);
656 EXPECT_OK(pid);
657 if (pid == 0) {
658 // Child: tell the parent that we have started before entering the loop,
659 // and importantly only do so once we have registered the SIGUSR1 handler.
660 close(pipefds[0]);
661 clear_had_signals();
662 signal(SIGUSR1, handle_signal);
663 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
664 // Child: watch for SIGUSR1 forever.
665 while (!had_signal[SIGUSR1]) {
666 usleep(100000);
667 }
668 exit(123);
669 }
670 // Wait for child to start
671 close(pipefds[1]);
672 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
673 close(pipefds[0]);
674
675 // Send an invalid signal.
676 EXPECT_EQ(-1, pdkill(pd, 0xFFFF));
677 EXPECT_EQ(EINVAL, errno);
678
679 // Send an expected SIGUSR1 to the pdfork()ed child.
680 EXPECT_PID_ALIVE(pid);
681 pdkill(pd, SIGUSR1);
682 EXPECT_PID_DEAD(pid);
683
684 // Child's exit status confirms whether it received the signal.
685 int status;
686 int rc = waitpid(pid, &status, 0);
687 EXPECT_OK(rc);
688 EXPECT_EQ(pid, rc);
689 EXPECT_TRUE(WIFEXITED(status)) << "status: 0x" << std::hex << status;
690 EXPECT_EQ(123, WEXITSTATUS(status));
691 }
692
PdforkParentDeath(int pdfork_flags)693 pid_t PdforkParentDeath(int pdfork_flags) {
694 // Set up:
695 // pid A: main process, here
696 // +--pid B: fork()ed process, starts a child process with pdfork() then
697 // waits for parent to send a shutdown message.
698 // +--pid C: pdfork()ed process, looping forever
699 int sock_fds[2];
700 EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
701 if (verbose) fprintf(stderr, "[%d] parent about to fork()...\n", getpid_());
702 pid_t child = fork();
703 EXPECT_OK(child);
704 if (child == 0) {
705 int pd;
706 if (verbose) fprintf(stderr, " [%d] child about to pdfork()...\n", getpid_());
707 int pipefds[2]; // for startup notification
708 EXPECT_OK(pipe(pipefds));
709 pid_t grandchild = pdfork(&pd, pdfork_flags);
710 if (grandchild == 0) {
711 close(pipefds[0]);
712 pid_t grandchildPid = getpid_();
713 EXPECT_EQ(sizeof(grandchildPid), (size_t)write(pipefds[1], &grandchildPid, sizeof(grandchildPid)));
714 while (true) {
715 if (verbose) fprintf(stderr, " [%d] grandchild: \"I aten't dead\"\n", grandchildPid);
716 sleep(1);
717 }
718 }
719 close(pipefds[1]);
720 if (verbose) fprintf(stderr, " [%d] pdfork()ed grandchild %d, sending ID to parent\n", getpid_(), grandchild);
721 // Wait for grandchild to start.
722 pid_t grandchild2;
723 EXPECT_EQ(sizeof(grandchild2), (size_t)read(pipefds[0], &grandchild2, sizeof(grandchild2)));
724 EXPECT_EQ(grandchild, grandchild2) << "received invalid grandchild pid";
725 if (verbose) fprintf(stderr, " [%d] grandchild %d has started successfully\n", getpid_(), grandchild);
726 close(pipefds[0]);
727
728 // Send grandchild pid to parent.
729 EXPECT_EQ(sizeof(grandchild), (size_t)write(sock_fds[1], &grandchild, sizeof(grandchild)));
730 if (verbose) fprintf(stderr, " [%d] sent grandchild pid %d to parent\n", getpid_(), grandchild);
731 // Wait for parent to acknowledge the message.
732 AWAIT_INT_MESSAGE(sock_fds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
733 if (verbose) fprintf(stderr, " [%d] parent acknowledged grandchild pid %d\n", getpid_(), grandchild);
734 if (verbose) fprintf(stderr, " [%d] child terminating\n", getpid_());
735 exit(testing::Test::HasFailure());
736 }
737 if (verbose) fprintf(stderr, "[%d] fork()ed child is %d\n", getpid_(), child);
738 pid_t grandchild;
739 read(sock_fds[0], &grandchild, sizeof(grandchild));
740 if (verbose) fprintf(stderr, "[%d] received grandchild id %d\n", getpid_(), grandchild);
741 EXPECT_PID_ALIVE(child);
742 EXPECT_PID_ALIVE(grandchild);
743 // Tell child to exit.
744 if (verbose) fprintf(stderr, "[%d] telling child %d to exit\n", getpid_(), child);
745 SEND_INT_MESSAGE(sock_fds[0], MSG_PARENT_REQUEST_CHILD_EXIT);
746 // Child dies, closing its process descriptor for the grandchild.
747 EXPECT_PID_DEAD(child);
748 CheckChildFinished(child);
749 return grandchild;
750 }
751
TEST(Pdfork,Bagpuss)752 TEST(Pdfork, Bagpuss) {
753 // "And of course when Bagpuss goes to sleep, all his friends go to sleep too"
754 pid_t grandchild = PdforkParentDeath(0);
755 // By default: child death => closed process descriptor => grandchild death.
756 EXPECT_PID_DEAD(grandchild);
757 }
758
TEST(Pdfork,BagpussDaemon)759 TEST(Pdfork, BagpussDaemon) {
760 pid_t grandchild = PdforkParentDeath(PD_DAEMON);
761 // With PD_DAEMON: child death => closed process descriptor => no effect on grandchild.
762 EXPECT_PID_ALIVE(grandchild);
763 if (grandchild > 0) {
764 EXPECT_OK(kill(grandchild, SIGKILL));
765 }
766 }
767
768 // The exit of a pdfork()ed process should not generate SIGCHLD.
TEST_F(PipePdfork,NoSigchld)769 TEST_F(PipePdfork, NoSigchld) {
770 clear_had_signals();
771 sighandler_t original = signal(SIGCHLD, handle_signal);
772 TerminateChild();
773 int rc = 0;
774 // Can waitpid() for the specific pid of the pdfork()ed child.
775 EXPECT_EQ(pid_, waitpid(pid_, &rc, 0));
776 EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
777 EXPECT_TRUE(had_signal[SIGCHLD]);
778 signal(SIGCHLD, original);
779 }
780
781 // The exit of a pdfork()ed process whose process descriptors have
782 // all been closed should generate SIGCHLD. The child process needs
783 // PD_DAEMON to survive the closure of the process descriptors.
TEST_F(PipePdforkDaemon,NoPDSigchld)784 TEST_F(PipePdforkDaemon, NoPDSigchld) {
785 clear_had_signals();
786 sighandler_t original = signal(SIGCHLD, handle_signal);
787
788 EXPECT_OK(close(pd_));
789 TerminateChild();
790 int rc = 0;
791 // Can waitpid() for the specific pid of the pdfork()ed child.
792 EXPECT_EQ(pid_, waitpid(pid_, &rc, 0));
793 EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
794 EXPECT_TRUE(had_signal[SIGCHLD]);
795 signal(SIGCHLD, original);
796 }
797
TEST_F(PipePdfork,ModeBits)798 TEST_F(PipePdfork, ModeBits) {
799 // Owner rwx bits indicate liveness of child
800 struct stat stat;
801 memset(&stat, 0, sizeof(stat));
802 EXPECT_OK(fstat(pd_, &stat));
803 if (verbose) print_stat(stderr, &stat);
804 EXPECT_EQ(S_IRWXU, (long)(stat.st_mode & S_IRWXU));
805
806 TerminateChild();
807 usleep(100000);
808
809 memset(&stat, 0, sizeof(stat));
810 EXPECT_OK(fstat(pd_, &stat));
811 if (verbose) print_stat(stderr, &stat);
812 EXPECT_EQ(0, (int)(stat.st_mode & S_IRWXU));
813 }
814
TEST_F(PipePdfork,WildcardWait)815 TEST_F(PipePdfork, WildcardWait) {
816 TerminateChild();
817 EXPECT_PID_ZOMBIE(pid_); // Ensure child is truly dead.
818
819 int rc;
820 EXPECT_EQ(pid_, waitpid(-1, &rc, WNOHANG));
821
822 EXPECT_OK(close(pd_));
823 pd_ = -1;
824 }
825
FORK_TEST(Pdfork,Pdkill)826 FORK_TEST(Pdfork, Pdkill) {
827 clear_had_signals();
828 int pd;
829 int pipefds[2];
830 EXPECT_OK(pipe(pipefds));
831 pid_t pid = pdfork(&pd, 0);
832 EXPECT_OK(pid);
833
834 if (pid == 0) {
835 // Child: set a SIGINT handler, notify the parent and sleep.
836 close(pipefds[0]);
837 clear_had_signals();
838 signal(SIGINT, handle_signal);
839 if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
840 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
841 if (verbose) fprintf(stderr, "[%d] child about to sleep(10)\n", getpid_());
842 // Note: we could receive the SIGINT just before sleep(), so we use a loop
843 // with a short delay instead of one long sleep().
844 for (int i = 0; i < 50 && !had_signal[SIGINT]; i++) {
845 usleep(100000);
846 }
847 if (verbose) fprintf(stderr, "[%d] child slept, had[SIGINT]=%d\n",
848 getpid_(), (int)had_signal[SIGINT]);
849 // Return non-zero if we didn't see SIGINT.
850 exit(had_signal[SIGINT] ? 0 : 99);
851 }
852
853 // Parent: get child's PID.
854 pid_t pd_pid;
855 EXPECT_OK(pdgetpid(pd, &pd_pid));
856 EXPECT_EQ(pid, pd_pid);
857
858 // Interrupt the child once it's registered the SIGINT handler.
859 close(pipefds[1]);
860 if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
861 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
862 EXPECT_OK(pdkill(pd, SIGINT));
863 if (verbose) fprintf(stderr, "[%d] sent SIGINT\n", getpid_());
864
865 // Make sure the child finished properly (caught signal then exited).
866 CheckChildFinished(pid);
867 }
868
FORK_TEST(Pdfork,PdkillSignal)869 FORK_TEST(Pdfork, PdkillSignal) {
870 int pd;
871 int pipefds[2];
872 EXPECT_OK(pipe(pipefds));
873 pid_t pid = pdfork(&pd, 0);
874 EXPECT_OK(pid);
875
876 if (pid == 0) {
877 close(pipefds[0]);
878 if (verbose) fprintf(stderr, "[%d] child started\n", getpid_());
879 SEND_INT_MESSAGE(pipefds[1], MSG_CHILD_STARTED);
880 // Child: wait for shutdown message. No SIGINT handler. The message should
881 // never be received, since SIGINT should terminate the process.
882 if (verbose) fprintf(stderr, "[%d] child about to read()\n", getpid_());
883 AWAIT_INT_MESSAGE(pipefds[1], MSG_PARENT_REQUEST_CHILD_EXIT);
884 fprintf(stderr, "[%d] child read() returned unexpectedly\n", getpid_());
885 exit(99);
886 }
887 // Wait for child to start before signalling.
888 if (verbose) fprintf(stderr, "[%d] waiting for child\n", getpid_());
889 close(pipefds[1]);
890 AWAIT_INT_MESSAGE(pipefds[0], MSG_CHILD_STARTED);
891 // Kill the child (as it doesn't handle SIGINT).
892 if (verbose) fprintf(stderr, "[%d] sending SIGINT\n", getpid_());
893 EXPECT_OK(pdkill(pd, SIGINT));
894
895 // Make sure the child finished properly (terminated by signal).
896 CheckChildFinished(pid, true);
897 }
898
899 //------------------------------------------------
900 // Test interactions with other parts of Capsicum:
901 // - capability mode
902 // - capabilities
903
FORK_TEST(Pdfork,DaemonUnrestricted)904 FORK_TEST(Pdfork, DaemonUnrestricted) {
905 EXPECT_OK(cap_enter());
906 int fd;
907
908 // Capability mode leaves pdfork() available, with and without flag.
909 int rc;
910 rc = pdfork(&fd, PD_DAEMON);
911 EXPECT_OK(rc);
912 if (rc == 0) {
913 // Child: immediately terminate.
914 exit(0);
915 }
916
917 rc = pdfork(&fd, 0);
918 EXPECT_OK(rc);
919 if (rc == 0) {
920 // Child: immediately terminate.
921 exit(0);
922 }
923 }
924
TEST(Pdfork,MissingRights)925 TEST(Pdfork, MissingRights) {
926 pid_t parent = getpid_();
927 int pd = -1;
928 pid_t pid = pdfork(&pd, 0);
929 EXPECT_OK(pid);
930 if (pid == 0) {
931 // Child: loop forever.
932 EXPECT_NE(parent, getpid_());
933 while (true) sleep(1);
934 }
935 // Create two capabilities from the process descriptor.
936 cap_rights_t r_ro;
937 cap_rights_init(&r_ro, CAP_READ, CAP_LOOKUP);
938 int cap_incapable = dup(pd);
939 EXPECT_OK(cap_incapable);
940 EXPECT_OK(cap_rights_limit(cap_incapable, &r_ro));
941 cap_rights_t r_pdall;
942 cap_rights_init(&r_pdall, CAP_PDGETPID, CAP_PDWAIT, CAP_PDKILL);
943 int cap_capable = dup(pd);
944 EXPECT_OK(cap_capable);
945 EXPECT_OK(cap_rights_limit(cap_capable, &r_pdall));
946
947 pid_t other_pid;
948 EXPECT_NOTCAPABLE(pdgetpid(cap_incapable, &other_pid));
949 EXPECT_NOTCAPABLE(pdkill(cap_incapable, SIGINT));
950 int status;
951 EXPECT_NOTCAPABLE(pdwait4_(cap_incapable, &status, 0, NULL));
952
953 EXPECT_OK(pdgetpid(cap_capable, &other_pid));
954 EXPECT_EQ(pid, other_pid);
955 EXPECT_OK(pdkill(cap_capable, SIGINT));
956 int rc = pdwait4_(pd, &status, 0, NULL);
957 EXPECT_OK(rc);
958 EXPECT_EQ(pid, rc);
959 }
960
961
962 //------------------------------------------------
963 // Passing process descriptors between processes.
964
TEST_F(PipePdfork,PassProcessDescriptor)965 TEST_F(PipePdfork, PassProcessDescriptor) {
966 int sock_fds[2];
967 EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
968
969 struct msghdr mh;
970 mh.msg_name = NULL; // No address needed
971 mh.msg_namelen = 0;
972 char buffer1[1024];
973 struct iovec iov[1];
974 iov[0].iov_base = buffer1;
975 iov[0].iov_len = sizeof(buffer1);
976 mh.msg_iov = iov;
977 mh.msg_iovlen = 1;
978 char buffer2[1024];
979 mh.msg_control = buffer2;
980 mh.msg_controllen = sizeof(buffer2);
981 struct cmsghdr *cmptr;
982
983 if (verbose) fprintf(stderr, "[%d] about to fork()\n", getpid_());
984 pid_t child2 = fork();
985 if (child2 == 0) {
986 // Child: close our copy of the original process descriptor.
987 close(pd_);
988 SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_STARTED);
989 // Child: wait to receive process descriptor over socket
990 if (verbose) fprintf(stderr, " [%d] child of %d waiting for process descriptor on socket\n", getpid_(), getppid());
991 int rc = recvmsg(sock_fds[0], &mh, 0);
992 EXPECT_OK(rc);
993 EXPECT_LE(CMSG_LEN(sizeof(int)), mh.msg_controllen);
994 cmptr = CMSG_FIRSTHDR(&mh);
995 int pd = *(int*)CMSG_DATA(cmptr);
996 EXPECT_EQ(CMSG_LEN(sizeof(int)), cmptr->cmsg_len);
997 cmptr = CMSG_NXTHDR(&mh, cmptr);
998 EXPECT_TRUE(cmptr == NULL);
999 if (verbose) fprintf(stderr, " [%d] got process descriptor %d on socket\n", getpid_(), pd);
1000 SEND_INT_MESSAGE(sock_fds[0], MSG_CHILD_FD_RECEIVED);
1001
1002 // Child: confirm we can do pd*() operations on the process descriptor
1003 pid_t other;
1004 EXPECT_OK(pdgetpid(pd, &other));
1005 if (verbose) fprintf(stderr, " [%d] process descriptor %d is pid %d\n", getpid_(), pd, other);
1006
1007 // Wait until the parent has closed the process descriptor.
1008 AWAIT_INT_MESSAGE(sock_fds[0], MSG_PARENT_CLOSED_FD);
1009
1010 if (verbose) fprintf(stderr, " [%d] close process descriptor %d\n", getpid_(), pd);
1011 close(pd);
1012
1013 // Last process descriptor closed, expect death
1014 EXPECT_PID_DEAD(other);
1015
1016 exit(HasFailure());
1017 }
1018 // Wait until the child has started.
1019 AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_STARTED);
1020
1021 // Send the process descriptor over the pipe to the sub-process
1022 mh.msg_controllen = CMSG_LEN(sizeof(int));
1023 cmptr = CMSG_FIRSTHDR(&mh);
1024 cmptr->cmsg_level = SOL_SOCKET;
1025 cmptr->cmsg_type = SCM_RIGHTS;
1026 cmptr->cmsg_len = CMSG_LEN(sizeof(int));
1027 *(int *)CMSG_DATA(cmptr) = pd_;
1028 buffer1[0] = 0;
1029 iov[0].iov_len = 1;
1030 if (verbose) fprintf(stderr, "[%d] send process descriptor %d on socket\n", getpid_(), pd_);
1031 int rc = sendmsg(sock_fds[1], &mh, 0);
1032 EXPECT_OK(rc);
1033 // Wait until the child has received the process descriptor.
1034 AWAIT_INT_MESSAGE(sock_fds[1], MSG_CHILD_FD_RECEIVED);
1035
1036 if (verbose) fprintf(stderr, "[%d] close process descriptor %d\n", getpid_(), pd_);
1037 close(pd_); // Not last open process descriptor
1038 SEND_INT_MESSAGE(sock_fds[1], MSG_PARENT_CLOSED_FD);
1039
1040 // wait for child2
1041 int status;
1042 EXPECT_EQ(child2, waitpid(child2, &status, 0));
1043 rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1044 EXPECT_EQ(0, rc);
1045
1046 // confirm death all round
1047 EXPECT_PID_DEAD(child2);
1048 EXPECT_PID_DEAD(pid_);
1049 }
1050