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