summaryrefslogtreecommitdiff
path: root/usr.sbin/ldapd/ldape.c
blob: a663cf88f29bbd7585460b3d831c4b27c2ef6514 (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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*	$OpenBSD: ldape.c,v 1.9 2010/06/30 17:16:09 martinh 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/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>

#include <err.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "ldapd.h"

void			 ldape_sig_handler(int fd, short why, void *data);
void			 ldape_dispatch_ldapd(int fd, short event, void *ptr);
static void		 ldape_auth_result(struct imsg *imsg);
static void		 ldape_open_result(struct imsg *imsg);

int			 ldap_starttls(struct request *req);
void			 send_ldap_extended_response(struct conn *conn,
				int msgid, unsigned long type,
				long long result_code,
				const char *extended_oid);

struct imsgev		*iev_ldapd;
struct control_sock	 csock;

void
ldape_sig_handler(int sig, short why, void *data)
{
	log_debug("ldape: got signal %d", sig);
	if (sig == SIGCHLD) {
		for (;;) {
			pid_t	 pid;
			int	 status;

			pid = waitpid(WAIT_ANY, &status, WNOHANG);
			if (pid <= 0)
				break;
		}
		return;
	}

	event_loopexit(NULL);
}

void
send_ldap_extended_response(struct conn *conn, int msgid, unsigned long type,
    long long result_code, const char *extended_oid)
{
	int			 rc;
	struct ber_element	*root, *elm;
	void			*buf;

	log_debug("sending response %u with result %lld", type, result_code);

	if ((root = ber_add_sequence(NULL)) == NULL)
		goto fail;

	elm = ber_printf_elements(root, "d{tEss",
	    msgid, BER_CLASS_APP, type, result_code, "", "");
	if (elm == NULL)
		goto fail;

	if (extended_oid)
		elm = ber_add_string(elm, extended_oid);

	rc = ber_write_elements(&conn->ber, root);
	ber_free_elements(root);

	if (rc < 0)
		log_warn("failed to create ldap result");
	else {
		ber_get_writebuf(&conn->ber, &buf);
		if (bufferevent_write(conn->bev, buf, rc) != 0)
			log_warn("failed to send ldap result");
	}

	return;
fail:
	if (root)
		ber_free_elements(root);
}

int
ldap_refer(struct request *req, const char *basedn, struct search *search,
    struct referrals *refs)
{
	struct ber_element	*root, *elm, *ref_root = NULL;
	struct referral		*ref;
	long long		 result_code = LDAP_REFERRAL;
	unsigned long		 type;
	int			 rc;
	void			*buf;
	char			*url, *scope_str = NULL;

	if (req->type == LDAP_REQ_SEARCH)
		type = LDAP_RES_SEARCH_RESULT;
	else
		type = req->type + 1;

	if (search != NULL) {
		if (search->scope != LDAP_SCOPE_SUBTREE)
			scope_str = "base";
		else
			scope_str = "sub";
	}

	log_debug("sending referral in response %u on msgid %i", type, req->msgid);

	if ((root = ber_add_sequence(NULL)) == NULL)
		goto fail;

	if ((elm = ref_root = ber_add_sequence(NULL)) == NULL)
		goto fail;
	ber_set_header(ref_root, BER_CLASS_CONTEXT, LDAP_REQ_SEARCH);
	SLIST_FOREACH(ref, refs, next) {
		if (search != NULL)
			asprintf(&url, "%s/%s??%s", ref->url, basedn,
			    scope_str);
		else
			asprintf(&url, "%s/%s", ref->url, basedn);
		if (url == NULL) {
			log_warn("asprintf");
			goto fail;
		}
		log_debug("adding referral '%s'", url);
		elm = ber_add_string(elm, url);
		free(url);
		if (elm == NULL)
			goto fail;
	}

	elm = ber_printf_elements(root, "d{tEsse",
	    req->msgid, BER_CLASS_APP, type, result_code, "", "", ref_root);
	if (elm == NULL)
		goto fail;
	ref_root = NULL;

	rc = ber_write_elements(&req->conn->ber, root);
	ber_free_elements(root);

	if (rc < 0)
		log_warn("failed to create ldap result");
	else {
		ber_get_writebuf(&req->conn->ber, &buf);
		if (bufferevent_write(req->conn->bev, buf, rc) != 0)
			log_warn("failed to send ldap result");
	}

	request_free(req);
	return LDAP_REFERRAL;

fail:
	if (root != NULL)
		ber_free_elements(root);
	if (ref_root != NULL)
		ber_free_elements(ref_root);
	request_free(req);
	return LDAP_REFERRAL;
}

void
send_ldap_result(struct conn *conn, int msgid, unsigned long type,
    long long result_code)
{
	send_ldap_extended_response(conn, msgid, type, result_code, NULL);
}

int
ldap_respond(struct request *req, int code)
{
	if (code >= 0)
		send_ldap_result(req->conn, req->msgid, req->type + 1, code);
	request_free(req);
	return code;
}

int
ldap_abandon(struct request *req)
{
	long long	 msgid;
	struct search	*search;

	if (ber_scanf_elements(req->op, "i", &msgid) != 0) {
		request_free(req);
		return -1;	/* protocol error, but don't respond */
	}

	TAILQ_FOREACH(search, &req->conn->searches, next) {
		if (search->req->msgid == msgid) {
			/* unlinks the search from conn->searches */
			search_close(search);
			break;
		}
	}
	request_free(req);
	return -1;
}

int
ldap_unbind(struct request *req)
{
	log_debug("current bind dn = %s", req->conn->binddn);
	conn_disconnect(req->conn);
	request_free(req);
	return -1;		/* don't send any response */
}

int
ldap_starttls(struct request *req)
{
	if ((req->conn->listener->flags & F_STARTTLS) == 0) {
		log_debug("StartTLS not configured for this connection");
		return LDAP_OPERATIONS_ERROR;
	}

	req->conn->s_flags |= F_STARTTLS;
	return LDAP_SUCCESS;
}

int
ldap_extended(struct request *req)
{
	int			 i, rc = LDAP_PROTOCOL_ERROR;
	char			*oid = NULL;
	struct ber_element	*ext_val = NULL;
	struct {
		const char	*oid;
		int (*fn)(struct request *);
	} extended_ops[] = {
		{ "1.3.6.1.4.1.1466.20037", ldap_starttls },
		{ NULL }
	};

	if (ber_scanf_elements(req->op, "{se", &oid, &ext_val) != 0)
		goto done;

	log_debug("got extended operation %s", oid);
	req->op = ext_val;

	for (i = 0; extended_ops[i].oid != NULL; i++) {
		if (strcmp(oid, extended_ops[i].oid) == 0) {
			rc = extended_ops[i].fn(req);
			break;
		}
	}

	if (extended_ops[i].fn == NULL)
		log_warnx("unimplemented extended operation %s", oid);

done:
	send_ldap_extended_response(req->conn, req->msgid, LDAP_RES_EXTENDED,
	    rc, oid);

	request_free(req);
	return 0;
}

pid_t
ldape(struct passwd *pw, char *csockpath, int pipe_parent2ldap[2])
{
	int			 on = 1;
	pid_t			 pid;
	struct namespace	*ns;
	struct listener		*l;
	struct sockaddr_un	*sun = NULL;
	struct event		 ev_sigint;
	struct event		 ev_sigterm;
	struct event		 ev_sigchld;
	struct event		 ev_sighup;
	char			 host[128];

	TAILQ_INIT(&conn_list);

	pid = fork();
	if (pid < 0)
		fatal("ldape: fork");
	if (pid > 0)
		return pid;

	setproctitle("ldap server");
	event_init();

	signal_set(&ev_sigint, SIGINT, ldape_sig_handler, NULL);
	signal_set(&ev_sigterm, SIGTERM, ldape_sig_handler, NULL);
	signal_set(&ev_sigchld, SIGCHLD, ldape_sig_handler, NULL);
	signal_set(&ev_sighup, SIGHUP, ldape_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);

	close(pipe_parent2ldap[0]);

	/* Initialize parent imsg events. */
	if ((iev_ldapd = calloc(1, sizeof(struct imsgev))) == NULL)
		fatal("calloc");
	imsg_init(&iev_ldapd->ibuf, pipe_parent2ldap[1]);
	iev_ldapd->handler = ldape_dispatch_ldapd;
	imsg_event_add(iev_ldapd);

	/* Initialize control socket. */
	bzero(&csock, sizeof(csock));
	csock.cs_name = csockpath;
	control_init(&csock);
	control_listen(&csock);
	TAILQ_INIT(&ctl_conns);

	/* Initialize LDAP listeners.
	 */
	TAILQ_FOREACH(l, &conf->listeners, entry) {
		l->fd = socket(l->ss.ss_family, SOCK_STREAM, 0);
		if (l->fd < 0)
			fatal("ldape: socket");

		setsockopt(l->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

		if (l->ss.ss_family == AF_UNIX) {
			sun = (struct sockaddr_un *)&l->ss;
			log_info("listening on %s", sun->sun_path);
			if (unlink(sun->sun_path) == -1 && errno != ENOENT)
				fatal("ldape: unlink");
		} else {
			print_host(&l->ss, host, sizeof(host));
			log_info("listening on %s:%d", host, ntohs(l->port));
		}

		if (bind(l->fd, (struct sockaddr *)&l->ss, l->ss.ss_len) != 0)
			fatal("ldape: bind");
		if (listen(l->fd, 20) != 0)
			fatal("ldape: listen");

		if (l->ss.ss_family == AF_UNIX) {
			mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
			if (chmod(sun->sun_path, mode) == -1) {
				unlink(sun->sun_path);
				fatal("ldape: chmod");
			}
		}

		fd_nonblock(l->fd);

		event_set(&l->ev, l->fd, EV_READ|EV_PERSIST, conn_accept, l);
		event_add(&l->ev, NULL);

		ssl_setup(conf, l);
	}

	TAILQ_FOREACH(ns, &conf->namespaces, next) {
		if (!namespace_has_referrals(ns) && namespace_open(ns) != 0)
			fatal(ns->suffix);
	}

	if (pw != NULL) {
		if (chroot(pw->pw_dir) == -1)
			fatal("chroot");
		if (chdir("/") == -1)
			fatal("chdir(\"/\")");

		if (setgroups(1, &pw->pw_gid) ||
		    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
		    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
			fatal("cannot drop privileges");
	}

	log_debug("ldape: entering event loop");
	event_dispatch();

	while ((ns = TAILQ_FIRST(&conf->namespaces)) != NULL)
		namespace_remove(ns);

	control_cleanup(&csock);

	log_info("ldape: exiting");
	_exit(0);
}

void
ldape_dispatch_ldapd(int fd, short event, void *ptr)
{
	struct imsgev		*iev = ptr;
	struct imsgbuf		*ibuf;
	struct imsg		 imsg;
	ssize_t			 n;

	if (imsg_event_handle(iev, event) != 0)
		return;

	ibuf = &iev->ibuf;
	for (;;) {
		if ((n = imsg_get(ibuf, &imsg)) == -1)
			fatal("ldape_dispatch_ldapd: imsg_read error");
		if (n == 0)
			break;

		switch (imsg.hdr.type) {
		case IMSG_LDAPD_AUTH_RESULT:
			ldape_auth_result(&imsg);
			break;
		case IMSG_LDAPD_OPEN_RESULT:
			ldape_open_result(&imsg);
			break;
		default:
			log_debug("ldape_dispatch_ldapd: unexpected imsg %d",
			    imsg.hdr.type);
			break;
		}
		imsg_free(&imsg);
	}
	imsg_event_add(iev);
}

static void
ldape_auth_result(struct imsg *imsg)
{
	struct conn		*conn;
	struct auth_res		*ares = imsg->data;

	log_debug("authentication on conn %i/%lld = %d", ares->fd, ares->msgid,
	    ares->ok);
	conn = conn_by_fd(ares->fd);
	if (conn->bind_req != NULL && conn->bind_req->msgid == ares->msgid)
		ldap_bind_continue(conn, ares->ok);
	else
		log_warnx("spurious auth result");
}

static void
ldape_open_result(struct imsg *imsg)
{
	struct namespace	*ns;
	struct open_req		*oreq = imsg->data;

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

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

	log_debug("open(%s) returned fd %i", oreq->path, imsg->fd);

	TAILQ_FOREACH(ns, &conf->namespaces, next) {
		if (namespace_has_referrals(ns))
			continue;
		if (strcmp(oreq->path, ns->data_path) == 0) {
			namespace_set_data_fd(ns, imsg->fd);
			break;
		}
		if (strcmp(oreq->path, ns->indx_path) == 0) {
			namespace_set_indx_fd(ns, imsg->fd);
			break;
		}
	}

	if (ns == NULL) {
		log_warnx("spurious open result");
		close(imsg->fd);
	} else
		namespace_queue_schedule(ns);
}