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