(no commit message)
[strongswan.git] / src / pluto / plutomain.c
1 /* Pluto main program
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 *
15 * RCSID $Id: plutomain.c,v 1.16 2005/09/25 21:30:52 as Exp $
16 */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/un.h>
27 #include <fcntl.h>
28 #include <getopt.h>
29 #include <resolv.h>
30 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
31 #include <sys/queue.h>
32
33 #include <freeswan.h>
34
35 #include <pfkeyv2.h>
36 #include <pfkey.h>
37
38 #include "constants.h"
39 #include "defs.h"
40 #include "id.h"
41 #include "ca.h"
42 #include "certs.h"
43 #include "ac.h"
44 #include "connections.h"
45 #include "foodgroups.h"
46 #include "packet.h"
47 #include "demux.h" /* needs packet.h */
48 #include "server.h"
49 #include "kernel.h"
50 #include "log.h"
51 #include "keys.h"
52 #include "adns.h" /* needs <resolv.h> */
53 #include "dnskey.h" /* needs keys.h and adns.h */
54 #include "rnd.h"
55 #include "state.h"
56 #include "ipsec_doi.h" /* needs demux.h and state.h */
57 #include "ocsp.h"
58 #include "crl.h"
59 #include "fetch.h"
60
61 #include "sha1.h"
62 #include "md5.h"
63 #include "crypto.h" /* requires sha1.h and md5.h */
64
65 #ifdef VIRTUAL_IP
66 #include "virtual.h"
67 #endif
68
69 #ifdef NAT_TRAVERSAL
70 #include "nat_traversal.h"
71 #endif
72
73 static void
74 usage(const char *mess)
75 {
76 if (mess != NULL && *mess != '\0')
77 fprintf(stderr, "%s\n", mess);
78 fprintf(stderr
79 , "Usage: pluto"
80 " [--help]"
81 " [--version]"
82 " [--optionsfrom <filename>]"
83 " \\\n\t"
84 "[--nofork]"
85 " [--stderrlog]"
86 " [--noklips]"
87 " [--nocrsend]"
88 " \\\n\t"
89 "[--strictcrlpolicy]"
90 " [--crlcheckinterval]"
91 " [--cachecrls]"
92 " [--uniqueids]"
93 " \\\n\t"
94 "[--interface <ifname>]"
95 " [--ikeport <port-number>]"
96 " \\\n\t"
97 "[--ctlbase <path>]"
98 " \\\n\t"
99 "[--perpeerlogbase <path>] [--perpeerlog]"
100 " \\\n\t"
101 "[--secretsfile <secrets-file>]"
102 " [--policygroupsdir <policygroups-dir>]"
103 " \\\n\t"
104 "[--adns <pathname>]"
105 "[--pkcs11module <path>]"
106 "[--pkcs11keepstate"
107 #ifdef DEBUG
108 " \\\n\t"
109 "[--debug-none]"
110 " [--debug-all]"
111 " \\\n\t"
112 "[--debug-raw]"
113 " [--debug-crypt]"
114 " [--debug-parsing]"
115 " [--debug-emitting]"
116 " \\\n\t"
117 "[--debug-control]"
118 " [--debug-lifecycle]"
119 " [--debug-klips]"
120 " [--debug-dns]"
121 " \\\n\t"
122 "[--debug-oppo]"
123 " [--debug-controlmore]"
124 " [--debug-private]"
125 #endif
126 #ifdef NAT_TRAVERSAL
127 " [ --debug-natt]"
128 " \\\n\t"
129 "[--nat_traversal] [--keep_alive <delay_sec>]"
130 " \\\n\t"
131 "[--force_keepalive] [--disable_port_floating]"
132 #endif
133 #ifdef VIRTUAL_IP
134 " \\\n\t"
135 "[--virtual_private <network_list>]"
136 #endif
137 "\n"
138 "strongSwan %s\n"
139 , ipsec_version_code());
140 exit_pluto(mess == NULL? 0 : 1);
141 }
142
143
144 /* lock file support
145 * - provides convenient way for scripts to find Pluto's pid
146 * - prevents multiple Plutos competing for the same port
147 * - same basename as unix domain control socket
148 * NOTE: will not take account of sharing LOCK_DIR with other systems.
149 */
150
151 static char pluto_lock[sizeof(ctl_addr.sun_path)] = DEFAULT_CTLBASE LOCK_SUFFIX;
152 static bool pluto_lock_created = FALSE;
153
154 /* create lockfile, or die in the attempt */
155 static int
156 create_lock(void)
157 {
158 int fd = open(pluto_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC
159 , S_IRUSR | S_IRGRP | S_IROTH);
160
161 if (fd < 0)
162 {
163 if (errno == EEXIST)
164 {
165 fprintf(stderr, "pluto: lock file \"%s\" already exists\n"
166 , pluto_lock);
167 exit_pluto(10);
168 }
169 else
170 {
171 fprintf(stderr
172 , "pluto: unable to create lock file \"%s\" (%d %s)\n"
173 , pluto_lock, errno, strerror(errno));
174 exit_pluto(1);
175 }
176 }
177 pluto_lock_created = TRUE;
178 return fd;
179 }
180
181 static bool
182 fill_lock(int lockfd, pid_t pid)
183 {
184 char buf[30]; /* holds "<pid>\n" */
185 int len = snprintf(buf, sizeof(buf), "%u\n", (unsigned int) pid);
186 bool ok = len > 0 && write(lockfd, buf, len) == len;
187
188 close(lockfd);
189 return ok;
190 }
191
192 static void
193 delete_lock(void)
194 {
195 if (pluto_lock_created)
196 {
197 delete_ctl_socket();
198 unlink(pluto_lock); /* is noting failure useful? */
199 }
200 }
201
202 /* by default pluto sends certificate requests to its peers */
203 bool no_cr_send = FALSE;
204
205 /* by default the CRL policy is lenient */
206 bool strict_crl_policy = FALSE;
207
208 /* by default CRLs are cached locally as files */
209 bool cache_crls = FALSE;
210
211 /* by default pluto does not check crls dynamically */
212 long crl_check_interval = 0;
213
214 /* path to the PKCS#11 module */
215 char *pkcs11_module_path = NULL;
216
217 /* by default pluto logs out after every smartcard use */
218 bool pkcs11_keep_state = FALSE;
219
220 /* by default pluto does not allow pkcs11 proxy access via whack */
221 bool pkcs11_proxy = FALSE;
222
223 int
224 main(int argc, char **argv)
225 {
226 bool fork_desired = TRUE;
227 bool log_to_stderr_desired = FALSE;
228 #ifdef NAT_TRAVERSAL
229 bool nat_traversal = FALSE;
230 bool nat_t_spf = TRUE; /* support port floating */
231 unsigned int keep_alive = 0;
232 bool force_keepalive = FALSE;
233 #endif
234 #ifdef VIRTUAL_IP
235 char *virtual_private = NULL;
236 #endif
237 int lockfd;
238
239 /* handle arguments */
240 for (;;)
241 {
242 # define DBG_OFFSET 256
243 static const struct option long_opts[] = {
244 /* name, has_arg, flag, val */
245 { "help", no_argument, NULL, 'h' },
246 { "version", no_argument, NULL, 'v' },
247 { "optionsfrom", required_argument, NULL, '+' },
248 { "nofork", no_argument, NULL, 'd' },
249 { "stderrlog", no_argument, NULL, 'e' },
250 { "noklips", no_argument, NULL, 'n' },
251 { "nocrsend", no_argument, NULL, 'c' },
252 { "strictcrlpolicy", no_argument, NULL, 'r' },
253 { "crlcheckinterval", required_argument, NULL, 'x'},
254 { "cachecrls", no_argument, NULL, 'C' },
255 { "uniqueids", no_argument, NULL, 'u' },
256 { "interface", required_argument, NULL, 'i' },
257 { "ikeport", required_argument, NULL, 'p' },
258 { "ctlbase", required_argument, NULL, 'b' },
259 { "secretsfile", required_argument, NULL, 's' },
260 { "foodgroupsdir", required_argument, NULL, 'f' },
261 { "perpeerlogbase", required_argument, NULL, 'P' },
262 { "perpeerlog", no_argument, NULL, 'l' },
263 { "policygroupsdir", required_argument, NULL, 'f' },
264 #ifdef USE_LWRES
265 { "lwdnsq", required_argument, NULL, 'a' },
266 #else /* !USE_LWRES */
267 { "adns", required_argument, NULL, 'a' },
268 #endif /* !USE_LWRES */
269 { "pkcs11module", required_argument, NULL, 'm' },
270 { "pkcs11keepstate", no_argument, NULL, 'k' },
271 { "pkcs11proxy", no_argument, NULL, 'y' },
272 #ifdef NAT_TRAVERSAL
273 { "nat_traversal", no_argument, NULL, '1' },
274 { "keep_alive", required_argument, NULL, '2' },
275 { "force_keepalive", no_argument, NULL, '3' },
276 { "disable_port_floating", no_argument, NULL, '4' },
277 { "debug-natt", no_argument, NULL, '5' },
278 #endif
279 #ifdef VIRTUAL_IP
280 { "virtual_private", required_argument, NULL, '6' },
281 #endif
282 #ifdef DEBUG
283 { "debug-none", no_argument, NULL, 'N' },
284 { "debug-all", no_argument, NULL, 'A' },
285
286 { "debug-raw", no_argument, NULL, DBG_RAW + DBG_OFFSET },
287 { "debug-crypt", no_argument, NULL, DBG_CRYPT + DBG_OFFSET },
288 { "debug-parsing", no_argument, NULL, DBG_PARSING + DBG_OFFSET },
289 { "debug-emitting", no_argument, NULL, DBG_EMITTING + DBG_OFFSET },
290 { "debug-control", no_argument, NULL, DBG_CONTROL + DBG_OFFSET },
291 { "debug-lifecycle", no_argument, NULL, DBG_LIFECYCLE + DBG_OFFSET },
292 { "debug-klips", no_argument, NULL, DBG_KLIPS + DBG_OFFSET },
293 { "debug-dns", no_argument, NULL, DBG_DNS + DBG_OFFSET },
294 { "debug-oppo", no_argument, NULL, DBG_OPPO + DBG_OFFSET },
295 { "debug-controlmore", no_argument, NULL, DBG_CONTROLMORE + DBG_OFFSET },
296 { "debug-private", no_argument, NULL, DBG_PRIVATE + DBG_OFFSET },
297
298 { "impair-delay-adns-key-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_KEY_ANSWER + DBG_OFFSET },
299 { "impair-delay-adns-txt-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_TXT_ANSWER + DBG_OFFSET },
300 { "impair-bust-mi2", no_argument, NULL, IMPAIR_BUST_MI2 + DBG_OFFSET },
301 { "impair-bust-mr2", no_argument, NULL, IMPAIR_BUST_MR2 + DBG_OFFSET },
302 #endif
303 { 0,0,0,0 }
304 };
305 /* Note: we don't like the way short options get parsed
306 * by getopt_long, so we simply pass an empty string as
307 * the list. It could be "hvdenp:l:s:" "NARXPECK".
308 */
309 int c = getopt_long(argc, argv, "", long_opts, NULL);
310
311 /* Note: "breaking" from case terminates loop */
312 switch (c)
313 {
314 case EOF: /* end of flags */
315 break;
316
317 case 0: /* long option already handled */
318 continue;
319
320 case ':': /* diagnostic already printed by getopt_long */
321 case '?': /* diagnostic already printed by getopt_long */
322 usage("");
323 break; /* not actually reached */
324
325 case 'h': /* --help */
326 usage(NULL);
327 break; /* not actually reached */
328
329 case 'v': /* --version */
330 {
331 const char **sp = ipsec_copyright_notice();
332
333 printf("%s%s\n", ipsec_version_string(),
334 compile_time_interop_options);
335 for (; *sp != NULL; sp++)
336 puts(*sp);
337 }
338 exit_pluto(0);
339 break; /* not actually reached */
340
341 case '+': /* --optionsfrom <filename> */
342 optionsfrom(optarg, &argc, &argv, optind, stderr);
343 /* does not return on error */
344 continue;
345
346 case 'd': /* --nofork*/
347 fork_desired = FALSE;
348 continue;
349
350 case 'e': /* --stderrlog */
351 log_to_stderr_desired = TRUE;
352 continue;
353
354 case 'n': /* --noklips */
355 no_klips = TRUE;
356 continue;
357
358 case 'c': /* --nocrsend */
359 no_cr_send = TRUE;
360 continue;
361
362 case 'r': /* --strictcrlpolicy */
363 strict_crl_policy = TRUE;
364 continue;
365
366 case 'x': /* --crlcheckinterval <time>*/
367 if (optarg == NULL || !isdigit(optarg[0]))
368 usage("missing interval time");
369
370 {
371 char *endptr;
372 long interval = strtol(optarg, &endptr, 0);
373
374 if (*endptr != '\0' || endptr == optarg
375 || interval <= 0)
376 usage("<interval-time> must be a positive number");
377 crl_check_interval = interval;
378 }
379 continue;
380
381 case 'C': /* --cachecrls */
382 cache_crls = TRUE;
383 continue;
384
385 case 'u': /* --uniqueids */
386 uniqueIDs = TRUE;
387 continue;
388
389 case 'i': /* --interface <ifname> */
390 if (!use_interface(optarg))
391 usage("too many --interface specifications");
392 continue;
393
394 case 'p': /* --port <portnumber> */
395 if (optarg == NULL || !isdigit(optarg[0]))
396 usage("missing port number");
397
398 {
399 char *endptr;
400 long port = strtol(optarg, &endptr, 0);
401
402 if (*endptr != '\0' || endptr == optarg
403 || port <= 0 || port > 0x10000)
404 usage("<port-number> must be a number between 1 and 65535");
405 pluto_port = port;
406 }
407 continue;
408
409 case 'b': /* --ctlbase <path> */
410 if (snprintf(ctl_addr.sun_path, sizeof(ctl_addr.sun_path)
411 , "%s%s", optarg, CTL_SUFFIX) == -1)
412 usage("<path>" CTL_SUFFIX " too long for sun_path");
413 if (snprintf(info_addr.sun_path, sizeof(info_addr.sun_path)
414 , "%s%s", optarg, INFO_SUFFIX) == -1)
415 usage("<path>" INFO_SUFFIX " too long for sun_path");
416 if (snprintf(pluto_lock, sizeof(pluto_lock)
417 , "%s%s", optarg, LOCK_SUFFIX) == -1)
418 usage("<path>" LOCK_SUFFIX " must fit");
419 continue;
420
421 case 's': /* --secretsfile <secrets-file> */
422 shared_secrets_file = optarg;
423 continue;
424
425 case 'f': /* --policygroupsdir <policygroups-dir> */
426 policygroups_dir = optarg;
427 continue;
428
429 case 'a': /* --adns <pathname> */
430 pluto_adns_option = optarg;
431 continue;
432
433 case 'm': /* --pkcs11module <pathname> */
434 pkcs11_module_path = optarg;
435 continue;
436
437 case 'k': /* --pkcs11keepstate */
438 pkcs11_keep_state = TRUE;
439 continue;
440
441 case 'y': /* --pkcs11proxy */
442 pkcs11_proxy = TRUE;
443 continue;
444
445 #ifdef DEBUG
446 case 'N': /* --debug-none */
447 base_debugging = DBG_NONE;
448 continue;
449
450 case 'A': /* --debug-all */
451 base_debugging = DBG_ALL;
452 continue;
453 #endif
454
455 case 'P': /* --perpeerlogbase */
456 base_perpeer_logdir = optarg;
457 continue;
458
459 case 'l':
460 log_to_perpeer = TRUE;
461 continue;
462
463 #ifdef NAT_TRAVERSAL
464 case '1': /* --nat_traversal */
465 nat_traversal = TRUE;
466 continue;
467 case '2': /* --keep_alive */
468 keep_alive = atoi(optarg);
469 continue;
470 case '3': /* --force_keepalive */
471 force_keepalive = TRUE;
472 continue;
473 case '4': /* --disable_port_floating */
474 nat_t_spf = FALSE;
475 continue;
476 case '5': /* --debug-nat_t */
477 base_debugging |= DBG_NATT;
478 continue;
479 #endif
480 #ifdef VIRTUAL_IP
481 case '6': /* --virtual_private */
482 virtual_private = optarg;
483 continue;
484 #endif
485
486 default:
487 #ifdef DEBUG
488 if (c >= DBG_OFFSET)
489 {
490 base_debugging |= c - DBG_OFFSET;
491 continue;
492 }
493 # undef DBG_OFFSET
494 #endif
495 bad_case(c);
496 }
497 break;
498 }
499 if (optind != argc)
500 usage("unexpected argument");
501 reset_debugging();
502 lockfd = create_lock();
503
504 /* select between logging methods */
505
506 if (log_to_stderr_desired)
507 log_to_syslog = FALSE;
508 else
509 log_to_stderr = FALSE;
510
511 /* set the logging function of pfkey debugging */
512 #ifdef DEBUG
513 pfkey_debug_func = DBG_log;
514 #else
515 pfkey_debug_func = NULL;
516 #endif
517
518 /* create control socket.
519 * We must create it before the parent process returns so that
520 * there will be no race condition in using it. The easiest
521 * place to do this is before the daemon fork.
522 */
523 {
524 err_t ugh = init_ctl_socket();
525
526 if (ugh != NULL)
527 {
528 fprintf(stderr, "pluto: %s", ugh);
529 exit_pluto(1);
530 }
531 }
532
533 #ifdef IPSECPOLICY
534 /* create info socket. */
535 {
536 err_t ugh = init_info_socket();
537
538 if (ugh != NULL)
539 {
540 fprintf(stderr, "pluto: %s", ugh);
541 exit_pluto(1);
542 }
543 }
544 #endif
545
546 /* If not suppressed, do daemon fork */
547
548 if (fork_desired)
549 {
550 {
551 pid_t pid = fork();
552
553 if (pid < 0)
554 {
555 int e = errno;
556
557 fprintf(stderr, "pluto: fork failed (%d %s)\n",
558 errno, strerror(e));
559 exit_pluto(1);
560 }
561
562 if (pid != 0)
563 {
564 /* parent: die, after filling PID into lock file.
565 * must not use exit_pluto: lock would be removed!
566 */
567 exit(fill_lock(lockfd, pid)? 0 : 1);
568 }
569 }
570
571 if (setsid() < 0)
572 {
573 int e = errno;
574
575 fprintf(stderr, "setsid() failed in main(). Errno %d: %s\n",
576 errno, strerror(e));
577 exit_pluto(1);
578 }
579 }
580 else
581 {
582 /* no daemon fork: we have to fill in lock file */
583 (void) fill_lock(lockfd, getpid());
584 fprintf(stdout, "Pluto initialized\n");
585 fflush(stdout);
586 }
587
588 /* Close everything but ctl_fd and (if needed) stderr.
589 * There is some danger that a library that we don't know
590 * about is using some fd that we don't know about.
591 * I guess we'll soon find out.
592 */
593 {
594 int i;
595
596 for (i = getdtablesize() - 1; i >= 0; i--) /* Bad hack */
597 if ((!log_to_stderr || i != 2)
598 #ifdef IPSECPOLICY
599 && i != info_fd
600 #endif
601 && i != ctl_fd)
602 close(i);
603
604 /* make sure that stdin, stdout, stderr are reserved */
605 if (open("/dev/null", O_RDONLY) != 0)
606 abort();
607 if (dup2(0, 1) != 1)
608 abort();
609 if (!log_to_stderr && dup2(0, 2) != 2)
610 abort();
611 }
612
613 init_constants();
614 init_log("pluto");
615
616 /* Note: some scripts may look for this exact message -- don't change
617 * ipsec barf was one, but it no longer does.
618 */
619 plog("Starting Pluto (strongSwan Version %s%s)"
620 , ipsec_version_code()
621 , compile_time_interop_options);
622
623 #ifdef NAT_TRAVERSAL
624 init_nat_traversal(nat_traversal, keep_alive, force_keepalive, nat_t_spf);
625 #endif
626
627 #ifdef VIRTUAL_IP
628 init_virtual_ip(virtual_private);
629 #endif
630 scx_init(pkcs11_module_path); /* load and initialize PKCS #11 module */
631 init_rnd_pool();
632 init_secret();
633 init_states();
634 init_crypto();
635 init_demux();
636 init_kernel();
637 init_adns();
638 init_id();
639 init_fetch();
640
641 /* loading X.509 CA certificates */
642 load_authcerts("CA cert", CA_CERT_PATH, AUTH_CA);
643 /* loading X.509 AA certificates */
644 load_authcerts("AA cert", AA_CERT_PATH, AUTH_AA);
645 /* loading X.509 OCSP certificates */
646 load_authcerts("OCSP cert", OCSP_CERT_PATH, AUTH_OCSP);
647 /* loading X.509 CRLs */
648 load_crls();
649 /* loading attribute certificates (experimental) */
650 load_acerts();
651
652 daily_log_event();
653 call_server();
654 return -1; /* Shouldn't ever reach this */
655 }
656
657 /* leave pluto, with status.
658 * Once child is launched, parent must not exit this way because
659 * the lock would be released.
660 *
661 * 0 OK
662 * 1 general discomfort
663 * 10 lock file exists
664 */
665 void
666 exit_pluto(int status)
667 {
668 reset_globals(); /* needed because we may be called in odd state */
669 free_preshared_secrets();
670 free_remembered_public_keys();
671 delete_every_connection();
672 free_crl_fetch(); /* free chain of crl fetch requests */
673 free_ocsp_fetch(); /* free chain of ocsp fetch requests */
674 free_authcerts(); /* free chain of X.509 authority certificates */
675 free_crls(); /* free chain of X.509 CRLs */
676 free_acerts(); /* free chain of X.509 attribute certificates */
677 free_ca_infos(); /* free chain of X.509 CA information records */
678 free_ocsp(); /* free ocsp cache */
679 free_ifaces();
680 scx_finalize(); /* finalize and unload PKCS #11 module */
681 stop_adns();
682 free_md_pool();
683 delete_lock();
684 #ifdef LEAK_DETECTIVE
685 report_leaks();
686 #endif /* LEAK_DETECTIVE */
687 close_log();
688 exit(status);
689 }
690
691 /*
692 * Local Variables:
693 * c-basic-offset:4
694 * c-style: pluto
695 * End:
696 */