Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
4 * Copyright (c) 2005 Claudio Jeker <claudio@openbsd.org>
5 * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
6 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
21 #include <sys/socket.h>
22 #include <sys/wait.h>
24 #include <arpa/inet.h>
25 #include <netinet/in.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <pwd.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <unistd.h>
37 #include "client.h"
38 #include "control.h"
39 #include "kamid.h"
40 #include "listener.h"
41 #include "log.h"
42 #include "sandbox.h"
43 #include "utils.h"
45 enum kd_process {
46 PROC_MAIN,
47 PROC_LISTENER,
48 PROC_CLIENTCONN,
49 };
51 const char *saved_argv0;
52 static int debug, nflag;
53 int verbose;
55 __dead void usage(void);
57 void main_sig_handler(int, short, void *);
58 void main_dispatch_listener(int, short, void *);
59 int main_reload(void);
60 int main_imsg_send_config(struct kd_conf *);
61 void main_dispatch_listener(int, short, void *);
62 __dead void main_shutdown(void);
64 static pid_t start_child(enum kd_process, int, int, int);
66 struct kd_conf *main_conf;
67 static struct imsgev *iev_listener;
68 const char *conffile;
69 pid_t listener_pid;
70 uint32_t cmd_opts;
72 __dead void
73 usage(void)
74 {
75 fprintf(stderr, "usage: %s [-dnv] [-f file] [-s socket]\n",
76 getprogname());
77 exit(1);
78 }
80 int
81 main(int argc, char **argv)
82 {
83 struct event ev_sigint, ev_sigterm, ev_sighup;
84 int ch;
85 int listener_flag = 0, client_flag = 0;
86 int pipe_main2listener[2];
87 int control_fd;
88 const char *csock;
90 conffile = KD_CONF_FILE;
91 csock = KD_SOCKET;
93 log_init(1, LOG_DAEMON); /* Log to stderr until deamonized. */
94 log_setverbose(1);
96 saved_argv0 = argv[0];
97 if (saved_argv0 == NULL)
98 saved_argv0 = "kamid";
100 while ((ch = getopt(argc, argv, "D:df:nsT:v")) != -1) {
101 switch (ch) {
102 case 'D':
103 if (cmdline_symset(optarg) == -1)
104 log_warnx("could not parse macro definition %s",
105 optarg);
106 break;
107 case 'd':
108 debug = 1;
109 break;
110 case 'f':
111 conffile = optarg;
112 break;
113 case 'n':
114 nflag = 1;
115 break;
116 case 's':
117 csock = optarg;
118 break;
119 case 'T':
120 switch (*optarg) {
121 case 'c':
122 client_flag = 1;
123 break;
124 case 'l':
125 listener_flag = 1;
126 break;
127 default:
128 fatalx("invalid process spec %c", *optarg);
130 break;
131 case 'v':
132 verbose = 1;
133 break;
134 default:
135 usage();
139 argc -= optind;
140 argv += optind;
141 if (argc > 0 || (listener_flag && client_flag))
142 usage();
144 if (client_flag)
145 client(debug, verbose);
146 else if (listener_flag)
147 listener(debug, verbose);
149 if ((main_conf = parse_config(conffile)) == NULL)
150 exit(1);
152 if (nflag) {
153 fprintf(stderr, "configuratino OK\n");
154 exit(0);
157 /* Check for root privileges. */
158 if (geteuid())
159 fatalx("need root privileges");
161 /* Check for assigned daemon user. */
162 if (getpwnam(KD_USER) == NULL)
163 fatalx("unknown user %s", KD_USER);
165 log_init(debug, LOG_DAEMON);
166 log_setverbose(verbose);
168 if (!debug)
169 daemon(1, 0);
171 log_info("startup");
173 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
174 PF_UNSPEC, pipe_main2listener) == -1)
175 fatal("main2listener socketpair");
177 /* Start children. */
178 listener_pid = start_child(PROC_LISTENER, pipe_main2listener[1],
179 debug, verbose);
181 log_procinit("main");
183 event_init();
185 /* Setup signal handler */
186 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
187 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
188 signal_set(&ev_sighup, SIGHUP, main_sig_handler, NULL);
190 signal_add(&ev_sigint, NULL);
191 signal_add(&ev_sigterm, NULL);
192 signal_add(&ev_sighup, NULL);
194 signal(SIGCHLD, SIG_IGN);
195 signal(SIGPIPE, SIG_IGN);
197 if ((iev_listener = malloc(sizeof(*iev_listener))) == NULL)
198 fatal(NULL);
199 imsg_init(&iev_listener->ibuf, pipe_main2listener[0]);
200 iev_listener->handler = main_dispatch_listener;
202 /* Setup event handlers for pipes to listener. */
203 iev_listener->events = EV_READ;
204 event_set(&iev_listener->ev, iev_listener->ibuf.fd,
205 iev_listener->events, iev_listener->handler, iev_listener);
206 event_add(&iev_listener->ev, NULL);
208 if ((control_fd = control_init(csock)) == -1)
209 fatalx("control socket setup failed");
211 main_imsg_compose_listener(IMSG_CONTROLFD, control_fd, 0,
212 NULL, 0);
213 main_imsg_send_config(main_conf);
215 sandbox_main();
217 event_dispatch();
219 main_shutdown();
220 return 0;
223 void
224 main_sig_handler(int sig, short event, void *arg)
226 /*
227 * Normal signal handler rules don't apply because libevent
228 * decouples for us.
229 */
231 switch (sig) {
232 case SIGTERM:
233 case SIGINT:
234 main_shutdown();
235 break;
236 case SIGHUP:
237 if (main_reload() == -1)
238 log_warnx("configuration reload failed");
239 else
240 log_debug("configuration reloaded");
241 break;
242 default:
243 fatalx("unexpected signal %d", sig);
247 static inline void
248 do_auth_tls(struct imsg *imsg)
250 const char *hash, *username = "op";
251 struct passwd *pw;
252 int p[2];
254 hash = imsg->data;
255 if (hash[IMSG_DATA_SIZE(*imsg)-1] != '\0')
256 goto err;
258 log_debug("tls hash=%s", hash);
259 log_debug("assuming it refers to user `%s'",
260 username);
262 if ((pw = getpwnam(username)) == NULL) {
263 log_warn("getpwnam(%s)", username);
264 goto err;
267 if (socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK,
268 PF_UNSPEC, p) == -1)
269 fatal("socketpair");
271 start_child(PROC_CLIENTCONN, p[1], debug, verbose);
273 main_imsg_compose_listener(IMSG_AUTH, p[0], imsg->hdr.peerid,
274 username, strlen(username)+1);
275 main_imsg_compose_listener(IMSG_AUTH_DIR, -1, imsg->hdr.peerid,
276 pw->pw_dir, strlen(pw->pw_dir)+1);
278 return;
280 err:
281 main_imsg_compose_listener(IMSG_AUTH, -1, imsg->hdr.peerid,
282 NULL, 0);
285 void
286 main_dispatch_listener(int fd, short event, void *d)
288 struct imsgev *iev = d;
289 struct imsgbuf *ibuf;
290 struct imsg imsg;
291 ssize_t n;
292 int shut = 0;
294 ibuf = &iev->ibuf;
296 if (event & EV_READ) {
297 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
298 fatal("imsg_read error");
299 if (n == 0) /* Connection closed. */
300 shut = 1;
302 if (event & EV_WRITE) {
303 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
304 fatal("msgbuf_write");
305 if (n == 0) /* Connection closed. */
306 shut = 1;
309 for (;;) {
310 if ((n = imsg_get(ibuf, &imsg)) == -1)
311 fatal("imsg_get");
312 if (n == 0) /* No more messages. */
313 break;
315 switch (imsg.hdr.type) {
316 case IMSG_AUTH_TLS:
317 do_auth_tls(&imsg);
318 break;
319 default:
320 log_debug("%s: error handling imsg %d", __func__,
321 imsg.hdr.type);
322 break;
324 imsg_free(&imsg);
326 if (!shut)
327 imsg_event_add(iev);
328 else {
329 /* This pipe is dead. Remove its event handler. */
330 event_del(&iev->ev);
331 event_loopexit(NULL);
335 int
336 main_reload(void)
338 struct kd_conf *xconf;
340 if ((xconf = parse_config(conffile)) == NULL)
341 return -1;
343 if (main_imsg_send_config(xconf) == -1)
344 return -1;
346 merge_config(main_conf, xconf);
348 return 0;
351 static inline int
352 make_socket_for(struct kd_listen_conf *l)
354 struct sockaddr_in addr4;
355 size_t len;
356 int fd, v;
358 memset(&addr4, 0, sizeof(addr4));
359 addr4.sin_family = AF_INET;
360 addr4.sin_port = htons(l->port);
361 addr4.sin_addr.s_addr = INADDR_ANY;
363 if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
364 fatal("socket");
366 v = 1;
367 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
368 fatal("setsockopt(SO_REUSEADDR)");
370 v = 1;
371 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
372 fatal("setsockopt(SO_REUSEPORT)");
374 len = sizeof(addr4);
375 if (bind(fd, (struct sockaddr *)&addr4, len) == -1)
376 fatal("bind(%s, %d)", l->iface, l->port);
378 if (listen(fd, 16) == -1)
379 fatal("l(%s, %d)", l->iface, l->port);
381 return fd;
384 int
385 main_imsg_send_config(struct kd_conf *xconf)
387 struct kd_pki_conf *pki;
388 struct kd_listen_conf *listen;
390 #define SEND(type, fd, data, len) do { \
391 if (main_imsg_compose_listener(type, fd, 0, data, len) \
392 == -1) \
393 return -1; \
394 } while (0)
396 /* Send fixed part of config to children. */
397 SEND(IMSG_RECONF_CONF, -1, xconf, sizeof(*xconf));
399 SIMPLEQ_FOREACH(pki, &xconf->pki_head, entry) {
400 log_debug("sending pki %s", pki->name);
401 SEND(IMSG_RECONF_PKI, -1, pki->name, sizeof(pki->name));
402 SEND(IMSG_RECONF_PKI_CERT, -1, pki->cert, pki->certlen);
403 SEND(IMSG_RECONF_PKI_KEY, -1, pki->key, pki->keylen);
406 SIMPLEQ_FOREACH(listen, &xconf->listen_head, entry) {
407 log_debug("sending listen on port %d", listen->port);
408 SEND(IMSG_RECONF_LISTEN, make_socket_for(listen), listen,
409 sizeof(*listen));
412 SEND(IMSG_RECONF_END, -1, NULL, 0);
413 return 0;
415 #undef SEND
418 void
419 merge_config(struct kd_conf *conf, struct kd_conf *xconf)
421 /* do stuff... */
423 free(xconf);
426 struct kd_conf *
427 config_new_empty(void)
429 struct kd_conf *xconf;
431 if ((xconf = calloc(1, sizeof(*xconf))) == NULL)
432 fatal(NULL);
434 /* set default values */
436 return xconf;
439 void
440 config_clear(struct kd_conf *conf)
442 struct kd_conf *xconf;
444 /* Merge current config with an empty one. */
445 xconf = config_new_empty();
446 merge_config(conf, xconf);
448 free(conf);
451 __dead void
452 main_shutdown(void)
454 pid_t pid;
455 int status;
457 /* close pipes. */
458 config_clear(main_conf);
460 log_debug("waiting for children to terminate");
461 do {
462 pid = wait(&status);
463 if (pid == -1) {
464 if (errno != EINTR && errno != ECHILD)
465 fatal("wait");
466 } else if (WIFSIGNALED(status))
467 log_warnx("%s terminated; signal %d",
468 (pid == listener_pid) ? "logger" : "clientconn",
469 WTERMSIG(status));
470 } while (pid != -1 || (pid == -1 && errno == EINTR));
472 free(iev_listener);
474 log_info("terminating");
475 exit(0);
478 static pid_t
479 start_child(enum kd_process p, int fd, int debug, int verbose)
481 const char *argv[5];
482 int argc = 0;
483 pid_t pid;
485 switch (pid = fork()) {
486 case -1:
487 fatal("cannot fork");
488 case 0:
489 break;
490 default:
491 close(fd);
492 return pid;
495 if (fd != 3) {
496 if (dup2(fd, 3) == -1)
497 fatal("cannot setup imsg fd");
498 } else if (fcntl(F_SETFD, 0) == -1)
499 fatal("cannot setup imsg fd");
501 argv[argc++] = saved_argv0;
502 switch (p) {
503 case PROC_MAIN:
504 fatalx("Can not start main process");
505 case PROC_LISTENER:
506 argv[argc++] = "-Tl";
507 break;
508 case PROC_CLIENTCONN:
509 argv[argc++] = "-Tc";
510 break;
512 if (debug)
513 argv[argc++] = "-d";
514 if (verbose)
515 argv[argc++] = "-v";
516 argv[argc++] = NULL;
518 /* really? */
519 execvp(saved_argv0, (char *const *)argv);
520 fatal("execvp");
523 void
524 imsg_event_add(struct imsgev *iev)
526 iev->events = EV_READ;
527 if (iev->ibuf.w.queued)
528 iev->events |= EV_WRITE;
530 event_del(&iev->ev);
531 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
532 event_add(&iev->ev, NULL);
535 int
536 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
537 pid_t pid, int fd, const void *data, uint16_t datalen)
539 int ret;
541 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
542 datalen) != -1))
543 imsg_event_add(iev);
545 return ret;
548 int
549 main_imsg_compose_listener(int type, int fd, uint32_t peerid,
550 const void *data, uint16_t datalen)
552 if (iev_listener)
553 return imsg_compose_event(iev_listener, type, peerid, 0,
554 fd, data, datalen);
555 else
556 return -1;