xref: /openbsd-src/usr.sbin/ypldap/ypldap.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: ypldap.c,v 1.10 2011/08/28 11:53:16 aschrijver Exp $ */
2 
3 /*
4  * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/queue.h>
22 #include <sys/socket.h>
23 #include <sys/tree.h>
24 #include <sys/wait.h>
25 
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 
29 #include <err.h>
30 #include <event.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <pwd.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 
38 #include "ypldap.h"
39 
40 __dead void	 usage(void);
41 int		 check_child(pid_t, const char *);
42 void		 main_sig_handler(int, short, void *);
43 void		 main_shutdown(void);
44 void		 main_dispatch_client(int, short, void *);
45 void		 main_configure_client(struct env *);
46 void		 main_init_timer(int, short, void *);
47 void		 main_start_update(struct env *);
48 void		 main_trash_update(struct env *);
49 void		 main_end_update(struct env *);
50 int		 main_create_user_groups(struct env *);
51 void		 purge_config(struct env *);
52 void		 reconfigure(struct env *);
53 void		 set_nonblock(int);
54 
55 int		 pipe_main2client[2];
56 
57 pid_t		 client_pid = 0;
58 char		*conffile = YPLDAP_CONF_FILE;
59 int		 opts = 0;
60 
61 void
62 usage(void)
63 {
64 	extern const char	*__progname;
65 
66 	fprintf(stderr, "usage: %s [-dnv] [-D macro=value] [-f file]\n",
67 	    __progname);
68 	exit(1);
69 }
70 
71 int
72 check_child(pid_t pid, const char *pname)
73 {
74 	int	status;
75 
76 	if (waitpid(pid, &status, WNOHANG) > 0) {
77 		if (WIFEXITED(status)) {
78 			log_warnx("check_child: lost child %s exited", pname);
79 			return (1);
80 		}
81 		if (WIFSIGNALED(status)) {
82 			log_warnx("check_child: lost child %s terminated; "
83 			    "signal %d", pname, WTERMSIG(status));
84 			return (1);
85 		}
86 	}
87 	return (0);
88 }
89 
90 /* ARGUSED */
91 void
92 main_sig_handler(int sig, short event, void *p)
93 {
94 	int		 die = 0;
95 
96 	switch (sig) {
97 	case SIGTERM:
98 	case SIGINT:
99 		die = 1;
100 		/* FALLTHROUGH */
101 	case SIGCHLD:
102 		if (check_child(client_pid, "ldap client")) {
103 			client_pid = 0;
104 			die = 1;
105 		}
106 		if (die)
107 			main_shutdown();
108 		break;
109 	case SIGHUP:
110 		/* reconfigure */
111 		break;
112 	default:
113 		fatalx("unexpected signal");
114 	}
115 }
116 
117 void
118 main_shutdown(void)
119 {
120 	_exit(0);
121 }
122 
123 void
124 main_start_update(struct env *env)
125 {
126 	env->update_trashed = 0;
127 
128 	log_debug("starting directory update");
129 	env->sc_user_line_len = 0;
130 	env->sc_group_line_len = 0;
131 	if ((env->sc_user_names_t = calloc(1,
132 	    sizeof(*env->sc_user_names_t))) == NULL ||
133 	    (env->sc_group_names_t = calloc(1,
134 	    sizeof(*env->sc_group_names_t))) == NULL)
135 		fatal(NULL);
136 	RB_INIT(env->sc_user_names_t);
137 	RB_INIT(env->sc_group_names_t);
138 }
139 
140 /*
141  * XXX: Currently this function should only be called when updating is
142  * finished. A notification should be send to ldapclient that it should stop
143  * sending new pwd/grp entries before it can be called from different places.
144  */
145 void
146 main_trash_update(struct env *env)
147 {
148 	struct userent	*ue;
149 	struct groupent	*ge;
150 
151 	env->update_trashed = 1;
152 
153 	while ((ue = RB_ROOT(env->sc_user_names_t)) != NULL) {
154 		RB_REMOVE(user_name_tree,
155 		    env->sc_user_names_t, ue);
156 		free(ue->ue_line);
157 		free(ue->ue_netid_line);
158 		free(ue);
159 	}
160 	free(env->sc_user_names_t);
161 	env->sc_user_names_t = NULL;
162 	while ((ge = RB_ROOT(env->sc_group_names_t))
163 	    != NULL) {
164 		RB_REMOVE(group_name_tree,
165 		    env->sc_group_names_t, ge);
166 		free(ge->ge_line);
167 		free(ge);
168 	}
169 	free(env->sc_group_names_t);
170 	env->sc_group_names_t = NULL;
171 }
172 
173 int
174 main_create_user_groups(struct env *env)
175 {
176 	struct userent		*ue;
177 	struct userent		 ukey;
178 	struct groupent		*ge;
179 	gid_t			 pw_gid;
180 	char			*bp, *cp;
181 	char			*p;
182 	const char		*errstr = NULL;
183 	size_t			 len;
184 
185 	RB_FOREACH(ue, user_name_tree, env->sc_user_names_t) {
186 		bp = cp = ue->ue_line;
187 
188 		/* name */
189 		bp += strlen(bp) + 1;
190 
191 		/* password */
192 		bp += strcspn(bp, ":") + 1;
193 
194 		/* uid */
195 		bp += strcspn(bp, ":") + 1;
196 
197 		/* gid */
198 		bp[strcspn(bp, ":")] = '\0';
199 
200 		pw_gid = (gid_t)strtonum(bp, 0, GID_MAX, &errstr);
201 		if (errstr) {
202 			log_warnx("main: failed to parse gid for uid: %d\n", ue->ue_uid);
203 			return (-1);
204 		}
205 
206 		/* bring gid column back to its proper state */
207 		bp[strlen(bp)] = ':';
208 
209 		if ((ue->ue_netid_line = calloc(1, LINE_WIDTH)) == NULL) {
210 			return (-1);
211 		}
212 
213 		if (snprintf(ue->ue_netid_line, LINE_WIDTH-1, "%d:%d", ue->ue_uid, pw_gid) >= LINE_WIDTH) {
214 
215 			return (-1);
216 		}
217 
218 		ue->ue_gid = pw_gid;
219 	}
220 
221 	RB_FOREACH(ge, group_name_tree, env->sc_group_names_t) {
222 		bp = cp = ge->ge_line;
223 
224 		/* name */
225 		bp += strlen(bp) + 1;
226 
227 		/* password */
228 		bp += strcspn(bp, ":") + 1;
229 
230 		/* gid */
231 		bp += strcspn(bp, ":") + 1;
232 
233 		cp = bp;
234 		if (*bp == '\0')
235 			continue;
236 		bp = cp;
237 		for (;;) {
238 			if (!(cp = strsep(&bp, ",")))
239 				break;
240 			ukey.ue_line = cp;
241 			if ((ue = RB_FIND(user_name_tree, env->sc_user_names_t,
242 			    &ukey)) == NULL) {
243 				/* User not found */
244 				log_warnx("main: user: %s is referenced as a "
245 					"group member, but can't be found in the "
246 					"users map.\n", ukey.ue_line);
247 				if (bp != NULL)
248 					*(bp-1) = ',';
249 				return (-1);
250 			}
251 			if (bp != NULL)
252 				*(bp-1) = ',';
253 
254 			/* Make sure the new group doesn't equal to the main gid */
255 			if (ge->ge_gid == ue->ue_gid)
256 				continue;
257 
258 			len = strlen(ue->ue_netid_line);
259 			p = ue->ue_netid_line + len;
260 
261 			if ((snprintf(p, LINE_WIDTH-len-1, ",%d",
262 				ge->ge_gid)) >= (int)(LINE_WIDTH-len)) {
263 				return (-1);
264 			}
265 		}
266 	}
267 
268 	return (0);
269 }
270 
271 void
272 main_end_update(struct env *env)
273 {
274 	struct userent		*ue;
275 	struct groupent		*ge;
276 
277 	if (env->update_trashed)
278 		return;
279 
280 	log_debug("updates are over, cleaning up trees now");
281 
282 	if (main_create_user_groups(env) == -1) {
283 		main_trash_update(env);
284 		return;
285 	}
286 
287 	if (env->sc_user_names == NULL) {
288 		env->sc_user_names = env->sc_user_names_t;
289 		env->sc_user_lines = NULL;
290 		env->sc_user_names_t = NULL;
291 
292 		env->sc_group_names = env->sc_group_names_t;
293 		env->sc_group_lines = NULL;
294 		env->sc_group_names_t = NULL;
295 
296 		flatten_entries(env);
297 		goto make_uids;
298 	}
299 
300 	/*
301 	 * clean previous tree.
302 	 */
303 	while ((ue = RB_ROOT(env->sc_user_names)) != NULL) {
304 		RB_REMOVE(user_name_tree, env->sc_user_names,
305 		    ue);
306 		free(ue);
307 	}
308 	free(env->sc_user_names);
309 	free(env->sc_user_lines);
310 
311 	env->sc_user_names = env->sc_user_names_t;
312 	env->sc_user_lines = NULL;
313 	env->sc_user_names_t = NULL;
314 
315 	while ((ge = RB_ROOT(env->sc_group_names)) != NULL) {
316 		RB_REMOVE(group_name_tree,
317 		    env->sc_group_names, ge);
318 		free(ge);
319 	}
320 	free(env->sc_group_names);
321 	free(env->sc_group_lines);
322 
323 	env->sc_group_names = env->sc_group_names_t;
324 	env->sc_group_lines = NULL;
325 	env->sc_group_names_t = NULL;
326 
327 
328 	flatten_entries(env);
329 
330 	/*
331 	 * trees are flat now. build up uid, gid and netid trees.
332 	 */
333 
334 make_uids:
335 	RB_INIT(&env->sc_user_uids);
336 	RB_INIT(&env->sc_group_gids);
337 	RB_FOREACH(ue, user_name_tree, env->sc_user_names)
338 		RB_INSERT(user_uid_tree,
339 		    &env->sc_user_uids, ue);
340 	RB_FOREACH(ge, group_name_tree, env->sc_group_names)
341 		RB_INSERT(group_gid_tree,
342 		    &env->sc_group_gids, ge);
343 
344 }
345 
346 void
347 main_dispatch_client(int fd, short event, void *p)
348 {
349 	int		 n;
350 	int		 shut = 0;
351 	struct env	*env = p;
352 	struct imsgev	*iev = env->sc_iev;
353 	struct imsgbuf	*ibuf = &iev->ibuf;
354 	struct idm_req	 ir;
355 	struct imsg	 imsg;
356 
357 	switch (event) {
358 	case EV_READ:
359 		if ((n = imsg_read(ibuf)) == -1)
360 			fatal("imsg_read error");
361 		if (n == 0)
362 			shut = 1;
363 		break;
364 	case EV_WRITE:
365 		if (msgbuf_write(&ibuf->w) == -1)
366 			fatal("msgbuf_write");
367 		imsg_event_add(iev);
368 		return;
369 	default:
370 		fatalx("unknown event");
371 	}
372 
373 	for (;;) {
374 		if ((n = imsg_get(ibuf, &imsg)) == -1)
375 			fatal("main_dispatch_client: imsg_get error");
376 		if (n == 0)
377 			break;
378 
379 		switch (imsg.hdr.type) {
380 		case IMSG_START_UPDATE:
381 			main_start_update(env);
382 			break;
383 		case IMSG_PW_ENTRY: {
384 			struct userent	*ue;
385 			size_t		 len;
386 
387 			if (env->update_trashed)
388 				break;
389 
390 			(void)memcpy(&ir, imsg.data, sizeof(ir));
391 			if ((ue = calloc(1, sizeof(*ue))) == NULL ||
392 			    (ue->ue_line = strdup(ir.ir_line)) == NULL) {
393 				/*
394 				 * should cancel tree update instead.
395 				 */
396 				fatal("out of memory");
397 			}
398 			ue->ue_uid = ir.ir_key.ik_uid;
399 			len = strlen(ue->ue_line) + 1;
400 			ue->ue_line[strcspn(ue->ue_line, ":")] = '\0';
401 			if (RB_INSERT(user_name_tree, env->sc_user_names_t,
402 			    ue) != NULL) { /* dup */
403 				free(ue->ue_line);
404 				free(ue);
405 			} else
406 				env->sc_user_line_len += len;
407 			break;
408 		}
409 		case IMSG_GRP_ENTRY: {
410 			struct groupent	*ge;
411 			size_t		 len;
412 
413 			if (env->update_trashed)
414 				break;
415 
416 			(void)memcpy(&ir, imsg.data, sizeof(ir));
417 			if ((ge = calloc(1, sizeof(*ge))) == NULL ||
418 			    (ge->ge_line = strdup(ir.ir_line)) == NULL) {
419 				/*
420 				 * should cancel tree update instead.
421 				 */
422 				fatal("out of memory");
423 			}
424 			ge->ge_gid = ir.ir_key.ik_gid;
425 			len = strlen(ge->ge_line) + 1;
426 			ge->ge_line[strcspn(ge->ge_line, ":")] = '\0';
427 			if (RB_INSERT(group_name_tree, env->sc_group_names_t,
428 			    ge) != NULL) { /* dup */
429 				free(ge->ge_line);
430 				free(ge);
431 			} else
432 				env->sc_group_line_len += len;
433 			break;
434 		}
435 		case IMSG_TRASH_UPDATE:
436 			main_trash_update(env);
437 			break;
438 		case IMSG_END_UPDATE: {
439 			main_end_update(env);
440 			break;
441 		}
442 		default:
443 			log_debug("main_dispatch_client: unexpected imsg %d",
444 			   imsg.hdr.type);
445 			break;
446 		}
447 		imsg_free(&imsg);
448 	}
449 	if (!shut)
450 		imsg_event_add(iev);
451 	else {
452 		log_debug("king bula sez: ran into dead pipe");
453 		event_del(&iev->ev);
454 		event_loopexit(NULL);
455 	}
456 }
457 
458 void
459 main_configure_client(struct env *env)
460 {
461 	struct idm	*idm;
462 	struct imsgev	*iev = env->sc_iev;
463 
464 	imsg_compose_event(iev, IMSG_CONF_START, 0, 0, -1, env, sizeof(*env));
465 	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
466 		imsg_compose_event(iev, IMSG_CONF_IDM, 0, 0, -1,
467 		    idm, sizeof(*idm));
468 	}
469 	imsg_compose_event(iev, IMSG_CONF_END, 0, 0, -1, NULL, 0);
470 }
471 
472 void
473 main_init_timer(int fd, short event, void *p)
474 {
475 	struct env	*env = p;
476 
477 	main_configure_client(env);
478 }
479 
480 void
481 purge_config(struct env *env)
482 {
483 	struct idm	*idm;
484 
485 	while ((idm = TAILQ_FIRST(&env->sc_idms)) != NULL) {
486 		TAILQ_REMOVE(&env->sc_idms, idm, idm_entry);
487 		free(idm);
488 	}
489 }
490 
491 int
492 main(int argc, char *argv[])
493 {
494 	int		 c;
495 	int		 debug;
496 	struct passwd	*pw;
497 	struct env	 env;
498 	struct event	 ev_sigint;
499 	struct event	 ev_sigterm;
500 	struct event	 ev_sigchld;
501 	struct event	 ev_sighup;
502 	struct event	 ev_timer;
503 	struct timeval	 tv;
504 
505 	debug = 0;
506 	ypldap_process = PROC_MAIN;
507 
508 	log_init(1);
509 
510 	while ((c = getopt(argc, argv, "dD:nf:v")) != -1) {
511 		switch (c) {
512 		case 'd':
513 			debug = 2;
514 			break;
515 		case 'D':
516 			if (cmdline_symset(optarg) < 0)
517 				log_warnx("could not parse macro definition %s",
518 				    optarg);
519 			break;
520 		case 'n':
521 			debug = 2;
522 			opts |= YPLDAP_OPT_NOACTION;
523 			break;
524 		case 'f':
525 			conffile = optarg;
526 			break;
527 		case 'v':
528 			opts |= YPLDAP_OPT_VERBOSE;
529 			break;
530 		default:
531 			usage();
532 		}
533 	}
534 
535 	argc -= optind;
536 	argv += optind;
537 
538 	if (argc)
539 		usage();
540 
541 	RB_INIT(&env.sc_user_uids);
542 	RB_INIT(&env.sc_group_gids);
543 
544 	if (parse_config(&env, conffile, opts))
545 		exit(1);
546 	if (opts & YPLDAP_OPT_NOACTION) {
547 		fprintf(stderr, "configuration OK\n");
548 		exit(0);
549 	}
550 
551 	if (geteuid())
552 		errx(1, "need root privileges");
553 
554 	log_init(debug);
555 
556 	if (!debug) {
557 		if (daemon(1, 0) == -1)
558 			err(1, "failed to daemonize");
559 	}
560 
561 	log_info("startup%s", (debug > 1)?" [debug mode]":"");
562 
563 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC,
564 	    pipe_main2client) == -1)
565 		fatal("socketpair");
566 
567 	set_nonblock(pipe_main2client[0]);
568 	set_nonblock(pipe_main2client[1]);
569 
570 	client_pid = ldapclient(pipe_main2client);
571 
572 	setproctitle("parent");
573 	event_init();
574 
575 	signal_set(&ev_sigint, SIGINT, main_sig_handler, &env);
576 	signal_set(&ev_sigterm, SIGTERM, main_sig_handler, &env);
577 	signal_set(&ev_sighup, SIGHUP, main_sig_handler, &env);
578 	signal_set(&ev_sigchld, SIGCHLD, main_sig_handler, &env);
579 	signal_add(&ev_sigint, NULL);
580 	signal_add(&ev_sigterm, NULL);
581 	signal_add(&ev_sighup, NULL);
582 	signal_add(&ev_sigchld, NULL);
583 
584 	close(pipe_main2client[1]);
585 	if ((env.sc_iev = calloc(1, sizeof(*env.sc_iev))) == NULL)
586 		fatal(NULL);
587 	imsg_init(&env.sc_iev->ibuf, pipe_main2client[0]);
588 	env.sc_iev->handler = main_dispatch_client;
589 
590 	env.sc_iev->events = EV_READ;
591 	env.sc_iev->data = &env;
592 	event_set(&env.sc_iev->ev, env.sc_iev->ibuf.fd, env.sc_iev->events,
593 	     env.sc_iev->handler, &env);
594 	event_add(&env.sc_iev->ev, NULL);
595 
596 	yp_init(&env);
597 
598 	if ((pw = getpwnam(YPLDAP_USER)) == NULL)
599 		fatal("getpwnam");
600 
601 #ifndef DEBUG
602 	if (setgroups(1, &pw->pw_gid) ||
603 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
604 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
605 		fatal("cannot drop privileges");
606 #else
607 #warning disabling privilege revocation in debug mode
608 #endif
609 
610 	bzero(&tv, sizeof(tv));
611 	evtimer_set(&ev_timer, main_init_timer, &env);
612 	evtimer_add(&ev_timer, &tv);
613 
614 	yp_enable_events();
615 	event_dispatch();
616 	main_shutdown();
617 
618 	return (0);
619 }
620 
621 void
622 imsg_event_add(struct imsgev *iev)
623 {
624 	if (iev->handler == NULL) {
625 		imsg_flush(&iev->ibuf);
626 		return;
627 	}
628 
629 	iev->events = EV_READ;
630 	if (iev->ibuf.w.queued)
631 		iev->events |= EV_WRITE;
632 
633 	event_del(&iev->ev);
634 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
635 	event_add(&iev->ev, NULL);
636 }
637 
638 int
639 imsg_compose_event(struct imsgev *iev, u_int16_t type, u_int32_t peerid,
640     pid_t pid, int fd, void *data, u_int16_t datalen)
641 {
642 	int	ret;
643 
644 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
645 	    pid, fd, data, datalen)) != -1)
646 		imsg_event_add(iev);
647 	return (ret);
648 }
649 
650 void
651 set_nonblock(int fd)
652 {
653 	int	flags;
654 
655 	if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
656 		fatal("fcntl F_GETFL");
657 
658 	flags |= O_NONBLOCK;
659 
660 	if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
661 		fatal("fcntl F_SETFL");
662 }
663