xref: /dragonfly/contrib/dhcpcd/src/privsep.c (revision a444603f)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * Privilege Separation for dhcpcd
4  * Copyright (c) 2006-2020 Roy Marples <roy@marples.name>
5  * All rights reserved
6 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * The current design is this:
31  * Spawn a priv process to carry out privileged actions and
32  * spawning unpriv process to initate network connections such as BPF
33  * or address specific listener.
34  * Spawn an unpriv process to send/receive common network data.
35  * Then drop all privs and start running.
36  * Every process aside from the privileged actioneer is chrooted.
37  * All privsep processes ignore signals - only the master process accepts them.
38  *
39  * dhcpcd will maintain the config file in the chroot, no need to handle
40  * this in a script or something.
41  */
42 
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <sys/wait.h>
48 
49 #ifdef AF_LINK
50 #include <net/if_dl.h>
51 #endif
52 
53 #include <assert.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <grp.h>
57 #include <paths.h>
58 #include <pwd.h>
59 #include <stddef.h>	/* For offsetof, struct padding debug */
60 #include <signal.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include "arp.h"
66 #include "common.h"
67 #include "control.h"
68 #include "dev.h"
69 #include "dhcp.h"
70 #include "dhcp6.h"
71 #include "eloop.h"
72 #include "ipv6nd.h"
73 #include "logerr.h"
74 #include "privsep.h"
75 
76 #ifdef HAVE_CAPSICUM
77 #include <sys/capsicum.h>
78 #include <capsicum_helpers.h>
79 #endif
80 #ifdef HAVE_UTIL_H
81 #include <util.h>
82 #endif
83 
84 int
85 ps_init(struct dhcpcd_ctx *ctx)
86 {
87 	struct passwd *pw;
88 	struct stat st;
89 
90 	errno = 0;
91 	if ((ctx->ps_user = pw = getpwnam(PRIVSEP_USER)) == NULL) {
92 		ctx->options &= ~DHCPCD_PRIVSEP;
93 		if (errno == 0) {
94 			logerrx("no such user %s", PRIVSEP_USER);
95 			/* Just incase logerrx caused an error... */
96 			errno = 0;
97 		} else
98 			logerr("getpwnam");
99 		return -1;
100 	}
101 
102 	if (stat(pw->pw_dir, &st) == -1 || !S_ISDIR(st.st_mode)) {
103 		ctx->options &= ~DHCPCD_PRIVSEP;
104 		logerrx("refusing chroot: %s: %s",
105 		    PRIVSEP_USER, pw->pw_dir);
106 		errno = 0;
107 		return -1;
108 	}
109 
110 	ctx->options |= DHCPCD_PRIVSEP;
111 	return 0;
112 }
113 
114 static int
115 ps_dropprivs(struct dhcpcd_ctx *ctx)
116 {
117 	struct passwd *pw = ctx->ps_user;
118 
119 	if (ctx->options & DHCPCD_LAUNCHER)
120 		logdebugx("chrooting as %s to %s", pw->pw_name, pw->pw_dir);
121 	if (chroot(pw->pw_dir) == -1 &&
122 	    (errno != EPERM || ctx->options & DHCPCD_FORKED))
123 		logerr("%s: chroot: %s", __func__, pw->pw_dir);
124 	if (chdir("/") == -1)
125 		logerr("%s: chdir: /", __func__);
126 
127 	if ((setgroups(1, &pw->pw_gid) == -1 ||
128 	     setgid(pw->pw_gid) == -1 ||
129 	     setuid(pw->pw_uid) == -1) &&
130 	     (errno != EPERM || ctx->options & DHCPCD_FORKED))
131 	{
132 		logerr("failed to drop privileges");
133 		return -1;
134 	}
135 
136 	struct rlimit rzero = { .rlim_cur = 0, .rlim_max = 0 };
137 
138 	if (ctx->ps_control_pid != getpid()) {
139 		/* Prohibit new files, sockets, etc */
140 #if defined(__linux__) || defined(__sun) || defined(__OpenBSD__)
141 		/*
142 		 * If poll(2) is called with nfds > RLIMIT_NOFILE
143 		 * then it returns EINVAL.
144 		 * This blows.
145 		 * Do the best we can and limit to what we need.
146 		 * An attacker could potentially close a file and
147 		 * open a new one still, but that cannot be helped.
148 		 */
149 		unsigned long maxfd;
150 		maxfd = (unsigned long)eloop_event_count(ctx->eloop);
151 		if (IN_PRIVSEP_SE(ctx))
152 			maxfd++; /* XXX why? */
153 
154 		struct rlimit rmaxfd = {
155 		    .rlim_cur = maxfd,
156 		    .rlim_max = maxfd
157 		};
158 		if (setrlimit(RLIMIT_NOFILE, &rmaxfd) == -1)
159 			logerr("setrlimit RLIMIT_NOFILE");
160 #else
161 		if (setrlimit(RLIMIT_NOFILE, &rzero) == -1)
162 			logerr("setrlimit RLIMIT_NOFILE");
163 #endif
164 	}
165 
166 	/* Prohibit writing to files.
167 	 * Obviously this won't work if we are using a logfile
168 	 * or redirecting stderr to a file. */
169 	if (ctx->logfile == NULL &&
170 	    (ctx->options & DHCPCD_STARTED ||
171 	     !ctx->stderr_valid || isatty(STDERR_FILENO) == 1))
172 	{
173 		if (setrlimit(RLIMIT_FSIZE, &rzero) == -1)
174 			logerr("setrlimit RLIMIT_FSIZE");
175 	}
176 
177 #ifdef RLIMIT_NPROC
178 	/* Prohibit forks */
179 	if (setrlimit(RLIMIT_NPROC, &rzero) == -1)
180 		logerr("setrlimit RLIMIT_NPROC");
181 #endif
182 
183 	return 0;
184 }
185 
186 static int
187 ps_setbuf0(int fd, int ctl, int minlen)
188 {
189 	int len;
190 	socklen_t slen;
191 
192 	slen = sizeof(len);
193 	if (getsockopt(fd, SOL_SOCKET, ctl, &len, &slen) == -1)
194 		return -1;
195 
196 #ifdef __linux__
197 	len /= 2;
198 #endif
199 	if (len >= minlen)
200 		return 0;
201 
202 	return setsockopt(fd, SOL_SOCKET, ctl, &minlen, sizeof(minlen));
203 }
204 
205 static int
206 ps_setbuf(int fd)
207 {
208 	/* Ensure we can receive a fully sized privsep message.
209 	 * Double the send buffer. */
210 	int minlen = (int)sizeof(struct ps_msg);
211 
212 	if (ps_setbuf0(fd, SO_RCVBUF, minlen) == -1 ||
213 	    ps_setbuf0(fd, SO_SNDBUF, minlen * 2) == -1)
214 	{
215 		logerr(__func__);
216 		return -1;
217 	}
218 	return 0;
219 }
220 
221 int
222 ps_setbuf_fdpair(int fd[])
223 {
224 
225 	if (ps_setbuf(fd[0]) == -1 || ps_setbuf(fd[1]) == -1)
226 		return -1;
227 	return 0;
228 }
229 
230 #ifdef PRIVSEP_RIGHTS
231 int
232 ps_rights_limit_ioctl(int fd)
233 {
234 	cap_rights_t rights;
235 
236 	cap_rights_init(&rights, CAP_IOCTL);
237 	if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
238 		return -1;
239 	return 0;
240 }
241 
242 int
243 ps_rights_limit_fd_fctnl(int fd)
244 {
245 	cap_rights_t rights;
246 
247 	cap_rights_init(&rights, CAP_READ, CAP_WRITE, CAP_EVENT,
248 	    CAP_ACCEPT, CAP_FCNTL);
249 	if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
250 		return -1;
251 	return 0;
252 }
253 
254 int
255 ps_rights_limit_fd(int fd)
256 {
257 	cap_rights_t rights;
258 
259 	cap_rights_init(&rights, CAP_READ, CAP_WRITE, CAP_EVENT, CAP_SHUTDOWN);
260 	if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
261 		return -1;
262 	return 0;
263 }
264 
265 int
266 ps_rights_limit_fd_sockopt(int fd)
267 {
268 	cap_rights_t rights;
269 
270 	cap_rights_init(&rights, CAP_READ, CAP_WRITE, CAP_EVENT,
271 	    CAP_GETSOCKOPT, CAP_SETSOCKOPT);
272 	if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
273 		return -1;
274 	return 0;
275 }
276 
277 int
278 ps_rights_limit_fd_rdonly(int fd)
279 {
280 	cap_rights_t rights;
281 
282 	cap_rights_init(&rights, CAP_READ, CAP_EVENT);
283 	if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
284 		return -1;
285 	return 0;
286 }
287 
288 int
289 ps_rights_limit_fdpair(int fd[])
290 {
291 
292 	if (ps_rights_limit_fd(fd[0]) == -1 || ps_rights_limit_fd(fd[1]) == -1)
293 		return -1;
294 	return 0;
295 }
296 
297 static int
298 ps_rights_limit_stdio(struct dhcpcd_ctx *ctx)
299 {
300 	const int iebadf = CAPH_IGNORE_EBADF;
301 	int error = 0;
302 
303 	if (ctx->stdin_valid &&
304 	    caph_limit_stream(STDIN_FILENO, CAPH_READ | iebadf) == -1)
305 		error = -1;
306 	if (ctx->stdout_valid &&
307 	    caph_limit_stream(STDOUT_FILENO, CAPH_WRITE | iebadf) == -1)
308 		error = -1;
309 	if (ctx->stderr_valid &&
310 	    caph_limit_stream(STDERR_FILENO, CAPH_WRITE | iebadf) == -1)
311 		error = -1;
312 
313 	return error;
314 }
315 #endif
316 
317 pid_t
318 ps_dostart(struct dhcpcd_ctx *ctx,
319     pid_t *priv_pid, int *priv_fd,
320     void (*recv_msg)(void *), void (*recv_unpriv_msg),
321     void *recv_ctx, int (*callback)(void *), void (*signal_cb)(int, void *),
322     unsigned int flags)
323 {
324 	int fd[2];
325 	pid_t pid;
326 
327 	if (xsocketpair(AF_UNIX, SOCK_DGRAM | SOCK_CXNB, 0, fd) == -1) {
328 		logerr("%s: socketpair", __func__);
329 		return -1;
330 	}
331 	if (ps_setbuf_fdpair(fd) == -1) {
332 		logerr("%s: ps_setbuf_fdpair", __func__);
333 		return -1;
334 	}
335 #ifdef PRIVSEP_RIGHTS
336 	if (ps_rights_limit_fdpair(fd) == -1) {
337 		logerr("%s: ps_rights_limit_fdpair", __func__);
338 		return -1;
339 	}
340 #endif
341 
342 	switch (pid = fork()) {
343 	case -1:
344 		logerr("fork");
345 		return -1;
346 	case 0:
347 		*priv_fd = fd[1];
348 		close(fd[0]);
349 		break;
350 	default:
351 		*priv_pid = pid;
352 		*priv_fd = fd[0];
353 		close(fd[1]);
354 		if (recv_unpriv_msg == NULL)
355 			;
356 		else if (eloop_event_add(ctx->eloop, *priv_fd,
357 		    recv_unpriv_msg, recv_ctx) == -1)
358 		{
359 			logerr("%s: eloop_event_add", __func__);
360 			return -1;
361 		}
362 		return pid;
363 	}
364 
365 	ctx->options |= DHCPCD_UNPRIV | DHCPCD_FORKED;
366 	if (ctx->fork_fd != -1) {
367 		close(ctx->fork_fd);
368 		ctx->fork_fd = -1;
369 	}
370 	pidfile_clean();
371 	eloop_clear(ctx->eloop);
372 
373 	/* We are not root */
374 	if (priv_fd != &ctx->ps_root_fd) {
375 		ps_freeprocesses(ctx, recv_ctx);
376 		if (ctx->ps_root_fd != -1) {
377 			close(ctx->ps_root_fd);
378 			ctx->ps_root_fd = -1;
379 		}
380 
381 #ifdef PRIVSEP_RIGHTS
382 		/* We cannot limit the root process in any way. */
383 		if (ps_rights_limit_stdio(ctx) == -1) {
384 			logerr("ps_rights_limit_stdio");
385 			goto errexit;
386 		}
387 #endif
388 	}
389 
390 	if (priv_fd != &ctx->ps_inet_fd && ctx->ps_inet_fd != -1) {
391 		close(ctx->ps_inet_fd);
392 		ctx->ps_inet_fd = -1;
393 	}
394 
395 	eloop_signal_set_cb(ctx->eloop,
396 	    dhcpcd_signals, dhcpcd_signals_len, signal_cb, ctx);
397 
398 	/* ctx->sigset aready has the initial sigmask set in main() */
399 	if (eloop_signal_mask(ctx->eloop, NULL) == -1) {
400 		logerr("%s: eloop_signal_mask", __func__);
401 		goto errexit;
402 	}
403 
404 	if (eloop_event_add(ctx->eloop, *priv_fd, recv_msg, recv_ctx) == -1)
405 	{
406 		logerr("%s: eloop_event_add", __func__);
407 		goto errexit;
408 	}
409 
410 	if (callback(recv_ctx) == -1)
411 		goto errexit;
412 
413 	if (flags & PSF_DROPPRIVS)
414 		ps_dropprivs(ctx);
415 
416 	return 0;
417 
418 errexit:
419 	/* Failure to start root or inet processes is fatal. */
420 	if (priv_fd == &ctx->ps_root_fd || priv_fd == &ctx->ps_inet_fd)
421 		(void)ps_sendcmd(ctx, *priv_fd, PS_STOP, 0, NULL, 0);
422 	shutdown(*priv_fd, SHUT_RDWR);
423 	*priv_fd = -1;
424 	eloop_exit(ctx->eloop, EXIT_FAILURE);
425 	return -1;
426 }
427 
428 int
429 ps_dostop(struct dhcpcd_ctx *ctx, pid_t *pid, int *fd)
430 {
431 	int err = 0;
432 
433 #ifdef PRIVSEP_DEBUG
434 	logdebugx("%s: pid=%d fd=%d", __func__, *pid, *fd);
435 #endif
436 
437 	if (*fd != -1) {
438 		eloop_event_delete(ctx->eloop, *fd);
439 		if (ps_sendcmd(ctx, *fd, PS_STOP, 0, NULL, 0) == -1) {
440 			logerr(__func__);
441 			err = -1;
442 		}
443 		(void)shutdown(*fd, SHUT_RDWR);
444 		close(*fd);
445 		*fd = -1;
446 	}
447 
448 	/* Don't wait for the process as it may not respond to the shutdown
449 	 * request. We'll reap the process on receipt of SIGCHLD. */
450 	*pid = 0;
451 	return err;
452 }
453 
454 int
455 ps_start(struct dhcpcd_ctx *ctx)
456 {
457 	pid_t pid;
458 
459 	TAILQ_INIT(&ctx->ps_processes);
460 
461 	switch (pid = ps_root_start(ctx)) {
462 	case -1:
463 		logerr("ps_root_start");
464 		return -1;
465 	case 0:
466 		return 0;
467 	default:
468 		logdebugx("spawned privileged actioneer on PID %d", pid);
469 	}
470 
471 	/* No point in spawning the generic network listener if we're
472 	 * not going to use it. */
473 	if (!ps_inet_canstart(ctx))
474 		goto started_net;
475 
476 	switch (pid = ps_inet_start(ctx)) {
477 	case -1:
478 		return -1;
479 	case 0:
480 		return 0;
481 	default:
482 		logdebugx("spawned network proxy on PID %d", pid);
483 	}
484 
485 started_net:
486 	if (!(ctx->options & DHCPCD_TEST)) {
487 		switch (pid = ps_ctl_start(ctx)) {
488 		case -1:
489 			return -1;
490 		case 0:
491 			return 0;
492 		default:
493 			logdebugx("spawned controller proxy on PID %d", pid);
494 		}
495 	}
496 
497 #ifdef ARC4RANDOM_H
498 	/* Seed the random number generator early incase it needs /dev/urandom
499 	 * which won't be available in the chroot. */
500 	arc4random();
501 #endif
502 
503 	return 1;
504 }
505 
506 int
507 ps_entersandbox(const char *_pledge, const char **sandbox)
508 {
509 
510 #if !defined(HAVE_PLEDGE)
511 	UNUSED(_pledge);
512 #endif
513 
514 #if defined(HAVE_CAPSICUM)
515 	if (sandbox != NULL)
516 		*sandbox = "capsicum";
517 	return cap_enter();
518 #elif defined(HAVE_PLEDGE)
519 	if (sandbox != NULL)
520 		*sandbox = "pledge";
521 	return pledge(_pledge, NULL);
522 #elif defined(HAVE_SECCOMP)
523 	if (sandbox != NULL)
524 		*sandbox = "seccomp";
525 	return ps_seccomp_enter();
526 #else
527 	if (sandbox != NULL)
528 		*sandbox = "posix resource limited";
529 	return 0;
530 #endif
531 }
532 
533 int
534 ps_mastersandbox(struct dhcpcd_ctx *ctx, const char *_pledge)
535 {
536 	const char *sandbox = NULL;
537 	bool forked;
538 	int dropped;
539 
540 	forked = ctx->options & DHCPCD_FORKED;
541 	ctx->options &= ~DHCPCD_FORKED;
542 	dropped = ps_dropprivs(ctx);
543 	if (forked)
544 		ctx->options |= DHCPCD_FORKED;
545 	if (dropped == -1) {
546 		logerr("%s: ps_dropprivs", __func__);
547 		return -1;
548 	}
549 
550 #ifdef PRIVSEP_RIGHTS
551 	if ((ctx->pf_inet_fd != -1 &&
552 	    ps_rights_limit_ioctl(ctx->pf_inet_fd) == -1) ||
553 	     ps_rights_limit_stdio(ctx) == -1)
554 	{
555 		logerr("%s: cap_rights_limit", __func__);
556 		return -1;
557 	}
558 #endif
559 
560 	if (_pledge == NULL)
561 		_pledge = "stdio";
562 	if (ps_entersandbox(_pledge, &sandbox) == -1) {
563 		if (errno == ENOSYS) {
564 			if (sandbox != NULL)
565 				logwarnx("sandbox unavailable: %s", sandbox);
566 			return 0;
567 		}
568 		logerr("%s: %s", __func__, sandbox);
569 		return -1;
570 	} else if (ctx->options & DHCPCD_LAUNCHER)
571 		logdebugx("sandbox: %s", sandbox);
572 	return 0;
573 }
574 
575 int
576 ps_stop(struct dhcpcd_ctx *ctx)
577 {
578 	int r, ret = 0;
579 
580 	if (!(ctx->options & DHCPCD_PRIVSEP) ||
581 	    ctx->options & DHCPCD_FORKED ||
582 	    ctx->eloop == NULL)
583 		return 0;
584 
585 	r = ps_ctl_stop(ctx);
586 	if (r != 0)
587 		ret = r;
588 
589 	r = ps_inet_stop(ctx);
590 	if (r != 0)
591 		ret = r;
592 
593 	/* We've been chrooted, so we need to tell the
594 	 * privileged actioneer to remove the pidfile. */
595 	ps_root_unlink(ctx, ctx->pidfile);
596 
597 	r = ps_root_stop(ctx);
598 	if (r != 0)
599 		ret = r;
600 
601 	ctx->options &= ~DHCPCD_PRIVSEP;
602 	return ret;
603 }
604 
605 void
606 ps_freeprocess(struct ps_process *psp)
607 {
608 
609 	TAILQ_REMOVE(&psp->psp_ctx->ps_processes, psp, next);
610 	if (psp->psp_fd != -1) {
611 		eloop_event_delete(psp->psp_ctx->eloop, psp->psp_fd);
612 		close(psp->psp_fd);
613 	}
614 	if (psp->psp_work_fd != -1) {
615 		eloop_event_delete(psp->psp_ctx->eloop, psp->psp_work_fd);
616 		close(psp->psp_work_fd);
617 	}
618 #ifdef INET
619 	if (psp->psp_bpf != NULL)
620 		bpf_close(psp->psp_bpf);
621 #endif
622 	free(psp);
623 }
624 
625 static void
626 ps_free(struct dhcpcd_ctx *ctx)
627 {
628 	struct ps_process *psp;
629 	bool stop = ctx->ps_root_pid == getpid();
630 
631 	while ((psp = TAILQ_FIRST(&ctx->ps_processes)) != NULL) {
632 		if (stop)
633 			ps_dostop(ctx, &psp->psp_pid, &psp->psp_fd);
634 		ps_freeprocess(psp);
635 	}
636 }
637 
638 int
639 ps_unrollmsg(struct msghdr *msg, struct ps_msghdr *psm,
640     const void *data, size_t len)
641 {
642 	uint8_t *datap, *namep, *controlp;
643 
644 	namep = UNCONST(data);
645 	controlp = namep + psm->ps_namelen;
646 	datap = controlp + psm->ps_controllen;
647 
648 	if (psm->ps_namelen != 0) {
649 		if (psm->ps_namelen > len) {
650 			errno = EINVAL;
651 			return -1;
652 		}
653 		msg->msg_name = namep;
654 		len -= psm->ps_namelen;
655 	} else
656 		msg->msg_name = NULL;
657 	msg->msg_namelen = psm->ps_namelen;
658 
659 	if (psm->ps_controllen != 0) {
660 		if (psm->ps_controllen > len) {
661 			errno = EINVAL;
662 			return -1;
663 		}
664 		msg->msg_control = controlp;
665 		len -= psm->ps_controllen;
666 	} else
667 		msg->msg_control = NULL;
668 	msg->msg_controllen = psm->ps_controllen;
669 
670 	if (len != 0) {
671 		msg->msg_iovlen = 1;
672 		msg->msg_iov[0].iov_base = datap;
673 		msg->msg_iov[0].iov_len = len;
674 	} else {
675 		msg->msg_iovlen = 0;
676 		msg->msg_iov[0].iov_base = NULL;
677 		msg->msg_iov[0].iov_len = 0;
678 	}
679 	return 0;
680 }
681 
682 ssize_t
683 ps_sendpsmmsg(struct dhcpcd_ctx *ctx, int fd,
684     struct ps_msghdr *psm, const struct msghdr *msg)
685 {
686 	struct iovec iov[] = {
687 		{ .iov_base = UNCONST(psm), .iov_len = sizeof(*psm) },
688 		{ .iov_base = NULL, },	/* name */
689 		{ .iov_base = NULL, },	/* control */
690 		{ .iov_base = NULL, },	/* payload 1 */
691 		{ .iov_base = NULL, },	/* payload 2 */
692 		{ .iov_base = NULL, },	/* payload 3 */
693 	};
694 	int iovlen;
695 	ssize_t len;
696 
697 	if (msg != NULL) {
698 		struct iovec *iovp = &iov[1];
699 		int i;
700 
701 		psm->ps_namelen = msg->msg_namelen;
702 		psm->ps_controllen = (socklen_t)msg->msg_controllen;
703 
704 		iovp->iov_base = msg->msg_name;
705 		iovp->iov_len = msg->msg_namelen;
706 		iovp++;
707 		iovp->iov_base = msg->msg_control;
708 		iovp->iov_len = msg->msg_controllen;
709 		iovlen = 3;
710 
711 		for (i = 0; i < (int)msg->msg_iovlen; i++) {
712 			if ((size_t)(iovlen + i) > __arraycount(iov)) {
713 				errno =	ENOBUFS;
714 				return -1;
715 			}
716 			iovp++;
717 			iovp->iov_base = msg->msg_iov[i].iov_base;
718 			iovp->iov_len = msg->msg_iov[i].iov_len;
719 		}
720 		iovlen += i;
721 	} else
722 		iovlen = 1;
723 
724 	len = writev(fd, iov, iovlen);
725 	if (len == -1) {
726 		logerr(__func__);
727 		if (ctx->options & DHCPCD_FORKED &&
728 		    !(ctx->options & DHCPCD_PRIVSEPROOT))
729 			eloop_exit(ctx->eloop, EXIT_FAILURE);
730 	}
731 	return len;
732 }
733 
734 ssize_t
735 ps_sendpsmdata(struct dhcpcd_ctx *ctx, int fd,
736     struct ps_msghdr *psm, const void *data, size_t len)
737 {
738 	struct iovec iov[] = {
739 		{ .iov_base = UNCONST(data), .iov_len = len },
740 	};
741 	struct msghdr msg = {
742 		.msg_iov = iov, .msg_iovlen = 1,
743 	};
744 
745 	return ps_sendpsmmsg(ctx, fd, psm, &msg);
746 }
747 
748 
749 ssize_t
750 ps_sendmsg(struct dhcpcd_ctx *ctx, int fd, uint16_t cmd, unsigned long flags,
751     const struct msghdr *msg)
752 {
753 	struct ps_msghdr psm = {
754 		.ps_cmd = cmd,
755 		.ps_flags = flags,
756 		.ps_namelen = msg->msg_namelen,
757 		.ps_controllen = (socklen_t)msg->msg_controllen,
758 	};
759 	size_t i;
760 
761 	for (i = 0; i < (size_t)msg->msg_iovlen; i++)
762 		psm.ps_datalen += msg->msg_iov[i].iov_len;
763 
764 #if 0	/* For debugging structure padding. */
765 	logerrx("psa.family %lu %zu", offsetof(struct ps_addr, psa_family), sizeof(psm.ps_id.psi_addr.psa_family));
766 	logerrx("psa.pad %lu %zu", offsetof(struct ps_addr, psa_pad), sizeof(psm.ps_id.psi_addr.psa_pad));
767 	logerrx("psa.psa_u %lu %zu", offsetof(struct ps_addr, psa_u), sizeof(psm.ps_id.psi_addr.psa_u));
768 	logerrx("psa %zu", sizeof(psm.ps_id.psi_addr));
769 
770 	logerrx("psi.addr %lu %zu", offsetof(struct ps_id, psi_addr), sizeof(psm.ps_id.psi_addr));
771 	logerrx("psi.index %lu %zu", offsetof(struct ps_id, psi_ifindex), sizeof(psm.ps_id.psi_ifindex));
772 	logerrx("psi.cmd %lu %zu", offsetof(struct ps_id, psi_cmd), sizeof(psm.ps_id.psi_cmd));
773 	logerrx("psi.pad %lu %zu", offsetof(struct ps_id, psi_pad), sizeof(psm.ps_id.psi_pad));
774 	logerrx("psi %zu", sizeof(struct ps_id));
775 
776 	logerrx("ps_cmd %lu", offsetof(struct ps_msghdr, ps_cmd));
777 	logerrx("ps_pad %lu %zu", offsetof(struct ps_msghdr, ps_pad), sizeof(psm.ps_pad));
778 	logerrx("ps_flags %lu %zu", offsetof(struct ps_msghdr, ps_flags), sizeof(psm.ps_flags));
779 
780 	logerrx("ps_id %lu %zu", offsetof(struct ps_msghdr, ps_id), sizeof(psm.ps_id));
781 
782 	logerrx("ps_namelen %lu %zu", offsetof(struct ps_msghdr, ps_namelen), sizeof(psm.ps_namelen));
783 	logerrx("ps_controllen %lu %zu", offsetof(struct ps_msghdr, ps_controllen), sizeof(psm.ps_controllen));
784 	logerrx("ps_pad2 %lu %zu", offsetof(struct ps_msghdr, ps_pad2), sizeof(psm.ps_pad2));
785 	logerrx("ps_datalen %lu %zu", offsetof(struct ps_msghdr, ps_datalen), sizeof(psm.ps_datalen));
786 	logerrx("psm %zu", sizeof(psm));
787 #endif
788 
789 	return ps_sendpsmmsg(ctx, fd, &psm, msg);
790 }
791 
792 ssize_t
793 ps_sendcmd(struct dhcpcd_ctx *ctx, int fd, uint16_t cmd, unsigned long flags,
794     const void *data, size_t len)
795 {
796 	struct ps_msghdr psm = {
797 		.ps_cmd = cmd,
798 		.ps_flags = flags,
799 	};
800 	struct iovec iov[] = {
801 		{ .iov_base = UNCONST(data), .iov_len = len }
802 	};
803 	struct msghdr msg = {
804 		.msg_iov = iov, .msg_iovlen = 1,
805 	};
806 
807 	return ps_sendpsmmsg(ctx, fd, &psm, &msg);
808 }
809 
810 static ssize_t
811 ps_sendcmdmsg(int fd, uint16_t cmd, const struct msghdr *msg)
812 {
813 	struct ps_msghdr psm = { .ps_cmd = cmd };
814 	uint8_t data[PS_BUFLEN], *p = data;
815 	struct iovec iov[] = {
816 		{ .iov_base = &psm, .iov_len = sizeof(psm) },
817 		{ .iov_base = data, .iov_len = 0 },
818 	};
819 	size_t dl = sizeof(data);
820 
821 	if (msg->msg_namelen != 0) {
822 		if (msg->msg_namelen > dl)
823 			goto nobufs;
824 		psm.ps_namelen = msg->msg_namelen;
825 		memcpy(p, msg->msg_name, msg->msg_namelen);
826 		p += msg->msg_namelen;
827 		dl -= msg->msg_namelen;
828 	}
829 
830 	if (msg->msg_controllen != 0) {
831 		if (msg->msg_controllen > dl)
832 			goto nobufs;
833 		psm.ps_controllen = (socklen_t)msg->msg_controllen;
834 		memcpy(p, msg->msg_control, msg->msg_controllen);
835 		p += msg->msg_controllen;
836 		dl -= msg->msg_controllen;
837 	}
838 
839 	psm.ps_datalen = msg->msg_iov[0].iov_len;
840 	if (psm.ps_datalen > dl)
841 		goto nobufs;
842 
843 	iov[1].iov_len = psm.ps_namelen + psm.ps_controllen + psm.ps_datalen;
844 	if (psm.ps_datalen != 0)
845 		memcpy(p, msg->msg_iov[0].iov_base, psm.ps_datalen);
846 	return writev(fd, iov, __arraycount(iov));
847 
848 nobufs:
849 	errno = ENOBUFS;
850 	return -1;
851 }
852 
853 ssize_t
854 ps_recvmsg(struct dhcpcd_ctx *ctx, int rfd, uint16_t cmd, int wfd)
855 {
856 	struct sockaddr_storage ss = { .ss_family = AF_UNSPEC };
857 	uint8_t controlbuf[sizeof(struct sockaddr_storage)] = { 0 };
858 	uint8_t databuf[64 * 1024];
859 	struct iovec iov[] = {
860 	    { .iov_base = databuf, .iov_len = sizeof(databuf) }
861 	};
862 	struct msghdr msg = {
863 		.msg_name = &ss, .msg_namelen = sizeof(ss),
864 		.msg_control = controlbuf, .msg_controllen = sizeof(controlbuf),
865 		.msg_iov = iov, .msg_iovlen = 1,
866 	};
867 
868 	ssize_t len = recvmsg(rfd, &msg, 0);
869 
870 	if (len == -1)
871 		logerr("%s: recvmsg", __func__);
872 	if (len == -1 || len == 0) {
873 		if (ctx->options & DHCPCD_FORKED &&
874 		    !(ctx->options & DHCPCD_PRIVSEPROOT))
875 			eloop_exit(ctx->eloop,
876 			    len == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
877 		return len;
878 	}
879 
880 	iov[0].iov_len = (size_t)len;
881 	len = ps_sendcmdmsg(wfd, cmd, &msg);
882 	if (len == -1) {
883 		logerr("ps_sendcmdmsg");
884 		if (ctx->options & DHCPCD_FORKED &&
885 		    !(ctx->options & DHCPCD_PRIVSEPROOT))
886 			eloop_exit(ctx->eloop, EXIT_FAILURE);
887 	}
888 	return len;
889 }
890 
891 ssize_t
892 ps_recvpsmsg(struct dhcpcd_ctx *ctx, int fd,
893     ssize_t (*callback)(void *, struct ps_msghdr *, struct msghdr *),
894     void *cbctx)
895 {
896 	struct ps_msg psm;
897 	ssize_t len;
898 	size_t dlen;
899 	struct iovec iov[1];
900 	struct msghdr msg = { .msg_iov = iov, .msg_iovlen = 1 };
901 	bool stop = false;
902 
903 	len = read(fd, &psm, sizeof(psm));
904 #ifdef PRIVSEP_DEBUG
905 	logdebugx("%s: %zd", __func__, len);
906 #endif
907 
908 	if (len == -1 || len == 0)
909 		stop = true;
910 	else {
911 		dlen = (size_t)len;
912 		if (dlen < sizeof(psm.psm_hdr)) {
913 			errno = EINVAL;
914 			return -1;
915 		}
916 
917 		if (psm.psm_hdr.ps_cmd == PS_STOP) {
918 			stop = true;
919 			len = 0;
920 		}
921 	}
922 
923 	if (stop) {
924 #ifdef PRIVSEP_DEBUG
925 		logdebugx("process %d stopping", getpid());
926 #endif
927 		ps_free(ctx);
928 #ifdef PLUGIN_DEV
929 		dev_stop(ctx);
930 #endif
931 		eloop_exit(ctx->eloop, len != -1 ? EXIT_SUCCESS : EXIT_FAILURE);
932 		return len;
933 	}
934 	dlen -= sizeof(psm.psm_hdr);
935 
936 	if (ps_unrollmsg(&msg, &psm.psm_hdr, psm.psm_data, dlen) == -1)
937 		return -1;
938 
939 	if (callback == NULL)
940 		return 0;
941 
942 	errno = 0;
943 	return callback(cbctx, &psm.psm_hdr, &msg);
944 }
945 
946 struct ps_process *
947 ps_findprocess(struct dhcpcd_ctx *ctx, struct ps_id *psid)
948 {
949 	struct ps_process *psp;
950 
951 	TAILQ_FOREACH(psp, &ctx->ps_processes, next) {
952 		if (memcmp(&psp->psp_id, psid, sizeof(psp->psp_id)) == 0)
953 			return psp;
954 	}
955 	errno = ESRCH;
956 	return NULL;
957 }
958 
959 struct ps_process *
960 ps_newprocess(struct dhcpcd_ctx *ctx, struct ps_id *psid)
961 {
962 	struct ps_process *psp;
963 
964 	psp = calloc(1, sizeof(*psp));
965 	if (psp == NULL)
966 		return NULL;
967 	psp->psp_ctx = ctx;
968 	memcpy(&psp->psp_id, psid, sizeof(psp->psp_id));
969 	psp->psp_work_fd = -1;
970 	TAILQ_INSERT_TAIL(&ctx->ps_processes, psp, next);
971 	return psp;
972 }
973 
974 void
975 ps_freeprocesses(struct dhcpcd_ctx *ctx, struct ps_process *notthis)
976 {
977 	struct ps_process *psp, *psn;
978 
979 	TAILQ_FOREACH_SAFE(psp, &ctx->ps_processes, next, psn) {
980 		if (psp == notthis)
981 			continue;
982 		ps_freeprocess(psp);
983 	}
984 }
985