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