summaryrefslogtreecommitdiff
path: root/usr.sbin/ldapd/ldapd.c
blob: eb3ff811e34c4aca221e65420244e4487bef5b1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*	$OpenBSD: ldapd.c,v 1.29 2021/07/14 13:33:57 kn Exp $ */

/*
 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <assert.h>
#include <bsd_auth.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <event.h>
#include <fcntl.h>
#include <login_cap.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <syslog.h>

#include "ldapd.h"
#include "log.h"

void		 usage(void);
void		 ldapd_sig_handler(int fd, short why, void *data);
void		 ldapd_sigchld_handler(int sig, short why, void *data);
static void	 ldapd_imsgev(struct imsgev *iev, int code, struct imsg *imsg);
static void	 ldapd_needfd(struct imsgev *iev);
static void	 ldapd_auth_request(struct imsgev *iev, struct imsg *imsg);
static void	 ldapd_open_request(struct imsgev *iev, struct imsg *imsg);
static void	 ldapd_log_verbose(struct imsg *imsg);
static pid_t	 start_child(enum ldapd_process, char *, int, int, int,
		    char *, char *);

struct ldapd_stats	 stats;
pid_t			 ldape_pid;
char			*datadir = DATADIR;

void
usage(void)
{
	extern char	*__progname;

	fprintf(stderr, "usage: %s [-dnv] [-D macro=value] "
	    "[-f file] [-r directory] [-s file]\n", __progname);
	exit(1);
}

void
ldapd_sig_handler(int sig, short why, void *data)
{
	log_info("ldapd: got signal %d", sig);
	if (sig == SIGINT || sig == SIGTERM)
		event_loopexit(NULL);
}

void
ldapd_sigchld_handler(int sig, short why, void *data)
{
	pid_t		 pid;
	int		 status;

	while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
		if (pid == -1) {
			if (errno == EINTR)
				continue;
			if (errno != ECHILD)
				log_warn("waitpid");
			break;
		}

		if (WIFEXITED(status))
			log_debug("child %d exited with status %d",
			    pid, WEXITSTATUS(status));
		else if (WIFSIGNALED(status))
			log_debug("child %d exited due to signal %d",
			    pid, WTERMSIG(status));
		else
			log_debug("child %d terminated abnormally", pid);

		if (pid == ldape_pid) {
			log_info("ldapd: lost ldap server");
			event_loopexit(NULL);
			break;
		}
	}
}

int
main(int argc, char *argv[])
{
	int			 c;
	int			 debug = 0, verbose = 0, eflag = 0;
	int			 configtest = 0;
	int			 pipe_parent2ldap[2];
	char			*conffile = CONFFILE;
	char			*csockpath = LDAPD_SOCKET;
	char			*saved_argv0;
	struct imsgev		*iev_ldape;
	struct event		 ev_sigint;
	struct event		 ev_sigterm;
	struct event		 ev_sigchld;
	struct event		 ev_sighup;
	struct stat		 sb;

	log_init(1, LOG_DAEMON);	/* log to stderr until daemonized */

	saved_argv0 = argv[0];
	if (saved_argv0 == NULL)
		saved_argv0 = "ldapd";

	while ((c = getopt(argc, argv, "dhvD:f:nr:s:E")) != -1) {

		switch (c) {
		case 'd':
			debug = 1;
			break;
		case 'D':
			if (cmdline_symset(optarg) < 0) {
				warnx("could not parse macro definition %s",
				    optarg);
			}
			break;
		case 'f':
			conffile = optarg;
			break;
		case 'h':
			usage();
			/* NOTREACHED */
		case 'n':
			configtest = 1;
			break;
		case 'r':
			datadir = optarg;
			break;
		case 's':
			csockpath = optarg;
			break;
		case 'v':
			verbose++;
			break;
		case 'E':
			eflag = 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	argc -= optind;
	if (argc > 0)
		usage();

	/* check for root privileges  */
	if (geteuid())
		errx(1, "need root privileges");

	/* check for ldapd user */
	if (getpwnam(LDAPD_USER) == NULL)
		errx(1, "unknown user %s", LDAPD_USER);

	log_setverbose(verbose);
	stats.started_at = time(0);

	if (parse_config(conffile) != 0)
		exit(2);

	if (configtest) {
		fprintf(stderr, "configuration ok\n");
		exit(0);
	}

	log_init(debug, LOG_DAEMON);

	if (eflag)
		ldape(debug, verbose, csockpath);

	if (stat(datadir, &sb) == -1)
		err(1, "%s", datadir);
	if (!S_ISDIR(sb.st_mode))
		errx(1, "%s is not a directory", datadir);

	if (!debug) {
		if (daemon(1, 0) == -1)
			err(1, "failed to daemonize");
	}

	log_info("startup");

	if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
	    PF_UNSPEC, pipe_parent2ldap) != 0)
		fatal("socketpair");
	
	ldape_pid = start_child(PROC_LDAP_SERVER, saved_argv0,
	    pipe_parent2ldap[1], debug, verbose, csockpath, conffile);

	ldap_loginit("auth", debug, verbose);
	setproctitle("auth");
	event_init();

	signal_set(&ev_sigint, SIGINT, ldapd_sig_handler, NULL);
	signal_set(&ev_sigterm, SIGTERM, ldapd_sig_handler, NULL);
	signal_set(&ev_sigchld, SIGCHLD, ldapd_sigchld_handler, NULL);
	signal_set(&ev_sighup, SIGHUP, ldapd_sig_handler, NULL);
	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);
	signal_add(&ev_sigchld, NULL);
	signal_add(&ev_sighup, NULL);
	signal(SIGPIPE, SIG_IGN);

	if ((iev_ldape = calloc(1, sizeof(struct imsgev))) == NULL)
		fatal("calloc");
	imsgev_init(iev_ldape, pipe_parent2ldap[0], NULL, ldapd_imsgev,
	    ldapd_needfd);

	if (unveil(_PATH_NOLOGIN, "r") == -1)
		err(1, "unveil %s", _PATH_NOLOGIN);
	if (unveil(_PATH_LOGIN_CONF, "r") == -1)
		err(1, "unveil %s", _PATH_LOGIN_CONF);
	if (unveil(_PATH_LOGIN_CONF ".db", "r") == -1)
		err(1, "unveil %s.db", _PATH_LOGIN_CONF);
	if (unveil(_PATH_AUTHPROGDIR, "x") == -1)
		err(1, "unveil %s", _PATH_AUTHPROGDIR);
	if (unveil(datadir, "rw") == -1)
		err(1, "unveil %s", datadir);
	if (unveil(NULL, NULL) == -1)
		err(1, "unveil");

	if (pledge("stdio rpath wpath cpath getpw sendfd proc exec",
	    NULL) == -1)
		err(1, "pledge");

	event_dispatch();

	log_debug("ldapd: exiting");

	return 0;
}

static void
ldapd_imsgev(struct imsgev *iev, int code, struct imsg *imsg)
{
	switch (code) {
	case IMSGEV_IMSG:
		log_debug("%s: got imsg %d on fd %d",
		    __func__, imsg->hdr.type, iev->ibuf.fd);
		switch (imsg->hdr.type) {
		case IMSG_LDAPD_AUTH:
			ldapd_auth_request(iev, imsg);
			break;
		case IMSG_CTL_LOG_VERBOSE:
			ldapd_log_verbose(imsg);
			break;
		case IMSG_LDAPD_OPEN:
			ldapd_open_request(iev, imsg);
			break;
		default:
			log_debug("%s: unexpected imsg %d",
			    __func__, imsg->hdr.type);
			break;
		}
		break;
	case IMSGEV_EREAD:
	case IMSGEV_EWRITE:
	case IMSGEV_EIMSG:
		fatal("imsgev read/write error");
		break;
	case IMSGEV_DONE:
		event_loopexit(NULL);
		break;
	}
}

static void
ldapd_needfd(struct imsgev *iev)
{
	fatal("should never need an fd for parent messages");
}

static int
ldapd_auth_classful(char *name, char *password)
{
	login_cap_t		*lc = NULL;
	char			*class = NULL, *style = NULL;
	auth_session_t		*as;

	if ((class = strchr(name, '#')) == NULL) {
		log_debug("regular auth");
		return auth_userokay(name, NULL, "auth-ldap", password);
	}
	*class++ = '\0';

	if ((lc = login_getclass(class)) == NULL) {
		log_debug("login_getclass(%s) for [%s] failed", class, name);
		return 0;
	}
	if ((style = login_getstyle(lc, style, "auth-ldap")) == NULL) {
		log_debug("login_getstyle() for [%s] failed", name);
		login_close(lc);
		return 0;
	}
	if (password) {
		if ((as = auth_open()) == NULL) {
			login_close(lc);
			return 0;
		}
		auth_setitem(as, AUTHV_SERVICE, "response");
		auth_setdata(as, "", 1);
		auth_setdata(as, password, strlen(password) + 1);
		explicit_bzero(password, strlen(password));
	} else
		as = NULL;

	as = auth_verify(as, style, name, lc->lc_class, (char *)NULL);
	login_close(lc);
	return (as != NULL ? auth_close(as) : 0);
}

static void
ldapd_auth_request(struct imsgev *iev, struct imsg *imsg)
{
	struct auth_req		*areq = imsg->data;
	struct auth_res		 ares;

	if (imsg->hdr.len != sizeof(*areq) + IMSG_HEADER_SIZE)
		fatal("invalid size of auth request");

	/* make sure name and password are null-terminated */
	areq->name[sizeof(areq->name) - 1] = '\0';
	areq->password[sizeof(areq->password) - 1] = '\0';

	log_debug("authenticating [%s]", areq->name);
	ares.ok = ldapd_auth_classful(areq->name, areq->password);
	ares.fd = areq->fd;
	ares.msgid = areq->msgid;
	memset(areq, 0, sizeof(*areq));
	imsgev_compose(iev, IMSG_LDAPD_AUTH_RESULT, 0, 0, -1, &ares,
	    sizeof(ares));
}

static void
ldapd_log_verbose(struct imsg *imsg)
{
	int	 verbose;

	if (imsg->hdr.len != sizeof(verbose) + IMSG_HEADER_SIZE)
		fatal("invalid size of log verbose request");

	bcopy(imsg->data, &verbose, sizeof(verbose));
	log_setverbose(verbose);
}

static void
ldapd_open_request(struct imsgev *iev, struct imsg *imsg)
{
	struct open_req		*oreq = imsg->data;
	int			 oflags, fd;

	if (imsg->hdr.len != sizeof(*oreq) + IMSG_HEADER_SIZE)
		fatal("invalid size of open request");

	/* make sure path is null-terminated */
	oreq->path[PATH_MAX] = '\0';

	if (strncmp(oreq->path, datadir, strlen(datadir)) != 0) {
		log_warnx("refusing to open file %s", oreq->path);
		fatal("ldape sent invalid open request");
	}

	if (oreq->rdonly)
		oflags = O_RDONLY;
	else
		oflags = O_RDWR | O_CREAT | O_APPEND;

	log_debug("opening [%s]", oreq->path);
	fd = open(oreq->path, oflags | O_NOFOLLOW, 0600);
	if (fd == -1)
		log_warn("%s", oreq->path);

	imsgev_compose(iev, IMSG_LDAPD_OPEN_RESULT, 0, 0, fd, oreq,
	    sizeof(*oreq));
}

static pid_t
start_child(enum ldapd_process p, char *argv0, int fd, int debug,
    int verbose, char *csockpath, char *conffile)
{
	char		*argv[11];
	int		 argc = 0;
	pid_t		 pid;

	switch (pid = fork()) {
	case -1:
		fatal("cannot fork");
	case 0:
		break;
	default:
		close(fd);
		return (pid);
	}

	if (fd != PROC_PARENT_SOCK_FILENO) {
		if (dup2(fd, PROC_PARENT_SOCK_FILENO) == -1)
			fatal("cannot setup imsg fd");
	} else if (fcntl(fd, F_SETFD, 0) == -1)
		fatal("cannot setup imsg fd");

	argv[argc++] = argv0;
	switch (p) {
	case PROC_MAIN_AUTH:
		fatalx("Can not start main process");
	case PROC_LDAP_SERVER:
		argv[argc++] = "-E";
		break;
	}
	if (debug)
		argv[argc++] = "-d";
	if (verbose >= 3)
		argv[argc++] = "-vvv";
	else if (verbose == 2)
		argv[argc++] = "-vv";
	else if (verbose == 1)
		argv[argc++] = "-v";
	if (csockpath) {
		argv[argc++] = "-s";
		argv[argc++] = csockpath;
	}
	if (conffile) {
		argv[argc++] = "-f";
		argv[argc++] = conffile;
	}
	if (datadir) {
		argv[argc++] = "-r";
		argv[argc++] = datadir;
	}

	argv[argc++] = NULL;

	execvp(argv0, argv);
	fatal("execvp");
}