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