xref: /openbsd-src/sbin/iked/iked.c (revision f1dd7b858388b4a23f4f67a4957ec5ff656ebbe8)
1 /*	$OpenBSD: iked.c,v 1.57 2021/05/13 15:20:48 tobhe Exp $	*/
2 
3 /*
4  * Copyright (c) 2019 Tobias Heider <tobias.heider@stusta.de>
5  * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/queue.h>
21 #include <sys/socket.h>
22 #include <sys/wait.h>
23 #include <sys/uio.h>
24 
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <getopt.h>
30 #include <signal.h>
31 #include <syslog.h>
32 #include <errno.h>
33 #include <err.h>
34 #include <pwd.h>
35 #include <event.h>
36 
37 #include "iked.h"
38 #include "ikev2.h"
39 
40 __dead void usage(void);
41 
42 void	 parent_shutdown(struct iked *);
43 void	 parent_sig_handler(int, short, void *);
44 int	 parent_dispatch_ca(int, struct privsep_proc *, struct imsg *);
45 int	 parent_dispatch_control(int, struct privsep_proc *, struct imsg *);
46 int	 parent_dispatch_ikev2(int, struct privsep_proc *, struct imsg *);
47 int	 parent_configure(struct iked *);
48 
49 static struct privsep_proc procs[] = {
50 	{ "ca",		PROC_CERT,	parent_dispatch_ca, caproc, IKED_CA },
51 	{ "control",	PROC_CONTROL,	parent_dispatch_control, control },
52 	{ "ikev2",	PROC_IKEV2,	parent_dispatch_ikev2, ikev2 }
53 };
54 
55 __dead void
56 usage(void)
57 {
58 	extern char	*__progname;
59 
60 	fprintf(stderr, "usage: %s [-dnSTtv] [-D macro=value] "
61 	    "[-f file] [-p udpencap_port] [-s socket]\n", __progname);
62 	exit(1);
63 }
64 
65 int
66 main(int argc, char *argv[])
67 {
68 	int		 c;
69 	int		 debug = 0, verbose = 0;
70 	int		 opts = 0;
71 	enum natt_mode	 natt_mode = NATT_DEFAULT;
72 	in_port_t	 port = IKED_NATT_PORT;
73 	const char	*conffile = IKED_CONFIG;
74 	const char	*sock = IKED_SOCKET;
75 	const char	*errstr;
76 	struct iked	*env = NULL;
77 	struct privsep	*ps;
78 
79 	log_init(1, LOG_DAEMON);
80 
81 	while ((c = getopt(argc, argv, "6D:df:np:Ss:Ttv")) != -1) {
82 		switch (c) {
83 		case '6':
84 			log_warnx("the -6 option is ignored and will be "
85 			    "removed in the future.");
86 			break;
87 		case 'D':
88 			if (cmdline_symset(optarg) < 0)
89 				log_warnx("could not parse macro definition %s",
90 				    optarg);
91 			break;
92 		case 'd':
93 			debug++;
94 			break;
95 		case 'f':
96 			conffile = optarg;
97 			break;
98 		case 'n':
99 			debug = 1;
100 			opts |= IKED_OPT_NOACTION;
101 			break;
102 		case 'p':
103 			if (natt_mode == NATT_DISABLE)
104 				errx(1, "-T and -p are mutually exclusive");
105 			port = strtonum(optarg, 1, UINT16_MAX, &errstr);
106 			if (errstr != NULL)
107 				errx(1, "port is %s: %s", errstr, optarg);
108 			natt_mode = NATT_FORCE;
109 			break;
110 		case 'S':
111 			opts |= IKED_OPT_PASSIVE;
112 			break;
113 		case 's':
114 			sock = optarg;
115 			break;
116 		case 'T':
117 			if (natt_mode == NATT_FORCE)
118 				errx(1, "-T and -t/-p are mutually exclusive");
119 			natt_mode = NATT_DISABLE;
120 			break;
121 		case 't':
122 			if (natt_mode == NATT_DISABLE)
123 				errx(1, "-T and -t are mutually exclusive");
124 			natt_mode = NATT_FORCE;
125 			break;
126 		case 'v':
127 			verbose++;
128 			opts |= IKED_OPT_VERBOSE;
129 			break;
130 		default:
131 			usage();
132 		}
133 	}
134 
135 	argc -= optind;
136 	argv += optind;
137 	if (argc > 0)
138 		usage();
139 
140 	if ((env = calloc(1, sizeof(*env))) == NULL)
141 		fatal("calloc: env");
142 
143 	env->sc_opts = opts;
144 	env->sc_nattmode = natt_mode;
145 	env->sc_nattport = port;
146 
147 	ps = &env->sc_ps;
148 	ps->ps_env = env;
149 	TAILQ_INIT(&ps->ps_rcsocks);
150 
151 	if (strlcpy(env->sc_conffile, conffile, PATH_MAX) >= PATH_MAX)
152 		errx(1, "config file exceeds PATH_MAX");
153 
154 	ca_sslinit();
155 	policy_init(env);
156 
157 	/* check for root privileges */
158 	if (geteuid())
159 		errx(1, "need root privileges");
160 
161 	if ((ps->ps_pw =  getpwnam(IKED_USER)) == NULL)
162 		errx(1, "unknown user %s", IKED_USER);
163 
164 	/* Configure the control socket */
165 	ps->ps_csock.cs_name = sock;
166 
167 	log_init(debug, LOG_DAEMON);
168 	log_setverbose(verbose);
169 
170 	if (opts & IKED_OPT_NOACTION)
171 		ps->ps_noaction = 1;
172 
173 	if (!debug && daemon(0, 0) == -1)
174 		err(1, "failed to daemonize");
175 
176 	group_init();
177 
178 	ps->ps_ninstances = 1;
179 	proc_init(ps, procs, nitems(procs));
180 
181 	setproctitle("parent");
182 	log_procinit("parent");
183 
184 	event_init();
185 
186 	signal_set(&ps->ps_evsigint, SIGINT, parent_sig_handler, ps);
187 	signal_set(&ps->ps_evsigterm, SIGTERM, parent_sig_handler, ps);
188 	signal_set(&ps->ps_evsigchld, SIGCHLD, parent_sig_handler, ps);
189 	signal_set(&ps->ps_evsighup, SIGHUP, parent_sig_handler, ps);
190 	signal_set(&ps->ps_evsigpipe, SIGPIPE, parent_sig_handler, ps);
191 	signal_set(&ps->ps_evsigusr1, SIGUSR1, parent_sig_handler, ps);
192 
193 	signal_add(&ps->ps_evsigint, NULL);
194 	signal_add(&ps->ps_evsigterm, NULL);
195 	signal_add(&ps->ps_evsigchld, NULL);
196 	signal_add(&ps->ps_evsighup, NULL);
197 	signal_add(&ps->ps_evsigpipe, NULL);
198 	signal_add(&ps->ps_evsigusr1, NULL);
199 
200 	proc_listen(ps, procs, nitems(procs));
201 
202 	vroute_init(env);
203 
204 	if (parent_configure(env) == -1)
205 		fatalx("configuration failed");
206 
207 	event_dispatch();
208 
209 	log_debug("%d parent exiting", getpid());
210 	parent_shutdown(env);
211 
212 	return (0);
213 }
214 
215 int
216 parent_configure(struct iked *env)
217 {
218 	struct sockaddr_storage	 ss;
219 
220 	if (parse_config(env->sc_conffile, env) == -1) {
221 		proc_kill(&env->sc_ps);
222 		exit(1);
223 	}
224 
225 	if (env->sc_opts & IKED_OPT_NOACTION) {
226 		fprintf(stderr, "configuration OK\n");
227 		proc_kill(&env->sc_ps);
228 		exit(0);
229 	}
230 
231 	env->sc_pfkey = -1;
232 	config_setpfkey(env);
233 
234 	/* Send private and public keys to cert after forking the children */
235 	if (config_setkeys(env) == -1)
236 		fatalx("%s: failed to send keys", __func__);
237 	config_setreset(env, RESET_CA, PROC_CERT);
238 
239 	/* Now compile the policies and calculate skip steps */
240 	config_setcompile(env, PROC_IKEV2);
241 
242 	bzero(&ss, sizeof(ss));
243 	ss.ss_family = AF_INET;
244 
245 	/* see comment on config_setsocket() */
246 	if (env->sc_nattmode != NATT_FORCE)
247 		config_setsocket(env, &ss, htons(IKED_IKE_PORT), PROC_IKEV2);
248 	if (env->sc_nattmode != NATT_DISABLE)
249 		config_setsocket(env, &ss, htons(env->sc_nattport), PROC_IKEV2);
250 
251 	bzero(&ss, sizeof(ss));
252 	ss.ss_family = AF_INET6;
253 
254 	if (env->sc_nattmode != NATT_FORCE)
255 		config_setsocket(env, &ss, htons(IKED_IKE_PORT), PROC_IKEV2);
256 	if (env->sc_nattmode != NATT_DISABLE)
257 		config_setsocket(env, &ss, htons(env->sc_nattport), PROC_IKEV2);
258 
259 	/*
260 	 * pledge in the parent process:
261 	 * It has to run fairly late to allow forking the processes and
262 	 * opening the PFKEY socket and the listening UDP sockets (once)
263 	 * that need the bypass ioctls that are never allowed by pledge.
264 	 *
265 	 * Other flags:
266 	 * stdio - for malloc and basic I/O including events.
267 	 * rpath - for reload to open and read the configuration files.
268 	 * proc - run kill to terminate its children safely.
269 	 * dns - for reload and ocsp connect.
270 	 * inet - for ocsp connect.
271 	 * route - for using interfaces in iked.conf (SIOCGIFGMEMB)
272 	 * wroute - for adding and removing addresses (SIOCAIFGMEMB)
273 	 * sendfd - for ocsp sockets.
274 	 */
275 	if (pledge("stdio rpath proc dns inet route wroute sendfd", NULL) == -1)
276 		fatal("pledge");
277 
278 	config_setstatic(env);
279 	config_setcoupled(env, env->sc_decoupled ? 0 : 1);
280 	config_setocsp(env);
281 	config_setcertpartialchain(env);
282 	/* Must be last */
283 	config_setmode(env, env->sc_passive ? 1 : 0);
284 
285 	return (0);
286 }
287 
288 void
289 parent_reload(struct iked *env, int reset, const char *filename)
290 {
291 	/* Switch back to the default config file */
292 	if (filename == NULL || *filename == '\0')
293 		filename = env->sc_conffile;
294 
295 	log_debug("%s: level %d config file %s", __func__, reset, filename);
296 
297 	if (reset == RESET_RELOAD) {
298 		config_setreset(env, RESET_POLICY, PROC_IKEV2);
299 		if (config_setkeys(env) == -1)
300 			fatalx("%s: failed to send keys", __func__);
301 		config_setreset(env, RESET_CA, PROC_CERT);
302 
303 		if (parse_config(filename, env) == -1) {
304 			log_debug("%s: failed to load config file %s",
305 			    __func__, filename);
306 		}
307 
308 		/* Re-compile policies and skip steps */
309 		config_setcompile(env, PROC_IKEV2);
310 
311 		config_setstatic(env);
312 		config_setcoupled(env, env->sc_decoupled ? 0 : 1);
313 		config_setocsp(env);
314 		config_setcertpartialchain(env);
315  		/* Must be last */
316 		config_setmode(env, env->sc_passive ? 1 : 0);
317 	} else {
318 		config_setreset(env, reset, PROC_IKEV2);
319 		config_setreset(env, reset, PROC_CERT);
320 	}
321 }
322 
323 void
324 parent_sig_handler(int sig, short event, void *arg)
325 {
326 	struct privsep	*ps = arg;
327 	int		 die = 0, status, fail, id;
328 	pid_t		 pid;
329 	char		*cause;
330 
331 	switch (sig) {
332 	case SIGHUP:
333 		log_info("%s: reload requested with SIGHUP", __func__);
334 
335 		/*
336 		 * This is safe because libevent uses async signal handlers
337 		 * that run in the event loop and not in signal context.
338 		 */
339 		parent_reload(ps->ps_env, 0, NULL);
340 		break;
341 	case SIGPIPE:
342 		log_info("%s: ignoring SIGPIPE", __func__);
343 		break;
344 	case SIGUSR1:
345 		log_info("%s: ignoring SIGUSR1", __func__);
346 		break;
347 	case SIGTERM:
348 	case SIGINT:
349 		die = 1;
350 		/* FALLTHROUGH */
351 	case SIGCHLD:
352 		do {
353 			int len;
354 
355 			pid = waitpid(-1, &status, WNOHANG);
356 			if (pid <= 0)
357 				continue;
358 
359 			fail = 0;
360 			if (WIFSIGNALED(status)) {
361 				fail = 1;
362 				len = asprintf(&cause, "terminated; signal %d",
363 				    WTERMSIG(status));
364 			} else if (WIFEXITED(status)) {
365 				if (WEXITSTATUS(status) != 0) {
366 					fail = 1;
367 					len = asprintf(&cause,
368 					    "exited abnormally");
369 				} else
370 					len = asprintf(&cause, "exited okay");
371 			} else
372 				fatalx("unexpected cause of SIGCHLD");
373 
374 			if (len == -1)
375 				fatal("asprintf");
376 
377 			die = 1;
378 
379 			for (id = 0; id < PROC_MAX; id++)
380 				if (pid == ps->ps_pid[id]) {
381 					if (fail)
382 						log_warnx("lost child: %s %s",
383 						    ps->ps_title[id], cause);
384 					break;
385 				}
386 
387 			free(cause);
388 		} while (pid > 0 || (pid == -1 && errno == EINTR));
389 
390 		if (die)
391 			parent_shutdown(ps->ps_env);
392 		break;
393 	default:
394 		fatalx("unexpected signal");
395 	}
396 }
397 
398 int
399 parent_dispatch_ca(int fd, struct privsep_proc *p, struct imsg *imsg)
400 {
401 	struct iked	*env = p->p_ps->ps_env;
402 
403 	switch (imsg->hdr.type) {
404 	case IMSG_OCSP_FD:
405 		ocsp_connect(env, imsg);
406 		break;
407 	default:
408 		return (-1);
409 	}
410 
411 	return (0);
412 }
413 
414 int
415 parent_dispatch_control(int fd, struct privsep_proc *p, struct imsg *imsg)
416 {
417 	struct iked	*env = p->p_ps->ps_env;
418 	int		 v;
419 	char		*str = NULL;
420 	unsigned int	 type = imsg->hdr.type;
421 
422 	switch (type) {
423 	case IMSG_CTL_RESET:
424 		IMSG_SIZE_CHECK(imsg, &v);
425 		memcpy(&v, imsg->data, sizeof(v));
426 		parent_reload(env, v, NULL);
427 		break;
428 	case IMSG_CTL_COUPLE:
429 	case IMSG_CTL_DECOUPLE:
430 	case IMSG_CTL_ACTIVE:
431 	case IMSG_CTL_PASSIVE:
432 		proc_compose(&env->sc_ps, PROC_IKEV2, type, NULL, 0);
433 		break;
434 	case IMSG_CTL_RELOAD:
435 		if (IMSG_DATA_SIZE(imsg) > 0)
436 			str = get_string(imsg->data, IMSG_DATA_SIZE(imsg));
437 		parent_reload(env, 0, str);
438 		free(str);
439 		break;
440 	case IMSG_CTL_VERBOSE:
441 		proc_forward_imsg(&env->sc_ps, imsg, PROC_IKEV2, -1);
442 		proc_forward_imsg(&env->sc_ps, imsg, PROC_CERT, -1);
443 
444 		/* return 1 to let proc.c handle it locally */
445 		return (1);
446 	default:
447 		return (-1);
448 	}
449 
450 	return (0);
451 }
452 
453 int
454 parent_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg)
455 {
456 	struct iked	*env = p->p_ps->ps_env;
457 
458 	switch (imsg->hdr.type) {
459 	case IMSG_IF_ADDADDR:
460 	case IMSG_IF_DELADDR:
461 		return (vroute_getaddr(env, imsg));
462 	case IMSG_VROUTE_ADD:
463 	case IMSG_VROUTE_DEL:
464 		return (vroute_getroute(env, imsg));
465 	case IMSG_VROUTE_CLONE:
466 		return (vroute_getcloneroute(env, imsg));
467 	default:
468 		return (-1);
469 	}
470 
471 	return (0);
472 }
473 
474 void
475 parent_shutdown(struct iked *env)
476 {
477 	proc_kill(&env->sc_ps);
478 
479 	vroute_cleanup(env);
480 	free(env->sc_vroute);
481 	free(env);
482 
483 	log_warnx("parent terminating");
484 	exit(0);
485 }
486