1/* $OpenBSD: ldapclient.c,v 1.31 2014/11/16 23:24:44 tedu Exp $ */
2
3/*
4 * Copyright (c) 2008 Alexander Schrijver <aschrijver@openbsd.org>
5 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@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/types.h>
21#include <sys/param.h>
22#include <sys/queue.h>
23#include <sys/socket.h>
24#include <sys/tree.h>
25
26#include <netinet/in.h>
27#include <arpa/inet.h>
28
29#include <netdb.h>
30#include <errno.h>
31#include <err.h>
32#include <event.h>
33#include <fcntl.h>
34#include <unistd.h>
35#include <pwd.h>
36#include <signal.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40
41#include "aldap.h"
42#include "ypldap.h"
43
44void    client_sig_handler(int, short, void *);
45void	client_dispatch_dns(int, short, void *);
46void    client_dispatch_parent(int, short, void *);
47void    client_shutdown(void);
48void    client_connect(int, short, void *);
49void    client_configure(struct env *);
50void    client_periodic_update(int, short, void *);
51int	client_build_req(struct idm *, struct idm_req *, struct aldap_message *,
52	    int, int);
53int	client_search_idm(struct env *, struct idm *, struct aldap *,
54	    char **, char *, int, int, enum imsg_type);
55int	client_try_idm(struct env *, struct idm *);
56int	client_addr_init(struct idm *);
57int	client_addr_free(struct idm *);
58
59struct aldap	*client_aldap_open(struct ypldap_addr_list *);
60
61/*
62 * dummy wrapper to provide aldap_init with its fd's.
63 */
64struct aldap *
65client_aldap_open(struct ypldap_addr_list *addr)
66{
67	int			 fd = -1;
68	struct ypldap_addr	 *p;
69
70	TAILQ_FOREACH(p, addr, next) {
71		char			 hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
72		struct sockaddr		*sa = (struct sockaddr *)&p->ss;
73
74		if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), sbuf,
75			sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV))
76				errx(1, "could not get numeric hostname");
77
78		if ((fd = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
79			return NULL;
80
81		if (connect(fd, sa, sa->sa_len) == 0)
82			break;
83
84		warn("connect to %s port %s (%s) failed", hbuf, sbuf, "tcp");
85		close(fd);
86	}
87
88	if (fd == -1)
89		return NULL;
90
91	return aldap_init(fd);
92}
93
94int
95client_addr_init(struct idm *idm)
96{
97        struct sockaddr_in      *sa_in;
98        struct sockaddr_in6     *sa_in6;
99        struct ypldap_addr         *h;
100
101	TAILQ_FOREACH(h, &idm->idm_addr, next) {
102                switch (h->ss.ss_family) {
103                case AF_INET:
104                        sa_in = (struct sockaddr_in *)&h->ss;
105                        if (ntohs(sa_in->sin_port) == 0)
106                                sa_in->sin_port = htons(LDAP_PORT);
107                        idm->idm_state = STATE_DNS_DONE;
108                        break;
109                case AF_INET6:
110                        sa_in6 = (struct sockaddr_in6 *)&h->ss;
111                        if (ntohs(sa_in6->sin6_port) == 0)
112                                sa_in6->sin6_port = htons(LDAP_PORT);
113                        idm->idm_state = STATE_DNS_DONE;
114                        break;
115                default:
116                        fatalx("king bula sez: wrong AF in client_addr_init");
117                        /* not reached */
118                }
119        }
120
121        return (0);
122}
123
124int
125client_addr_free(struct idm *idm)
126{
127        struct ypldap_addr         *h;
128
129	while (!TAILQ_EMPTY(&idm->idm_addr)) {
130		h = TAILQ_FIRST(&idm->idm_addr);
131		TAILQ_REMOVE(&idm->idm_addr, h, next);
132		free(h);
133	}
134
135	return (0);
136}
137
138void
139client_sig_handler(int sig, short event, void *p)
140{
141	switch (sig) {
142	case SIGINT:
143	case SIGTERM:
144		client_shutdown();
145		break;
146	default:
147		fatalx("unexpected signal");
148	}
149}
150
151void
152client_dispatch_dns(int fd, short events, void *p)
153{
154	struct imsg		 imsg;
155	u_int16_t		 dlen;
156	u_char			*data;
157	struct ypldap_addr	*h;
158	int			 n, wait_cnt = 0;
159	struct idm		*idm;
160	int			 shut = 0;
161
162	struct env		*env = p;
163	struct imsgev		*iev = env->sc_iev_dns;
164	struct imsgbuf		*ibuf = &iev->ibuf;
165
166	if ((events & (EV_READ | EV_WRITE)) == 0)
167		fatalx("unknown event");
168
169	if (events & EV_READ) {
170		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
171			fatal("imsg_read error");
172		if (n == 0)
173			shut = 1;
174	}
175	if (events & EV_WRITE) {
176		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
177			fatal("msgbuf_write");
178		if (n == 0)
179			shut = 1;
180		goto done;
181	}
182
183	for (;;) {
184		if ((n = imsg_get(ibuf, &imsg)) == -1)
185			fatal("client_dispatch_dns: imsg_get error");
186		if (n == 0)
187			break;
188
189		switch (imsg.hdr.type) {
190		case IMSG_HOST_DNS:
191			TAILQ_FOREACH(idm, &env->sc_idms, idm_entry)
192				if (idm->idm_id == imsg.hdr.peerid)
193					break;
194			if (idm == NULL) {
195				log_warnx("IMSG_HOST_DNS with invalid peerID");
196				break;
197			}
198			if (!TAILQ_EMPTY(&idm->idm_addr)) {
199				log_warnx("IMSG_HOST_DNS but addrs set!");
200				break;
201			}
202
203			dlen = imsg.hdr.len - IMSG_HEADER_SIZE;
204			if (dlen == 0) {	/* no data -> temp error */
205				idm->idm_state = STATE_DNS_TEMPFAIL;
206				break;
207			}
208
209			data = (u_char *)imsg.data;
210			while (dlen >= sizeof(struct sockaddr_storage)) {
211				if ((h = calloc(1, sizeof(*h))) == NULL)
212					fatal(NULL);
213				memcpy(&h->ss, data, sizeof(h->ss));
214				TAILQ_INSERT_HEAD(&idm->idm_addr, h, next);
215
216				data += sizeof(h->ss);
217				dlen -= sizeof(h->ss);
218			}
219			if (dlen != 0)
220				fatalx("IMSG_HOST_DNS: dlen != 0");
221
222			client_addr_init(idm);
223
224			break;
225		default:
226			break;
227		}
228		imsg_free(&imsg);
229	}
230
231	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
232		if (client_try_idm(env, idm) == -1)
233			idm->idm_state = STATE_LDAP_FAIL;
234
235		if (idm->idm_state < STATE_LDAP_DONE)
236			wait_cnt++;
237	}
238	if (wait_cnt == 0)
239		imsg_compose_event(env->sc_iev, IMSG_END_UPDATE, 0, 0, -1,
240		    NULL, 0);
241
242done:
243	if (!shut)
244		imsg_event_add(iev);
245	else {
246		/* this pipe is dead, so remove the event handler */
247		event_del(&iev->ev);
248		event_loopexit(NULL);
249	}
250}
251
252void
253client_dispatch_parent(int fd, short events, void *p)
254{
255	int			 n;
256	int			 shut = 0;
257	struct imsg		 imsg;
258	struct env		*env = p;
259	struct imsgev		*iev = env->sc_iev;
260	struct imsgbuf		*ibuf = &iev->ibuf;
261
262	if ((events & (EV_READ | EV_WRITE)) == 0)
263		fatalx("unknown event");
264
265	if (events & EV_READ) {
266		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
267			fatal("imsg_read error");
268		if (n == 0)
269			shut = 1;
270	}
271	if (events & EV_WRITE) {
272		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
273			fatal("msgbuf_write");
274		if (n == 0)
275			shut = 1;
276		goto done;
277	}
278
279	for (;;) {
280		if ((n = imsg_get(ibuf, &imsg)) == -1)
281			fatal("client_dispatch_parent: imsg_get error");
282		if (n == 0)
283			break;
284
285		switch (imsg.hdr.type) {
286		case IMSG_CONF_START: {
287			struct env	params;
288
289			if (env->sc_flags & F_CONFIGURING) {
290				log_warnx("configuration already in progress");
291				break;
292			}
293			memcpy(&params, imsg.data, sizeof(params));
294			log_debug("configuration starting");
295			env->sc_flags |= F_CONFIGURING;
296			purge_config(env);
297			memcpy(&env->sc_conf_tv, &params.sc_conf_tv,
298			    sizeof(env->sc_conf_tv));
299			env->sc_flags |= params.sc_flags;
300			break;
301		}
302		case IMSG_CONF_IDM: {
303			struct idm	*idm;
304
305			if (!(env->sc_flags & F_CONFIGURING))
306				break;
307			if ((idm = calloc(1, sizeof(*idm))) == NULL)
308				fatal(NULL);
309			memcpy(idm, imsg.data, sizeof(*idm));
310			idm->idm_env = env;
311			TAILQ_INSERT_TAIL(&env->sc_idms, idm, idm_entry);
312			break;
313		}
314		case IMSG_CONF_END:
315			env->sc_flags &= ~F_CONFIGURING;
316			log_debug("applying configuration");
317			client_configure(env);
318			break;
319		default:
320			log_debug("client_dispatch_parent: unexpect imsg %d",
321			    imsg.hdr.type);
322
323			break;
324		}
325		imsg_free(&imsg);
326	}
327
328done:
329	if (!shut)
330		imsg_event_add(iev);
331	else {
332		/* this pipe is dead, so remove the event handler */
333		event_del(&iev->ev);
334		event_loopexit(NULL);
335	}
336}
337
338void
339client_shutdown(void)
340{
341	log_info("ldap client exiting");
342	_exit(0);
343}
344
345pid_t
346ldapclient(int pipe_main2client[2])
347{
348	pid_t            pid;
349	int              pipe_dns[2];
350	struct passwd	*pw;
351	struct event	 ev_sigint;
352	struct event	 ev_sigterm;
353	struct env	 env;
354
355	switch (pid = fork()) {
356	case -1:
357		fatal("cannot fork");
358		break;
359	case 0:
360		break;
361	default:
362		return (pid);
363	}
364
365	memset(&env, 0, sizeof(env));
366	TAILQ_INIT(&env.sc_idms);
367
368	if ((pw = getpwnam(YPLDAP_USER)) == NULL)
369		fatal("getpwnam");
370
371	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_dns) == -1)
372		fatal("socketpair");
373	ypldap_dns(pipe_dns, pw);
374	close(pipe_dns[1]);
375
376#ifndef DEBUG
377	if (chroot(pw->pw_dir) == -1)
378		fatal("chroot");
379	if (chdir("/") == -1)
380		fatal("chdir");
381#else
382#warning disabling chrooting in DEBUG mode
383#endif
384	setproctitle("ldap client");
385	ypldap_process = PROC_CLIENT;
386
387#ifndef DEBUG
388	if (setgroups(1, &pw->pw_gid) ||
389	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
390	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
391		fatal("cannot drop privileges");
392#else
393#warning disabling privilege revocation in DEBUG mode
394#endif
395
396	event_init();
397	signal(SIGPIPE, SIG_IGN);
398	signal_set(&ev_sigint, SIGINT, client_sig_handler, NULL);
399	signal_set(&ev_sigterm, SIGTERM, client_sig_handler, NULL);
400	signal_add(&ev_sigint, NULL);
401	signal_add(&ev_sigterm, NULL);
402
403	close(pipe_main2client[0]);
404	if ((env.sc_iev = calloc(1, sizeof(*env.sc_iev))) == NULL)
405		fatal(NULL);
406	if ((env.sc_iev_dns = calloc(1, sizeof(*env.sc_iev_dns))) == NULL)
407		fatal(NULL);
408
409	env.sc_iev->events = EV_READ;
410	env.sc_iev->data = &env;
411	imsg_init(&env.sc_iev->ibuf, pipe_main2client[1]);
412	env.sc_iev->handler = client_dispatch_parent;
413	event_set(&env.sc_iev->ev, env.sc_iev->ibuf.fd, env.sc_iev->events,
414	    env.sc_iev->handler, &env);
415	event_add(&env.sc_iev->ev, NULL);
416
417	env.sc_iev_dns->events = EV_READ;
418	env.sc_iev_dns->data = &env;
419	imsg_init(&env.sc_iev_dns->ibuf, pipe_dns[0]);
420	env.sc_iev_dns->handler = client_dispatch_dns;
421	event_set(&env.sc_iev_dns->ev, env.sc_iev_dns->ibuf.fd,
422	    env.sc_iev_dns->events, env.sc_iev_dns->handler, &env);
423	event_add(&env.sc_iev_dns->ev, NULL);
424
425	event_dispatch();
426	client_shutdown();
427
428	return (0);
429
430}
431
432int
433client_build_req(struct idm *idm, struct idm_req *ir, struct aldap_message *m,
434    int min_attr, int max_attr)
435{
436	char	**ldap_attrs;
437	int	 i, k;
438
439	memset(ir, 0, sizeof(*ir));
440	for (i = min_attr; i < max_attr; i++) {
441		if (idm->idm_flags & F_FIXED_ATTR(i)) {
442			if (strlcat(ir->ir_line, idm->idm_attrs[i],
443			    sizeof(ir->ir_line)) >= sizeof(ir->ir_line))
444				/*
445				 * entry yields a line > 1024, trash it.
446				 */
447				return (-1);
448
449			if (i == ATTR_UID) {
450				ir->ir_key.ik_uid = strtonum(
451				    idm->idm_attrs[i], 0,
452				    UID_MAX, NULL);
453			} else if (i == ATTR_GR_GID) {
454				ir->ir_key.ik_gid = strtonum(
455				    idm->idm_attrs[i], 0,
456				    GID_MAX, NULL);
457			}
458		} else if (idm->idm_list & F_LIST(i)) {
459			aldap_match_attr(m, idm->idm_attrs[i], &ldap_attrs);
460			for (k = 0; k >= 0 && ldap_attrs && ldap_attrs[k] != NULL; k++) {
461				/* XXX: Fail when attributes have illegal characters e.g. ',' */
462				if (strlcat(ir->ir_line, ldap_attrs[k],
463				    sizeof(ir->ir_line)) >= sizeof(ir->ir_line))
464					continue;
465				if (ldap_attrs[k+1] != NULL)
466					if (strlcat(ir->ir_line, ",",
467						    sizeof(ir->ir_line))
468					    >= sizeof(ir->ir_line)) {
469						aldap_free_attr(ldap_attrs);
470						return (-1);
471					}
472			}
473			aldap_free_attr(ldap_attrs);
474		} else {
475			if (aldap_match_attr(m, idm->idm_attrs[i], &ldap_attrs) == -1)
476				return (-1);
477			if (strlcat(ir->ir_line, ldap_attrs[0],
478			    sizeof(ir->ir_line)) >= sizeof(ir->ir_line)) {
479				aldap_free_attr(ldap_attrs);
480				return (-1);
481			}
482			if (i == ATTR_UID) {
483				ir->ir_key.ik_uid = strtonum(
484				    ldap_attrs[0], 0, UID_MAX, NULL);
485			} else if (i == ATTR_GR_GID) {
486				ir->ir_key.ik_uid = strtonum(
487				    ldap_attrs[0], 0, GID_MAX, NULL);
488			}
489			aldap_free_attr(ldap_attrs);
490		}
491
492		if (i + 1 != max_attr)
493			if (strlcat(ir->ir_line, ":",
494			    sizeof(ir->ir_line)) >= sizeof(ir->ir_line))
495				return (-1);
496	}
497
498	return (0);
499}
500
501int
502client_search_idm(struct env *env, struct idm *idm, struct aldap *al,
503    char **attrs, char *filter, int min_attr, int max_attr,
504    enum imsg_type type)
505{
506	struct idm_req		 ir;
507	struct aldap_message	*m;
508	struct aldap_page_control *pg = NULL;
509	const char		*errstr;
510	char			*dn;
511
512	dn = idm->idm_basedn;
513	if (type == IMSG_GRP_ENTRY && idm->idm_groupdn[0] != '\0')
514		dn = idm->idm_groupdn;
515
516	do {
517		if (aldap_search(al, dn, LDAP_SCOPE_SUBTREE,
518		    filter, attrs, 0, 0, 0, pg) == -1) {
519			aldap_get_errno(al, &errstr);
520			log_debug("%s", errstr);
521			return (-1);
522		}
523
524		if (pg != NULL) {
525			aldap_freepage(pg);
526			pg = NULL;
527		}
528
529		while ((m = aldap_parse(al)) != NULL) {
530			if (al->msgid != m->msgid) {
531				goto fail;
532			}
533
534			if (m->message_type == LDAP_RES_SEARCH_RESULT) {
535				if (m->page != NULL && m->page->cookie_len != 0)
536					pg = m->page;
537				else
538					pg = NULL;
539
540				aldap_freemsg(m);
541				break;
542			}
543
544			if (m->message_type != LDAP_RES_SEARCH_ENTRY) {
545				goto fail;
546			}
547
548			if (client_build_req(idm, &ir, m, min_attr, max_attr) == 0)
549				imsg_compose_event(env->sc_iev, type, 0, 0, -1,
550				    &ir, sizeof(ir));
551
552			aldap_freemsg(m);
553		}
554	} while (pg != NULL);
555
556	return (0);
557
558fail:
559	aldap_freemsg(m);
560	if (pg != NULL) {
561		aldap_freepage(pg);
562	}
563
564	return (-1);
565}
566
567int
568client_try_idm(struct env *env, struct idm *idm)
569{
570	const char		*where;
571	char			*attrs[ATTR_MAX+1];
572	int			 i, j;
573	struct aldap_message	*m;
574	struct aldap		*al;
575
576	where = "connect";
577	if ((al = client_aldap_open(&idm->idm_addr)) == NULL)
578		return (-1);
579
580	if (idm->idm_flags & F_NEEDAUTH) {
581		where = "binding";
582		if (aldap_bind(al, idm->idm_binddn, idm->idm_bindcred) == -1)
583			goto bad;
584
585		where = "parsing";
586		if ((m = aldap_parse(al)) == NULL)
587			goto bad;
588		where = "verifying msgid";
589		if (al->msgid != m->msgid) {
590			aldap_freemsg(m);
591			goto bad;
592		}
593		aldap_freemsg(m);
594	}
595
596	memset(attrs, 0, sizeof(attrs));
597	for (i = 0, j = 0; i < ATTR_MAX; i++) {
598		if (idm->idm_flags & F_FIXED_ATTR(i))
599			continue;
600		attrs[j++] = idm->idm_attrs[i];
601	}
602	attrs[j] = NULL;
603
604	/*
605	 * build password line.
606	 */
607	where = "search";
608	log_debug("searching password entries");
609	if (client_search_idm(env, idm, al, attrs,
610	    idm->idm_filters[FILTER_USER], 0, ATTR_MAX, IMSG_PW_ENTRY) == -1)
611		goto bad;
612
613	memset(attrs, 0, sizeof(attrs));
614	for (i = ATTR_GR_MIN, j = 0; i < ATTR_GR_MAX; i++) {
615		if (idm->idm_flags & F_FIXED_ATTR(i))
616			continue;
617		attrs[j++] = idm->idm_attrs[i];
618	}
619	attrs[j] = NULL;
620
621	/*
622	 * build group line.
623	 */
624	where = "search";
625	log_debug("searching group entries");
626	if (client_search_idm(env, idm, al, attrs,
627	    idm->idm_filters[FILTER_GROUP], ATTR_GR_MIN, ATTR_GR_MAX,
628	    IMSG_GRP_ENTRY) == -1)
629		goto bad;
630
631	aldap_close(al);
632
633	idm->idm_state = STATE_LDAP_DONE;
634
635	return (0);
636bad:
637	aldap_close(al);
638	log_debug("directory %s errored out in %s", idm->idm_name, where);
639	return (-1);
640}
641
642void
643client_periodic_update(int fd, short event, void *p)
644{
645	struct env	*env = p;
646
647	struct idm	*idm;
648	int		 fail_cnt = 0;
649
650	/* If LDAP isn't finished, notify the master process to trash the
651	 * update. */
652	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
653		if (idm->idm_state < STATE_LDAP_DONE)
654			fail_cnt++;
655
656		idm->idm_state = STATE_NONE;
657
658		client_addr_free(idm);
659	}
660	if (fail_cnt > 0) {
661		log_debug("trash the update");
662		imsg_compose_event(env->sc_iev, IMSG_TRASH_UPDATE, 0, 0, -1,
663		    NULL, 0);
664	}
665
666	client_configure(env);
667}
668
669void
670client_configure(struct env *env)
671{
672	struct timeval	 tv;
673	struct idm	*idm;
674        u_int16_t        dlen;
675
676	log_debug("connecting to directories");
677
678	imsg_compose_event(env->sc_iev, IMSG_START_UPDATE, 0, 0, -1, NULL, 0);
679
680	/* Start the DNS lookups */
681	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
682		dlen = strlen(idm->idm_name) + 1;
683		imsg_compose_event(env->sc_iev_dns, IMSG_HOST_DNS, idm->idm_id,
684		    0, -1, idm->idm_name, dlen);
685	}
686
687	tv.tv_sec = env->sc_conf_tv.tv_sec;
688	tv.tv_usec = env->sc_conf_tv.tv_usec;
689	evtimer_set(&env->sc_conf_ev, client_periodic_update, env);
690	evtimer_add(&env->sc_conf_ev, &tv);
691}
692