xref: /openbsd-src/usr.sbin/ldapd/ldapd.c (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
1 /*	$OpenBSD: ldapd.c,v 1.31 2021/12/15 11:36:40 jmatthew Exp $ */
2 
3 /*
4  * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
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/queue.h>
20 #include <sys/stat.h>
21 #include <sys/un.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 
25 #include <assert.h>
26 #include <bsd_auth.h>
27 #include <ctype.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <event.h>
31 #include <fcntl.h>
32 #include <login_cap.h>
33 #include <paths.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <syslog.h>
41 
42 #include "ldapd.h"
43 #include "log.h"
44 
45 void		 usage(void);
46 void		 ldapd_sig_handler(int fd, short why, void *data);
47 void		 ldapd_sigchld_handler(int sig, short why, void *data);
48 static void	 ldapd_imsgev(struct imsgev *iev, int code, struct imsg *imsg);
49 static void	 ldapd_needfd(struct imsgev *iev);
50 static void	 ldapd_auth_request(struct imsgev *iev, struct imsg *imsg);
51 static void	 ldapd_open_request(struct imsgev *iev, struct imsg *imsg);
52 static void	 ldapd_log_verbose(struct imsg *imsg);
53 static pid_t	 start_child(enum ldapd_process, char *, int, int, int,
54 		    char *, char *);
55 
56 struct ldapd_stats	 stats;
57 pid_t			 ldape_pid;
58 char			*datadir = DATADIR;
59 
60 void
61 usage(void)
62 {
63 	extern char	*__progname;
64 
65 	fprintf(stderr, "usage: %s [-dnv] [-D macro=value] "
66 	    "[-f file] [-r directory] [-s file]\n", __progname);
67 	exit(1);
68 }
69 
70 void
71 ldapd_sig_handler(int sig, short why, void *data)
72 {
73 	log_info("ldapd: got signal %d", sig);
74 	if (sig == SIGINT || sig == SIGTERM)
75 		event_loopexit(NULL);
76 }
77 
78 void
79 ldapd_sigchld_handler(int sig, short why, void *data)
80 {
81 	pid_t		 pid;
82 	int		 status;
83 
84 	while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
85 		if (pid == -1) {
86 			if (errno == EINTR)
87 				continue;
88 			if (errno != ECHILD)
89 				log_warn("waitpid");
90 			break;
91 		}
92 
93 		if (WIFEXITED(status))
94 			log_debug("child %d exited with status %d",
95 			    pid, WEXITSTATUS(status));
96 		else if (WIFSIGNALED(status))
97 			log_debug("child %d exited due to signal %d",
98 			    pid, WTERMSIG(status));
99 		else
100 			log_debug("child %d terminated abnormally", pid);
101 
102 		if (pid == ldape_pid) {
103 			log_info("ldapd: lost ldap server");
104 			event_loopexit(NULL);
105 			break;
106 		}
107 	}
108 }
109 
110 int
111 main(int argc, char *argv[])
112 {
113 	int			 c;
114 	int			 debug = 0, verbose = 0, eflag = 0;
115 	int			 configtest = 0;
116 	int			 pipe_parent2ldap[2];
117 	char			*conffile = CONFFILE;
118 	char			*csockpath = LDAPD_SOCKET;
119 	char			*saved_argv0;
120 	struct imsgev		*iev_ldape;
121 	struct event		 ev_sigint;
122 	struct event		 ev_sigterm;
123 	struct event		 ev_sigchld;
124 	struct event		 ev_sighup;
125 	struct stat		 sb;
126 
127 	log_init(1, LOG_DAEMON);	/* log to stderr until daemonized */
128 
129 	saved_argv0 = argv[0];
130 	if (saved_argv0 == NULL)
131 		saved_argv0 = "ldapd";
132 
133 	while ((c = getopt(argc, argv, "dhvD:f:nr:s:E")) != -1) {
134 
135 		switch (c) {
136 		case 'd':
137 			debug = 1;
138 			break;
139 		case 'D':
140 			if (cmdline_symset(optarg) < 0) {
141 				warnx("could not parse macro definition %s",
142 				    optarg);
143 			}
144 			break;
145 		case 'f':
146 			conffile = optarg;
147 			break;
148 		case 'h':
149 			usage();
150 			/* NOTREACHED */
151 		case 'n':
152 			configtest = 1;
153 			break;
154 		case 'r':
155 			datadir = optarg;
156 			break;
157 		case 's':
158 			csockpath = optarg;
159 			break;
160 		case 'v':
161 			verbose++;
162 			break;
163 		case 'E':
164 			eflag = 1;
165 			break;
166 		default:
167 			usage();
168 			/* NOTREACHED */
169 		}
170 	}
171 
172 	argc -= optind;
173 	if (argc > 0)
174 		usage();
175 
176 	/* check for root privileges  */
177 	if (geteuid())
178 		errx(1, "need root privileges");
179 
180 	/* check for ldapd user */
181 	if (getpwnam(LDAPD_USER) == NULL)
182 		errx(1, "unknown user %s", LDAPD_USER);
183 
184 	log_setverbose(verbose);
185 	stats.started_at = time(0);
186 
187 	if (parse_config(conffile) != 0)
188 		exit(2);
189 
190 	if (configtest) {
191 		fprintf(stderr, "configuration ok\n");
192 		exit(0);
193 	}
194 
195 	log_init(debug, LOG_DAEMON);
196 
197 	if (eflag)
198 		ldape(debug, verbose, csockpath);
199 
200 	if (stat(datadir, &sb) == -1)
201 		err(1, "%s", datadir);
202 	if (!S_ISDIR(sb.st_mode))
203 		errx(1, "%s is not a directory", datadir);
204 
205 	if (!debug) {
206 		if (daemon(1, 0) == -1)
207 			err(1, "failed to daemonize");
208 	}
209 
210 	log_info("startup");
211 
212 	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
213 	    PF_UNSPEC, pipe_parent2ldap) != 0)
214 		fatal("socketpair");
215 
216 	ldape_pid = start_child(PROC_LDAP_SERVER, saved_argv0,
217 	    pipe_parent2ldap[1], debug, verbose, csockpath, conffile);
218 
219 	ldap_loginit("auth", debug, verbose);
220 	setproctitle("auth");
221 	event_init();
222 
223 	signal_set(&ev_sigint, SIGINT, ldapd_sig_handler, NULL);
224 	signal_set(&ev_sigterm, SIGTERM, ldapd_sig_handler, NULL);
225 	signal_set(&ev_sigchld, SIGCHLD, ldapd_sigchld_handler, NULL);
226 	signal_set(&ev_sighup, SIGHUP, ldapd_sig_handler, NULL);
227 	signal_add(&ev_sigint, NULL);
228 	signal_add(&ev_sigterm, NULL);
229 	signal_add(&ev_sigchld, NULL);
230 	signal_add(&ev_sighup, NULL);
231 	signal(SIGPIPE, SIG_IGN);
232 
233 	if ((iev_ldape = calloc(1, sizeof(struct imsgev))) == NULL)
234 		fatal("calloc");
235 	imsgev_init(iev_ldape, pipe_parent2ldap[0], NULL, ldapd_imsgev,
236 	    ldapd_needfd);
237 
238 	if (unveil(_PATH_NOLOGIN, "r") == -1)
239 		err(1, "unveil %s", _PATH_NOLOGIN);
240 	if (unveil(_PATH_LOGIN_CONF, "r") == -1)
241 		err(1, "unveil %s", _PATH_LOGIN_CONF);
242 	if (unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
243 		err(1, "unveil %s.db", _PATH_LOGIN_CONF);
244 	if (unveil(_PATH_AUTHPROGDIR, "x") == -1)
245 		err(1, "unveil %s", _PATH_AUTHPROGDIR);
246 	if (unveil(datadir, "rwc") == -1)
247 		err(1, "unveil %s", datadir);
248 	if (unveil(NULL, NULL) == -1)
249 		err(1, "unveil");
250 
251 	if (pledge("stdio rpath wpath cpath getpw sendfd proc exec",
252 	    NULL) == -1)
253 		err(1, "pledge");
254 
255 	event_dispatch();
256 
257 	log_debug("ldapd: exiting");
258 
259 	return 0;
260 }
261 
262 static void
263 ldapd_imsgev(struct imsgev *iev, int code, struct imsg *imsg)
264 {
265 	switch (code) {
266 	case IMSGEV_IMSG:
267 		log_debug("%s: got imsg %d on fd %d",
268 		    __func__, imsg->hdr.type, iev->ibuf.fd);
269 		switch (imsg->hdr.type) {
270 		case IMSG_LDAPD_AUTH:
271 			ldapd_auth_request(iev, imsg);
272 			break;
273 		case IMSG_CTL_LOG_VERBOSE:
274 			ldapd_log_verbose(imsg);
275 			break;
276 		case IMSG_LDAPD_OPEN:
277 			ldapd_open_request(iev, imsg);
278 			break;
279 		default:
280 			log_debug("%s: unexpected imsg %d",
281 			    __func__, imsg->hdr.type);
282 			break;
283 		}
284 		break;
285 	case IMSGEV_EREAD:
286 	case IMSGEV_EWRITE:
287 	case IMSGEV_EIMSG:
288 		fatal("imsgev read/write error");
289 		break;
290 	case IMSGEV_DONE:
291 		event_loopexit(NULL);
292 		break;
293 	}
294 }
295 
296 static void
297 ldapd_needfd(struct imsgev *iev)
298 {
299 	fatal("should never need an fd for parent messages");
300 }
301 
302 static int
303 ldapd_auth_classful(char *name, char *password)
304 {
305 	login_cap_t		*lc = NULL;
306 	char			*class = NULL, *style = NULL;
307 	auth_session_t		*as;
308 
309 	if ((class = strchr(name, '#')) == NULL) {
310 		log_debug("regular auth");
311 		return auth_userokay(name, NULL, "auth-ldap", password);
312 	}
313 	*class++ = '\0';
314 
315 	if ((lc = login_getclass(class)) == NULL) {
316 		log_debug("login_getclass(%s) for [%s] failed", class, name);
317 		return 0;
318 	}
319 	if ((style = login_getstyle(lc, style, "auth-ldap")) == NULL) {
320 		log_debug("login_getstyle() for [%s] failed", name);
321 		login_close(lc);
322 		return 0;
323 	}
324 	if (password) {
325 		if ((as = auth_open()) == NULL) {
326 			login_close(lc);
327 			return 0;
328 		}
329 		auth_setitem(as, AUTHV_SERVICE, "response");
330 		auth_setdata(as, "", 1);
331 		auth_setdata(as, password, strlen(password) + 1);
332 		explicit_bzero(password, strlen(password));
333 	} else
334 		as = NULL;
335 
336 	as = auth_verify(as, style, name, lc->lc_class, (char *)NULL);
337 	login_close(lc);
338 	return (as != NULL ? auth_close(as) : 0);
339 }
340 
341 static void
342 ldapd_auth_request(struct imsgev *iev, struct imsg *imsg)
343 {
344 	struct auth_req		*areq = imsg->data;
345 	struct auth_res		 ares;
346 
347 	if (imsg->hdr.len != sizeof(*areq) + IMSG_HEADER_SIZE)
348 		fatal("invalid size of auth request");
349 
350 	/* make sure name and password are null-terminated */
351 	areq->name[sizeof(areq->name) - 1] = '\0';
352 	areq->password[sizeof(areq->password) - 1] = '\0';
353 
354 	log_debug("authenticating [%s]", areq->name);
355 	ares.ok = ldapd_auth_classful(areq->name, areq->password);
356 	ares.fd = areq->fd;
357 	ares.msgid = areq->msgid;
358 	memset(areq, 0, sizeof(*areq));
359 	imsgev_compose(iev, IMSG_LDAPD_AUTH_RESULT, 0, 0, -1, &ares,
360 	    sizeof(ares));
361 }
362 
363 static void
364 ldapd_log_verbose(struct imsg *imsg)
365 {
366 	int	 verbose;
367 
368 	if (imsg->hdr.len != sizeof(verbose) + IMSG_HEADER_SIZE)
369 		fatal("invalid size of log verbose request");
370 
371 	bcopy(imsg->data, &verbose, sizeof(verbose));
372 	log_setverbose(verbose);
373 }
374 
375 static void
376 ldapd_open_request(struct imsgev *iev, struct imsg *imsg)
377 {
378 	struct open_req		*oreq = imsg->data;
379 	int			 oflags, fd;
380 
381 	if (imsg->hdr.len != sizeof(*oreq) + IMSG_HEADER_SIZE)
382 		fatal("invalid size of open request");
383 
384 	if (oreq->path[PATH_MAX-1] != '\0')
385 		fatal("bogus path");
386 
387 	if (strncmp(oreq->path, datadir, strlen(datadir)) != 0) {
388 		log_warnx("refusing to open file %s", oreq->path);
389 		fatal("ldape sent invalid open request");
390 	}
391 
392 	if (oreq->rdonly)
393 		oflags = O_RDONLY;
394 	else
395 		oflags = O_RDWR | O_CREAT | O_APPEND;
396 
397 	log_debug("opening [%s]", oreq->path);
398 	fd = open(oreq->path, oflags | O_NOFOLLOW, 0600);
399 	if (fd == -1)
400 		log_warn("%s", oreq->path);
401 
402 	imsgev_compose(iev, IMSG_LDAPD_OPEN_RESULT, 0, 0, fd, oreq,
403 	    sizeof(*oreq));
404 }
405 
406 static pid_t
407 start_child(enum ldapd_process p, char *argv0, int fd, int debug,
408     int verbose, char *csockpath, char *conffile)
409 {
410 	char		*argv[11];
411 	int		 argc = 0;
412 	pid_t		 pid;
413 
414 	switch (pid = fork()) {
415 	case -1:
416 		fatal("cannot fork");
417 	case 0:
418 		break;
419 	default:
420 		close(fd);
421 		return (pid);
422 	}
423 
424 	if (fd != PROC_PARENT_SOCK_FILENO) {
425 		if (dup2(fd, PROC_PARENT_SOCK_FILENO) == -1)
426 			fatal("cannot setup imsg fd");
427 	} else if (fcntl(fd, F_SETFD, 0) == -1)
428 		fatal("cannot setup imsg fd");
429 
430 	argv[argc++] = argv0;
431 	switch (p) {
432 	case PROC_MAIN_AUTH:
433 		fatalx("Can not start main process");
434 	case PROC_LDAP_SERVER:
435 		argv[argc++] = "-E";
436 		break;
437 	}
438 	if (debug)
439 		argv[argc++] = "-d";
440 	if (verbose >= 3)
441 		argv[argc++] = "-vvv";
442 	else if (verbose == 2)
443 		argv[argc++] = "-vv";
444 	else if (verbose == 1)
445 		argv[argc++] = "-v";
446 	if (csockpath) {
447 		argv[argc++] = "-s";
448 		argv[argc++] = csockpath;
449 	}
450 	if (conffile) {
451 		argv[argc++] = "-f";
452 		argv[argc++] = conffile;
453 	}
454 	if (datadir) {
455 		argv[argc++] = "-r";
456 		argv[argc++] = datadir;
457 	}
458 
459 	argv[argc++] = NULL;
460 
461 	execvp(argv0, argv);
462 	fatal("execvp");
463 }
464