xref: /openbsd-src/usr.sbin/ypldap/ypldap.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: ypldap.c,v 1.12 2012/03/15 01:44:22 jmatthew 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 				continue;
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->ue_netid_line);
307 		free(ue);
308 	}
309 	free(env->sc_user_names);
310 	free(env->sc_user_lines);
311 
312 	env->sc_user_names = env->sc_user_names_t;
313 	env->sc_user_lines = NULL;
314 	env->sc_user_names_t = NULL;
315 
316 	while ((ge = RB_ROOT(env->sc_group_names)) != NULL) {
317 		RB_REMOVE(group_name_tree,
318 		    env->sc_group_names, ge);
319 		free(ge);
320 	}
321 	free(env->sc_group_names);
322 	free(env->sc_group_lines);
323 
324 	env->sc_group_names = env->sc_group_names_t;
325 	env->sc_group_lines = NULL;
326 	env->sc_group_names_t = NULL;
327 
328 
329 	flatten_entries(env);
330 
331 	/*
332 	 * trees are flat now. build up uid, gid and netid trees.
333 	 */
334 
335 make_uids:
336 	RB_INIT(&env->sc_user_uids);
337 	RB_INIT(&env->sc_group_gids);
338 	RB_FOREACH(ue, user_name_tree, env->sc_user_names)
339 		RB_INSERT(user_uid_tree,
340 		    &env->sc_user_uids, ue);
341 	RB_FOREACH(ge, group_name_tree, env->sc_group_names)
342 		RB_INSERT(group_gid_tree,
343 		    &env->sc_group_gids, ge);
344 
345 }
346 
347 void
348 main_dispatch_client(int fd, short event, void *p)
349 {
350 	int		 n;
351 	int		 shut = 0;
352 	struct env	*env = p;
353 	struct imsgev	*iev = env->sc_iev;
354 	struct imsgbuf	*ibuf = &iev->ibuf;
355 	struct idm_req	 ir;
356 	struct imsg	 imsg;
357 
358 	switch (event) {
359 	case EV_READ:
360 		if ((n = imsg_read(ibuf)) == -1)
361 			fatal("imsg_read error");
362 		if (n == 0)
363 			shut = 1;
364 		break;
365 	case EV_WRITE:
366 		if (msgbuf_write(&ibuf->w) == -1)
367 			fatal("msgbuf_write");
368 		imsg_event_add(iev);
369 		return;
370 	default:
371 		fatalx("unknown event");
372 	}
373 
374 	for (;;) {
375 		if ((n = imsg_get(ibuf, &imsg)) == -1)
376 			fatal("main_dispatch_client: imsg_get error");
377 		if (n == 0)
378 			break;
379 
380 		switch (imsg.hdr.type) {
381 		case IMSG_START_UPDATE:
382 			main_start_update(env);
383 			break;
384 		case IMSG_PW_ENTRY: {
385 			struct userent	*ue;
386 			size_t		 len;
387 
388 			if (env->update_trashed)
389 				break;
390 
391 			(void)memcpy(&ir, imsg.data, sizeof(ir));
392 			if ((ue = calloc(1, sizeof(*ue))) == NULL ||
393 			    (ue->ue_line = strdup(ir.ir_line)) == NULL) {
394 				/*
395 				 * should cancel tree update instead.
396 				 */
397 				fatal("out of memory");
398 			}
399 			ue->ue_uid = ir.ir_key.ik_uid;
400 			len = strlen(ue->ue_line) + 1;
401 			ue->ue_line[strcspn(ue->ue_line, ":")] = '\0';
402 			if (RB_INSERT(user_name_tree, env->sc_user_names_t,
403 			    ue) != NULL) { /* dup */
404 				free(ue->ue_line);
405 				free(ue);
406 			} else
407 				env->sc_user_line_len += len;
408 			break;
409 		}
410 		case IMSG_GRP_ENTRY: {
411 			struct groupent	*ge;
412 			size_t		 len;
413 
414 			if (env->update_trashed)
415 				break;
416 
417 			(void)memcpy(&ir, imsg.data, sizeof(ir));
418 			if ((ge = calloc(1, sizeof(*ge))) == NULL ||
419 			    (ge->ge_line = strdup(ir.ir_line)) == NULL) {
420 				/*
421 				 * should cancel tree update instead.
422 				 */
423 				fatal("out of memory");
424 			}
425 			ge->ge_gid = ir.ir_key.ik_gid;
426 			len = strlen(ge->ge_line) + 1;
427 			ge->ge_line[strcspn(ge->ge_line, ":")] = '\0';
428 			if (RB_INSERT(group_name_tree, env->sc_group_names_t,
429 			    ge) != NULL) { /* dup */
430 				free(ge->ge_line);
431 				free(ge);
432 			} else
433 				env->sc_group_line_len += len;
434 			break;
435 		}
436 		case IMSG_TRASH_UPDATE:
437 			main_trash_update(env);
438 			break;
439 		case IMSG_END_UPDATE: {
440 			main_end_update(env);
441 			break;
442 		}
443 		default:
444 			log_debug("main_dispatch_client: unexpected imsg %d",
445 			   imsg.hdr.type);
446 			break;
447 		}
448 		imsg_free(&imsg);
449 	}
450 	if (!shut)
451 		imsg_event_add(iev);
452 	else {
453 		log_debug("king bula sez: ran into dead pipe");
454 		event_del(&iev->ev);
455 		event_loopexit(NULL);
456 	}
457 }
458 
459 void
460 main_configure_client(struct env *env)
461 {
462 	struct idm	*idm;
463 	struct imsgev	*iev = env->sc_iev;
464 
465 	imsg_compose_event(iev, IMSG_CONF_START, 0, 0, -1, env, sizeof(*env));
466 	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
467 		imsg_compose_event(iev, IMSG_CONF_IDM, 0, 0, -1,
468 		    idm, sizeof(*idm));
469 	}
470 	imsg_compose_event(iev, IMSG_CONF_END, 0, 0, -1, NULL, 0);
471 }
472 
473 void
474 main_init_timer(int fd, short event, void *p)
475 {
476 	struct env	*env = p;
477 
478 	main_configure_client(env);
479 }
480 
481 void
482 purge_config(struct env *env)
483 {
484 	struct idm	*idm;
485 
486 	while ((idm = TAILQ_FIRST(&env->sc_idms)) != NULL) {
487 		TAILQ_REMOVE(&env->sc_idms, idm, idm_entry);
488 		free(idm);
489 	}
490 }
491 
492 int
493 main(int argc, char *argv[])
494 {
495 	int		 c;
496 	int		 debug;
497 	struct passwd	*pw;
498 	struct env	 env;
499 	struct event	 ev_sigint;
500 	struct event	 ev_sigterm;
501 	struct event	 ev_sigchld;
502 	struct event	 ev_sighup;
503 	struct event	 ev_timer;
504 	struct timeval	 tv;
505 
506 	debug = 0;
507 	ypldap_process = PROC_MAIN;
508 
509 	log_init(1);
510 
511 	while ((c = getopt(argc, argv, "dD:nf:v")) != -1) {
512 		switch (c) {
513 		case 'd':
514 			debug = 2;
515 			break;
516 		case 'D':
517 			if (cmdline_symset(optarg) < 0)
518 				log_warnx("could not parse macro definition %s",
519 				    optarg);
520 			break;
521 		case 'n':
522 			debug = 2;
523 			opts |= YPLDAP_OPT_NOACTION;
524 			break;
525 		case 'f':
526 			conffile = optarg;
527 			break;
528 		case 'v':
529 			opts |= YPLDAP_OPT_VERBOSE;
530 			break;
531 		default:
532 			usage();
533 		}
534 	}
535 
536 	argc -= optind;
537 	argv += optind;
538 
539 	if (argc)
540 		usage();
541 
542 	RB_INIT(&env.sc_user_uids);
543 	RB_INIT(&env.sc_group_gids);
544 
545 	if (parse_config(&env, conffile, opts))
546 		exit(1);
547 	if (opts & YPLDAP_OPT_NOACTION) {
548 		fprintf(stderr, "configuration OK\n");
549 		exit(0);
550 	}
551 
552 	if (geteuid())
553 		errx(1, "need root privileges");
554 
555 	log_init(debug);
556 
557 	if (!debug) {
558 		if (daemon(1, 0) == -1)
559 			err(1, "failed to daemonize");
560 	}
561 
562 	log_info("startup%s", (debug > 1)?" [debug mode]":"");
563 
564 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC,
565 	    pipe_main2client) == -1)
566 		fatal("socketpair");
567 
568 	set_nonblock(pipe_main2client[0]);
569 	set_nonblock(pipe_main2client[1]);
570 
571 	client_pid = ldapclient(pipe_main2client);
572 
573 	setproctitle("parent");
574 	event_init();
575 
576 	signal_set(&ev_sigint, SIGINT, main_sig_handler, &env);
577 	signal_set(&ev_sigterm, SIGTERM, main_sig_handler, &env);
578 	signal_set(&ev_sighup, SIGHUP, main_sig_handler, &env);
579 	signal_set(&ev_sigchld, SIGCHLD, main_sig_handler, &env);
580 	signal_add(&ev_sigint, NULL);
581 	signal_add(&ev_sigterm, NULL);
582 	signal_add(&ev_sighup, NULL);
583 	signal_add(&ev_sigchld, NULL);
584 
585 	close(pipe_main2client[1]);
586 	if ((env.sc_iev = calloc(1, sizeof(*env.sc_iev))) == NULL)
587 		fatal(NULL);
588 	imsg_init(&env.sc_iev->ibuf, pipe_main2client[0]);
589 	env.sc_iev->handler = main_dispatch_client;
590 
591 	env.sc_iev->events = EV_READ;
592 	env.sc_iev->data = &env;
593 	event_set(&env.sc_iev->ev, env.sc_iev->ibuf.fd, env.sc_iev->events,
594 	     env.sc_iev->handler, &env);
595 	event_add(&env.sc_iev->ev, NULL);
596 
597 	yp_init(&env);
598 
599 	if ((pw = getpwnam(YPLDAP_USER)) == NULL)
600 		fatal("getpwnam");
601 
602 #ifndef DEBUG
603 	if (setgroups(1, &pw->pw_gid) ||
604 	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
605 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
606 		fatal("cannot drop privileges");
607 #else
608 #warning disabling privilege revocation in debug mode
609 #endif
610 
611 	bzero(&tv, sizeof(tv));
612 	evtimer_set(&ev_timer, main_init_timer, &env);
613 	evtimer_add(&ev_timer, &tv);
614 
615 	yp_enable_events();
616 	event_dispatch();
617 	main_shutdown();
618 
619 	return (0);
620 }
621 
622 void
623 imsg_event_add(struct imsgev *iev)
624 {
625 	if (iev->handler == NULL) {
626 		imsg_flush(&iev->ibuf);
627 		return;
628 	}
629 
630 	iev->events = EV_READ;
631 	if (iev->ibuf.w.queued)
632 		iev->events |= EV_WRITE;
633 
634 	event_del(&iev->ev);
635 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
636 	event_add(&iev->ev, NULL);
637 }
638 
639 int
640 imsg_compose_event(struct imsgev *iev, u_int16_t type, u_int32_t peerid,
641     pid_t pid, int fd, void *data, u_int16_t datalen)
642 {
643 	int	ret;
644 
645 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
646 	    pid, fd, data, datalen)) != -1)
647 		imsg_event_add(iev);
648 	return (ret);
649 }
650 
651 void
652 set_nonblock(int fd)
653 {
654 	int	flags;
655 
656 	if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
657 		fatal("fcntl F_GETFL");
658 
659 	flags |= O_NONBLOCK;
660 
661 	if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
662 		fatal("fcntl F_SETFL");
663 }
664