2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2018 Florian Obser <florian@openbsd.org>
4 * Copyright (c) 2004, 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>
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.
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.
23 #include <sys/socket.h>
43 static struct kd_conf *listener_conf;
44 static struct imsgev *iev_main;
46 static void listener_sig_handler(int, short, void *);
47 ATTR_DEAD void listener_shutdown(void);
49 SPLAY_HEAD(clients_tree_id, client) clients;
59 struct bufferevent *bev;
60 SPLAY_ENTRY(client) sp_entry;
63 static void listener_imsg_event_add(struct imsgev *, void *);
64 static void listener_dispatch_client(int, short, void *);
65 static int listener_imsg_compose_client(struct client *, int,
66 uint32_t, const void *, uint16_t);
68 static void apply_config(struct kd_conf *);
69 static void handle_accept(int, short, void *);
71 static void handle_handshake(int, short, void *);
72 static void client_read(struct bufferevent *, void *);
73 static void client_write(struct bufferevent *, void *);
74 static void client_error(struct bufferevent *, short, void *);
75 static void client_tls_readcb(int, short, void *);
76 static void client_tls_writecb(int, short, void *);
77 static void close_conn(struct client *);
78 static void handle_close(int, short, void *);
81 clients_tree_cmp(struct client *a, struct client *b)
85 else if (a->id < b->id)
91 SPLAY_PROTOTYPE(clients_tree_id, client, sp_entry, clients_tree_cmp);
92 SPLAY_GENERATE(clients_tree_id, client, sp_entry, clients_tree_cmp)
95 listener_sig_handler(int sig, short event, void *d)
98 * Normal signal handler rules don't apply because libevent
107 fatalx("unexpected signal %d", sig);
112 listener(int debug, int verbose)
114 struct event ev_sigint, ev_sigterm;
117 /* listener_conf = config_new_empty(); */
119 log_init(debug, LOG_DAEMON);
120 log_setverbose(verbose);
122 if ((pw = getpwnam(KD_USER)) == NULL)
125 if (chroot(pw->pw_dir) == -1)
127 if (chdir("/") == -1)
128 fatal("chdir(\"/\")");
130 setproctitle("listener");
131 log_procinit("listener");
133 if (setgroups(1, &pw->pw_gid) ||
134 setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
135 setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
136 fatal("can't drop privileges");
140 /* Setup signal handlers(s). */
141 signal_set(&ev_sigint, SIGINT, listener_sig_handler, NULL);
142 signal_set(&ev_sigterm, SIGTERM, listener_sig_handler, NULL);
144 signal_add(&ev_sigint, NULL);
145 signal_add(&ev_sigterm, NULL);
147 signal(SIGPIPE, SIG_IGN);
148 signal(SIGHUP, SIG_IGN);
150 /* Setup pipe and event handler to the main process. */
151 if ((iev_main = malloc(sizeof(*iev_main))) == NULL)
154 imsg_init(&iev_main->ibuf, 3);
155 iev_main->handler = listener_dispatch_main;
157 /* Setup event handlers. */
158 iev_main->events = EV_READ;
159 event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
160 iev_main->handler, iev_main);
161 event_add(&iev_main->ev, NULL);
169 listener_shutdown(void)
171 msgbuf_clear(&iev_main->ibuf.w);
172 close(iev_main->ibuf.fd);
174 config_clear(listener_conf);
178 log_info("listener exiting");
183 listener_receive_config(struct imsg *imsg, struct kd_conf **nconf,
184 struct kd_pki_conf **pki)
186 struct kd_listen_conf *listen;
189 switch (imsg->hdr.type) {
190 case IMSG_RECONF_CONF:
192 fatalx("%s: IMSG_RECONF_CONF already in "
193 "progress", __func__);
195 if (listener_conf != NULL)
196 fatalx("%s: don't know how reload the "
197 "configuration yet", __func__);
199 if (IMSG_DATA_SIZE(*imsg) != sizeof(struct kd_conf))
200 fatalx("%s: IMSG_RECONF_CONF wrong length: %lu",
201 __func__, IMSG_DATA_SIZE(*imsg));
202 if ((*nconf = malloc(sizeof(**nconf))) == NULL)
204 memcpy(*nconf, imsg->data, sizeof(**nconf));
205 memset(&(*nconf)->pki_head, 0, sizeof((*nconf)->pki_head));
206 memset(&(*nconf)->table_head, 0, sizeof((*nconf)->table_head));
207 memset(&(*nconf)->listen_head, 0, sizeof((*nconf)->listen_head));
209 case IMSG_RECONF_PKI:
211 fatalx("%s: IMSG_RECONF_PKI without "
212 "IMSG_RECONF_CONF", __func__);
213 *pki = xcalloc(1, sizeof(**pki));
215 t[IMSG_DATA_SIZE(*imsg)-1] = '\0';
216 strlcpy((*pki)->name, t, sizeof((*pki)->name));
218 case IMSG_RECONF_PKI_CERT:
220 fatalx("%s: IMSG_RECONF_PKI_CERT without "
221 "IMSG_RECONF_PKI", __func__);
222 (*pki)->certlen = IMSG_DATA_SIZE(*imsg);
223 (*pki)->cert = xmemdup(imsg->data, (*pki)->certlen);
225 case IMSG_RECONF_PKI_KEY:
227 fatalx("%s: IMSG_RECONF_PKI_KEY without "
228 "IMSG_RECONF_PKI", __func__);
229 (*pki)->keylen = IMSG_DATA_SIZE(*imsg);
230 (*pki)->key = xmemdup(imsg->data, (*pki)->keylen);
231 SIMPLEQ_INSERT_HEAD(&(*nconf)->pki_head, *pki, entry);
234 case IMSG_RECONF_LISTEN:
236 fatalx("%s: IMSG_RECONF_LISTEN without "
237 "IMSG_RECONF_CONF", __func__);
238 if (IMSG_DATA_SIZE(*imsg) != sizeof(*listen))
239 fatalx("%s: IMSG_RECONF_LISTEN wrong length: %lu",
240 __func__, IMSG_DATA_SIZE(*imsg));
241 listen = xcalloc(1, sizeof(*listen));
242 memcpy(listen, imsg->data, sizeof(*listen));
243 memset(&listen->entry, 0, sizeof(listen->entry));
244 if ((listen->fd = imsg->fd) == -1)
245 fatalx("%s: IMSG_RECONF_LISTEN no fd",
247 listen->auth_table = NULL;
248 memset(&listen->ev, 0, sizeof(listen->ev));
249 SIMPLEQ_INSERT_HEAD(&(*nconf)->listen_head, listen, entry);
251 case IMSG_RECONF_END:
253 fatalx("%s: IMSG_RECONF_END without "
254 "IMSG_RECONF_CONF", __func__);
255 /* merge_config(listener_conf, nconf); */
256 apply_config(*nconf);
262 static inline struct kd_listen_conf *
263 listen_by_id(uint32_t id)
265 struct kd_listen_conf *l;
267 SIMPLEQ_FOREACH(l, &listener_conf->listen_head, entry) {
275 listener_dispatch_main(int fd, short event, void *d)
277 static struct kd_conf *nconf;
278 static struct kd_pki_conf *pki;
279 struct kd_listen_conf *listen;
280 struct client *client, find;
282 struct imsgev *iev = d;
283 struct imsgbuf *ibuf;
289 if (event & EV_READ) {
290 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
291 fatal("imsg_read error");
292 if (n == 0) /* Connection closed. */
295 if (event & EV_WRITE) {
296 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
297 fatal("msgbuf_write");
298 if (n == 0) /* Connection closed. */
303 if ((n = imsg_get(ibuf, &imsg)) == -1)
304 fatal("%s: imsg_get error", __func__);
305 if (n == 0) /* No more messages. */
308 switch (imsg.hdr.type) {
310 if ((fd = imsg.fd) == -1)
311 fatalx("%s: expected to receive imsg "
312 "control fd but didn't receive any",
314 /* Listen on control socket. */
317 case IMSG_RECONF_CONF:
318 case IMSG_RECONF_PKI:
319 case IMSG_RECONF_PKI_CERT:
320 case IMSG_RECONF_PKI_KEY:
321 case IMSG_RECONF_LISTEN:
322 case IMSG_RECONF_END:
323 listener_receive_config(&imsg, &nconf, &pki);
326 find.id = imsg.hdr.peerid;
327 client = SPLAY_FIND(clients_tree_id, &clients, &find);
328 if (client == NULL) {
337 imsg_init(&client->iev.ibuf, imsg.fd);
338 client->iev.events = EV_READ;
339 client->iev.handler = listener_dispatch_client;
340 event_set(&client->iev.ev, client->iev.ibuf.fd,
341 client->iev.events, client->iev.handler, client);
342 listener_imsg_compose_client(client, IMSG_AUTH,
343 0, imsg.data, IMSG_DATA_SIZE(imsg));
346 find.id = imsg.hdr.peerid;
347 client = SPLAY_FIND(clients_tree_id, &clients, &find);
348 if (client == NULL) {
349 log_info("got AUTH_DIR but client gone");
353 listener_imsg_compose_client(client, IMSG_AUTH_DIR,
354 0, imsg.data, IMSG_DATA_SIZE(imsg));
356 client->bev = bufferevent_new(client->fd,
357 client_read, client_write, client_error,
359 if (client->bev == NULL) {
360 log_info("failed to allocate client buffer");
365 listen = listen_by_id(client->lid);
366 if (listen->flags & L_TLS) {
367 event_set(&client->bev->ev_read, client->fd,
368 EV_READ, client_tls_readcb, client->bev);
369 event_set(&client->bev->ev_write, client->fd,
370 EV_WRITE, client_tls_writecb, client->bev);
374 * Read or write at least a header before
375 * firing the callbacks. High watermark of 0
376 * to never stop reading/writing; probably to
379 bufferevent_setwatermark(client->bev, EV_READ|EV_WRITE,
380 sizeof(struct np_msg_header), 0);
381 bufferevent_enable(client->bev, EV_READ|EV_WRITE);
385 log_debug("%s: unexpected imsg %d", __func__,
393 listener_imsg_event_add(iev, d);
395 /* This pipe is dead. Remove its event handler. */
397 log_warnx("pipe closed, shutting down...");
398 event_loopexit(NULL);
403 listener_imsg_compose_main(int type, uint32_t peerid, const void *data,
406 return imsg_compose_event(iev_main, type, peerid, 0, -1, data,
411 listener_imsg_event_add(struct imsgev *iev, void *d)
413 iev->events = EV_READ;
414 if (iev->ibuf.w.queued)
415 iev->events |= EV_WRITE;
418 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, d);
419 event_add(&iev->ev, NULL);
423 listener_dispatch_client(int fd, short event, void *d)
425 struct client find, *client = d;
428 struct imsgbuf *ibuf;
435 if (event & EV_READ) {
436 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
437 fatal("imsg_read error");
438 if (n == 0) /* Connection closed */
442 if (event & EV_WRITE) {
443 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
444 fatal("msgbuf_write");
445 if (n == 0) /* Connection closed. */
450 if ((n = imsg_get(ibuf, &imsg)) == -1)
451 fatal("%s: imsg_get error", __func__);
452 if (n == 0) /* No more messages. */
455 switch (imsg.hdr.type) {
457 find.id = imsg.hdr.peerid;
458 client = SPLAY_FIND(clients_tree_id, &clients, &find);
459 if (client == NULL) {
460 log_info("got IMSG_BUF but client (%d) gone",
464 r = bufferevent_write(client->bev, imsg.data,
465 IMSG_DATA_SIZE(imsg));
467 log_warn("%s: bufferevent_write failed",
474 log_debug("%s: unexpected imsg %d", __func__,
482 listener_imsg_event_add(iev, d);
484 /* This pipe is dead. Remove its handler */
485 log_debug("client proc vanished");
491 listener_imsg_compose_client(struct client *client, int type,
492 uint32_t peerid, const void *data, uint16_t len)
496 if ((ret = imsg_compose(&client->iev.ibuf, type, peerid, 0, -1,
498 listener_imsg_event_add(&client->iev, client);
503 static inline struct kd_pki_conf *
504 pki_by_name(const char *name)
506 struct kd_pki_conf *pki;
508 SIMPLEQ_FOREACH(pki, &listener_conf->pki_head, entry) {
509 if (!strcmp(name, pki->name))
517 apply_config(struct kd_conf *conf)
519 struct kd_pki_conf *pki;
520 struct kd_listen_conf *listen;
522 listener_conf = conf;
524 /* prepare the various tls_config */
525 SIMPLEQ_FOREACH(pki, &listener_conf->pki_head, entry) {
526 if ((pki->tlsconf = tls_config_new()) == NULL)
527 fatal("tls_config_new");
528 tls_config_verify_client_optional(pki->tlsconf);
529 tls_config_insecure_noverifycert(pki->tlsconf);
530 if (tls_config_set_keypair_mem(pki->tlsconf,
531 pki->cert, pki->certlen,
532 pki->key, pki->keylen) == -1)
533 fatalx("tls_config_set_keypair_mem: %s",
534 tls_config_error(pki->tlsconf));
537 /* prepare and kickoff the listeners */
538 SIMPLEQ_FOREACH(listen, &listener_conf->listen_head, entry) {
539 if ((listen->ctx = tls_server()) == NULL)
542 pki = pki_by_name(listen->pki);
543 if (tls_configure(listen->ctx, pki->tlsconf) == -1)
544 fatalx("tls_configure: %s",
545 tls_config_error(pki->tlsconf));
547 event_set(&listen->ev, listen->fd, EV_READ|EV_PERSIST,
548 handle_accept, listen);
549 event_add(&listen->ev, NULL);
554 yield_r(struct client *c, void (*fn)(int, short, void *))
556 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
557 event_del(&c->event);
558 event_set(&c->event, c->fd, EV_READ, fn, c);
559 event_add(&c->event, NULL);
563 yield_w(struct client *c, void (*fn)(int, short, void *))
565 if (event_pending(&c->event, EV_WRITE|EV_READ, NULL))
566 event_del(&c->event);
567 event_set(&c->event, c->fd, EV_WRITE, fn, c);
568 event_add(&c->event, NULL);
571 static inline uint32_t
575 # define RANDID() arc4random()
577 /* not as pretty as a random id */
578 static uint32_t counter = 0;
579 # define RANDID() counter++
582 struct client find, *res;
586 res = SPLAY_FIND(clients_tree_id, &clients, &find);
595 handle_accept(int fd, short ev, void *data)
597 struct kd_listen_conf *listen = data;
601 if ((s = accept(fd, NULL, NULL)) == -1) {
606 c = xcalloc(1, sizeof(*c));
610 if (tls_accept_socket(listen->ctx, &c->ctx, s) == -1) {
611 log_warnx("tls_accept_socket: %s",
612 tls_error(listen->ctx));
621 SPLAY_INSERT(clients_tree_id, &clients, c);
623 /* initialize the event */
624 event_set(&c->event, c->fd, EV_READ, NULL, NULL);
626 yield_r(c, handle_handshake);
630 handle_handshake(int fd, short ev, void *data)
632 struct client *c = data;
633 struct kd_auth_req auth;
637 switch (r = tls_handshake(c->ctx)) {
638 case TLS_WANT_POLLIN:
639 yield_r(c, handle_handshake);
641 case TLS_WANT_POLLOUT:
642 yield_w(c, handle_handshake);
645 log_debug("handhsake failed: %s", tls_error(c->ctx));
650 if ((hash = tls_peer_cert_hash(c->ctx)) == NULL) {
651 log_warnx("client didn't provide certificate");
656 memset(&auth, 0, sizeof(auth));
657 auth.listen_id = c->lid;
658 strlcpy(auth.hash, hash, sizeof(auth.hash));
659 log_debug("sending hash %s", auth.hash);
661 listener_imsg_compose_main(IMSG_AUTH_TLS, c->id,
662 &auth, sizeof(auth));
666 client_read(struct bufferevent *bev, void *d)
668 struct client *client = d;
669 struct evbuffer *src = EVBUFFER_INPUT(bev);
673 if (EVBUFFER_LENGTH(src) < 4)
676 memcpy(&len, EVBUFFER_DATA(src), sizeof(len));
679 if (len > EVBUFFER_LENGTH(src))
682 listener_imsg_compose_client(client, IMSG_BUF, client->id,
683 EVBUFFER_DATA(src), len);
684 evbuffer_drain(src, len);
689 client_write(struct bufferevent *bev, void *d)
692 * here we can do some fancy logic like deciding when to call
694 * (*bev->errorcb)(bev, EVBUFFER_WRITE, bev->cbarg)
696 * to signal the end of the transaction.
703 client_error(struct bufferevent *bev, short err, void *d)
705 struct client *client = d;
706 struct evbuffer *buf;
708 if (err & EVBUFFER_ERROR) {
709 if (errno == EFBIG) {
710 bufferevent_enable(bev, EV_READ);
713 log_debug("buffer event error");
718 if (err & EVBUFFER_EOF) {
723 if (err & (EVBUFFER_READ|EVBUFFER_WRITE)) {
724 bufferevent_disable(bev, EV_READ|EV_WRITE);
727 buf = EVBUFFER_OUTPUT(client->bev);
728 if (EVBUFFER_LENGTH(buf) != 0) {
729 /* finish writing all the data first */
730 bufferevent_enable(client->bev, EV_WRITE);
738 log_warnx("unknown event error, closing client connection");
743 client_tls_readcb(int fd, short event, void *d)
745 struct bufferevent *bufev = d;
746 struct client *client = bufev->cbarg;
747 char buf[IBUF_READ_SIZE];
748 int what = EVBUFFER_READ;
749 int howmuch = IBUF_READ_SIZE;
753 if (event == EV_TIMEOUT) {
754 what |= EVBUFFER_TIMEOUT;
758 if (bufev->wm_read.high != 0)
759 howmuch = MIN(sizeof(buf), bufev->wm_read.high);
761 switch (ret = tls_read(client->ctx, buf, howmuch)) {
762 case TLS_WANT_POLLIN:
763 case TLS_WANT_POLLOUT:
766 what |= EVBUFFER_ERROR;
772 what |= EVBUFFER_EOF;
776 if (evbuffer_add(bufev->input, buf, len) == -1) {
777 what |= EVBUFFER_ERROR;
781 event_add(&bufev->ev_read, NULL);
783 len = EVBUFFER_LENGTH(bufev->input);
784 if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
786 if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
788 * here we could implement some read pressure
793 if (bufev->readcb != NULL)
794 (*bufev->readcb)(bufev, bufev->cbarg);
799 event_add(&bufev->ev_read, NULL);
803 (*bufev->errorcb)(bufev, what, bufev->cbarg);
807 client_tls_writecb(int fd, short event, void *d)
809 struct bufferevent *bufev = d;
810 struct client *client = bufev->cbarg;
813 short what = EVBUFFER_WRITE;
815 if (event == EV_TIMEOUT) {
816 what |= EVBUFFER_TIMEOUT;
820 if (EVBUFFER_LENGTH(bufev->output) != 0) {
821 ret = tls_write(client->ctx,
822 EVBUFFER_DATA(bufev->output),
823 EVBUFFER_LENGTH(bufev->output));
825 case TLS_WANT_POLLIN:
826 case TLS_WANT_POLLOUT:
829 what |= EVBUFFER_ERROR;
833 evbuffer_drain(bufev->output, len);
836 if (EVBUFFER_LENGTH(bufev->output) != 0)
837 event_add(&bufev->ev_write, NULL);
839 if (bufev->writecb != NULL &&
840 EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
841 (*bufev->writecb)(bufev, bufev->cbarg);
845 event_add(&bufev->ev_write, NULL);
849 (*bufev->errorcb)(bufev, what, bufev->cbarg);
853 close_conn(struct client *c)
855 log_debug("closing connection");
857 if (c->iev.ibuf.fd != -1) {
858 listener_imsg_compose_client(c, IMSG_CONN_GONE, 0, NULL, 0);
859 imsg_flush(&c->iev.ibuf);
860 msgbuf_clear(&c->iev.ibuf.w);
861 event_del(&c->iev.ev);
862 close(c->iev.ibuf.fd);
865 handle_close(c->fd, 0, c);
869 handle_close(int fd, short ev, void *d)
871 struct client *c = d;
873 switch (tls_close(c->ctx)) {
874 case TLS_WANT_POLLIN:
875 yield_r(c, handle_close);
877 case TLS_WANT_POLLOUT:
878 yield_w(c, handle_close);
882 event_del(&c->event);