2 * Copyright (C) 2004-2006 Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 1999-2002 Internet Software Consortium.
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
18 /* $Id: os.c,v 1.46.2.4.8.24 2006/02/03 23:51:37 marka Exp $ */
23 #include <sys/types.h> /* dev_t FreeBSD 2.1 */
29 #include <grp.h> /* Required for initgroups() on IRIX. */
40 #include <isc/buffer.h>
42 #include <isc/print.h>
43 #include <isc/result.h>
44 #include <isc/strerror.h>
45 #include <isc/string.h>
47 #include <named/main.h>
50 #include <named/ns_smf_globals.h>
53 static char *pidfile = NULL;
54 static int devnullfd = -1;
57 #define ISC_FACILITY LOG_DAEMON
61 * If there's no <linux/capability.h>, we don't care about <sys/prctl.h>
63 #ifndef HAVE_LINUX_CAPABILITY_H
64 #undef HAVE_SYS_PRCTL_H
69 * (T) HAVE_LINUXTHREADS
70 * (C) HAVE_LINUX_CAPABILITY_H
71 * (P) HAVE_SYS_PRCTL_H
72 * The possible cases are:
73 * none: setuid() normally
75 * C: setuid() normally, drop caps (keep CAP_SETUID)
76 * T+C: no setuid(), drop caps (don't keep CAP_SETUID)
77 * T+C+P: setuid() early, drop caps (keep CAP_SETUID)
78 * C+P: setuid() normally, drop caps (keep CAP_SETUID)
83 * caps = BIND_SERVICE + CHROOT + SETGID
84 * if ((T && C && P) || !T)
89 * if (T && C && P && -u)
96 * if (C && (P || !-u))
101 * It will be nice when Linux threads work properly with setuid().
104 #ifdef HAVE_LINUXTHREADS
105 static pid_t mainpid = 0;
108 static struct passwd *runas_pw = NULL;
109 static isc_boolean_t done_setuid = ISC_FALSE;
110 static int dfd[2] = { -1, -1 };
112 #ifdef HAVE_LINUX_CAPABILITY_H
114 static isc_boolean_t non_root = ISC_FALSE;
115 static isc_boolean_t non_root_caps = ISC_FALSE;
118 * We define _LINUX_FS_H to prevent it from being included. We don't need
119 * anything from it, and the files it includes cause warnings with 2.2
120 * kernels, and compilation failures (due to conflicts between <linux/string.h>
121 * and <string.h>) on 2.3 kernels.
125 #include <sys/syscall.h> /* Required for syscall(). */
126 #include <linux/capability.h> /* Required for _LINUX_CAPABILITY_VERSION. */
128 #ifdef HAVE_SYS_PRCTL_H
129 #include <sys/prctl.h> /* Required for prctl(). */
132 * If the value of PR_SET_KEEPCAPS is not in <sys/prctl.h>, define it
133 * here. This allows setuid() to work on systems running a new enough
134 * kernel but with /usr/include/linux pointing to "standard" kernel
137 #ifndef PR_SET_KEEPCAPS
138 #define PR_SET_KEEPCAPS 8
141 #endif /* HAVE_SYS_PRCTL_H */
145 #include <asm/unistd.h> /* Slackware 4.0 needs this. */
147 #define SYS_capset __NR_capset
151 linux_setcaps(unsigned int caps) {
152 struct __user_cap_header_struct caphead;
153 struct __user_cap_data_struct cap;
154 char strbuf[ISC_STRERRORSIZE];
156 if ((getuid() != 0 && !non_root_caps) || non_root)
159 memset(&caphead, 0, sizeof(caphead));
160 caphead.version = _LINUX_CAPABILITY_VERSION;
162 memset(&cap, 0, sizeof(cap));
163 cap.effective = caps;
164 cap.permitted = caps;
166 if (syscall(SYS_capset, &caphead, &cap) < 0) {
167 isc__strerror(errno, strbuf, sizeof(strbuf));
168 ns_main_earlyfatal("capset failed: %s:"
169 " please ensure that the capset kernel"
170 " module is loaded. see insmod(8)",
176 linux_initialprivs(void) {
180 * We don't need most privileges, so we drop them right away.
181 * Later on linux_minprivs() will be called, which will drop our
182 * capabilities to the minimum needed to run the server.
188 * We need to be able to bind() to privileged ports, notably port 53!
190 caps |= (1 << CAP_NET_BIND_SERVICE);
193 * We need chroot() initially too.
195 caps |= (1 << CAP_SYS_CHROOT);
197 #if defined(HAVE_SYS_PRCTL_H) || !defined(HAVE_LINUXTHREADS)
199 * We can setuid() only if either the kernel supports keeping
200 * capabilities after setuid() (which we don't know until we've
201 * tried) or we're not using threads. If either of these is
202 * true, we want the setuid capability.
204 caps |= (1 << CAP_SETUID);
208 * Since we call initgroups, we need this.
210 caps |= (1 << CAP_SETGID);
213 * Without this, we run into problems reading a configuration file
214 * owned by a non-root user and non-world-readable on startup.
216 caps |= (1 << CAP_DAC_READ_SEARCH);
219 * XXX We might want to add CAP_SYS_RESOURCE, though it's not
220 * clear it would work right given the way linuxthreads work.
221 * XXXDCL But since we need to be able to set the maximum number
222 * of files, the stack size, data size, and core dump size to
223 * support named.conf options, this is now being added to test.
225 caps |= (1 << CAP_SYS_RESOURCE);
231 linux_minprivs(void) {
235 * Drop all privileges except the ability to bind() to privileged
238 * It's important that we drop CAP_SYS_CHROOT. If we didn't, it
239 * chroot() could be used to escape from the chrooted area.
243 caps |= (1 << CAP_NET_BIND_SERVICE);
246 * XXX We might want to add CAP_SYS_RESOURCE, though it's not
247 * clear it would work right given the way linuxthreads work.
248 * XXXDCL But since we need to be able to set the maximum number
249 * of files, the stack size, data size, and core dump size to
250 * support named.conf options, this is now being added to test.
252 caps |= (1 << CAP_SYS_RESOURCE);
257 #ifdef HAVE_SYS_PRCTL_H
259 linux_keepcaps(void) {
260 char strbuf[ISC_STRERRORSIZE];
262 * Ask the kernel to allow us to keep our capabilities after we
266 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
267 if (errno != EINVAL) {
268 isc__strerror(errno, strbuf, sizeof(strbuf));
269 ns_main_earlyfatal("prctl() failed: %s", strbuf);
272 non_root_caps = ISC_TRUE;
279 #endif /* HAVE_LINUX_CAPABILITY_H */
283 setup_syslog(const char *progname) {
288 options |= LOG_NDELAY;
290 openlog(isc_file_basename(progname), options, ISC_FACILITY);
294 ns_os_init(const char *progname) {
295 setup_syslog(progname);
296 #ifdef HAVE_LINUX_CAPABILITY_H
297 linux_initialprivs();
299 #ifdef HAVE_LINUXTHREADS
303 signal(SIGXFSZ, SIG_IGN);
308 ns_os_daemonize(void) {
310 char strbuf[ISC_STRERRORSIZE];
312 if (pipe(dfd) == -1) {
313 isc__strerror(errno, strbuf, sizeof(strbuf));
314 ns_main_earlyfatal("pipe(): %s", strbuf);
319 isc__strerror(errno, strbuf, sizeof(strbuf));
320 ns_main_earlyfatal("fork(): %s", strbuf);
325 * Wait for the child to finish loading for the first time.
326 * This would be so much simpler if fork() worked once we
327 * were multi-threaded.
332 n = read(dfd[0], &buf, 1);
335 } while (n == -1 && errno == EINTR);
344 #ifdef HAVE_LINUXTHREADS
348 if (setsid() == -1) {
349 isc__strerror(errno, strbuf, sizeof(strbuf));
350 ns_main_earlyfatal("setsid(): %s", strbuf);
354 * Try to set stdin, stdout, and stderr to /dev/null, but press
355 * on even if it fails.
357 * XXXMLG The close() calls here are unneeded on all but NetBSD, but
358 * are harmless to include everywhere. dup2() is supposed to close
359 * the FD if it is in use, but unproven-pthreads-0.16 is broken
360 * and will end up closing the wrong FD. This will be fixed eventually,
361 * and these calls will be removed.
363 if (devnullfd != -1) {
364 if (devnullfd != STDIN_FILENO) {
365 (void)close(STDIN_FILENO);
366 (void)dup2(devnullfd, STDIN_FILENO);
368 if (devnullfd != STDOUT_FILENO) {
369 (void)close(STDOUT_FILENO);
370 (void)dup2(devnullfd, STDOUT_FILENO);
372 if (devnullfd != STDERR_FILENO) {
373 (void)close(STDERR_FILENO);
374 (void)dup2(devnullfd, STDERR_FILENO);
380 ns_os_started(void) {
384 * Signal to the parent that we stated successfully.
386 if (dfd[0] != -1 && dfd[1] != -1) {
387 write(dfd[1], &buf, 1);
389 dfd[0] = dfd[1] = -1;
394 ns_os_opendevnull(void) {
395 devnullfd = open("/dev/null", O_RDWR, 0);
399 ns_os_closedevnull(void) {
400 if (devnullfd != STDIN_FILENO &&
401 devnullfd != STDOUT_FILENO &&
402 devnullfd != STDERR_FILENO) {
409 all_digits(const char *s) {
413 if (!isdigit((*s)&0xff))
421 ns_os_chroot(const char *root) {
422 char strbuf[ISC_STRERRORSIZE];
427 if (chroot(root) < 0) {
428 isc__strerror(errno, strbuf, sizeof(strbuf));
429 ns_main_earlyfatal("chroot(): %s", strbuf);
431 if (chdir("/") < 0) {
432 isc__strerror(errno, strbuf, sizeof(strbuf));
433 ns_main_earlyfatal("chdir(/): %s", strbuf);
436 /* Set ns_smf_chroot flag on successful chroot. */
443 ns_os_inituserinfo(const char *username) {
444 char strbuf[ISC_STRERRORSIZE];
445 if (username == NULL)
448 if (all_digits(username))
449 runas_pw = getpwuid((uid_t)atoi(username));
451 runas_pw = getpwnam(username);
454 if (runas_pw == NULL)
455 ns_main_earlyfatal("user '%s' unknown", username);
458 if (initgroups(runas_pw->pw_name, runas_pw->pw_gid) < 0) {
459 isc__strerror(errno, strbuf, sizeof(strbuf));
460 ns_main_earlyfatal("initgroups(): %s", strbuf);
467 ns_os_changeuser(void) {
468 char strbuf[ISC_STRERRORSIZE];
469 if (runas_pw == NULL || done_setuid)
472 done_setuid = ISC_TRUE;
474 #ifdef HAVE_LINUXTHREADS
475 #ifdef HAVE_LINUX_CAPABILITY_H
477 ns_main_earlyfatal("-u with Linux threads not supported: "
478 "requires kernel support for "
479 "prctl(PR_SET_KEEPCAPS)");
481 ns_main_earlyfatal("-u with Linux threads not supported: "
482 "no capabilities support or capabilities "
483 "disabled at build time");
487 if (setgid(runas_pw->pw_gid) < 0) {
488 isc__strerror(errno, strbuf, sizeof(strbuf));
489 ns_main_earlyfatal("setgid(): %s", strbuf);
492 if (setuid(runas_pw->pw_uid) < 0) {
493 isc__strerror(errno, strbuf, sizeof(strbuf));
494 ns_main_earlyfatal("setuid(): %s", strbuf);
497 #if defined(HAVE_LINUX_CAPABILITY_H) && !defined(HAVE_LINUXTHREADS)
500 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
502 * Restore the ability of named to drop core after the setuid()
503 * call has disabled it.
505 prctl(PR_SET_DUMPABLE,1,0,0,0);
510 ns_os_minprivs(void) {
511 #ifdef HAVE_SYS_PRCTL_H
515 #ifdef HAVE_LINUXTHREADS
516 ns_os_changeuser(); /* Call setuid() before threads are started */
519 #if defined(HAVE_LINUX_CAPABILITY_H) && defined(HAVE_LINUXTHREADS)
525 safe_open(const char *filename, isc_boolean_t append) {
529 if (stat(filename, &sb) == -1) {
532 } else if ((sb.st_mode & S_IFREG) == 0) {
538 fd = open(filename, O_WRONLY|O_CREAT|O_APPEND,
539 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
541 (void)unlink(filename);
542 fd = open(filename, O_WRONLY|O_CREAT|O_EXCL,
543 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
549 cleanup_pidfile(void) {
550 if (pidfile != NULL) {
551 (void)unlink(pidfile);
558 ns_os_writepidfile(const char *filename, isc_boolean_t first_time) {
563 char strbuf[ISC_STRERRORSIZE];
564 void (*report)(const char *, ...);
567 * The caller must ensure any required synchronization.
570 report = first_time ? ns_main_earlyfatal : ns_main_earlywarning;
574 if (filename == NULL)
577 len = strlen(filename);
578 pidfile = malloc(len + 1);
579 if (pidfile == NULL) {
580 isc__strerror(errno, strbuf, sizeof(strbuf));
581 (*report)("couldn't malloc '%s': %s", filename, strbuf);
585 strcpy(pidfile, filename);
587 fd = safe_open(filename, ISC_FALSE);
589 isc__strerror(errno, strbuf, sizeof(strbuf));
590 (*report)("couldn't open pid file '%s': %s", filename, strbuf);
595 lockfile = fdopen(fd, "w");
596 if (lockfile == NULL) {
597 isc__strerror(errno, strbuf, sizeof(strbuf));
598 (*report)("could not fdopen() pid file '%s': %s",
604 #ifdef HAVE_LINUXTHREADS
609 if (fprintf(lockfile, "%ld\n", (long)pid) < 0) {
610 (*report)("fprintf() to pid file '%s' failed", filename);
611 (void)fclose(lockfile);
615 if (fflush(lockfile) == EOF) {
616 (*report)("fflush() to pid file '%s' failed", filename);
617 (void)fclose(lockfile);
621 (void)fclose(lockfile);
625 ns_os_shutdown(void) {
631 ns_os_gethostname(char *buf, size_t len) {
634 n = gethostname(buf, len);
635 return ((n == 0) ? ISC_R_SUCCESS : ISC_R_FAILURE);
639 next_token(char **stringp, const char *delim) {
643 res = strsep(stringp, delim);
646 } while (*res == '\0');
651 ns_os_shutdownmsg(char *command, isc_buffer_t *text) {
658 /* Skip the command name. */
659 ptr = next_token(&input, " \t");
663 ptr = next_token(&input, " \t");
667 if (strcmp(ptr, "-p") != 0)
670 #ifdef HAVE_LINUXTHREADS
676 n = snprintf((char *)isc_buffer_used(text),
677 isc_buffer_availablelength(text),
678 "pid: %ld", (long)pid);
679 /* Only send a message if it is complete. */
680 if (n < isc_buffer_availablelength(text))
681 isc_buffer_add(text, n);