xref: /openbsd-src/usr.sbin/ldapd/ldapd.c (revision de8cc8edbc71bd3e3bc7fbffa27ba0e564c37d8b)
1 /*	$OpenBSD: ldapd.c,v 1.27 2021/01/27 22:12:28 rob 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 	tls_init();
187 
188 	if (parse_config(conffile) != 0)
189 		exit(2);
190 
191 	if (configtest) {
192 		fprintf(stderr, "configuration ok\n");
193 		exit(0);
194 	}
195 
196 	log_init(debug, LOG_DAEMON);
197 
198 	if (eflag)
199 		ldape(debug, verbose, csockpath);
200 
201 	if (stat(datadir, &sb) == -1)
202 		err(1, "%s", datadir);
203 	if (!S_ISDIR(sb.st_mode))
204 		errx(1, "%s is not a directory", datadir);
205 
206 	if (!debug) {
207 		if (daemon(1, 0) == -1)
208 			err(1, "failed to daemonize");
209 	}
210 
211 	log_info("startup");
212 
213 	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
214 	    PF_UNSPEC, pipe_parent2ldap) != 0)
215 		fatal("socketpair");
216 
217 	ldape_pid = start_child(PROC_LDAP_SERVER, saved_argv0,
218 	    pipe_parent2ldap[1], debug, verbose, csockpath, conffile);
219 
220 	ldap_loginit("auth", debug, verbose);
221 	setproctitle("auth");
222 	event_init();
223 
224 	signal_set(&ev_sigint, SIGINT, ldapd_sig_handler, NULL);
225 	signal_set(&ev_sigterm, SIGTERM, ldapd_sig_handler, NULL);
226 	signal_set(&ev_sigchld, SIGCHLD, ldapd_sigchld_handler, NULL);
227 	signal_set(&ev_sighup, SIGHUP, ldapd_sig_handler, NULL);
228 	signal_add(&ev_sigint, NULL);
229 	signal_add(&ev_sigterm, NULL);
230 	signal_add(&ev_sigchld, NULL);
231 	signal_add(&ev_sighup, NULL);
232 	signal(SIGPIPE, SIG_IGN);
233 
234 	if ((iev_ldape = calloc(1, sizeof(struct imsgev))) == NULL)
235 		fatal("calloc");
236 	imsgev_init(iev_ldape, pipe_parent2ldap[0], NULL, ldapd_imsgev,
237 	    ldapd_needfd);
238 
239 	if (unveil(_PATH_NOLOGIN, "r") == -1)
240 		err(1, "unveil");
241 	if (unveil(_PATH_LOGIN_CONF, "r") == -1)
242 		err(1, "unveil");
243 	if (unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
244 		err(1, "unveil");
245 	if (unveil(_PATH_AUTHPROGDIR, "x") == -1)
246 		err(1, "unveil");
247 	if (unveil(datadir, "rw") == -1)
248 		err(1, "unveil");
249 	if (unveil(NULL, NULL) == -1)
250 		err(1, "unveil");
251 
252 	if (pledge("stdio rpath wpath cpath getpw sendfd proc exec",
253 	    NULL) == -1)
254 		err(1, "pledge");
255 
256 	event_dispatch();
257 
258 	log_debug("ldapd: exiting");
259 
260 	return 0;
261 }
262 
263 static void
264 ldapd_imsgev(struct imsgev *iev, int code, struct imsg *imsg)
265 {
266 	switch (code) {
267 	case IMSGEV_IMSG:
268 		log_debug("%s: got imsg %d on fd %d",
269 		    __func__, imsg->hdr.type, iev->ibuf.fd);
270 		switch (imsg->hdr.type) {
271 		case IMSG_LDAPD_AUTH:
272 			ldapd_auth_request(iev, imsg);
273 			break;
274 		case IMSG_CTL_LOG_VERBOSE:
275 			ldapd_log_verbose(imsg);
276 			break;
277 		case IMSG_LDAPD_OPEN:
278 			ldapd_open_request(iev, imsg);
279 			break;
280 		default:
281 			log_debug("%s: unexpected imsg %d",
282 			    __func__, imsg->hdr.type);
283 			break;
284 		}
285 		break;
286 	case IMSGEV_EREAD:
287 	case IMSGEV_EWRITE:
288 	case IMSGEV_EIMSG:
289 		fatal("imsgev read/write error");
290 		break;
291 	case IMSGEV_DONE:
292 		event_loopexit(NULL);
293 		break;
294 	}
295 }
296 
297 static void
298 ldapd_needfd(struct imsgev *iev)
299 {
300 	fatal("should never need an fd for parent messages");
301 }
302 
303 static int
304 ldapd_auth_classful(char *name, char *password)
305 {
306 	login_cap_t		*lc = NULL;
307 	char			*class = NULL, *style = NULL;
308 	auth_session_t		*as;
309 
310 	if ((class = strchr(name, '#')) == NULL) {
311 		log_debug("regular auth");
312 		return auth_userokay(name, NULL, "auth-ldap", password);
313 	}
314 	*class++ = '\0';
315 
316 	if ((lc = login_getclass(class)) == NULL) {
317 		log_debug("login_getclass(%s) for [%s] failed", class, name);
318 		return 0;
319 	}
320 	if ((style = login_getstyle(lc, style, "auth-ldap")) == NULL) {
321 		log_debug("login_getstyle() for [%s] failed", name);
322 		login_close(lc);
323 		return 0;
324 	}
325 	if (password) {
326 		if ((as = auth_open()) == NULL) {
327 			login_close(lc);
328 			return 0;
329 		}
330 		auth_setitem(as, AUTHV_SERVICE, "response");
331 		auth_setdata(as, "", 1);
332 		auth_setdata(as, password, strlen(password) + 1);
333 		explicit_bzero(password, strlen(password));
334 	} else
335 		as = NULL;
336 
337 	as = auth_verify(as, style, name, lc->lc_class, (char *)NULL);
338 	login_close(lc);
339 	return (as != NULL ? auth_close(as) : 0);
340 }
341 
342 static void
343 ldapd_auth_request(struct imsgev *iev, struct imsg *imsg)
344 {
345 	struct auth_req		*areq = imsg->data;
346 	struct auth_res		 ares;
347 
348 	if (imsg->hdr.len != sizeof(*areq) + IMSG_HEADER_SIZE)
349 		fatal("invalid size of auth request");
350 
351 	/* make sure name and password are null-terminated */
352 	areq->name[sizeof(areq->name) - 1] = '\0';
353 	areq->password[sizeof(areq->password) - 1] = '\0';
354 
355 	log_debug("authenticating [%s]", areq->name);
356 	ares.ok = ldapd_auth_classful(areq->name, areq->password);
357 	ares.fd = areq->fd;
358 	ares.msgid = areq->msgid;
359 	memset(areq, 0, sizeof(*areq));
360 	imsgev_compose(iev, IMSG_LDAPD_AUTH_RESULT, 0, 0, -1, &ares,
361 	    sizeof(ares));
362 }
363 
364 static void
365 ldapd_log_verbose(struct imsg *imsg)
366 {
367 	int	 verbose;
368 
369 	if (imsg->hdr.len != sizeof(verbose) + IMSG_HEADER_SIZE)
370 		fatal("invalid size of log verbose request");
371 
372 	bcopy(imsg->data, &verbose, sizeof(verbose));
373 	log_setverbose(verbose);
374 }
375 
376 static void
377 ldapd_open_request(struct imsgev *iev, struct imsg *imsg)
378 {
379 	struct open_req		*oreq = imsg->data;
380 	int			 oflags, fd;
381 
382 	if (imsg->hdr.len != sizeof(*oreq) + IMSG_HEADER_SIZE)
383 		fatal("invalid size of open request");
384 
385 	/* make sure path is null-terminated */
386 	oreq->path[PATH_MAX] = '\0';
387 
388 	if (strncmp(oreq->path, datadir, strlen(datadir)) != 0) {
389 		log_warnx("refusing to open file %s", oreq->path);
390 		fatal("ldape sent invalid open request");
391 	}
392 
393 	if (oreq->rdonly)
394 		oflags = O_RDONLY;
395 	else
396 		oflags = O_RDWR | O_CREAT | O_APPEND;
397 
398 	log_debug("opening [%s]", oreq->path);
399 	fd = open(oreq->path, oflags | O_NOFOLLOW, 0600);
400 	if (fd == -1)
401 		log_warn("%s", oreq->path);
402 
403 	imsgev_compose(iev, IMSG_LDAPD_OPEN_RESULT, 0, 0, fd, oreq,
404 	    sizeof(*oreq));
405 }
406 
407 static pid_t
408 start_child(enum ldapd_process p, char *argv0, int fd, int debug,
409     int verbose, char *csockpath, char *conffile)
410 {
411 	char		*argv[11];
412 	int		 argc = 0;
413 	pid_t		 pid;
414 
415 	switch (pid = fork()) {
416 	case -1:
417 		fatal("cannot fork");
418 	case 0:
419 		break;
420 	default:
421 		close(fd);
422 		return (pid);
423 	}
424 
425 	if (fd != PROC_PARENT_SOCK_FILENO) {
426 		if (dup2(fd, PROC_PARENT_SOCK_FILENO) == -1)
427 			fatal("cannot setup imsg fd");
428 	} else if (fcntl(fd, F_SETFD, 0) == -1)
429 		fatal("cannot setup imsg fd");
430 
431 	argv[argc++] = argv0;
432 	switch (p) {
433 	case PROC_MAIN_AUTH:
434 		fatalx("Can not start main process");
435 	case PROC_LDAP_SERVER:
436 		argv[argc++] = "-E";
437 		break;
438 	}
439 	if (debug)
440 		argv[argc++] = "-d";
441 	if (verbose >= 3)
442 		argv[argc++] = "-vvv";
443 	else if (verbose == 2)
444 		argv[argc++] = "-vv";
445 	else if (verbose == 1)
446 		argv[argc++] = "-v";
447 	if (csockpath) {
448 		argv[argc++] = "-s";
449 		argv[argc++] = csockpath;
450 	}
451 	if (conffile) {
452 		argv[argc++] = "-f";
453 		argv[argc++] = conffile;
454 	}
455 	if (datadir) {
456 		argv[argc++] = "-r";
457 		argv[argc++] = datadir;
458 	}
459 
460 	argv[argc++] = NULL;
461 
462 	execvp(argv0, argv);
463 	fatal("execvp");
464 }
465