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