NEWS about eap-dynamic plugin added
[strongswan.git] / src / starter / starter.c
1 /* strongSwan IPsec starter
2 * Copyright (C) 2001-2002 Mathieu Lafon - Arkoon Network Security
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 */
14
15 #include <sys/select.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <sys/stat.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <signal.h>
22 #include <syslog.h>
23 #include <unistd.h>
24 #include <sys/time.h>
25 #include <time.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <pwd.h>
30 #include <grp.h>
31 #include <pthread.h>
32
33 #include <library.h>
34 #include <hydra.h>
35 #include <utils/backtrace.h>
36 #include <threading/thread.h>
37 #include <debug.h>
38
39 #include "confread.h"
40 #include "files.h"
41 #include "starterstroke.h"
42 #include "invokecharon.h"
43 #include "netkey.h"
44 #include "klips.h"
45 #include "cmp.h"
46
47 #ifndef LOG_AUTHPRIV
48 #define LOG_AUTHPRIV LOG_AUTH
49 #endif
50
51 #define CHARON_RESTART_DELAY 5
52
53 /* logging */
54 static bool log_to_stderr = TRUE;
55 static bool log_to_syslog = TRUE;
56 static level_t current_loglevel = 1;
57
58 /**
59 * logging function for scepclient
60 */
61 static void starter_dbg(debug_t group, level_t level, char *fmt, ...)
62 {
63 char buffer[8192];
64 char *current = buffer, *next;
65 va_list args;
66
67 if (level <= current_loglevel)
68 {
69 if (log_to_stderr)
70 {
71 va_start(args, fmt);
72 vfprintf(stderr, fmt, args);
73 va_end(args);
74 fprintf(stderr, "\n");
75 }
76 if (log_to_syslog)
77 {
78 /* write in memory buffer first */
79 va_start(args, fmt);
80 vsnprintf(buffer, sizeof(buffer), fmt, args);
81 va_end(args);
82
83 /* do a syslog with every line */
84 while (current)
85 {
86 next = strchr(current, '\n');
87 if (next)
88 {
89 *(next++) = '\0';
90 }
91 syslog(LOG_INFO, "%s\n", current);
92 current = next;
93 }
94 }
95 }
96 }
97
98 /**
99 * Initialize logging to stderr/syslog
100 */
101 static void init_log(const char *program)
102 {
103 dbg = starter_dbg;
104
105 if (log_to_stderr)
106 {
107 setbuf(stderr, NULL);
108 }
109 if (log_to_syslog)
110 {
111 openlog(program, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_AUTHPRIV);
112 }
113 }
114
115 /**
116 * Deinitialize logging to syslog
117 */
118 static void close_log()
119 {
120 if (log_to_syslog)
121 {
122 closelog();
123 }
124 }
125
126 /**
127 * Return codes defined by Linux Standard Base Core Specification 3.1
128 * in section 20.2. Init Script Actions
129 */
130 #define LSB_RC_SUCCESS 0 /* success */
131 #define LSB_RC_FAILURE 1 /* generic or unspecified error */
132 #define LSB_RC_INVALID_ARGUMENT 2 /* invalid or excess argument(s) */
133 #define LSB_RC_NOT_IMPLEMENTED 3 /* unimplemented feature (reload) */
134 #define LSB_RC_NOT_ALLOWED 4 /* user had insufficient privilege */
135 #define LSB_RC_NOT_INSTALLED 5 /* program is not installed */
136 #define LSB_RC_NOT_CONFIGURED 6 /* program is not configured */
137 #define LSB_RC_NOT_RUNNING 7 /* program is not running */
138
139 #define FLAG_ACTION_START_PLUTO 0x01
140 #define FLAG_ACTION_UPDATE 0x02
141 #define FLAG_ACTION_RELOAD 0x04
142 #define FLAG_ACTION_QUIT 0x08
143 #define FLAG_ACTION_LISTEN 0x10
144 #define FLAG_ACTION_START_CHARON 0x20
145
146 static unsigned int _action_ = 0;
147
148 /**
149 * Handle signals in the main thread
150 */
151 static void signal_handler(int signal)
152 {
153 switch (signal)
154 {
155 case SIGCHLD:
156 {
157 int status, exit_status = 0;
158 pid_t pid;
159 char *name = NULL;
160
161 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
162 {
163 if (pid == starter_charon_pid())
164 {
165 name = " (Charon)";
166 }
167 if (WIFSIGNALED(status))
168 {
169 DBG2(DBG_APP, "child %d%s has been killed by sig %d\n",
170 pid, name?name:"", WTERMSIG(status));
171 }
172 else if (WIFSTOPPED(status))
173 {
174 DBG2(DBG_APP, "child %d%s has been stopped by sig %d\n",
175 pid, name?name:"", WSTOPSIG(status));
176 }
177 else if (WIFEXITED(status))
178 {
179 exit_status = WEXITSTATUS(status);
180 if (exit_status >= SS_RC_FIRST && exit_status <= SS_RC_LAST)
181 {
182 _action_ = FLAG_ACTION_QUIT;
183 }
184 DBG2(DBG_APP, "child %d%s has quit (exit code %d)\n",
185 pid, name?name:"", exit_status);
186 }
187 else
188 {
189 DBG2(DBG_APP, "child %d%s has quit", pid, name?name:"");
190 }
191 if (pid == starter_charon_pid())
192 {
193 starter_charon_sigchild(pid, exit_status);
194 }
195 }
196 }
197 break;
198
199 case SIGALRM:
200 _action_ |= FLAG_ACTION_START_CHARON;
201 break;
202
203 case SIGHUP:
204 _action_ |= FLAG_ACTION_UPDATE;
205 break;
206
207 case SIGTERM:
208 case SIGQUIT:
209 case SIGINT:
210 _action_ |= FLAG_ACTION_QUIT;
211 break;
212
213 case SIGUSR1:
214 _action_ |= FLAG_ACTION_RELOAD;
215 _action_ |= FLAG_ACTION_UPDATE;
216 break;
217
218 default:
219 DBG1(DBG_APP, "fsig(): unknown signal %d -- investigate", signal);
220 break;
221 }
222 }
223
224 /**
225 * Handle fatal signals raised by threads
226 */
227 static void fatal_signal_handler(int signal)
228 {
229 backtrace_t *backtrace;
230
231 DBG1(DBG_APP, "thread %u received %d", thread_current_id(), signal);
232 backtrace = backtrace_create(2);
233 backtrace->log(backtrace, stderr, TRUE);
234 backtrace->destroy(backtrace);
235
236 DBG1(DBG_APP, "killing ourself, received critical signal");
237 abort();
238 }
239
240 #ifdef GENERATE_SELFCERT
241 static void generate_selfcert()
242 {
243 struct stat stb;
244
245 /* if ipsec.secrets file is missing then generate RSA default key pair */
246 if (stat(SECRETS_FILE, &stb) != 0)
247 {
248 mode_t oldmask;
249 FILE *f;
250 uid_t uid = 0;
251 gid_t gid = 0;
252
253 #ifdef IPSEC_GROUP
254 {
255 char buf[1024];
256 struct group group, *grp;
257
258 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) == 0 && grp)
259 {
260 gid = grp->gr_gid;
261 }
262 }
263 #endif
264 #ifdef IPSEC_USER
265 {
266 char buf[1024];
267 struct passwd passwd, *pwp;
268
269 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) == 0 && pwp)
270 {
271 uid = pwp->pw_uid;
272 }
273 }
274 #endif
275 setegid(gid);
276 seteuid(uid);
277 ignore_result(system("ipsec scepclient --out pkcs1 --out cert-self --quiet"));
278 seteuid(0);
279 setegid(0);
280
281 /* ipsec.secrets is root readable only */
282 oldmask = umask(0066);
283
284 f = fopen(SECRETS_FILE, "w");
285 if (f)
286 {
287 fprintf(f, "# /etc/ipsec.secrets - strongSwan IPsec secrets file\n");
288 fprintf(f, "\n");
289 fprintf(f, ": RSA myKey.der\n");
290 fclose(f);
291 }
292 ignore_result(chown(SECRETS_FILE, uid, gid));
293 umask(oldmask);
294 }
295 }
296 #endif /* GENERATE_SELFCERT */
297
298 static bool check_pid(char *pid_file)
299 {
300 struct stat stb;
301 FILE *pidfile;
302
303 if (stat(pid_file, &stb) == 0)
304 {
305 pidfile = fopen(pid_file, "r");
306 if (pidfile)
307 {
308 char buf[64];
309 pid_t pid = 0;
310 memset(buf, 0, sizeof(buf));
311 if (fread(buf, 1, sizeof(buf), pidfile))
312 {
313 buf[sizeof(buf) - 1] = '\0';
314 pid = atoi(buf);
315 }
316 fclose(pidfile);
317 if (pid && kill(pid, 0) == 0)
318 { /* such a process is running */
319 return TRUE;
320 }
321 }
322 DBG1(DBG_APP, "removing pidfile '%s', process not running", pid_file);
323 unlink(pid_file);
324 }
325 return FALSE;
326 }
327
328 static void usage(char *name)
329 {
330 fprintf(stderr, "Usage: starter [--nofork] [--auto-update <sec>] "
331 "[--debug|--debug-more|--debug-all]\n");
332 exit(LSB_RC_INVALID_ARGUMENT);
333 }
334
335 int main (int argc, char **argv)
336 {
337 starter_config_t *cfg = NULL;
338 starter_config_t *new_cfg;
339 starter_conn_t *conn, *conn2;
340 starter_ca_t *ca, *ca2;
341
342 struct sigaction action;
343 struct stat stb;
344
345 int i;
346 int id = 1;
347 struct timespec ts;
348 unsigned long auto_update = 0;
349 time_t last_reload;
350 bool no_fork = FALSE;
351 bool attach_gdb = FALSE;
352 bool load_warning = FALSE;
353
354 library_init(NULL);
355 atexit(library_deinit);
356
357 libhydra_init("starter");
358 atexit(libhydra_deinit);
359
360 /* parse command line */
361 for (i = 1; i < argc; i++)
362 {
363 if (streq(argv[i], "--debug"))
364 {
365 current_loglevel = 2;
366 }
367 else if (streq(argv[i], "--debug-more"))
368 {
369 current_loglevel = 3;
370 }
371 else if (streq(argv[i], "--debug-all"))
372 {
373 current_loglevel = 4;
374 }
375 else if (streq(argv[i], "--nofork"))
376 {
377 no_fork = TRUE;
378 }
379 else if (streq(argv[i], "--attach-gdb"))
380 {
381 no_fork = TRUE;
382 attach_gdb = TRUE;
383 }
384 else if (streq(argv[i], "--auto-update") && i+1 < argc)
385 {
386 auto_update = atoi(argv[++i]);
387 if (!auto_update)
388 usage(argv[0]);
389 }
390 else
391 {
392 usage(argv[0]);
393 }
394 }
395
396 init_log("ipsec_starter");
397
398 DBG1(DBG_APP, "Starting %sSwan "VERSION" IPsec [starter]...",
399 lib->settings->get_bool(lib->settings,
400 "charon.i_dont_care_about_security_and_use_aggressive_mode_psk",
401 FALSE) ? "weak" : "strong");
402
403 #ifdef LOAD_WARNING
404 load_warning = TRUE;
405 #endif
406
407 if (lib->settings->get_bool(lib->settings, "starter.load_warning", load_warning))
408 {
409 if (lib->settings->get_str(lib->settings, "charon.load", NULL))
410 {
411 DBG1(DBG_APP, "!! Your strongswan.conf contains manual plugin load options for charon.");
412 DBG1(DBG_APP, "!! This is recommended for experts only, see");
413 DBG1(DBG_APP, "!! http://wiki.strongswan.org/projects/strongswan/wiki/PluginLoad");
414 }
415 }
416
417 /* verify that we can start */
418 if (getuid() != 0)
419 {
420 DBG1(DBG_APP, "permission denied (must be superuser)");
421 exit(LSB_RC_NOT_ALLOWED);
422 }
423
424 if (check_pid(CHARON_PID_FILE))
425 {
426 DBG1(DBG_APP, "charon is already running (%s exists) -- skipping charon start",
427 CHARON_PID_FILE);
428 }
429 else
430 {
431 _action_ |= FLAG_ACTION_START_CHARON;
432 }
433 if (stat(DEV_RANDOM, &stb) != 0)
434 {
435 DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_RANDOM);
436 exit(LSB_RC_FAILURE);
437 }
438
439 if (stat(DEV_URANDOM, &stb)!= 0)
440 {
441 DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_URANDOM);
442 exit(LSB_RC_FAILURE);
443 }
444
445 cfg = confread_load(CONFIG_FILE);
446 if (cfg == NULL || cfg->err > 0)
447 {
448 DBG1(DBG_APP, "unable to start strongSwan -- fatal errors in config");
449 if (cfg)
450 {
451 confread_free(cfg);
452 }
453 exit(LSB_RC_INVALID_ARGUMENT);
454 }
455
456 /* determine if we have a native netkey IPsec stack */
457 if (!starter_netkey_init())
458 {
459 DBG1(DBG_APP, "no netkey IPsec stack detected");
460 if (!starter_klips_init())
461 {
462 DBG1(DBG_APP, "no KLIPS IPsec stack detected");
463 DBG1(DBG_APP, "no known IPsec stack detected, ignoring!");
464 }
465 }
466
467 last_reload = time_monotonic(NULL);
468
469 if (check_pid(STARTER_PID_FILE))
470 {
471 DBG1(DBG_APP, "starter is already running (%s exists) -- no fork done",
472 STARTER_PID_FILE);
473 confread_free(cfg);
474 exit(LSB_RC_SUCCESS);
475 }
476
477 #ifdef GENERATE_SELFCERT
478 generate_selfcert();
479 #endif
480
481 /* fork if we're not debugging stuff */
482 if (!no_fork)
483 {
484 log_to_stderr = FALSE;
485
486 switch (fork())
487 {
488 case 0:
489 {
490 int fnull;
491
492 close_log();
493 closefrom(3);
494
495 fnull = open("/dev/null", O_RDWR);
496 if (fnull >= 0)
497 {
498 dup2(fnull, STDIN_FILENO);
499 dup2(fnull, STDOUT_FILENO);
500 dup2(fnull, STDERR_FILENO);
501 close(fnull);
502 }
503
504 setsid();
505 init_log("ipsec_starter");
506 }
507 break;
508 case -1:
509 DBG1(DBG_APP, "can't fork: %s", strerror(errno));
510 break;
511 default:
512 confread_free(cfg);
513 exit(LSB_RC_SUCCESS);
514 }
515 }
516
517 /* save pid file in /var/run/starter.pid */
518 {
519 FILE *fd = fopen(STARTER_PID_FILE, "w");
520
521 if (fd)
522 {
523 fprintf(fd, "%u\n", getpid());
524 fclose(fd);
525 }
526 }
527
528 /* we handle these signals only in pselect() */
529 memset(&action, 0, sizeof(action));
530 sigemptyset(&action.sa_mask);
531 sigaddset(&action.sa_mask, SIGHUP);
532 sigaddset(&action.sa_mask, SIGINT);
533 sigaddset(&action.sa_mask, SIGTERM);
534 sigaddset(&action.sa_mask, SIGQUIT);
535 sigaddset(&action.sa_mask, SIGALRM);
536 sigaddset(&action.sa_mask, SIGUSR1);
537 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
538
539 /* install a handler for fatal signals */
540 action.sa_handler = fatal_signal_handler;
541 sigaction(SIGSEGV, &action, NULL);
542 sigaction(SIGILL, &action, NULL);
543 sigaction(SIGBUS, &action, NULL);
544 action.sa_handler = SIG_IGN;
545 sigaction(SIGPIPE, &action, NULL);
546
547 /* install main signal handler */
548 action.sa_handler = signal_handler;
549 sigaction(SIGHUP, &action, NULL);
550 sigaction(SIGINT, &action, NULL);
551 sigaction(SIGTERM, &action, NULL);
552 sigaction(SIGQUIT, &action, NULL);
553 sigaction(SIGALRM, &action, NULL);
554 sigaction(SIGUSR1, &action, NULL);
555 /* this is not blocked above as we want to receive it asynchronously */
556 sigaction(SIGCHLD, &action, NULL);
557
558 /* empty mask for pselect() call below */
559 sigemptyset(&action.sa_mask);
560
561 for (;;)
562 {
563 /*
564 * Stop charon (if started) and exit
565 */
566 if (_action_ & FLAG_ACTION_QUIT)
567 {
568 if (starter_charon_pid())
569 {
570 starter_stop_charon();
571 }
572 starter_netkey_cleanup();
573 confread_free(cfg);
574 unlink(STARTER_PID_FILE);
575 DBG1(DBG_APP, "ipsec starter stopped");
576 close_log();
577 exit(LSB_RC_SUCCESS);
578 }
579
580 /*
581 * Delete all connections. Will be added below
582 */
583 if (_action_ & FLAG_ACTION_RELOAD)
584 {
585 if (starter_charon_pid())
586 {
587 for (conn = cfg->conn_first; conn; conn = conn->next)
588 {
589 if (conn->state == STATE_ADDED)
590 {
591 if (starter_charon_pid())
592 {
593 starter_stroke_del_conn(conn);
594 }
595 conn->state = STATE_TO_ADD;
596 }
597 }
598 for (ca = cfg->ca_first; ca; ca = ca->next)
599 {
600 if (ca->state == STATE_ADDED)
601 {
602 if (starter_charon_pid())
603 {
604 starter_stroke_del_ca(ca);
605 }
606 ca->state = STATE_TO_ADD;
607 }
608 }
609 }
610 _action_ &= ~FLAG_ACTION_RELOAD;
611 }
612
613 /*
614 * Update configuration
615 */
616 if (_action_ & FLAG_ACTION_UPDATE)
617 {
618 DBG2(DBG_APP, "Reloading config...");
619 new_cfg = confread_load(CONFIG_FILE);
620
621 if (new_cfg && (new_cfg->err + new_cfg->non_fatal_err == 0))
622 {
623 /* Switch to new config. New conn will be loaded below */
624
625 /* Look for new connections that are already loaded */
626 for (conn = cfg->conn_first; conn; conn = conn->next)
627 {
628 if (conn->state == STATE_ADDED)
629 {
630 for (conn2 = new_cfg->conn_first; conn2; conn2 = conn2->next)
631 {
632 if (conn2->state == STATE_TO_ADD && starter_cmp_conn(conn, conn2))
633 {
634 conn->state = STATE_REPLACED;
635 conn2->state = STATE_ADDED;
636 conn2->id = conn->id;
637 break;
638 }
639 }
640 }
641 }
642
643 /* Remove conn sections that have become unused */
644 for (conn = cfg->conn_first; conn; conn = conn->next)
645 {
646 if (conn->state == STATE_ADDED)
647 {
648 if (starter_charon_pid())
649 {
650 starter_stroke_del_conn(conn);
651 }
652 }
653 }
654
655 /* Look for new ca sections that are already loaded */
656 for (ca = cfg->ca_first; ca; ca = ca->next)
657 {
658 if (ca->state == STATE_ADDED)
659 {
660 for (ca2 = new_cfg->ca_first; ca2; ca2 = ca2->next)
661 {
662 if (ca2->state == STATE_TO_ADD && starter_cmp_ca(ca, ca2))
663 {
664 ca->state = STATE_REPLACED;
665 ca2->state = STATE_ADDED;
666 break;
667 }
668 }
669 }
670 }
671
672 /* Remove ca sections that have become unused */
673 for (ca = cfg->ca_first; ca; ca = ca->next)
674 {
675 if (ca->state == STATE_ADDED)
676 {
677 if (starter_charon_pid())
678 {
679 starter_stroke_del_ca(ca);
680 }
681 }
682 }
683 confread_free(cfg);
684 cfg = new_cfg;
685 }
686 else
687 {
688 DBG1(DBG_APP, "can't reload config file due to errors -- keeping old one");
689 if (new_cfg)
690 {
691 confread_free(new_cfg);
692 }
693 }
694 _action_ &= ~FLAG_ACTION_UPDATE;
695 last_reload = time_monotonic(NULL);
696 }
697
698 /*
699 * Start charon
700 */
701 if (_action_ & FLAG_ACTION_START_CHARON)
702 {
703 if (cfg->setup.charonstart && !starter_charon_pid())
704 {
705 DBG2(DBG_APP, "Attempting to start charon...");
706 if (starter_start_charon(cfg, no_fork, attach_gdb))
707 {
708 /* schedule next try */
709 alarm(CHARON_RESTART_DELAY);
710 }
711 starter_stroke_configure(cfg);
712 }
713 _action_ &= ~FLAG_ACTION_START_CHARON;
714 }
715
716 /*
717 * Add stale conn and ca sections
718 */
719 if (starter_charon_pid())
720 {
721 for (ca = cfg->ca_first; ca; ca = ca->next)
722 {
723 if (ca->state == STATE_TO_ADD)
724 {
725 if (starter_charon_pid())
726 {
727 starter_stroke_add_ca(ca);
728 }
729 ca->state = STATE_ADDED;
730 }
731 }
732
733 for (conn = cfg->conn_first; conn; conn = conn->next)
734 {
735 if (conn->state == STATE_TO_ADD)
736 {
737 if (conn->id == 0)
738 {
739 /* affect new unique id */
740 conn->id = id++;
741 }
742 if (starter_charon_pid())
743 {
744 starter_stroke_add_conn(cfg, conn);
745 }
746 conn->state = STATE_ADDED;
747
748 if (conn->startup == STARTUP_START)
749 {
750 if (starter_charon_pid())
751 {
752 starter_stroke_initiate_conn(conn);
753 }
754 }
755 else if (conn->startup == STARTUP_ROUTE)
756 {
757 if (starter_charon_pid())
758 {
759 starter_stroke_route_conn(conn);
760 }
761 }
762 }
763 }
764 }
765
766 /*
767 * If auto_update activated, when to stop select
768 */
769 if (auto_update)
770 {
771 time_t now = time_monotonic(NULL);
772
773 ts.tv_sec = (now < last_reload + auto_update) ?
774 (last_reload + auto_update - now) : 0;
775 ts.tv_nsec = 0;
776 }
777
778 /*
779 * Wait for something to happen
780 */
781 if (pselect(0, NULL, NULL, NULL, auto_update ? &ts : NULL,
782 &action.sa_mask) == 0)
783 {
784 /* timeout -> auto_update */
785 _action_ |= FLAG_ACTION_UPDATE;
786 }
787 }
788 exit(LSB_RC_SUCCESS);
789 }
790