os.c 19.4 KB
Newer Older
Bob Halley's avatar
add  
Bob Halley committed
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4 5 6
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 8 9
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
Bob Halley's avatar
add  
Bob Halley committed
10 11
 */

12
/*! \file */
David Lawrence's avatar
David Lawrence committed
13

Bob Halley's avatar
add  
Bob Halley committed
14
#include <config.h>
15
#include <stdarg.h>
16
#include <stdbool.h>
Bob Halley's avatar
add  
Bob Halley committed
17

Mark Andrews's avatar
Mark Andrews committed
18
#include <sys/types.h>	/* dev_t FreeBSD 2.1 */
Bob Halley's avatar
Bob Halley committed
19
#include <sys/stat.h>
20 21 22
#ifdef HAVE_UNAME
#include <sys/utsname.h>
#endif
Bob Halley's avatar
add  
Bob Halley committed
23

24
#include <ctype.h>
Bob Halley's avatar
add  
Bob Halley committed
25
#include <errno.h>
26
#include <grp.h>
Bob Halley's avatar
Bob Halley committed
27
#include <fcntl.h>
28
#include <pwd.h>
29 30
#include <stdio.h>
#include <stdlib.h>
31
#include <signal.h>
32
#include <syslog.h>
Mark Andrews's avatar
Mark Andrews committed
33 34 35
#ifdef HAVE_TZSET
#include <time.h>
#endif
36
#include <unistd.h>
Bob Halley's avatar
add  
Bob Halley committed
37

38
#include <isc/buffer.h>
39
#include <isc/file.h>
40
#include <isc/print.h>
41
#include <isc/resource.h>
42
#include <isc/result.h>
43
#include <isc/strerr.h>
44
#include <isc/string.h>
Bob Halley's avatar
add  
Bob Halley committed
45

46
#include <named/globals.h>
Bob Halley's avatar
add  
Bob Halley committed
47 48
#include <named/main.h>
#include <named/os.h>
49
#ifdef HAVE_LIBSCF
Evan Hunt's avatar
Evan Hunt committed
50
#include <named/smf_globals.h>
51
#endif
Bob Halley's avatar
add  
Bob Halley committed
52

Bob Halley's avatar
Bob Halley committed
53
static char *pidfile = NULL;
54
static char *lockfile = NULL;
55
static int devnullfd = -1;
56
static int singletonfd = -1;
57

58 59 60 61
#ifndef ISC_FACILITY
#define ISC_FACILITY LOG_DAEMON
#endif

62
static struct passwd *runas_pw = NULL;
63
static bool done_setuid = false;
64
static int dfd[2] = { -1, -1 };
65

66
#ifdef HAVE_SYS_CAPABILITY_H
67

68 69
static bool non_root = false;
static bool non_root_caps = false;
70

71
#include <sys/capability.h>
72
#include <sys/prctl.h>
Bob Halley's avatar
Bob Halley committed
73

Bob Halley's avatar
add  
Bob Halley committed
74
static void
75
linux_setcaps(cap_t caps) {
76
	char strbuf[ISC_STRERRORSIZE];
Bob Halley's avatar
add  
Bob Halley committed
77

78
	if ((getuid() != 0 && !non_root_caps) || non_root) {
Bob Halley's avatar
add  
Bob Halley committed
79
		return;
80
	}
81
	if (cap_set_proc(caps) < 0) {
82
		strerror_r(errno, strbuf, sizeof(strbuf));
83
		named_main_earlyfatal("cap_set_proc() failed: %s:"
84 85 86
				      " please ensure that the capset kernel"
				      " module is loaded.  see insmod(8)",
				      strbuf);
87
	}
Bob Halley's avatar
add  
Bob Halley committed
88
}
89

90 91
#define SET_CAP(flag) \
	do { \
92
		cap_flag_value_t curval; \
93
		capval = (flag); \
94
		err = cap_get_flag(curcaps, capval, CAP_PERMITTED, &curval); \
95 96 97
		if (err != -1 && curval) { \
			err = cap_set_flag(caps, CAP_EFFECTIVE, 1, &capval, CAP_SET); \
			if (err == -1) { \
98
				strerror_r(errno, strbuf, sizeof(strbuf)); \
99
				named_main_earlyfatal("cap_set_proc failed: %s", strbuf); \
100 101 102 103
			} \
			\
			err = cap_set_flag(caps, CAP_PERMITTED, 1, &capval, CAP_SET); \
			if (err == -1) { \
104
				strerror_r(errno, strbuf, sizeof(strbuf)); \
105
				named_main_earlyfatal("cap_set_proc failed: %s", strbuf); \
106
			} \
107 108 109 110 111 112
		} \
	} while (0)
#define INIT_CAP \
	do { \
		caps = cap_init(); \
		if (caps == NULL) { \
113
			strerror_r(errno, strbuf, sizeof(strbuf)); \
114
			named_main_earlyfatal("cap_init failed: %s", strbuf); \
115
		} \
116 117
		curcaps = cap_get_proc(); \
		if (curcaps == NULL) { \
118
			strerror_r(errno, strbuf, sizeof(strbuf)); \
119
			named_main_earlyfatal("cap_get_proc failed: %s", strbuf); \
120 121 122 123 124 125
		} \
	} while (0)
#define FREE_CAP \
	{ \
		cap_free(caps); \
		cap_free(curcaps); \
126 127
	} while (0)

128 129
static void
linux_initialprivs(void) {
130
	cap_t caps;
131
	cap_t curcaps;
132 133 134
	cap_value_t capval;
	char strbuf[ISC_STRERRORSIZE];
	int err;
135

136
	/*%
Bob Halley's avatar
Bob Halley committed
137 138 139
	 * We don't need most privileges, so we drop them right away.
	 * Later on linux_minprivs() will be called, which will drop our
	 * capabilities to the minimum needed to run the server.
140
	 */
141
	INIT_CAP;
Bob Halley's avatar
Bob Halley committed
142 143 144 145

	/*
	 * We need to be able to bind() to privileged ports, notably port 53!
	 */
146
	SET_CAP(CAP_NET_BIND_SERVICE);
Bob Halley's avatar
Bob Halley committed
147 148 149 150

	/*
	 * We need chroot() initially too.
	 */
151
	SET_CAP(CAP_SYS_CHROOT);
Bob Halley's avatar
Bob Halley committed
152 153

	/*
154 155
	 * We need setuid() as the kernel supports keeping capabilities after
	 * setuid().
Bob Halley's avatar
Bob Halley committed
156
	 */
157
	SET_CAP(CAP_SETUID);
Bob Halley's avatar
Bob Halley committed
158

159 160 161
	/*
	 * Since we call initgroups, we need this.
	 */
162
	SET_CAP(CAP_SETGID);
163

164 165 166 167
	/*
	 * Without this, we run into problems reading a configuration file
	 * owned by a non-root user and non-world-readable on startup.
	 */
168
	SET_CAP(CAP_DAC_READ_SEARCH);
169

Bob Halley's avatar
Bob Halley committed
170 171 172
	/*
	 * XXX  We might want to add CAP_SYS_RESOURCE, though it's not
	 *      clear it would work right given the way linuxthreads work.
173 174 175
	 * XXXDCL But since we need to be able to set the maximum number
	 * of files, the stack size, data size, and core dump size to
	 * support named.conf options, this is now being added to test.
Bob Halley's avatar
Bob Halley committed
176
	 */
177
	SET_CAP(CAP_SYS_RESOURCE);
Bob Halley's avatar
Bob Halley committed
178

179 180 181 182 183 184
	/*
	 * We need to be able to set the ownership of the containing
	 * directory of the pid file when we create it.
	 */
	SET_CAP(CAP_CHOWN);

185
	linux_setcaps(caps);
186 187

	FREE_CAP;
188 189 190 191
}

static void
linux_minprivs(void) {
192
	cap_t caps;
193
	cap_t curcaps;
194 195 196
	cap_value_t capval;
	char strbuf[ISC_STRERRORSIZE];
	int err;
197

198
	INIT_CAP;
199
	/*%
Bob Halley's avatar
Bob Halley committed
200
	 * Drop all privileges except the ability to bind() to privileged
Bob Halley's avatar
Bob Halley committed
201
	 * ports.
Bob Halley's avatar
Bob Halley committed
202 203 204
	 *
	 * It's important that we drop CAP_SYS_CHROOT.  If we didn't, it
	 * chroot() could be used to escape from the chrooted area.
205 206
	 */

207
	SET_CAP(CAP_NET_BIND_SERVICE);
208

Mark Andrews's avatar
Mark Andrews committed
209 210 211 212 213 214 215
	/*
	 * XXX  We might want to add CAP_SYS_RESOURCE, though it's not
	 *      clear it would work right given the way linuxthreads work.
	 * XXXDCL But since we need to be able to set the maximum number
	 * of files, the stack size, data size, and core dump size to
	 * support named.conf options, this is now being added to test.
	 */
216
	SET_CAP(CAP_SYS_RESOURCE);
Mark Andrews's avatar
Mark Andrews committed
217

218
	linux_setcaps(caps);
219 220

	FREE_CAP;
221 222
}

Bob Halley's avatar
Bob Halley committed
223 224
static void
linux_keepcaps(void) {
225
	char strbuf[ISC_STRERRORSIZE];
226
	/*%
Bob Halley's avatar
Bob Halley committed
227 228 229 230 231
	 * Ask the kernel to allow us to keep our capabilities after we
	 * setuid().
	 */

	if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
232
		if (errno != EINVAL) {
233
			strerror_r(errno, strbuf, sizeof(strbuf));
234
			named_main_earlyfatal("prctl() failed: %s", strbuf);
235
		}
236
	} else {
237
		non_root_caps = true;
238
		if (getuid() != 0)
239
			non_root = true;
240
	}
Bob Halley's avatar
Bob Halley committed
241 242
}

243
#endif	/* HAVE_SYS_CAPABILITY_H */
244

Bob Halley's avatar
Bob Halley committed
245
static void
246
setup_syslog(const char *progname) {
Bob Halley's avatar
Bob Halley committed
247 248 249 250 251 252
	int options;

	options = LOG_PID;
#ifdef LOG_NDELAY
	options |= LOG_NDELAY;
#endif
253
	openlog(isc_file_basename(progname), options, ISC_FACILITY);
Bob Halley's avatar
Bob Halley committed
254
}
Bob Halley's avatar
add  
Bob Halley committed
255

256
void
257
named_os_init(const char *progname) {
258
	setup_syslog(progname);
259
#ifdef HAVE_SYS_CAPABILITY_H
260
	linux_initialprivs();
Bob Halley's avatar
add  
Bob Halley committed
261
#endif
262 263 264
#ifdef SIGXFSZ
	signal(SIGXFSZ, SIG_IGN);
#endif
Bob Halley's avatar
add  
Bob Halley committed
265 266
}

267
void
268
named_os_daemonize(void) {
Bob Halley's avatar
Bob Halley committed
269
	pid_t pid;
270
	char strbuf[ISC_STRERRORSIZE];
Bob Halley's avatar
Bob Halley committed
271

272
	if (pipe(dfd) == -1) {
273
		strerror_r(errno, strbuf, sizeof(strbuf));
274
		named_main_earlyfatal("pipe(): %s", strbuf);
275 276
	}

Bob Halley's avatar
Bob Halley committed
277
	pid = fork();
278
	if (pid == -1) {
279
		strerror_r(errno, strbuf, sizeof(strbuf));
280
		named_main_earlyfatal("fork(): %s", strbuf);
281
	}
282 283 284 285 286
	if (pid != 0) {
		int n;
		/*
		 * Wait for the child to finish loading for the first time.
		 * This would be so much simpler if fork() worked once we
Automatic Updater's avatar
Automatic Updater committed
287
		 * were multi-threaded.
288 289 290 291 292 293 294 295 296 297 298
		 */
		(void)close(dfd[1]);
		do {
			char buf;
			n = read(dfd[0], &buf, 1);
			if (n == 1)
				_exit(0);
		} while (n == -1 && errno == EINTR);
		_exit(1);
	}
	(void)close(dfd[0]);
Bob Halley's avatar
Bob Halley committed
299 300 301 302 303

	/*
	 * We're the child.
	 */

Mark Andrews's avatar
Mark Andrews committed
304
	if (setsid() == -1) {
305
		strerror_r(errno, strbuf, sizeof(strbuf));
306
		named_main_earlyfatal("setsid(): %s", strbuf);
307
	}
Bob Halley's avatar
Bob Halley committed
308 309 310 311

	/*
	 * Try to set stdin, stdout, and stderr to /dev/null, but press
	 * on even if it fails.
312 313 314 315 316 317
	 *
	 * XXXMLG The close() calls here are unneeded on all but NetBSD, but
	 * are harmless to include everywhere.  dup2() is supposed to close
	 * the FD if it is in use, but unproven-pthreads-0.16 is broken
	 * and will end up closing the wrong FD.  This will be fixed eventually,
	 * and these calls will be removed.
Bob Halley's avatar
Bob Halley committed
318
	 */
319 320 321 322 323 324 325 326 327
	if (devnullfd != -1) {
		if (devnullfd != STDIN_FILENO) {
			(void)close(STDIN_FILENO);
			(void)dup2(devnullfd, STDIN_FILENO);
		}
		if (devnullfd != STDOUT_FILENO) {
			(void)close(STDOUT_FILENO);
			(void)dup2(devnullfd, STDOUT_FILENO);
		}
328
		if (devnullfd != STDERR_FILENO && !named_g_keepstderr) {
329 330 331 332 333 334
			(void)close(STDERR_FILENO);
			(void)dup2(devnullfd, STDERR_FILENO);
		}
	}
}

335
void
336
named_os_started(void) {
337 338 339
	char buf = 0;

	/*
340
	 * Signal to the parent that we started successfully.
341 342
	 */
	if (dfd[0] != -1 && dfd[1] != -1) {
343
		if (write(dfd[1], &buf, 1) != 1)
344 345 346
			named_main_earlyfatal("unable to signal parent that we "
					      "otherwise started "
					      "successfully.");
347 348 349 350 351
		close(dfd[1]);
		dfd[0] = dfd[1] = -1;
	}
}

352
void
353
named_os_opendevnull(void) {
354 355 356 357
	devnullfd = open("/dev/null", O_RDWR, 0);
}

void
358
named_os_closedevnull(void) {
359 360 361 362 363
	if (devnullfd != STDIN_FILENO &&
	    devnullfd != STDOUT_FILENO &&
	    devnullfd != STDERR_FILENO) {
		close(devnullfd);
		devnullfd = -1;
Bob Halley's avatar
Bob Halley committed
364 365 366
	}
}

367
static bool
368 369
all_digits(const char *s) {
	if (*s == '\0')
370
		return (false);
371
	while (*s != '\0') {
Mark Andrews's avatar
lint  
Mark Andrews committed
372
		if (!isdigit((*s)&0xff))
373
			return (false);
374 375
		s++;
	}
376
	return (true);
377 378 379
}

void
380
named_os_chroot(const char *root) {
381
	char strbuf[ISC_STRERRORSIZE];
382
#ifdef HAVE_LIBSCF
383
	named_smf_chroot = 0;
384
#endif
385
	if (root != NULL) {
386
#ifdef HAVE_CHROOT
387
		if (chroot(root) < 0) {
388
			strerror_r(errno, strbuf, sizeof(strbuf));
389
			named_main_earlyfatal("chroot(): %s", strbuf);
390
		}
391
#else
392
		named_main_earlyfatal("chroot(): disabled");
393
#endif
394
		if (chdir("/") < 0) {
395
			strerror_r(errno, strbuf, sizeof(strbuf));
396
			named_main_earlyfatal("chdir(/): %s", strbuf);
397
		}
398
#ifdef HAVE_LIBSCF
399 400
		/* Set named_smf_chroot flag on successful chroot. */
		named_smf_chroot = 1;
401
#endif
402 403 404 405
	}
}

void
406
named_os_inituserinfo(const char *username) {
407
	char strbuf[ISC_STRERRORSIZE];
408
	if (username == NULL)
409 410 411
		return;

	if (all_digits(username))
412
		runas_pw = getpwuid((uid_t)atoi(username));
413
	else
414
		runas_pw = getpwnam(username);
415
	endpwent();
416

417
	if (runas_pw == NULL)
418
		named_main_earlyfatal("user '%s' unknown", username);
419 420

	if (getuid() == 0) {
421
		if (initgroups(runas_pw->pw_name, runas_pw->pw_gid) < 0) {
422
			strerror_r(errno, strbuf, sizeof(strbuf));
423
			named_main_earlyfatal("initgroups(): %s", strbuf);
424
		}
425 426
	}

427 428 429
}

void
430
named_os_changeuser(void) {
431
	char strbuf[ISC_STRERRORSIZE];
432
	if (runas_pw == NULL || done_setuid)
433 434
		return;

435
	done_setuid = true;
436

437
	if (setgid(runas_pw->pw_gid) < 0) {
438
		strerror_r(errno, strbuf, sizeof(strbuf));
439
		named_main_earlyfatal("setgid(): %s", strbuf);
440
	}
441

442
	if (setuid(runas_pw->pw_uid) < 0) {
443
		strerror_r(errno, strbuf, sizeof(strbuf));
444
		named_main_earlyfatal("setuid(): %s", strbuf);
445
	}
446

447
#if defined(HAVE_SYS_CAPABILITY_H)
448 449 450 451
	/*
	 * Restore the ability of named to drop core after the setuid()
	 * call has disabled it.
	 */
452
	if (prctl(PR_SET_DUMPABLE,1,0,0,0) < 0) {
453
		strerror_r(errno, strbuf, sizeof(strbuf));
454 455
		named_main_earlywarning("prctl(PR_SET_DUMPABLE) failed: %s",
					strbuf);
456
	}
457

458
	linux_minprivs();
459
#endif
460
}
Bob Halley's avatar
Bob Halley committed
461

462 463 464 465 466 467 468
uid_t
ns_os_uid(void) {
	if (runas_pw == NULL)
		return (0);
	return (runas_pw->pw_uid);
}

469
void
470
named_os_adjustnofile(void) {
471
#if defined(__linux__)
472 473 474 475 476 477 478 479 480 481 482
	isc_result_t result;
	isc_resourcevalue_t newvalue;

	/*
	 * Linux: max number of open files specified by one thread doesn't seem
	 * to apply to other threads on Linux.
	 */
	newvalue = ISC_RESOURCE_UNLIMITED;

	result = isc_resource_setlimit(isc_resource_openfiles, newvalue);
	if (result != ISC_R_SUCCESS)
483
		named_main_earlywarning("couldn't adjust limit on open files");
Automatic Updater's avatar
Automatic Updater committed
484
#endif
485 486
}

Bob Halley's avatar
Bob Halley committed
487
void
488
named_os_minprivs(void) {
489
#if defined(HAVE_SYS_CAPABILITY_H)
490
	linux_keepcaps();
491 492
	linux_minprivs();
#endif
Bob Halley's avatar
Bob Halley committed
493 494
}

Bob Halley's avatar
Bob Halley committed
495
static int
496
safe_open(const char *filename, mode_t mode, bool append) {
497
	int fd;
Mark Andrews's avatar
Mark Andrews committed
498
	struct stat sb;
Bob Halley's avatar
Bob Halley committed
499

Mark Andrews's avatar
Mark Andrews committed
500 501
	if (stat(filename, &sb) == -1) {
		if (errno != ENOENT)
Bob Halley's avatar
Bob Halley committed
502
			return (-1);
Mark Andrews's avatar
Mark Andrews committed
503
	} else if ((sb.st_mode & S_IFREG) == 0) {
504
		errno = EOPNOTSUPP;
Bob Halley's avatar
Bob Halley committed
505
		return (-1);
506
	}
Bob Halley's avatar
Bob Halley committed
507

508
	if (append)
509
		fd = open(filename, O_WRONLY|O_CREAT|O_APPEND, mode);
510
	else {
Mark Andrews's avatar
Mark Andrews committed
511 512
		if (unlink(filename) < 0 && errno != ENOENT)
			return (-1);
513
		fd = open(filename, O_WRONLY|O_CREAT|O_EXCL, mode);
514 515
	}
	return (fd);
Bob Halley's avatar
Bob Halley committed
516 517 518 519
}

static void
cleanup_pidfile(void) {
Mark Andrews's avatar
Mark Andrews committed
520
	int n;
521
	if (pidfile != NULL) {
Mark Andrews's avatar
Mark Andrews committed
522 523
		n = unlink(pidfile);
		if (n == -1 && errno != ENOENT)
524
			named_main_earlywarning("unlink '%s': failed", pidfile);
525 526
		free(pidfile);
	}
Bob Halley's avatar
Bob Halley committed
527 528 529
	pidfile = NULL;
}

530 531 532 533 534 535 536 537 538 539
static void
cleanup_lockfile(void) {
	if (singletonfd != -1) {
		close(singletonfd);
		singletonfd = -1;
	}

	if (lockfile != NULL) {
		int n = unlink(lockfile);
		if (n == -1 && errno != ENOENT)
540 541
			named_main_earlywarning("unlink '%s': failed",
						lockfile);
542 543 544 545 546 547 548 549 550 551
		free(lockfile);
		lockfile = NULL;
	}
}

/*
 * Ensure that a directory exists.
 * NOTE: This function overwrites the '/' characters in 'filename' with
 * nulls. The caller should copy the filename to a fresh buffer first.
 */
552 553 554 555 556 557 558 559 560 561 562 563
static int
mkdirpath(char *filename, void (*report)(const char *, ...)) {
	char *slash = strrchr(filename, '/');
	char strbuf[ISC_STRERRORSIZE];
	unsigned int mode;

	if (slash != NULL && slash != filename) {
		struct stat sb;
		*slash = '\0';

		if (stat(filename, &sb) == -1) {
			if (errno != ENOENT) {
564
				strerror_r(errno, strbuf, sizeof(strbuf));
565 566 567 568
				(*report)("couldn't stat '%s': %s", filename,
					  strbuf);
				goto error;
			}
Automatic Updater's avatar
Automatic Updater committed
569
			if (mkdirpath(filename, report) == -1)
570
				goto error;
571 572 573 574 575 576 577 578 579
			/*
			 * Handle "//", "/./" and "/../" in path.
			 */
			if (!strcmp(slash + 1, "") ||
			    !strcmp(slash + 1, ".") ||
			    !strcmp(slash + 1, "..")) {
				*slash = '/';
				return (0);
			}
580 581 582 583
			mode = S_IRUSR | S_IWUSR | S_IXUSR;	/* u=rwx */
			mode |= S_IRGRP | S_IXGRP;		/* g=rx */
			mode |= S_IROTH | S_IXOTH;		/* o=rx */
			if (mkdir(filename, mode) == -1) {
584
				strerror_r(errno, strbuf, sizeof(strbuf));
585 586 587 588
				(*report)("couldn't mkdir '%s': %s", filename,
					  strbuf);
				goto error;
			}
589 590 591
			if (runas_pw != NULL &&
			    chown(filename, runas_pw->pw_uid,
				  runas_pw->pw_gid) == -1) {
592
				strerror_r(errno, strbuf, sizeof(strbuf));
593 594 595
				(*report)("couldn't chown '%s': %s", filename,
					  strbuf);
			}
596 597 598 599 600 601 602 603 604 605
		}
		*slash = '/';
	}
	return (0);

 error:
	*slash = '/';
	return (-1);
}

606
static void
607
setperms(uid_t uid, gid_t gid) {
Mark Andrews's avatar
Mark Andrews committed
608
#if defined(HAVE_SETEGID) || defined(HAVE_SETRESGID)
609
	char strbuf[ISC_STRERRORSIZE];
Mark Andrews's avatar
Mark Andrews committed
610
#endif
611 612 613 614 615 616
#if !defined(HAVE_SETEGID) && defined(HAVE_SETRESGID)
	gid_t oldgid, tmpg;
#endif
#if !defined(HAVE_SETEUID) && defined(HAVE_SETRESUID)
	uid_t olduid, tmpu;
#endif
617
#if defined(HAVE_SETEGID)
618
	if (getegid() != gid && setegid(gid) == -1) {
619
		strerror_r(errno, strbuf, sizeof(strbuf));
620 621 622
		named_main_earlywarning("unable to set effective "
					"gid to %ld: %s",
					(long)gid, strbuf);
Automatic Updater's avatar
Automatic Updater committed
623
	}
624
#elif defined(HAVE_SETRESGID)
625 626
	if (getresgid(&tmpg, &oldgid, &tmpg) == -1 || oldgid != gid) {
		if (setresgid(-1, gid, -1) == -1) {
627
			strerror_r(errno, strbuf, sizeof(strbuf));
628 629
			named_main_earlywarning("unable to set effective "
						"gid to %d: %s", gid, strbuf);
630
		}
Automatic Updater's avatar
Automatic Updater committed
631
	}
632 633 634
#endif

#if defined(HAVE_SETEUID)
635
	if (geteuid() != uid && seteuid(uid) == -1) {
636
		strerror_r(errno, strbuf, sizeof(strbuf));
637 638 639
		named_main_earlywarning("unable to set effective "
					"uid to %ld: %s",
					(long)uid, strbuf);
Automatic Updater's avatar
Automatic Updater committed
640
	}
641
#elif defined(HAVE_SETRESUID)
642 643
	if (getresuid(&tmpu, &olduid, &tmpu) == -1 || olduid != uid) {
		if (setresuid(-1, uid, -1) == -1) {
644
			strerror_r(errno, strbuf, sizeof(strbuf));
645 646
			named_main_earlywarning("unable to set effective "
						"uid to %d: %s", uid, strbuf);
647
		}
Automatic Updater's avatar
Automatic Updater committed
648
	}
649 650 651
#endif
}

652
FILE *
653
named_os_openfile(const char *filename, mode_t mode, bool switch_user) {
654 655 656 657 658 659 660 661 662
	char strbuf[ISC_STRERRORSIZE], *f;
	FILE *fp;
	int fd;

	/*
	 * Make the containing directory if it doesn't exist.
	 */
	f = strdup(filename);
	if (f == NULL) {
663
		strerror_r(errno, strbuf, sizeof(strbuf));
664 665
		named_main_earlywarning("couldn't strdup() '%s': %s",
					filename, strbuf);
666 667
		return (NULL);
	}
668
	if (mkdirpath(f, named_main_earlywarning) == -1) {
669 670 671 672 673 674
		free(f);
		return (NULL);
	}
	free(f);

	if (switch_user && runas_pw != NULL) {
675
		gid_t oldgid = getgid();
676 677 678
		/* Set UID/GID to the one we'll be running with eventually */
		setperms(runas_pw->pw_uid, runas_pw->pw_gid);

679
		fd = safe_open(filename, mode, false);
680 681

		/* Restore UID/GID to root */
682
		setperms(0, oldgid);
683 684

		if (fd == -1) {
685
			fd = safe_open(filename, mode, false);
686
			if (fd != -1) {
687 688 689
				named_main_earlywarning("Required root "
							"permissions to open "
							"'%s'.", filename);
690
			} else {
691 692
				named_main_earlywarning("Could not open "
							"'%s'.", filename);
693
			}
694 695 696
			named_main_earlywarning("Please check file and "
						"directory permissions "
						"or reconfigure the filename.");
697 698
		}
	} else {
699
		fd = safe_open(filename, mode, false);
700 701 702
	}

	if (fd < 0) {
703
		strerror_r(errno, strbuf, sizeof(strbuf));
704 705
		named_main_earlywarning("could not open file '%s': %s",
					filename, strbuf);
706 707 708 709 710
		return (NULL);
	}

	fp = fdopen(fd, "w");
	if (fp == NULL) {
711
		strerror_r(errno, strbuf, sizeof(strbuf));
712 713
		named_main_earlywarning("could not fdopen() file '%s': %s",
					filename, strbuf);
714 715 716 717 718
	}

	return (fp);
}

Bob Halley's avatar
Bob Halley committed
719
void
720
named_os_writepidfile(const char *filename, bool first_time) {
Mark Andrews's avatar
Mark Andrews committed
721
	FILE *fh;
Bob Halley's avatar
Bob Halley committed
722
	pid_t pid;
723
	char strbuf[ISC_STRERRORSIZE];
724
	void (*report)(const char *, ...);
Bob Halley's avatar
Bob Halley committed
725 726 727 728 729

	/*
	 * The caller must ensure any required synchronization.
	 */

730
	report = first_time ? named_main_earlyfatal : named_main_earlywarning;
731

Bob Halley's avatar
Bob Halley committed
732 733
	cleanup_pidfile();

734
	if (filename == NULL)
735
		return;
736

737
	pidfile = strdup(filename);
738
	if (pidfile == NULL) {
739
		strerror_r(errno, strbuf, sizeof(strbuf));
740
		(*report)("couldn't strdup() '%s': %s", filename, strbuf);
741
		return;
742
	}
743

744 745
	fh = named_os_openfile(filename, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH,
			       first_time);
Mark Andrews's avatar
Mark Andrews committed
746
	if (fh == NULL) {
747 748
		cleanup_pidfile();
		return;
749
	}
Bob Halley's avatar
Bob Halley committed
750
	pid = getpid();
Mark Andrews's avatar
Mark Andrews committed
751
	if (fprintf(fh, "%ld\n", (long)pid) < 0) {
Mark Andrews's avatar
Mark Andrews committed
752
		(*report)("fprintf() to pid file '%s' failed", filename);
Mark Andrews's avatar
Mark Andrews committed
753
		(void)fclose(fh);
754 755 756
		cleanup_pidfile();
		return;
	}
Mark Andrews's avatar
Mark Andrews committed
757
	if (fflush(fh) == EOF) {
Mark Andrews's avatar
Mark Andrews committed
758
		(*report)("fflush() to pid file '%s' failed", filename);
Mark Andrews's avatar
Mark Andrews committed
759
		(void)fclose(fh);
760 761 762
		cleanup_pidfile();
		return;
	}
Mark Andrews's avatar
Mark Andrews committed
763
	(void)fclose(fh);
Bob Halley's avatar
Bob Halley committed
764 765
}

766
bool