xref: /openbsd-src/usr.sbin/ypldap/ypldap.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ypldap.c,v 1.19 2016/04/28 22:28:36 schwarze 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/queue.h>
21 #include <sys/socket.h>
22 #include <sys/signal.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 <errno.h>
31 #include <event.h>
32 #include <unistd.h>
33 #include <pwd.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <limits.h>
38 
39 #include "ypldap.h"
40 
41 __dead void	 usage(void);
42 int		 check_child(pid_t, const char *);
43 void		 main_sig_handler(int, short, void *);
44 void		 main_shutdown(void);
45 void		 main_dispatch_client(int, short, void *);
46 void		 main_configure_client(struct env *);
47 void		 main_init_timer(int, short, void *);
48 void		 main_start_update(struct env *);
49 void		 main_trash_update(struct env *);
50 void		 main_end_update(struct env *);
51 int		 main_create_user_groups(struct env *);
52 void		 purge_config(struct env *);
53 void		 reconfigure(struct env *);
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: unknown user %s in group %s\n",
245 				    ukey.ue_line, ge->ge_line);
246 				if (bp != NULL)
247 					*(bp-1) = ',';
248 				continue;
249 			}
250 			if (bp != NULL)
251 				*(bp-1) = ',';
252 
253 			/* Make sure the new group doesn't equal to the main gid */
254 			if (ge->ge_gid == ue->ue_gid)
255 				continue;
256 
257 			len = strlen(ue->ue_netid_line);
258 			p = ue->ue_netid_line + len;
259 
260 			if ((snprintf(p, LINE_WIDTH-len-1, ",%d",
261 				ge->ge_gid)) >= (int)(LINE_WIDTH-len)) {
262 				return (-1);
263 			}
264 		}
265 	}
266 
267 	return (0);
268 }
269 
270 void
271 main_end_update(struct env *env)
272 {
273 	struct userent		*ue;
274 	struct groupent		*ge;
275 
276 	if (env->update_trashed)
277 		return;
278 
279 	log_debug("updates are over, cleaning up trees now");
280 
281 	if (main_create_user_groups(env) == -1) {
282 		main_trash_update(env);
283 		return;
284 	}
285 
286 	if (env->sc_user_names == NULL) {
287 		env->sc_user_names = env->sc_user_names_t;
288 		env->sc_user_lines = NULL;
289 		env->sc_user_names_t = NULL;
290 
291 		env->sc_group_names = env->sc_group_names_t;
292 		env->sc_group_lines = NULL;
293 		env->sc_group_names_t = NULL;
294 
295 		flatten_entries(env);
296 		goto make_uids;
297 	}
298 
299 	/*
300 	 * clean previous tree.
301 	 */
302 	while ((ue = RB_ROOT(env->sc_user_names)) != NULL) {
303 		RB_REMOVE(user_name_tree, env->sc_user_names,
304 		    ue);
305 		free(ue->ue_netid_line);
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 events, 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 	if ((events & (EV_READ | EV_WRITE)) == 0)
358 		fatalx("unknown event");
359 
360 	if (events & EV_READ) {
361 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
362 			fatal("imsg_read error");
363 		if (n == 0)
364 			shut = 1;
365 	}
366 	if (events & EV_WRITE) {
367 		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
368 			fatal("msgbuf_write");
369 		if (n == 0)
370 			shut = 1;
371 		goto done;
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 
451 done:
452 	if (!shut)
453 		imsg_event_add(iev);
454 	else {
455 		log_debug("king bula sez: ran into dead pipe");
456 		event_del(&iev->ev);
457 		event_loopexit(NULL);
458 	}
459 }
460 
461 void
462 main_configure_client(struct env *env)
463 {
464 	struct idm	*idm;
465 	struct imsgev	*iev = env->sc_iev;
466 
467 	imsg_compose_event(iev, IMSG_CONF_START, 0, 0, -1, env, sizeof(*env));
468 	TAILQ_FOREACH(idm, &env->sc_idms, idm_entry) {
469 		imsg_compose_event(iev, IMSG_CONF_IDM, 0, 0, -1,
470 		    idm, sizeof(*idm));
471 	}
472 	imsg_compose_event(iev, IMSG_CONF_END, 0, 0, -1, NULL, 0);
473 }
474 
475 void
476 main_init_timer(int fd, short event, void *p)
477 {
478 	struct env	*env = p;
479 
480 	main_configure_client(env);
481 }
482 
483 void
484 purge_config(struct env *env)
485 {
486 	struct idm	*idm;
487 
488 	while ((idm = TAILQ_FIRST(&env->sc_idms)) != NULL) {
489 		TAILQ_REMOVE(&env->sc_idms, idm, idm_entry);
490 		free(idm);
491 	}
492 }
493 
494 int
495 main(int argc, char *argv[])
496 {
497 	int		 c;
498 	int		 debug;
499 	struct passwd	*pw;
500 	struct env	 env;
501 	struct event	 ev_sigint;
502 	struct event	 ev_sigterm;
503 	struct event	 ev_sigchld;
504 	struct event	 ev_sighup;
505 	struct event	 ev_timer;
506 	struct timeval	 tv;
507 
508 	debug = 0;
509 	ypldap_process = PROC_MAIN;
510 
511 	log_init(1);
512 
513 	while ((c = getopt(argc, argv, "dD:nf:v")) != -1) {
514 		switch (c) {
515 		case 'd':
516 			debug = 2;
517 			break;
518 		case 'D':
519 			if (cmdline_symset(optarg) < 0)
520 				log_warnx("could not parse macro definition %s",
521 				    optarg);
522 			break;
523 		case 'n':
524 			debug = 2;
525 			opts |= YPLDAP_OPT_NOACTION;
526 			break;
527 		case 'f':
528 			conffile = optarg;
529 			break;
530 		case 'v':
531 			opts |= YPLDAP_OPT_VERBOSE;
532 			break;
533 		default:
534 			usage();
535 		}
536 	}
537 
538 	argc -= optind;
539 	argv += optind;
540 
541 	if (argc)
542 		usage();
543 
544 	RB_INIT(&env.sc_user_uids);
545 	RB_INIT(&env.sc_group_gids);
546 
547 	if (parse_config(&env, conffile, opts))
548 		exit(1);
549 	if (opts & YPLDAP_OPT_NOACTION) {
550 		fprintf(stderr, "configuration OK\n");
551 		exit(0);
552 	}
553 
554 	if (geteuid())
555 		errx(1, "need root privileges");
556 
557 	log_init(debug);
558 
559 	if (!debug) {
560 		if (daemon(1, 0) == -1)
561 			err(1, "failed to daemonize");
562 	}
563 
564 	log_info("startup%s", (debug > 1)?" [debug mode]":"");
565 
566 	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, PF_UNSPEC,
567 	    pipe_main2client) == -1)
568 		fatal("socketpair");
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 	if (pledge("stdio inet", NULL) == -1)
611 		fatal("pledge");
612 
613 	bzero(&tv, sizeof(tv));
614 	evtimer_set(&ev_timer, main_init_timer, &env);
615 	evtimer_add(&ev_timer, &tv);
616 
617 	yp_enable_events();
618 	event_dispatch();
619 	main_shutdown();
620 
621 	return (0);
622 }
623 
624 void
625 imsg_event_add(struct imsgev *iev)
626 {
627 	if (iev->handler == NULL) {
628 		imsg_flush(&iev->ibuf);
629 		return;
630 	}
631 
632 	iev->events = EV_READ;
633 	if (iev->ibuf.w.queued)
634 		iev->events |= EV_WRITE;
635 
636 	event_del(&iev->ev);
637 	event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data);
638 	event_add(&iev->ev, NULL);
639 }
640 
641 int
642 imsg_compose_event(struct imsgev *iev, u_int16_t type, u_int32_t peerid,
643     pid_t pid, int fd, void *data, u_int16_t datalen)
644 {
645 	int	ret;
646 
647 	if ((ret = imsg_compose(&iev->ibuf, type, peerid,
648 	    pid, fd, data, datalen)) != -1)
649 		imsg_event_add(iev);
650 	return (ret);
651 }
652