]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bind9/bin/named/unix/os.c
add -n option to suppress clearing the build tree and add -DNO_CLEAN
[FreeBSD/FreeBSD.git] / contrib / bind9 / bin / named / unix / os.c
1 /*
2  * Copyright (C) 2004-2006  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1999-2002  Internet Software Consortium.
4  *
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.
8  *
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.
16  */
17
18 /* $Id: os.c,v 1.66.18.11 2006/02/03 23:51:38 marka Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23 #include <stdarg.h>
24
25 #include <sys/types.h>  /* dev_t FreeBSD 2.1 */
26 #include <sys/stat.h>
27
28 #include <ctype.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <grp.h>                /* Required for initgroups() on IRIX. */
32 #include <pwd.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <signal.h>
36 #include <syslog.h>
37 #ifdef HAVE_TZSET
38 #include <time.h>
39 #endif
40 #include <unistd.h>
41
42 #include <isc/buffer.h>
43 #include <isc/file.h>
44 #include <isc/print.h>
45 #include <isc/result.h>
46 #include <isc/strerror.h>
47 #include <isc/string.h>
48
49 #include <named/main.h>
50 #include <named/os.h>
51 #ifdef HAVE_LIBSCF
52 #include <named/ns_smf_globals.h>
53 #endif
54
55 static char *pidfile = NULL;
56 static int devnullfd = -1;
57
58 #ifndef ISC_FACILITY
59 #define ISC_FACILITY LOG_DAEMON
60 #endif
61
62 /*
63  * If there's no <linux/capability.h>, we don't care about <sys/prctl.h>
64  */
65 #ifndef HAVE_LINUX_CAPABILITY_H
66 #undef HAVE_SYS_PRCTL_H
67 #endif
68
69 /*
70  * Linux defines:
71  *      (T) HAVE_LINUXTHREADS
72  *      (C) HAVE_LINUX_CAPABILITY_H
73  *      (P) HAVE_SYS_PRCTL_H
74  * The possible cases are:
75  *      none:   setuid() normally
76  *      T:      no setuid()
77  *      C:      setuid() normally, drop caps (keep CAP_SETUID)
78  *      T+C:    no setuid(), drop caps (don't keep CAP_SETUID)
79  *      T+C+P:  setuid() early, drop caps (keep CAP_SETUID)
80  *      C+P:    setuid() normally, drop caps (keep CAP_SETUID)
81  *      P:      not possible
82  *      T+P:    not possible
83  *
84  * if (C)
85  *      caps = BIND_SERVICE + CHROOT + SETGID
86  *      if ((T && C && P) || !T)
87  *              caps += SETUID
88  *      endif
89  *      capset(caps)
90  * endif
91  * if (T && C && P && -u)
92  *      setuid()
93  * else if (T && -u)
94  *      fail
95  * --> start threads
96  * if (!T && -u)
97  *      setuid()
98  * if (C && (P || !-u))
99  *      caps = BIND_SERVICE
100  *      capset(caps)
101  * endif
102  *
103  * It will be nice when Linux threads work properly with setuid().
104  */
105
106 #ifdef HAVE_LINUXTHREADS
107 static pid_t mainpid = 0;
108 #endif
109
110 static struct passwd *runas_pw = NULL;
111 static isc_boolean_t done_setuid = ISC_FALSE;
112 static int dfd[2] = { -1, -1 };
113
114 #ifdef HAVE_LINUX_CAPABILITY_H
115
116 static isc_boolean_t non_root = ISC_FALSE;
117 static isc_boolean_t non_root_caps = ISC_FALSE;
118
119 /*%
120  * We define _LINUX_FS_H to prevent it from being included.  We don't need
121  * anything from it, and the files it includes cause warnings with 2.2
122  * kernels, and compilation failures (due to conflicts between <linux/string.h>
123  * and <string.h>) on 2.3 kernels.
124  */
125 #define _LINUX_FS_H
126
127 #include <sys/syscall.h>        /* Required for syscall(). */
128 #include <linux/capability.h>   /* Required for _LINUX_CAPABILITY_VERSION. */
129
130 #ifdef HAVE_SYS_PRCTL_H
131 #include <sys/prctl.h>          /* Required for prctl(). */
132
133 /*
134  * If the value of PR_SET_KEEPCAPS is not in <sys/prctl.h>, define it
135  * here.  This allows setuid() to work on systems running a new enough
136  * kernel but with /usr/include/linux pointing to "standard" kernel
137  * headers.
138  */
139 #ifndef PR_SET_KEEPCAPS
140 #define PR_SET_KEEPCAPS 8
141 #endif
142
143 #endif /* HAVE_SYS_PRCTL_H */
144
145 #ifndef SYS_capset
146 #ifndef __NR_capset
147 #include <asm/unistd.h> /* Slackware 4.0 needs this. */
148 #endif
149 #define SYS_capset __NR_capset
150 #endif
151
152 static void
153 linux_setcaps(unsigned int caps) {
154         struct __user_cap_header_struct caphead;
155         struct __user_cap_data_struct cap;
156         char strbuf[ISC_STRERRORSIZE];
157
158         if ((getuid() != 0 && !non_root_caps) || non_root)
159                 return;
160
161         memset(&caphead, 0, sizeof(caphead));
162         caphead.version = _LINUX_CAPABILITY_VERSION;
163         caphead.pid = 0;
164         memset(&cap, 0, sizeof(cap));
165         cap.effective = caps;
166         cap.permitted = caps;
167         cap.inheritable = 0;
168         if (syscall(SYS_capset, &caphead, &cap) < 0) {
169                 isc__strerror(errno, strbuf, sizeof(strbuf));
170                 ns_main_earlyfatal("capset failed: %s:"
171                                    " please ensure that the capset kernel"
172                                    " module is loaded.  see insmod(8)",
173                                    strbuf);
174         }
175 }
176
177 static void
178 linux_initialprivs(void) {
179         unsigned int caps;
180
181         /*%
182          * We don't need most privileges, so we drop them right away.
183          * Later on linux_minprivs() will be called, which will drop our
184          * capabilities to the minimum needed to run the server.
185          */
186
187         caps = 0;
188
189         /*
190          * We need to be able to bind() to privileged ports, notably port 53!
191          */
192         caps |= (1 << CAP_NET_BIND_SERVICE);
193
194         /*
195          * We need chroot() initially too.
196          */
197         caps |= (1 << CAP_SYS_CHROOT);
198
199 #if defined(HAVE_SYS_PRCTL_H) || !defined(HAVE_LINUXTHREADS)
200         /*
201          * We can setuid() only if either the kernel supports keeping
202          * capabilities after setuid() (which we don't know until we've
203          * tried) or we're not using threads.  If either of these is
204          * true, we want the setuid capability.
205          */
206         caps |= (1 << CAP_SETUID);
207 #endif
208
209         /*
210          * Since we call initgroups, we need this.
211          */
212         caps |= (1 << CAP_SETGID);
213
214         /*
215          * Without this, we run into problems reading a configuration file
216          * owned by a non-root user and non-world-readable on startup.
217          */
218         caps |= (1 << CAP_DAC_READ_SEARCH);
219
220         /*
221          * XXX  We might want to add CAP_SYS_RESOURCE, though it's not
222          *      clear it would work right given the way linuxthreads work.
223          * XXXDCL But since we need to be able to set the maximum number
224          * of files, the stack size, data size, and core dump size to
225          * support named.conf options, this is now being added to test.
226          */
227         caps |= (1 << CAP_SYS_RESOURCE);
228
229         linux_setcaps(caps);
230 }
231
232 static void
233 linux_minprivs(void) {
234         unsigned int caps;
235
236         /*%
237          * Drop all privileges except the ability to bind() to privileged
238          * ports.
239          *
240          * It's important that we drop CAP_SYS_CHROOT.  If we didn't, it
241          * chroot() could be used to escape from the chrooted area.
242          */
243
244         caps = 0;
245         caps |= (1 << CAP_NET_BIND_SERVICE);
246
247         /*
248          * XXX  We might want to add CAP_SYS_RESOURCE, though it's not
249          *      clear it would work right given the way linuxthreads work.
250          * XXXDCL But since we need to be able to set the maximum number
251          * of files, the stack size, data size, and core dump size to
252          * support named.conf options, this is now being added to test.
253          */
254         caps |= (1 << CAP_SYS_RESOURCE);
255
256         linux_setcaps(caps);
257 }
258
259 #ifdef HAVE_SYS_PRCTL_H
260 static void
261 linux_keepcaps(void) {
262         char strbuf[ISC_STRERRORSIZE];
263         /*%
264          * Ask the kernel to allow us to keep our capabilities after we
265          * setuid().
266          */
267
268         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
269                 if (errno != EINVAL) {
270                         isc__strerror(errno, strbuf, sizeof(strbuf));
271                         ns_main_earlyfatal("prctl() failed: %s", strbuf);
272                 }
273         } else {
274                 non_root_caps = ISC_TRUE;
275                 if (getuid() != 0)
276                         non_root = ISC_TRUE;
277         }
278 }
279 #endif
280
281 #endif  /* HAVE_LINUX_CAPABILITY_H */
282
283
284 static void
285 setup_syslog(const char *progname) {
286         int options;
287
288         options = LOG_PID;
289 #ifdef LOG_NDELAY
290         options |= LOG_NDELAY;
291 #endif
292         openlog(isc_file_basename(progname), options, ISC_FACILITY);
293 }
294
295 void
296 ns_os_init(const char *progname) {
297         setup_syslog(progname);
298 #ifdef HAVE_LINUX_CAPABILITY_H
299         linux_initialprivs();
300 #endif
301 #ifdef HAVE_LINUXTHREADS
302         mainpid = getpid();
303 #endif
304 #ifdef SIGXFSZ
305         signal(SIGXFSZ, SIG_IGN);
306 #endif
307 }
308
309 void
310 ns_os_daemonize(void) {
311         pid_t pid;
312         char strbuf[ISC_STRERRORSIZE];
313
314         if (pipe(dfd) == -1) {
315                 isc__strerror(errno, strbuf, sizeof(strbuf));
316                 ns_main_earlyfatal("pipe(): %s", strbuf);
317         }
318
319         pid = fork();
320         if (pid == -1) {
321                 isc__strerror(errno, strbuf, sizeof(strbuf));
322                 ns_main_earlyfatal("fork(): %s", strbuf);
323         }
324         if (pid != 0) {
325                 int n;
326                 /*
327                  * Wait for the child to finish loading for the first time.
328                  * This would be so much simpler if fork() worked once we
329                  * were multi-threaded.
330                  */
331                 (void)close(dfd[1]);
332                 do {
333                         char buf;
334                         n = read(dfd[0], &buf, 1);
335                         if (n == 1)
336                                 _exit(0);
337                 } while (n == -1 && errno == EINTR);
338                 _exit(1);
339         }
340         (void)close(dfd[0]);
341
342         /*
343          * We're the child.
344          */
345
346 #ifdef HAVE_LINUXTHREADS
347         mainpid = getpid();
348 #endif
349
350         if (setsid() == -1) {
351                 isc__strerror(errno, strbuf, sizeof(strbuf));
352                 ns_main_earlyfatal("setsid(): %s", strbuf);
353         }
354
355         /*
356          * Try to set stdin, stdout, and stderr to /dev/null, but press
357          * on even if it fails.
358          *
359          * XXXMLG The close() calls here are unneeded on all but NetBSD, but
360          * are harmless to include everywhere.  dup2() is supposed to close
361          * the FD if it is in use, but unproven-pthreads-0.16 is broken
362          * and will end up closing the wrong FD.  This will be fixed eventually,
363          * and these calls will be removed.
364          */
365         if (devnullfd != -1) {
366                 if (devnullfd != STDIN_FILENO) {
367                         (void)close(STDIN_FILENO);
368                         (void)dup2(devnullfd, STDIN_FILENO);
369                 }
370                 if (devnullfd != STDOUT_FILENO) {
371                         (void)close(STDOUT_FILENO);
372                         (void)dup2(devnullfd, STDOUT_FILENO);
373                 }
374                 if (devnullfd != STDERR_FILENO) {
375                         (void)close(STDERR_FILENO);
376                         (void)dup2(devnullfd, STDERR_FILENO);
377                 }
378         }
379 }
380
381 void
382 ns_os_started(void) {
383         char buf = 0;
384
385         /*
386          * Signal to the parent that we stated successfully.
387          */
388         if (dfd[0] != -1 && dfd[1] != -1) {
389                 write(dfd[1], &buf, 1);
390                 close(dfd[1]);
391                 dfd[0] = dfd[1] = -1;
392         }
393 }
394
395 void
396 ns_os_opendevnull(void) {
397         devnullfd = open("/dev/null", O_RDWR, 0);
398 }
399
400 void
401 ns_os_closedevnull(void) {
402         if (devnullfd != STDIN_FILENO &&
403             devnullfd != STDOUT_FILENO &&
404             devnullfd != STDERR_FILENO) {
405                 close(devnullfd);
406                 devnullfd = -1;
407         }
408 }
409
410 static isc_boolean_t
411 all_digits(const char *s) {
412         if (*s == '\0')
413                 return (ISC_FALSE);
414         while (*s != '\0') {
415                 if (!isdigit((*s)&0xff))
416                         return (ISC_FALSE);
417                 s++;
418         }
419         return (ISC_TRUE);
420 }
421
422 void
423 ns_os_chroot(const char *root) {
424         char strbuf[ISC_STRERRORSIZE];
425 #ifdef HAVE_LIBSCF
426         ns_smf_chroot = 0;
427 #endif
428         if (root != NULL) {
429                 if (chroot(root) < 0) {
430                         isc__strerror(errno, strbuf, sizeof(strbuf));
431                         ns_main_earlyfatal("chroot(): %s", strbuf);
432                 }
433                 if (chdir("/") < 0) {
434                         isc__strerror(errno, strbuf, sizeof(strbuf));
435                         ns_main_earlyfatal("chdir(/): %s", strbuf);
436                 }
437 #ifdef HAVE_LIBSCF
438                 /* Set ns_smf_chroot flag on successful chroot. */
439                 ns_smf_chroot = 1;
440 #endif
441         }
442 }
443
444 void
445 ns_os_inituserinfo(const char *username) {
446         char strbuf[ISC_STRERRORSIZE];
447         if (username == NULL)
448                 return;
449
450         if (all_digits(username))
451                 runas_pw = getpwuid((uid_t)atoi(username));
452         else
453                 runas_pw = getpwnam(username);
454         endpwent();
455
456         if (runas_pw == NULL)
457                 ns_main_earlyfatal("user '%s' unknown", username);
458
459         if (getuid() == 0) {
460                 if (initgroups(runas_pw->pw_name, runas_pw->pw_gid) < 0) {
461                         isc__strerror(errno, strbuf, sizeof(strbuf));
462                         ns_main_earlyfatal("initgroups(): %s", strbuf);
463                 }
464         }
465
466 }
467
468 void
469 ns_os_changeuser(void) {
470         char strbuf[ISC_STRERRORSIZE];
471         if (runas_pw == NULL || done_setuid)
472                 return;
473
474         done_setuid = ISC_TRUE;
475
476 #ifdef HAVE_LINUXTHREADS
477 #ifdef HAVE_LINUX_CAPABILITY_H
478         if (!non_root_caps)
479                 ns_main_earlyfatal("-u with Linux threads not supported: "
480                                    "requires kernel support for "
481                                    "prctl(PR_SET_KEEPCAPS)");
482 #else
483         ns_main_earlyfatal("-u with Linux threads not supported: "
484                            "no capabilities support or capabilities "
485                            "disabled at build time");
486 #endif
487 #endif
488
489         if (setgid(runas_pw->pw_gid) < 0) {
490                 isc__strerror(errno, strbuf, sizeof(strbuf));
491                 ns_main_earlyfatal("setgid(): %s", strbuf);
492         }
493
494         if (setuid(runas_pw->pw_uid) < 0) {
495                 isc__strerror(errno, strbuf, sizeof(strbuf));
496                 ns_main_earlyfatal("setuid(): %s", strbuf);
497         }
498
499 #if defined(HAVE_LINUX_CAPABILITY_H) && !defined(HAVE_LINUXTHREADS)
500         linux_minprivs();
501 #endif
502 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
503         /*
504          * Restore the ability of named to drop core after the setuid()
505          * call has disabled it.
506          */
507         prctl(PR_SET_DUMPABLE,1,0,0,0);
508 #endif
509 }
510
511 void
512 ns_os_minprivs(void) {
513 #ifdef HAVE_SYS_PRCTL_H
514         linux_keepcaps();
515 #endif
516
517 #ifdef HAVE_LINUXTHREADS
518         ns_os_changeuser(); /* Call setuid() before threads are started */
519 #endif
520
521 #if defined(HAVE_LINUX_CAPABILITY_H) && defined(HAVE_LINUXTHREADS)
522         linux_minprivs();
523 #endif
524 }
525
526 static int
527 safe_open(const char *filename, isc_boolean_t append) {
528         int fd;
529         struct stat sb;
530
531         if (stat(filename, &sb) == -1) {
532                 if (errno != ENOENT)
533                         return (-1);
534         } else if ((sb.st_mode & S_IFREG) == 0) {
535                 errno = EOPNOTSUPP;
536                 return (-1);
537         }
538
539         if (append)
540                 fd = open(filename, O_WRONLY|O_CREAT|O_APPEND,
541                           S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
542         else {
543                 (void)unlink(filename);
544                 fd = open(filename, O_WRONLY|O_CREAT|O_EXCL,
545                           S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
546         }
547         return (fd);
548 }
549
550 static void
551 cleanup_pidfile(void) {
552         if (pidfile != NULL) {
553                 (void)unlink(pidfile);
554                 free(pidfile);
555         }
556         pidfile = NULL;
557 }
558
559 void
560 ns_os_writepidfile(const char *filename, isc_boolean_t first_time) {
561         int fd;
562         FILE *lockfile;
563         size_t len;
564         pid_t pid;
565         char strbuf[ISC_STRERRORSIZE];
566         void (*report)(const char *, ...);
567
568         /*
569          * The caller must ensure any required synchronization.
570          */
571
572         report = first_time ? ns_main_earlyfatal : ns_main_earlywarning;
573
574         cleanup_pidfile();
575
576         if (filename == NULL)
577                 return;
578
579         len = strlen(filename);
580         pidfile = malloc(len + 1);
581         if (pidfile == NULL) {
582                 isc__strerror(errno, strbuf, sizeof(strbuf));
583                 (*report)("couldn't malloc '%s': %s", filename, strbuf);
584                 return;
585         }
586         /* This is safe. */
587         strcpy(pidfile, filename);
588
589         fd = safe_open(filename, ISC_FALSE);
590         if (fd < 0) {
591                 isc__strerror(errno, strbuf, sizeof(strbuf));
592                 (*report)("couldn't open pid file '%s': %s", filename, strbuf);
593                 free(pidfile);
594                 pidfile = NULL;
595                 return;
596         }
597         lockfile = fdopen(fd, "w");
598         if (lockfile == NULL) {
599                 isc__strerror(errno, strbuf, sizeof(strbuf));
600                 (*report)("could not fdopen() pid file '%s': %s",
601                           filename, strbuf);
602                 (void)close(fd);
603                 cleanup_pidfile();
604                 return;
605         }
606 #ifdef HAVE_LINUXTHREADS
607         pid = mainpid;
608 #else
609         pid = getpid();
610 #endif
611         if (fprintf(lockfile, "%ld\n", (long)pid) < 0) {
612                 (*report)("fprintf() to pid file '%s' failed", filename);
613                 (void)fclose(lockfile);
614                 cleanup_pidfile();
615                 return;
616         }
617         if (fflush(lockfile) == EOF) {
618                 (*report)("fflush() to pid file '%s' failed", filename);
619                 (void)fclose(lockfile);
620                 cleanup_pidfile();
621                 return;
622         }
623         (void)fclose(lockfile);
624 }
625
626 void
627 ns_os_shutdown(void) {
628         closelog();
629         cleanup_pidfile();
630 }
631
632 isc_result_t
633 ns_os_gethostname(char *buf, size_t len) {
634         int n;
635
636         n = gethostname(buf, len);
637         return ((n == 0) ? ISC_R_SUCCESS : ISC_R_FAILURE);
638 }
639
640 static char *
641 next_token(char **stringp, const char *delim) {
642         char *res;
643
644         do {
645                 res = strsep(stringp, delim);
646                 if (res == NULL)
647                         break;
648         } while (*res == '\0');
649         return (res);
650 }
651
652 void
653 ns_os_shutdownmsg(char *command, isc_buffer_t *text) {
654         char *input, *ptr;
655         unsigned int n;
656         pid_t pid;
657
658         input = command;
659
660         /* Skip the command name. */
661         ptr = next_token(&input, " \t");
662         if (ptr == NULL)
663                 return;
664
665         ptr = next_token(&input, " \t");
666         if (ptr == NULL)
667                 return;
668         
669         if (strcmp(ptr, "-p") != 0)
670                 return;
671
672 #ifdef HAVE_LINUXTHREADS
673         pid = mainpid;
674 #else
675         pid = getpid();
676 #endif
677
678         n = snprintf((char *)isc_buffer_used(text),
679                      isc_buffer_availablelength(text),
680                      "pid: %ld", (long)pid);
681         /* Only send a message if it is complete. */
682         if (n < isc_buffer_availablelength(text))
683                 isc_buffer_add(text, n);
684 }
685
686 void
687 ns_os_tzset(void) {
688 #ifdef HAVE_TZSET
689         tzset();
690 #endif
691 }