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