summaryrefslogtreecommitdiff
path: root/usr.sbin/bind/lib/isc/unix/privsep.c
blob: 8e186436b87560a6fde225c83db036c89c9ee10b (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
/*	$OpenBSD: privsep.c,v 1.2 2004/03/19 20:36:28 canacar Exp $	*/

/*
 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
 * Copyright (c) 2004 Can Erkin Acar <canacar@openbsd.org>
 * Copyright (c) 2003 Anil Madhavapeddy <anil@recoil.org>
 *
 * 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/types.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <netinet/in.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>

#include <isc/buffer.h>
#include <isc/mem.h>
#include <isc/privsep.h>
#include <isc/string.h>
#include <isc/util.h>

enum priv_state {
	STATE_RUN,
	STATE_QUIT
};

/* allowed privileged port numbers */
#define		NAMED_PORT_DEFAULT	53
#define		RNDC_PORT_DEFAULT	953
#define		LWRES_PORT_DEFAULT	921

int		debug_level = LOG_DEBUG;
int		log_stderr = 1;
int		priv_fd = -1;

static volatile	pid_t child_pid = -1;
static volatile sig_atomic_t cur_state = STATE_RUN;

static int	check_bind(const struct sockaddr *, socklen_t);
static void	fatal(const char *);
static void	logmsg(int, const char *, ...);
static void	parent_bind(int);
static void	sig_pass_to_chld(int);
static void	sig_got_chld(int);
static void	write_command(int, int);

int
isc_priv_init(int lstderr)
{
	int i, socks[2], cmd;

	logmsg(LOG_NOTICE, "Starting privilege seperation");

	log_stderr = lstderr;

	/* Create sockets */
	if (socketpair(AF_LOCAL, SOCK_STREAM, PF_UNSPEC, socks) == -1)
		fatal("socketpair() failed");

	switch (child_pid = fork()) {
	case -1:
		fatal("failed to fork() for privsep");
	case 0:
		close(socks[0]);
		priv_fd = socks[1];
		return (0);
	default:
		break;
	}

	for (i = 1; i < _NSIG; i++)
		signal(i, SIG_DFL);

	signal(SIGALRM, sig_pass_to_chld);
	signal(SIGTERM, sig_pass_to_chld);
	signal(SIGHUP,  sig_pass_to_chld);
	signal(SIGINT,  sig_pass_to_chld);
	signal(SIGCHLD, sig_got_chld);

	/* Father - close unneeded sockets */
	for (i = STDERR_FILENO + 1; i < socks[0]; i++)
		close(i);
	closefrom(socks[0] + 1);

	setproctitle("[priv]");

	while (cur_state != STATE_QUIT) {
		if (may_read(socks[0], &cmd, sizeof(int)))
			break;
		switch (cmd) {
		case PRIV_BIND:
			parent_bind(socks[0]);
			break;
		default:
			logmsg(LOG_ERR, "[priv]: unknown command %d", cmd);
			_exit(1);
			/* NOTREACHED */
		}
	}

	_exit(0);
}

int
isc_drop_privs(const char *username)
{
	struct passwd *pw;
	
	if ((pw = getpwnam(username)) == NULL) {
		logmsg(LOG_ERR, "unknown user %s", username);
		exit(1);
	}

	if (chroot(pw->pw_dir) == -1)
		fatal("chroot failed");

	if (chdir("/"))
		fatal("chdir failed");

	if (setgroups(1, &pw->pw_gid) ||
	    setegid(pw->pw_gid) || setgid(pw->pw_gid) ||
	    seteuid(pw->pw_uid) || setuid(pw->pw_uid))
		fatal("can't drop privileges");

	endpwent();
	return (0);
}

static int
check_bind(const struct sockaddr *sa, socklen_t salen)
{
	const char *pname = child_pid ? "[priv]" : "[child]";
	in_port_t port;

	if (sa == NULL) {
		logmsg(LOG_ERR, "%s: NULL address", pname);
		return (1);
	}

	if (sa->sa_len != salen) {
		logmsg(LOG_ERR, "%s: length mismatch: %d %d", pname,
		    (int) sa->sa_len, (int) salen);
		return (1);
	}

	switch (sa->sa_family) {
	case AF_INET:
		if (salen != sizeof(struct sockaddr_in)) {
			logmsg(LOG_ERR, "%s: Invalid inet address length",
			    pname);
			return (1);
		}
		port = ((const struct sockaddr_in *)sa)->sin_port;
		break;
	case AF_INET6:
		if (salen != sizeof(struct sockaddr_in6)) {
			logmsg(LOG_ERR, "%s: Invalid inet6 address length",
			    pname);
			return (1);
		}
		port = ((const struct sockaddr_in6 *)sa)->sin6_port;
		break;
	default:
		logmsg(LOG_ERR, "%s: unknown address family", pname);
		return (1);
	}

	port = ntohs(port);

	if (port != NAMED_PORT_DEFAULT && port != RNDC_PORT_DEFAULT &&
	    port != LWRES_PORT_DEFAULT) {
		if (port || child_pid)
			logmsg(LOG_ERR, "%s: disallowed port %u", pname, port);
		return (1);
	}

	return (0);
}
	
static void
parent_bind(int fd)
{
	int sock, status;
	struct sockaddr_storage ss;
	socklen_t sslen;
	int er;

	logmsg(LOG_DEBUG, "[priv]: msg PRIV_BIND received");

	sock = receive_fd(fd);
	must_read(fd, &sslen, sizeof(sslen));
	if (sslen == 0 || sslen > sizeof(ss))
		_exit(1);

	must_read(fd, &ss, sslen);

	if (check_bind((struct sockaddr *) &ss, sslen))
		_exit(1);

	status = bind(sock, (struct sockaddr *)&ss, sslen);
	er = errno;
	must_write(fd, &er, sizeof(er));
	must_write(fd, &status, sizeof(status));

	close(sock);
}

/* Bind to allowed privileged ports using privsep, or try to bind locally */
int
isc_priv_bind(int fd, struct sockaddr *sa, socklen_t salen)
{
	int status, er;

	if (priv_fd < 0)
		errx(1, "%s called from privileged portion", __func__);

	if (check_bind(sa, salen)) {
		logmsg(LOG_DEBUG, "Binding locally");
		status = bind(fd, sa, salen);
	} else {
		logmsg(LOG_DEBUG, "Binding privsep");
		write_command(priv_fd, PRIV_BIND);
		send_fd(priv_fd, fd);
		must_write(priv_fd, &salen, sizeof(salen));
		must_write(priv_fd, sa, salen);
		must_read(priv_fd, &er, sizeof(er));
		must_read(priv_fd, &status, sizeof(status));
		errno = er;
	}

	return (status);
}

/* If priv parent gets a TERM or HUP, pass it through to child instead */
static void
sig_pass_to_chld(int sig)
{
	int save_err = errno;

	if (child_pid != -1)
		kill(child_pid, sig);
	errno = save_err;
}


/* When child dies, move into the shutdown state */
static void
sig_got_chld(int sig)
{
	pid_t pid;
	int status;
	int save_err = errno;

	do {
		pid = waitpid(child_pid, &status, WNOHANG);
	} while (pid == -1 && errno == EINTR);

	if (pid == child_pid && (WIFEXITED(status) || WIFSIGNALED(status)) &&
	    cur_state < STATE_QUIT)
		cur_state = STATE_QUIT;

	errno = save_err;
}

/* Read all data or return 1 for error.  */
int
may_read(int fd, void *buf, size_t n)
{
	char *s = buf;
	ssize_t res;
	size_t pos = 0;

	while (n > pos) {
		res = read(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			return (1);
		default:
			pos += res;
		}
	}
	return (0);
}

/* Read data with the assertion that it all must come through, or
 * else abort the process.  Based on atomicio() from openssh. */
void
must_read(int fd, void *buf, size_t n)
{
	char *s = buf;
	ssize_t res;
	size_t pos = 0;

	while (n > pos) {
		res = read(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			_exit(0);
		default:
			pos += res;
		}
	}
}

/* Write data with the assertion that it all has to be written, or
 * else abort the process.  Based on atomicio() from openssh. */
void
must_write(int fd, const void *buf, size_t n)
{
	const char *s = buf;
	ssize_t res;
	size_t pos = 0;

	while (n > pos) {
		res = write(fd, s + pos, n - pos);
		switch (res) {
		case -1:
			if (errno == EINTR || errno == EAGAIN)
				continue;
		case 0:
			_exit(0);
		default:
			pos += res;
		}
	}
}


/* write a command to the peer */
static void
write_command(int fd, int cmd)
{
	must_write(fd, &cmd, sizeof(cmd));
}

static void
logmsg(int pri, const char *message, ...)
{
	va_list ap;
	if (pri > debug_level)
		return;

	va_start(ap, message);
	if (log_stderr) {
		vfprintf(stderr, message, ap);
		fprintf(stderr, "\n");
	} else
		vsyslog(pri, message, ap);

	va_end(ap);
}

/* from bgpd */
static void
fatal(const char *emsg)
{
	const char *pname;

	if (child_pid == -1)
		pname = "bind";
	else if (child_pid)
		pname = "bind [priv]";
	else
		pname = "bind [child]";

	if (emsg == NULL)
		logmsg(LOG_CRIT, "fatal in %s: %s", pname, strerror(errno));
	else
		if (errno)
			logmsg(LOG_CRIT, "fatal in %s: %s: %s",
			    pname, emsg, strerror(errno));
		else
			logmsg(LOG_CRIT, "fatal in %s: %s", pname, emsg);

	if (child_pid)
		_exit(1);
	else				/* parent copes via SIGCHLD */
		exit(1);
}