]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/charon/charon.c
Allow charon to change group on files before dropping caps
[thirdparty/strongswan.git] / src / charon / charon.c
1 /*
2 * Copyright (C) 2006-2017 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2006 Daniel Roethlisberger
5 * Copyright (C) 2005 Jan Hutter
6 * HSR Hochschule fuer Technik Rapperswil
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2 of the License, or (at your
11 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 * for more details.
17 */
18
19 #include <stdio.h>
20 #include <signal.h>
21 #include <pthread.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <sys/utsname.h>
25 #include <unistd.h>
26 #include <getopt.h>
27 #include <fcntl.h>
28 #include <errno.h>
29
30 #include <daemon.h>
31
32 #include <library.h>
33 #include <utils/backtrace.h>
34 #include <threading/thread.h>
35
36 #ifdef ANDROID
37 #include <private/android_filesystem_config.h> /* for AID_VPN */
38 #endif
39
40 /**
41 * PID file, in which charon stores its process id
42 */
43 #define PID_FILE IPSEC_PIDDIR "/charon.pid"
44
45 /**
46 * Default user and group
47 */
48 #ifndef IPSEC_USER
49 #define IPSEC_USER NULL
50 #endif
51
52 #ifndef IPSEC_GROUP
53 #define IPSEC_GROUP NULL
54 #endif
55
56 /**
57 * Global reference to PID file (required to truncate, if undeletable)
58 */
59 static FILE *pidfile = NULL;
60
61 /**
62 * hook in library for debugging messages
63 */
64 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
65
66 /**
67 * Logging hook for library logs, using stderr output
68 */
69 static void dbg_stderr(debug_t group, level_t level, char *fmt, ...)
70 {
71 va_list args;
72
73 if (level <= 1)
74 {
75 va_start(args, fmt);
76 fprintf(stderr, "00[%N] ", debug_names, group);
77 vfprintf(stderr, fmt, args);
78 fprintf(stderr, "\n");
79 va_end(args);
80 }
81 }
82
83 /**
84 * Run the daemon and handle unix signals
85 */
86 static void run()
87 {
88 sigset_t set;
89
90 /* handle SIGINT, SIGHUP and SIGTERM in this handler */
91 sigemptyset(&set);
92 sigaddset(&set, SIGINT);
93 sigaddset(&set, SIGHUP);
94 sigaddset(&set, SIGTERM);
95 sigprocmask(SIG_BLOCK, &set, NULL);
96
97 while (TRUE)
98 {
99 int sig;
100
101 sig = sigwaitinfo(&set, NULL);
102 if (sig == -1)
103 {
104 if (errno == EINTR)
105 { /* ignore signals we didn't wait for */
106 continue;
107 }
108 DBG1(DBG_DMN, "waiting for signal failed: %s", strerror(errno));
109 return;
110 }
111 switch (sig)
112 {
113 case SIGHUP:
114 {
115 DBG1(DBG_DMN, "signal of type SIGHUP received. Reloading "
116 "configuration");
117 if (lib->settings->load_files(lib->settings, lib->conf, FALSE))
118 {
119 charon->load_loggers(charon);
120 lib->plugins->reload(lib->plugins, NULL);
121 }
122 else
123 {
124 DBG1(DBG_DMN, "reloading config failed, keeping old");
125 }
126 break;
127 }
128 case SIGINT:
129 {
130 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
131 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
132 return;
133 }
134 case SIGTERM:
135 {
136 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
137 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
138 return;
139 }
140 }
141 }
142 }
143
144 /**
145 * lookup UID and GID
146 */
147 static bool lookup_uid_gid()
148 {
149 char *name;
150
151 name = lib->settings->get_str(lib->settings, "charon.user", IPSEC_USER);
152 if (name && !lib->caps->resolve_uid(lib->caps, name))
153 {
154 return FALSE;
155 }
156 name = lib->settings->get_str(lib->settings, "charon.group", IPSEC_GROUP);
157 if (name && !lib->caps->resolve_gid(lib->caps, name))
158 {
159 return FALSE;
160 }
161 #ifdef ANDROID
162 lib->caps->set_uid(lib->caps, AID_VPN);
163 #endif
164 return TRUE;
165 }
166
167 /**
168 * Handle SIGSEGV/SIGILL signals raised by threads
169 */
170 static void segv_handler(int signal)
171 {
172 backtrace_t *backtrace;
173
174 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
175 backtrace = backtrace_create(2);
176 backtrace->log(backtrace, NULL, TRUE);
177 backtrace->log(backtrace, stderr, TRUE);
178 backtrace->destroy(backtrace);
179
180 DBG1(DBG_DMN, "killing ourself, received critical signal");
181 abort();
182 }
183
184 /**
185 * Check/create PID file, return TRUE if already running
186 */
187 static bool check_pidfile()
188 {
189 struct stat stb;
190
191 if (stat(PID_FILE, &stb) == 0)
192 {
193 pidfile = fopen(PID_FILE, "r");
194 if (pidfile)
195 {
196 char buf[64];
197 pid_t pid = 0;
198
199 memset(buf, 0, sizeof(buf));
200 if (fread(buf, 1, sizeof(buf), pidfile))
201 {
202 buf[sizeof(buf) - 1] = '\0';
203 pid = atoi(buf);
204 }
205 fclose(pidfile);
206 pidfile = NULL;
207 if (pid && pid != getpid() && kill(pid, 0) == 0)
208 {
209 DBG1(DBG_DMN, "charon already running ('"PID_FILE"' exists)");
210 return TRUE;
211 }
212 }
213 DBG1(DBG_DMN, "removing pidfile '"PID_FILE"', process not running");
214 unlink(PID_FILE);
215 }
216
217 /* create new pidfile */
218 pidfile = fopen(PID_FILE, "w");
219 if (pidfile)
220 {
221 int fd;
222
223 fd = fileno(pidfile);
224 if (fd == -1)
225 {
226 DBG1(DBG_DMN, "unable to determine fd for '"PID_FILE"'");
227 return TRUE;
228 }
229 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
230 {
231 DBG1(DBG_LIB, "setting FD_CLOEXEC for '"PID_FILE"' failed: %s",
232 strerror(errno));
233 }
234 /* Only change owner of the pidfile if we have CAP_CHOWN. Otherwise,
235 * attempt to change group of pidfile to group under which charon
236 * runs after dropping caps. This requires the user that charon
237 * starts as to:
238 * a) Have write access to the socket dir.
239 * b) Belong to the group that charon will run under after dropping
240 * caps. */
241 if (lib->caps->check(lib->caps, CAP_CHOWN))
242 {
243 ignore_result(fchown(fd,
244 lib->caps->get_uid(lib->caps),
245 lib->caps->get_gid(lib->caps)));
246 }
247 else
248 {
249 ignore_result(fchown(fd, -1,
250 lib->caps->get_gid(lib->caps)));
251 }
252 fprintf(pidfile, "%d\n", getpid());
253 fflush(pidfile);
254 return FALSE;
255 }
256 else
257 {
258 DBG1(DBG_DMN, "unable to create pidfile '"PID_FILE"'");
259 return TRUE;
260 }
261 }
262
263 /**
264 * Delete/truncate the PID file
265 */
266 static void unlink_pidfile()
267 {
268 /* because unlinking the PID file may fail, we truncate it to ensure the
269 * daemon can be properly restarted. one probable cause for this is the
270 * combination of not running as root and the effective user lacking
271 * permissions on the parent dir(s) of the PID file */
272 if (pidfile)
273 {
274 ignore_result(ftruncate(fileno(pidfile), 0));
275 fclose(pidfile);
276 unlink(PID_FILE);
277 }
278 }
279
280 /**
281 * print command line usage and exit
282 */
283 static void usage(const char *msg)
284 {
285 if (msg != NULL && *msg != '\0')
286 {
287 fprintf(stderr, "%s\n", msg);
288 }
289 fprintf(stderr, "Usage: charon\n"
290 " [--help]\n"
291 " [--version]\n"
292 " [--use-syslog]\n"
293 " [--debug-<type> <level>]\n"
294 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|asn|enc|tnc|imc|imv|pts|tls|esp|lib)\n"
295 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
296 " 2 = controlmore, 3 = raw, 4 = private)\n"
297 "\n"
298 );
299 }
300
301 /**
302 * Main function, starts the daemon.
303 */
304 int main(int argc, char *argv[])
305 {
306 struct sigaction action;
307 int group, status = SS_RC_INITIALIZATION_FAILED;
308 struct utsname utsname;
309 level_t levels[DBG_MAX];
310 bool use_syslog = FALSE;
311
312 /* logging for library during initialization, as we have no bus yet */
313 dbg = dbg_stderr;
314
315 /* initialize library */
316 if (!library_init(NULL, "charon"))
317 {
318 library_deinit();
319 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
320 }
321
322 if (lib->integrity &&
323 !lib->integrity->check_file(lib->integrity, "charon", argv[0]))
324 {
325 dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
326 library_deinit();
327 exit(SS_RC_DAEMON_INTEGRITY);
328 }
329
330 if (!libcharon_init())
331 {
332 dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
333 goto deinit;
334 }
335
336 /* use CTRL loglevel for default */
337 for (group = 0; group < DBG_MAX; group++)
338 {
339 levels[group] = LEVEL_CTRL;
340 }
341
342 /* handle arguments */
343 for (;;)
344 {
345 struct option long_opts[] = {
346 { "help", no_argument, NULL, 'h' },
347 { "version", no_argument, NULL, 'v' },
348 { "use-syslog", no_argument, NULL, 'l' },
349 /* TODO: handle "debug-all" */
350 { "debug-dmn", required_argument, &group, DBG_DMN },
351 { "debug-mgr", required_argument, &group, DBG_MGR },
352 { "debug-ike", required_argument, &group, DBG_IKE },
353 { "debug-chd", required_argument, &group, DBG_CHD },
354 { "debug-job", required_argument, &group, DBG_JOB },
355 { "debug-cfg", required_argument, &group, DBG_CFG },
356 { "debug-knl", required_argument, &group, DBG_KNL },
357 { "debug-net", required_argument, &group, DBG_NET },
358 { "debug-asn", required_argument, &group, DBG_ASN },
359 { "debug-enc", required_argument, &group, DBG_ENC },
360 { "debug-tnc", required_argument, &group, DBG_TNC },
361 { "debug-imc", required_argument, &group, DBG_IMC },
362 { "debug-imv", required_argument, &group, DBG_IMV },
363 { "debug-pts", required_argument, &group, DBG_PTS },
364 { "debug-tls", required_argument, &group, DBG_TLS },
365 { "debug-esp", required_argument, &group, DBG_ESP },
366 { "debug-lib", required_argument, &group, DBG_LIB },
367 { 0,0,0,0 }
368 };
369
370 int c = getopt_long(argc, argv, "", long_opts, NULL);
371 switch (c)
372 {
373 case EOF:
374 break;
375 case 'h':
376 usage(NULL);
377 status = 0;
378 goto deinit;
379 case 'v':
380 printf("Linux strongSwan %s\n", VERSION);
381 status = 0;
382 goto deinit;
383 case 'l':
384 use_syslog = TRUE;
385 continue;
386 case 0:
387 /* option is in group */
388 levels[group] = atoi(optarg);
389 continue;
390 default:
391 usage("");
392 status = 1;
393 goto deinit;
394 }
395 break;
396 }
397
398 if (!lookup_uid_gid())
399 {
400 dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
401 goto deinit;
402 }
403
404 charon->set_default_loggers(charon, levels, !use_syslog);
405 charon->load_loggers(charon);
406
407 if (uname(&utsname) != 0)
408 {
409 memset(&utsname, 0, sizeof(utsname));
410 }
411 DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
412 utsname.sysname, utsname.release, utsname.machine);
413 if (lib->integrity)
414 {
415 DBG1(DBG_DMN, "integrity tests enabled:");
416 DBG1(DBG_DMN, "lib 'libstrongswan': passed file and segment integrity tests");
417 DBG1(DBG_DMN, "lib 'libcharon': passed file and segment integrity tests");
418 DBG1(DBG_DMN, "daemon 'charon': passed file integrity test");
419 }
420
421 /* initialize daemon */
422 if (!charon->initialize(charon,
423 lib->settings->get_str(lib->settings, "charon.load", PLUGINS)))
424 {
425 DBG1(DBG_DMN, "initialization failed - aborting charon");
426 goto deinit;
427 }
428 lib->plugins->status(lib->plugins, LEVEL_CTRL);
429
430 if (check_pidfile())
431 {
432 goto deinit;
433 }
434
435 if (!lib->caps->drop(lib->caps))
436 {
437 DBG1(DBG_DMN, "capability dropping failed - aborting charon");
438 goto deinit;
439 }
440
441 /* add handler for SEGV and ILL,
442 * INT, TERM and HUP are handled by sigwaitinfo() in run() */
443 action.sa_handler = segv_handler;
444 action.sa_flags = 0;
445 sigemptyset(&action.sa_mask);
446 sigaddset(&action.sa_mask, SIGINT);
447 sigaddset(&action.sa_mask, SIGTERM);
448 sigaddset(&action.sa_mask, SIGHUP);
449 sigaction(SIGSEGV, &action, NULL);
450 sigaction(SIGILL, &action, NULL);
451 sigaction(SIGBUS, &action, NULL);
452 action.sa_handler = SIG_IGN;
453 sigaction(SIGPIPE, &action, NULL);
454
455 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
456
457 /* start daemon (i.e. the threads in the thread-pool) */
458 charon->start(charon);
459
460 /* main thread goes to run loop */
461 run();
462
463 status = 0;
464
465 deinit:
466 libcharon_deinit();
467 unlink_pidfile();
468 library_deinit();
469 return status;
470 }