Change where we do suid up/down.
[freeradius.git] / src / main / mainconfig.c
1 /*
2  * mainconf.c   Handle the server's configuration.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2002,2006-2007  The FreeRADIUS server project
21  * Copyright 2002  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/stat.h>
32
33 #ifdef HAVE_SYS_RESOURCE_H
34 #include <sys/resource.h>
35 #endif
36
37 #ifdef HAVE_PWD_H
38 #include <pwd.h>
39 #endif
40
41 #ifdef HAVE_GRP_H
42 #include <grp.h>
43 #endif
44
45 #ifdef HAVE_SYS_PRCTL_H
46 #include <sys/prctl.h>
47 #endif
48
49 #ifdef HAVE_SYSLOG_H
50 #       include <syslog.h>
51 #endif
52
53 #ifdef HAVE_SYS_STAT_H
54 #include <sys/stat.h>
55 #endif
56
57 #ifdef HAVE_FCNTL_H
58 #include <fcntl.h>
59 #endif
60
61 struct main_config_t mainconfig;
62 char *request_log_file = NULL;
63 char *debug_log_file = NULL;
64 char *debug_condition = NULL;
65
66 /*
67  *      Temporary local variables for parsing the configuration
68  *      file.
69  */
70 #ifndef __MINGW32__
71 uid_t server_uid;
72 static gid_t server_gid;
73 static const char *uid_name = NULL;
74 static const char *gid_name = NULL;
75 #endif
76 static const char *chroot_dir = NULL;
77 static int allow_core_dumps = 0;
78 static const char *radlog_dest = NULL;
79
80 /*
81  *      These are not used anywhere else..
82  */
83 static const char *localstatedir = NULL;
84 static const char *prefix = NULL;
85 static char *syslog_facility = NULL;
86 static const FR_NAME_NUMBER str2fac[] = {
87 #ifdef LOG_KERN
88         { "kern", LOG_KERN },
89 #endif
90 #ifdef LOG_USER
91         { "user", LOG_USER },
92 #endif
93 #ifdef LOG_MAIL
94         { "mail", LOG_MAIL },
95 #endif
96 #ifdef LOG_DAEMON
97         { "daemon", LOG_DAEMON },
98 #endif
99 #ifdef LOG_AUTH
100         { "auth", LOG_AUTH },
101 #endif
102 #ifdef LOG_LPR
103         { "lpr", LOG_LPR },
104 #endif
105 #ifdef LOG_NEWS
106         { "news", LOG_NEWS },
107 #endif
108 #ifdef LOG_UUCP
109         { "uucp", LOG_UUCP },
110 #endif
111 #ifdef LOG_CRON
112         { "cron", LOG_CRON },
113 #endif
114 #ifdef LOG_AUTHPRIV
115         { "authpriv", LOG_AUTHPRIV },
116 #endif
117 #ifdef LOG_FTP
118         { "ftp", LOG_FTP },
119 #endif
120 #ifdef LOG_LOCAL0
121         { "local0", LOG_LOCAL0 },
122 #endif
123 #ifdef LOG_LOCAL1
124         { "local1", LOG_LOCAL1 },
125 #endif
126 #ifdef LOG_LOCAL2
127         { "local2", LOG_LOCAL2 },
128 #endif
129 #ifdef LOG_LOCAL3
130         { "local3", LOG_LOCAL3 },
131 #endif
132 #ifdef LOG_LOCAL4
133         { "local4", LOG_LOCAL4 },
134 #endif
135 #ifdef LOG_LOCAL5
136         { "local5", LOG_LOCAL5 },
137 #endif
138 #ifdef LOG_LOCAL6
139         { "local6", LOG_LOCAL6 },
140 #endif
141 #ifdef LOG_LOCAL7
142         { "local7", LOG_LOCAL7 },
143 #endif
144         { NULL, -1 }
145 };
146
147 /*
148  *  Security configuration for the server.
149  */
150 static const CONF_PARSER security_config[] = {
151         { "max_attributes",  PW_TYPE_INTEGER, 0, &fr_max_attributes, Stringify(0) },
152         { "reject_delay",  PW_TYPE_INTEGER, 0, &mainconfig.reject_delay, Stringify(0) },
153         { "status_server", PW_TYPE_BOOLEAN, 0, &mainconfig.status_server, "no"},
154         { NULL, -1, 0, NULL, NULL }
155 };
156
157
158 /*
159  *      Logging configuration for the server.
160  */
161 static const CONF_PARSER logdest_config[] = {
162         { "destination",  PW_TYPE_STRING_PTR, 0, &radlog_dest, "files" },
163         { "syslog_facility",  PW_TYPE_STRING_PTR, 0, &syslog_facility, Stringify(0) },
164
165         { "file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, "${logdir}/radius.log" },
166         { "requests", PW_TYPE_STRING_PTR, -1, &request_log_file, NULL },
167         { "debug_file", PW_TYPE_STRING_PTR, -1, &debug_log_file, NULL },
168         { NULL, -1, 0, NULL, NULL }
169 };
170
171
172 static const CONF_PARSER serverdest_config[] = {
173         { "log", PW_TYPE_SUBSECTION, 0, NULL, (const void *) logdest_config },
174         { "log_file", PW_TYPE_STRING_PTR, -1, &mainconfig.log_file, NULL },
175         { "log_destination", PW_TYPE_STRING_PTR, -1, &radlog_dest, NULL },
176         { NULL, -1, 0, NULL, NULL }
177 };
178
179
180 static const CONF_PARSER log_config_nodest[] = {
181         { "stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names,"no" },
182
183         { "auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, "no" },
184         { "auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, "no" },
185         { "auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, "no" },
186
187         { NULL, -1, 0, NULL, NULL }
188 };
189
190
191 /*
192  *  A mapping of configuration file names to internal variables
193  */
194 static const CONF_PARSER server_config[] = {
195         /*
196          *      FIXME: 'prefix' is the ONLY one which should be
197          *      configured at compile time.  Hard-coding it here is
198          *      bad.  It will be cleaned up once we clean up the
199          *      hard-coded defines for the locations of the various
200          *      files.
201          */
202         { "prefix",             PW_TYPE_STRING_PTR, 0, &prefix,            "/usr/local"},
203         { "localstatedir",      PW_TYPE_STRING_PTR, 0, &localstatedir,     "${prefix}/var"},
204         { "logdir",             PW_TYPE_STRING_PTR, 0, &radlog_dir,        "${localstatedir}/log"},
205         { "libdir",             PW_TYPE_STRING_PTR, 0, &radlib_dir,        "${prefix}/lib"},
206         { "radacctdir",         PW_TYPE_STRING_PTR, 0, &radacct_dir,       "${logdir}/radacct" },
207         { "hostname_lookups",   PW_TYPE_BOOLEAN,    0, &fr_dns_lookups,      "no" },
208         { "max_request_time", PW_TYPE_INTEGER, 0, &mainconfig.max_request_time, Stringify(MAX_REQUEST_TIME) },
209         { "cleanup_delay", PW_TYPE_INTEGER, 0, &mainconfig.cleanup_delay, Stringify(CLEANUP_DELAY) },
210         { "max_requests", PW_TYPE_INTEGER, 0, &mainconfig.max_requests, Stringify(MAX_REQUESTS) },
211 #ifdef DELETE_BLOCKED_REQUESTS
212         { "delete_blocked_requests", PW_TYPE_INTEGER, 0, &mainconfig.kill_unresponsive_children, Stringify(FALSE) },
213 #endif
214         { "allow_core_dumps", PW_TYPE_BOOLEAN, 0, &allow_core_dumps, "no" },
215
216         { "pidfile", PW_TYPE_STRING_PTR, 0, &mainconfig.pid_file, "${run_dir}/radiusd.pid"},
217         { "checkrad", PW_TYPE_STRING_PTR, 0, &mainconfig.checkrad, "${sbindir}/checkrad" },
218
219         { "debug_level", PW_TYPE_INTEGER, 0, &mainconfig.debug_level, "0"},
220
221 #ifdef WITH_PROXY
222         { "proxy_requests", PW_TYPE_BOOLEAN, 0, &mainconfig.proxy_requests, "yes" },
223 #endif
224         { "log", PW_TYPE_SUBSECTION, 0, NULL, (const void *) log_config_nodest },
225
226         /*
227          *      People with old configs will have these.  They are listed
228          *      AFTER the "log" section, so if they exist in radiusd.conf,
229          *      it will prefer "log_foo = bar" to "log { foo = bar }".
230          *      They're listed with default values of NULL, so that if they
231          *      DON'T exist in radiusd.conf, then the previously parsed
232          *      values for "log { foo = bar}" will be used.
233          */
234         { "log_auth", PW_TYPE_BOOLEAN, -1, &mainconfig.log_auth, NULL },
235         { "log_auth_badpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_badpass, NULL },
236         { "log_auth_goodpass", PW_TYPE_BOOLEAN, 0, &mainconfig.log_auth_goodpass, NULL },
237         { "log_stripped_names", PW_TYPE_BOOLEAN, 0, &log_stripped_names, NULL },
238
239         {  "security", PW_TYPE_SUBSECTION, 0, NULL, (const void *) security_config },
240
241         { NULL, -1, 0, NULL, NULL }
242 };
243
244 #define MAX_ARGV (256)
245
246
247 static size_t config_escape_func(char *out, size_t outlen, const char *in)
248 {
249         size_t len = 0;
250         static const char *disallowed = "%{}\\'\"`";
251
252         while (in[0]) {
253                 /*
254                  *      Non-printable characters get replaced with their
255                  *      mime-encoded equivalents.
256                  */
257                 if ((in[0] < 32)) {
258                         if (outlen <= 3) break;
259
260                         snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
261                         in++;
262                         out += 3;
263                         outlen -= 3;
264                         len += 3;
265                         continue;
266
267                 } else if (strchr(disallowed, *in) != NULL) {
268                         if (outlen <= 2) break;
269
270                         out[0] = '\\';
271                         out[1] = *in;
272                         in++;
273                         out += 2;
274                         outlen -= 2;
275                         len += 2;
276                         continue;
277                 }
278
279                 /*
280                  *      Only one byte left.
281                  */
282                 if (outlen <= 1) {
283                         break;
284                 }
285
286                 /*
287                  *      Allowed character.
288                  */
289                 *out = *in;
290                 out++;
291                 in++;
292                 outlen--;
293                 len++;
294         }
295         *out = '\0';
296         return len;
297 }
298
299 /*
300  *      Xlat for %{config:section.subsection.attribute}
301  */
302 static size_t xlat_config(void *instance, REQUEST *request,
303                           char *fmt, char *out,
304                           size_t outlen,
305                           RADIUS_ESCAPE_STRING func)
306 {
307         const char *value;
308         CONF_PAIR *cp;
309         CONF_ITEM *ci;
310         char buffer[1024];
311
312         request = request;      /* -Wunused */
313         instance = instance;    /* -Wunused */
314
315         /*
316          *      Expand it safely.
317          */
318         if (!radius_xlat(buffer, sizeof(buffer), fmt, request, config_escape_func)) {
319                 return 0;
320         }
321
322         ci = cf_reference_item(request->root->config,
323                                request->root->config, buffer);
324         if (!ci || !cf_item_is_pair(ci)) {
325                 *out = '\0';
326                 return 0;
327         }
328
329         cp = cf_itemtopair(ci);
330
331         /*
332          *  Ensure that we only copy what's necessary.
333          *
334          *  If 'outlen' is too small, then the output is chopped to fit.
335          */
336         value = cf_pair_value(cp);
337         if (value) {
338                 if (outlen > strlen(value)) {
339                         outlen = strlen(value) + 1;
340                 }
341         }
342
343         return func(out, outlen, value);
344 }
345
346
347 /*
348  *      Xlat for %{client:foo}
349  */
350 static size_t xlat_client(UNUSED void *instance, REQUEST *request,
351                        char *fmt, char *out,
352                        size_t outlen,
353                        UNUSED RADIUS_ESCAPE_STRING func)
354 {
355         const char *value = NULL;
356         CONF_PAIR *cp;
357
358         if (!fmt || !out || (outlen < 1)) return 0;
359
360         if (!request || !request->client) {
361                 *out = '\0';
362                 return 0;
363         }
364
365         cp = cf_pair_find(request->client->cs, fmt);
366         if (!cp || !(value = cf_pair_value(cp))) {
367                 *out = '\0';
368                 return 0;
369         }
370         
371         strlcpy(out, value, outlen);
372
373         return strlen(out);
374 }
375
376 /*
377  *      Recursively make directories.
378  */
379 static int r_mkdir(const char *part)
380 {
381         char *ptr, parentdir[500];
382         struct stat st;
383
384         if (stat(part, &st) == 0)
385                 return(0);
386
387         ptr = strrchr(part, FR_DIR_SEP);
388
389         if (ptr == part)
390                 return(0);
391
392         snprintf(parentdir, (ptr - part)+1, "%s", part);
393
394         if (r_mkdir(parentdir) != 0)
395                 return(1);
396
397         if (mkdir(part, 0770) != 0) {
398                 radlog(L_ERR, "mkdir(%s) error: %s\n", part, strerror(errno));
399                 return(1);
400         }
401
402         return(0);
403 }
404
405
406 #ifndef __MINGW32__
407 int did_setuid = FALSE;
408
409 #if defined(HAVE_SETRESUID) && defined (HAVE_GETRESUID)
410 void fr_suid_up(void)
411 {
412         uid_t ruid, euid, suid;
413         
414         if (getresuid(&ruid, &euid, &suid) < 0) {
415                 radlog(L_ERR, "Failed getting saved UID's");
416                 _exit(1);
417         }
418
419         if (setresuid(-1, suid, -1) < 0) {
420                 radlog(L_ERR, "Failed switching to privileged user");
421                 _exit(1);
422         }
423
424         if (geteuid() != suid) {
425                 radlog(L_ERR, "Switched to unknown UID");
426                 _exit(1);
427         }
428 }
429
430 void fr_suid_down(void)
431 {
432         if (!did_setuid) return;
433
434         if (setresuid(-1, server_uid, geteuid()) < 0) {
435                 fprintf(stderr, "%s: Failed switching to uid %s: %s\n",
436                         progname, uid_name, strerror(errno));
437                 _exit(1);
438         }
439                 
440         if (geteuid() != server_uid) {
441                 fprintf(stderr, "%s: Failed switching uid: UID is incorrect\n",
442                         progname);
443                 _exit(1);
444         }
445 }
446
447 void fr_suid_down_permanent(void)
448 {
449         uid_t ruid, euid, suid;
450
451         if (!did_setuid) return;
452
453         if (getresuid(&ruid, &euid, &suid) < 0) {
454                 radlog(L_ERR, "Failed getting saved uid's");
455                 _exit(1);
456         }
457
458         if (setresuid(server_uid, server_uid, server_uid) < 0) {
459                 radlog(L_ERR, "Failed in permanent switch to uid %s: %s",
460                        uid_name, strerror(errno));
461                 _exit(1);
462         }
463
464         if (geteuid() != server_uid) {
465                 radlog(L_ERR, "Switched to unknown uid");
466                 _exit(1);
467         }
468
469
470         if (getresuid(&ruid, &euid, &suid) < 0) {
471                 radlog(L_ERR, "Failed getting saved uid's: %s",
472                        strerror(errno));
473                 _exit(1);
474         }
475 }
476 #else
477 /*
478  *      Much less secure...
479  */
480 void fr_suid_up(void)
481 {
482 }
483 void fr_suid_down(void)
484 {
485         if (!uid_name) return;
486
487         if (setuid(server_uid) < 0) {
488                 fprintf(stderr, "%s: Failed switching to uid %s: %s\n",
489                         progname, uid_name, strerror(errno));
490                 _exit(1);
491         }
492 }
493 void fr_suid_down_permanent(void)
494 {
495 }
496 #endif
497
498 /*
499  *  Do chroot, if requested.
500  *
501  *  Switch UID and GID to what is specified in the config file
502  */
503 static int switch_users(CONF_SECTION *cs)
504 {
505         CONF_PAIR *cp;
506
507 #ifdef HAVE_SYS_RESOURCE_H
508         struct rlimit core_limits;
509 #endif
510
511         /*
512          *      Don't do chroot/setuid/setgid if we're in debugging
513          *      as non-root.
514          */
515         if (debug_flag && (getuid() != 0)) return 1;
516
517 #ifdef HAVE_GRP_H
518         /*  Set GID.  */
519         cp = cf_pair_find(cs, "group");
520         if (cp) gid_name = cf_pair_value(cp);
521         if (gid_name) {
522                 struct group *gr;
523
524                 DEBUG2("group = %s", gid_name);
525                 gr = getgrnam(gid_name);
526                 if (gr == NULL) {
527                         fprintf(stderr, "%s: Cannot get ID for group %s: %s\n",
528                                 progname, gid_name, strerror(errno));
529                         return 0;
530                 }
531                 server_gid = gr->gr_gid;
532         } else {
533                 server_gid = getgid();
534         }
535 #endif
536
537 #ifdef HAVE_PWD_H
538         /*  Set UID.  */
539         cp = cf_pair_find(cs, "user");
540         if (cp) uid_name = cf_pair_value(cp);
541         if (uid_name) {
542                 struct passwd *pw;
543                 
544                 DEBUG2("user = %s", uid_name);
545                 pw = getpwnam(uid_name);
546                 if (pw == NULL) {
547                         fprintf(stderr, "%s: Cannot get passwd entry for user %s: %s\n",
548                                 progname, uid_name, strerror(errno));
549                         return 0;
550                 }
551                 server_uid = pw->pw_uid;
552 #ifdef HAVE_INITGROUPS
553                 if (initgroups(uid_name, server_gid) < 0) {
554                         fprintf(stderr, "%s: Cannot initialize supplementary group list for user %s: %s\n",
555                                 progname, uid_name, strerror(errno));
556                         return 0;
557                 }
558 #endif
559         } else {
560                 server_uid = getuid();
561         }
562 #endif
563
564         cp = cf_pair_find(cs, "chroot");
565         if (cp) chroot_dir = cf_pair_value(cp);
566         if (chroot_dir) {
567                 DEBUG2("chroot = %s", chroot_dir);
568                 if (chroot(chroot_dir) < 0) {
569                         fprintf(stderr, "%s: Failed to perform chroot %s: %s",
570                                 progname, chroot_dir, strerror(errno));
571                         return 0;
572                 }
573
574                 /*
575                  *      Note that we leave chdir alone.  It may be
576                  *      OUTSIDE of the root.  This allows us to read
577                  *      the configuration from "-d ./etc/raddb", with
578                  *      the chroot as "./chroot/" for example.  After
579                  *      the server has been loaded, it does a "cd
580                  *      ${logdir}" below, so that core files (if any)
581                  *      go to a logging directory.
582                  *
583                  *      This also allows the configuration of the
584                  *      server to be outside of the chroot.  If the
585                  *      server is statically linked, then the only
586                  *      things needed inside of the chroot are the
587                  *      logging directories.
588                  */
589                 radlog(L_INFO, "performing chroot to %s\n", chroot_dir);
590         }
591
592 #ifdef HAVE_GRP_H
593         /*  Set GID.  */
594         if (gid_name && (setgid(server_gid) < 0)) {
595                 fprintf(stderr, "%s: Failed setting group to %s: %s",
596                         progname, gid_name, strerror(errno));
597                 return 0;
598         }
599 #endif
600
601 #ifdef HAVE_PWD_H
602         if (uid_name) {
603                 fr_suid_down();
604
605                 /*
606                  *      Now core dumps are disabled on most secure systems.
607                  */
608                 
609                 did_setuid = TRUE;
610         }
611 #endif
612
613         /*
614          *      Double check that we can write to the log directory.
615          *
616          *      If we can't, don't start, as we can't log any errors!
617          */
618         if ((mainconfig.radlog_dest == RADLOG_FILES) &&
619             (mainconfig.log_file != NULL)) {
620                 int fd = open(mainconfig.log_file,
621                               O_WRONLY | O_APPEND | O_CREAT, 0640);
622                 if (fd < 0) {
623                         fprintf(stderr, "%s: Cannot write to log file %s: %s\n",
624                                 progname, mainconfig.log_file, strerror(errno));
625                         return 0;
626                 }
627                 close(fd);
628
629                 /*
630                  *      After this it's safe to call radlog(), as it's going
631                  *      to the right place.
632                  */
633         }
634
635 #ifdef HAVE_SYS_RESOURCE_H
636         /*  Get the current maximum for core files.  */
637         if (getrlimit(RLIMIT_CORE, &core_limits) < 0) {
638                 radlog(L_ERR, "Failed to get current core limit:  %s", strerror(errno));
639                 return 0;
640         }
641 #endif
642
643         /*
644          *      Core dumps are allowed if we're in debug mode, OR
645          *      we've allowed them, OR we did a setuid (which turns
646          *      core dumps off).
647          *
648          *      Otherwise, disable core dumps for security.
649          *      
650          */
651         if (!(debug_flag || allow_core_dumps || did_setuid)) {
652 #ifdef HAVE_SYS_RESOURCE_H
653                 struct rlimit no_core;
654
655                 no_core.rlim_cur = 0;
656                 no_core.rlim_max = 0;
657
658                 if (setrlimit(RLIMIT_CORE, &no_core) < 0) {
659                         radlog(L_ERR, "Failed disabling core dumps: %s",
660                                strerror(errno));
661                         return 0;
662                 }
663 #endif
664
665                 /*
666                  *      Otherwise, re-enable core dumps if we're
667                  *      running as a daemon, AND core dumps are
668                  *      allowed, AND we changed UID's.
669                  */
670         } else if ((debug_flag == 0) && allow_core_dumps && did_setuid) {
671                 /*
672                  *      Set the dumpable flag.
673                  */
674 #ifdef HAVE_SYS_PRCTL_H
675 #ifdef PR_SET_DUMPABLE
676                 if (prctl(PR_SET_DUMPABLE, 1) < 0) {
677                         radlog(L_ERR,"Cannot enable core dumps: prctl(PR_SET_DUMPABLE) failed: '%s'",
678                                strerror(errno));
679                 }
680 #endif
681 #endif
682
683                 /*
684                  *      Reset the core dump limits again, just to
685                  *      double check that they haven't changed.
686                  */
687 #ifdef HAVE_SYS_RESOURCE_H
688                 if (setrlimit(RLIMIT_CORE, &core_limits) < 0) {
689                         radlog(L_ERR, "Cannot update core dump limit: %s",
690                                         strerror(errno));
691                         return 0;
692                 }
693 #endif
694
695                 radlog(L_INFO, "Core dumps are enabled.");
696         }
697         /*
698          *      Else we're debugging (so core dumps are enabled)
699          *      OR we're not debugging, AND "allow_core_dumps == FALSE",
700          *      OR we're not debugging, AND core dumps are allowed,
701          *         BUT we didn't call setuid, so we haven't changed the
702          *         core dump capabilities inherited from the parent shell.
703          */
704
705         return 1;
706 }
707 #endif
708
709
710 static const FR_NAME_NUMBER str2dest[] = {
711         { "null", RADLOG_NULL },
712         { "files", RADLOG_FILES },
713         { "syslog", RADLOG_SYSLOG },
714         { "stdout", RADLOG_STDOUT },
715         { "stderr", RADLOG_STDERR },
716         { NULL, RADLOG_NUM_DEST }
717 };
718
719
720 /*
721  *      Read config files.
722  *
723  *      This function can ONLY be called from the main server process.
724  */
725 int read_mainconfig(int reload)
726 {
727         const char *p = NULL;
728         static int old_debug_level = -1;
729         CONF_PAIR *cp;
730         CONF_SECTION *cs;
731         struct stat statbuf;
732         char buffer[1024];
733
734         if (stat(radius_dir, &statbuf) < 0) {
735                 radlog(L_ERR, "Errors reading %s: %s",
736                        radius_dir, strerror(errno));
737                 return -1;
738         }
739
740 #ifdef S_IWOTH
741         if ((statbuf.st_mode & S_IWOTH) != 0) {
742                 radlog(L_ERR, "Configuration directory %s is globally writable.  Refusing to start due to insecure configuration.",
743                        radius_dir);
744           return -1;
745         }
746 #endif
747
748 #ifdef S_IROTH
749         if (0 && (statbuf.st_mode & S_IROTH) != 0) {
750                 radlog(L_ERR, "Configuration directory %s is globally readable.  Refusing to start due to insecure configuration.",
751                        radius_dir);
752                 return -1;
753         }
754 #endif
755
756         if (!reload) {
757                 radlog(L_INFO, "Starting - reading configuration files ...");
758         } else {
759                 radlog(L_INFO, "Reloading - reading configuration files...");
760         }
761
762         /* Read the configuration file */
763         snprintf(buffer, sizeof(buffer), "%.200s/%.50s.conf",
764                  radius_dir, mainconfig.name);
765         if ((cs = cf_file_read(buffer)) == NULL) {
766                 radlog(L_ERR, "Errors reading %s", buffer);
767                 return -1;
768         }
769
770         /*
771          *      If there was no log destination set on the command line,
772          *      set it now.
773          */
774         if (mainconfig.radlog_dest == RADLOG_NULL) {
775                 if (cf_section_parse(cs, NULL, serverdest_config) < 0) {
776                         fprintf(stderr, "radiusd: Error: Failed to parse log{} section.\n");
777                         cf_section_free(&cs);
778                         return -1;
779                 }
780                 
781                 if (!radlog_dest) {
782                         fprintf(stderr, "radiusd: Error: No log destination specified.\n");
783                         cf_section_free(&cs);
784                         return -1;
785                 }
786                 
787                 mainconfig.radlog_dest = fr_str2int(str2dest, radlog_dest,
788                                                     RADLOG_NUM_DEST);
789                 if (mainconfig.radlog_dest == RADLOG_NUM_DEST) {
790                         fprintf(stderr, "radiusd: Error: Unknown log_destination %s\n",
791                                 radlog_dest);
792                         cf_section_free(&cs);
793                         return -1;
794                 }
795                 
796                 if (mainconfig.radlog_dest == RADLOG_SYSLOG) {
797                         /*
798                          *      Make sure syslog_facility isn't NULL
799                          *      before using it
800                          */
801                         if (!syslog_facility) {
802                                 fprintf(stderr, "radiusd: Error: Syslog chosen but no facility was specified\n");
803                                 cf_section_free(&cs);
804                                 return -1;
805                         }
806                         mainconfig.syslog_facility = fr_str2int(str2fac, syslog_facility, -1);
807                         if (mainconfig.syslog_facility < 0) {
808                                 fprintf(stderr, "radiusd: Error: Unknown syslog_facility %s\n",
809                                         syslog_facility);
810                                 cf_section_free(&cs);
811                                 return -1;
812                         }
813                 }
814         }
815
816 #ifndef __MINGW32__
817         /*
818          *      We should really switch users earlier in the process.
819          */
820         if (!switch_users(cs)) exit(1);
821 #endif
822
823         /* Initialize the dictionary */
824         cp = cf_pair_find(cs, "dictionary");
825         if (cp) p = cf_pair_value(cp);
826         if (!p) p = radius_dir;
827         DEBUG2("including dictionary file %s/%s", p, RADIUS_DICTIONARY);
828         if (dict_init(p, RADIUS_DICTIONARY) != 0) {
829                 radlog(L_ERR, "Errors reading dictionary: %s",
830                                 fr_strerror());
831                 return -1;
832         }
833
834         /*
835          *      This allows us to figure out where, relative to
836          *      radiusd.conf, the other configuration files exist.
837          */
838         cf_section_parse(cs, NULL, server_config);
839
840         /*
841          *      Free the old configuration items, and replace them
842          *      with the new ones.
843          *
844          *      Note that where possible, we do atomic switch-overs,
845          *      to ensure that the pointers are always valid.
846          */
847         cf_section_free(&mainconfig.config);
848         mainconfig.config = cs;
849
850         if (!clients_parse_section(cs)) {
851                 return -1;
852         }
853
854         DEBUG2("%s: #### Loading Realms and Home Servers ####", mainconfig.name);
855
856         if (!realms_init(cs)) {
857                 return -1;
858         }
859
860         /*
861          *  Register the %{config:section.subsection} xlat function.
862          */
863         xlat_register("config", xlat_config, NULL);
864         xlat_register("client", xlat_client, NULL);
865
866         /*
867          *      Reload: change debug flag if it's changed in the
868          *      configuration file.
869          */
870         if (reload) {
871                 if (mainconfig.debug_level != old_debug_level) {
872                         debug_flag = mainconfig.debug_level;
873                 }
874
875         } else if (debug_flag == 0) {
876
877                 /*
878                  *      Starting the server, WITHOUT "-x" on the
879                  *      command-line: use whatever's in the config
880                  *      file.
881                  */
882                 debug_flag = mainconfig.debug_level;
883         }
884         fr_debug_flag = debug_flag;
885         old_debug_level = mainconfig.debug_level;
886
887         /*
888          *  Go update our behaviour, based on the configuration
889          *  changes.
890          */
891
892         /*
893          *      Sanity check the configuration for internal
894          *      consistency.
895          */
896         if (mainconfig.reject_delay > mainconfig.cleanup_delay) {
897                 mainconfig.reject_delay = mainconfig.cleanup_delay;
898         }
899         if (mainconfig.reject_delay < 0) mainconfig.reject_delay = 0;
900
901         /*  Reload the modules.  */
902         if (setup_modules(reload, mainconfig.config) < 0) {
903                 radlog(L_ERR, "Errors initializing modules");
904                 return -1;
905         }
906
907         if (chroot_dir) {
908                 if (chdir(radlog_dir) < 0) {
909                         radlog(L_ERR, "Failed to 'chdir %s' after chroot: %s",
910                                radlog_dir, strerror(errno));
911                         return -1;
912                 }
913         }
914
915         return 0;
916 }
917
918 /*
919  *      Free the configuration.  Called only when the server is exiting.
920  */
921 int free_mainconfig(void)
922 {
923         /*
924          *      Clean up the configuration data
925          *      structures.
926          */
927         cf_section_free(&mainconfig.config);
928         realms_free();
929         listen_free(&mainconfig.listen);
930         dict_free();
931
932         return 0;
933 }