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