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