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