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(PR_SET_DUMPABLE)
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
	}
#endif
458
#if defined(HAVE_SYS_CAPABILITY_H)
459
	linux_minprivs();
460
#endif
461
}
Bob Halley's avatar
Bob Halley committed
462

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

470
void
471
named_os_adjustnofile(void) {
472
#if defined(__linux__)
473 474 475 476 477 478 479 480 481 482 483
	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)
484
		named_main_earlywarning("couldn't adjust limit on open files");
Automatic Updater's avatar
Automatic Updater committed
485
#endif
486 487
}

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

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

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

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

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

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

	if (lockfile != NULL) {
		int n = unlink(lockfile);
		if (n == -1 && errno != ENOENT)
541 542
			named_main_earlywarning("unlink '%s': failed",
						lockfile);
543 544 545 546 547 548 549 550 551 552
		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.
 */
553 554 555 556 557 558 559 560 561 562 563 564
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) {
565
				strerror_r(errno, strbuf, sizeof(strbuf));
566 567 568 569
				(*report)("couldn't stat '%s': %s", filename,
					  strbuf);
				goto error;
			}
Automatic Updater's avatar
Automatic Updater committed
570
			if (mkdirpath(filename, report) == -1)
571
				goto error;
572 573 574 575 576 577 578 579 580
			/*
			 * Handle "//", "/./" and "/../" in path.
			 */
			if (!strcmp(slash + 1, "") ||
			    !strcmp(slash + 1, ".") ||
			    !strcmp(slash + 1, "..")) {
				*slash = '/';
				return (0);
			}
581 582 583 584
			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) {
585
				strerror_r(errno, strbuf, sizeof(strbuf));
586 587 588 589
				(*report)("couldn't mkdir '%s': %s", filename,
					  strbuf);
				goto error;
			}
590 591 592
			if (runas_pw != NULL &&
			    chown(filename, runas_pw->pw_uid,
				  runas_pw->pw_gid) == -1) {
593
				strerror_r(errno, strbuf, sizeof(strbuf));
594 595 596
				(*report)("couldn't chown '%s': %s", filename,
					  strbuf);
			}
597 598 599 600 601 602 603 604 605 606
		}
		*slash = '/';
	}
	return (0);

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

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

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

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

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

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

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

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

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

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

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

	return (fp);
}

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

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

731
	report = first_time ? named_main_earlyfatal : named_main_earlywarning;
732

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

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

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

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

767
bool
768
named_os_issingleton(const char *filename) {
769
	char strbuf[ISC_STRERRORSIZE];
770 771 772
	struct flock lock;

	if (singletonfd != -1)
773
		return (true);
774

775
	if (strcasecmp(filename, "none") == 0)
776
		return (true);
777 778 779 780 781 782

	/*
	 * Make the containing directory if it doesn't exist.
	 */
	lockfile = strdup(filename);
	if (lockfile == NULL) {
783
		strerror_r(errno, strbuf, sizeof(strbuf));
784 785
		named_main_earlyfatal("couldn't allocate memory for '%s': %s",
				      filename, strbuf);
786
	} else {
787
		int ret = mkdirpath(lockfile, named_main_earlywarning);
788
		if (ret == -1) {
789 790
			named_main_earlywarning("couldn't create '%s'",
						filename);
791
			cleanup_lockfile();
792
			return (false);
793 794 795
		}
	}

796
	/*
797
	 * named_os_openfile() uses safeopen() which removes any existing
798 799 800 801
	 * files. We can't use that here.
	 */
	singletonfd = open(filename, O_WRONLY | O_CREAT,
			   S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
802 803
	if (singletonfd == -1) {
		cleanup_lockfile();
804
		return (false);
805
	}
806 807 808 809 810 811 812 813 814 815 816

	memset(&lock, 0, sizeof(lock));
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 1;

	/* Non-blocking (does not wait for lock) */
	if (fcntl(singletonfd, F_SETLK, &lock) == -1) {
		close(singletonfd);
		singletonfd = -1;
817
		return (false);
818 819
	}

820
	return (true);
821 822
}

Bob Halley's avatar
Bob Halley committed
823