Exemple #1
0
int main(int arc, char *argv[])
{
	dispatcher_t *dispatcher;
	database_t *db;
	char *socket;
	bool debug;
	char *uri;
	int timeout, threads;

	library_init(NULL);
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "medsrv.load", PLUGINS)))
	{
		return 1;
	}

	socket = lib->settings->get_str(lib->settings, "medsrv.socket", NULL);
	debug = lib->settings->get_bool(lib->settings, "medsrv.debug", FALSE);
	timeout = lib->settings->get_time(lib->settings, "medsrv.timeout", 900);
	threads = lib->settings->get_int(lib->settings, "medsrv.threads", 5);
	uri = lib->settings->get_str(lib->settings, "medsrv.database", NULL);
	if (uri == NULL)
	{
		fprintf(stderr, "database URI medsrv.database not defined.\n");
		return 1;
	}

	db = lib->db->create(lib->db, uri);
	if (db == NULL)
	{
		fprintf(stderr, "opening database failed.\n");
		return 1;
	}

	dispatcher = dispatcher_create(socket, debug, timeout,
								   (context_constructor_t)user_create, db);
	dispatcher->add_filter(dispatcher,
						(filter_constructor_t)auth_filter_create, db);
	dispatcher->add_controller(dispatcher,
						(controller_constructor_t)user_controller_create, db);
	dispatcher->add_controller(dispatcher,
						(controller_constructor_t)peer_controller_create, db);

	dispatcher->run(dispatcher, threads);

	dispatcher->waitsignal(dispatcher);
	dispatcher->destroy(dispatcher);
	db->destroy(db);

	library_deinit();
	return 0;
}
Exemple #2
0
/**
 * Initialize library
 */
static void init()
{
    library_init(NULL, "tls_test");

    dbg = dbg_tls;

    lib->plugins->load(lib->plugins, PLUGINS);

    creds = mem_cred_create();
    lib->credmgr->add_set(lib->credmgr, &creds->set);

    atexit(cleanup);
}
int main(int argc, char* argv[])
{
	int i;

	/* forces link against libcharon, imports symbols needed to
	 * dlopen plugins */
	charon = NULL;

	/* avoid confusing leak reports in build process */
	setenv("LEAK_DETECTIVE_DISABLE", "1", 0);
	/* don't use a strongswan.conf, forces integrity check to disabled */
	library_init("", "checksum_builder");
	atexit(library_deinit);

	integrity = integrity_checker_create(NULL);

	printf("/**\n");
	printf(" * checksums of files and loaded code segments.\n");
	printf(" * created by %s\n", argv[0]);
	printf(" */\n");
	printf("\n");
	printf("#include <library.h>\n");
	printf("\n");
	printf("integrity_checksum_t checksums[] = {\n");
	fprintf(stderr, "integrity test data:\n");
	fprintf(stderr, "module name,            file size / checksum   "
					"segment size / checksum\n");
	for (i = 1; i < argc; i++)
	{
		build_binary_checksum(argv[i]);
	}
#ifdef S_PLUGINS
	build_plugin_checksums(S_PLUGINS);
#endif
#ifdef T_PLUGINS
	build_plugin_checksums(T_PLUGINS);
#endif
#ifdef C_PLUGINS
	build_plugin_checksums(C_PLUGINS);
#endif

	printf("};\n");
	printf("\n");
	printf("int checksum_count = countof(checksums);\n");
	printf("\n");
	integrity->destroy(integrity);

	exit(0);
}
/**
 * Load all available test suites, or optionally only selected ones.
 */
static array_t *load_suites(test_configuration_t configs[],
							test_runner_init_t init, char *cfg)
{
	array_t *suites;
	bool old = FALSE;
	int i;

	library_init(cfg, "test-runner");

	test_setup_handler();

	if (init && !init(TRUE))
	{
		library_deinit();
		return NULL;
	}
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	if (lib->leak_detective)
	{
		old = lib->leak_detective->set_state(lib->leak_detective, FALSE);
	}

	suites = array_create(0, 0);

	for (i = 0; configs[i].suite; i++)
	{
		if (configs[i].feature.type == 0 ||
			lib->plugins->has_feature(lib->plugins, configs[i].feature))
		{
			array_insert(suites, -1, configs[i].suite());
		}
	}
	filter_suites(suites);

	if (lib->leak_detective)
	{
		lib->leak_detective->set_state(lib->leak_detective, old);
	}

	if (init)
	{
		init(FALSE);
	}
	library_deinit();

	return suites;
}
Exemple #5
0
int main(int argc, char *argv[])
{
	char *uri;

	atexit(library_deinit);

	/* initialize library */
	if (!library_init(NULL, "pool"))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "pool", argv[0]))
	{
		fprintf(stderr, "integrity check of pool failed\n");
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "pool.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	/* TODO: make database URI or setting key configurable via command line */
	uri = lib->settings->get_str(lib->settings,
			"pool.database",
			lib->settings->get_str(lib->settings,
				"charon.plugins.attr-sql.database",
				lib->settings->get_str(lib->settings,
					"libhydra.plugins.attr-sql.database", NULL)));
	if (!uri)
	{
		fprintf(stderr, "database URI pool.database not set.\n");
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	db = lib->db->create(lib->db, uri);
	if (!db)
	{
		fprintf(stderr, "opening database failed.\n");
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	atexit(cleanup);

	do_args(argc, argv);

	exit(EXIT_SUCCESS);
}
Exemple #6
0
/**
 * Library initialization and operation parsing
 */
int main(int argc, char *argv[])
{
	atexit(library_deinit);
	if (!library_init(NULL))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "pki", argv[0]))
	{
		fprintf(stderr, "integrity check of pki failed\n");
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "pki.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	return command_dispatch(argc, argv);
}
Exemple #7
0
int main(int argc, char *argv[])
{
	/* enable attest debugging hook */
	dbg = pacman_dbg;
	openlog("pacman", 0, LOG_DEBUG);

	atexit(cleanup);

	/* initialize library */
	if (!library_init(NULL, "pacman"))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "pacman.load", "sqlite")))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	do_args(argc, argv);

	exit(EXIT_SUCCESS);
}
int main(int argc, char* argv[])
{
	int i;

	/* avoid confusing leak reports in build process */
	setenv("LEAK_DETECTIVE_DISABLE", "1", 0);
	library_init(NULL);
	atexit(library_deinit);

	integrity = integrity_checker_create(NULL);

	printf("/**\n");
	printf(" * checksums of files and loaded code segments.\n");
	printf(" * created by %s\n", argv[0]);
	printf(" */\n");
	printf("\n");
	printf("#include <library.h>\n");
	printf("\n");
	printf("integrity_checksum_t checksums[] = {\n");
	fprintf(stderr, "integrity test data:\n");
	fprintf(stderr, "module name,       file size / checksum   segment size / checksum\n");
	for (i = 1; i < argc; i++)
	{
		build_binary_checksum(argv[i]);
	}
	build_plugin_checksums(S_PLUGINS, S_PATH);
	build_plugin_checksums(H_PLUGINS, H_PATH);
	build_plugin_checksums(P_PLUGINS, P_PATH);
	build_plugin_checksums(C_PLUGINS, C_PATH);

	printf("};\n");
	printf("\n");
	printf("int checksum_count = countof(checksums);\n");
	printf("\n");
	integrity->destroy(integrity);

	exit(0);
}
Exemple #9
0
/**
 * Library initialization and operation parsing
 */
int main(int argc, char *argv[])
{
	atexit(cleanup);
	if (!library_init(NULL, "swanctl"))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "swanctl", argv[0]))
	{
		fprintf(stderr, "integrity check of swanctl failed\n");
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "swanctl.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	dbg_default_set_level(0);
	lib->processor->set_threads(lib->processor, 4);
	dbg_default_set_level(1);

	return command_dispatch(argc, argv);
}
int main(int argc, char **argv)
{
	bool fork_desired = TRUE;
	bool log_to_stderr_desired = FALSE;
	bool nat_traversal = FALSE;
	bool nat_t_spf = TRUE;  /* support port floating */
	unsigned int keep_alive = 0;
	bool force_keepalive = FALSE;
	char *virtual_private = NULL;
	int lockfd;
#ifdef CAPABILITIES
	cap_t caps;
	int keep[] = { CAP_NET_ADMIN, CAP_NET_BIND_SERVICE };
#endif /* CAPABILITIES */

	/* initialize library and optionsfrom */
	if (!library_init(NULL))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (!libhydra_init("pluto"))
	{
		libhydra_deinit();
		library_deinit();
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	if (!pluto_init(argv[0]))
	{
		pluto_deinit();
		libhydra_deinit();
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	options = options_create();

	ha_mcast_addr.s_addr = inet_addr(SA_SYNC_MULTICAST);

	/* handle arguments */
	for (;;)
	{
#       define DBG_OFFSET 256
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "nofork", no_argument, NULL, 'd' },
			{ "stderrlog", no_argument, NULL, 'e' },
			{ "noklips", no_argument, NULL, 'n' },
			{ "nocrsend", no_argument, NULL, 'c' },
			{ "strictcrlpolicy", no_argument, NULL, 'r' },
			{ "crlcheckinterval", required_argument, NULL, 'x'},
			{ "cachecrls", no_argument, NULL, 'C' },
			{ "probe-psk", no_argument, NULL, 'o' },
			{ "uniqueids", no_argument, NULL, 'u' },
			{ "interface", required_argument, NULL, 'i' },
			{ "ha_interface", required_argument, NULL, 'H' },
			{ "ha_multicast", required_argument, NULL, 'M' },
			{ "ha_vips", required_argument, NULL, 'V' },
			{ "ha_seqdiff_in", required_argument, NULL, 'S' },
			{ "ha_seqdiff_out", required_argument, NULL, 'O' },
			{ "ikeport", required_argument, NULL, 'p' },
			{ "ctlbase", required_argument, NULL, 'b' },
			{ "secretsfile", required_argument, NULL, 's' },
			{ "foodgroupsdir", required_argument, NULL, 'f' },
			{ "perpeerlogbase", required_argument, NULL, 'P' },
			{ "perpeerlog", no_argument, NULL, 'l' },
			{ "policygroupsdir", required_argument, NULL, 'f' },
#ifdef USE_LWRES
			{ "lwdnsq", required_argument, NULL, 'a' },
#else /* !USE_LWRES */
			{ "adns", required_argument, NULL, 'a' },
#endif /* !USE_LWRES */
			{ "pkcs11module", required_argument, NULL, 'm' },
			{ "pkcs11keepstate", no_argument, NULL, 'k' },
			{ "pkcs11initargs", required_argument, NULL, 'z' },
			{ "pkcs11proxy", no_argument, NULL, 'y' },
			{ "nat_traversal", no_argument, NULL, '1' },
			{ "keep_alive", required_argument, NULL, '2' },
			{ "force_keepalive", no_argument, NULL, '3' },
			{ "disable_port_floating", no_argument, NULL, '4' },
			{ "debug-natt", no_argument, NULL, '5' },
			{ "virtual_private", required_argument, NULL, '6' },
#ifdef DEBUG
			{ "debug-none", no_argument, NULL, 'N' },
			{ "debug-all", no_argument, NULL, 'A' },
			{ "debug-raw", no_argument, NULL, DBG_RAW + DBG_OFFSET },
			{ "debug-crypt", no_argument, NULL, DBG_CRYPT + DBG_OFFSET },
			{ "debug-parsing", no_argument, NULL, DBG_PARSING + DBG_OFFSET },
			{ "debug-emitting", no_argument, NULL, DBG_EMITTING + DBG_OFFSET },
			{ "debug-control", no_argument, NULL, DBG_CONTROL + DBG_OFFSET },
			{ "debug-lifecycle", no_argument, NULL, DBG_LIFECYCLE + DBG_OFFSET },
			{ "debug-klips", no_argument, NULL, DBG_KLIPS + DBG_OFFSET },
			{ "debug-dns", no_argument, NULL, DBG_DNS + DBG_OFFSET },
			{ "debug-oppo", no_argument, NULL, DBG_OPPO + DBG_OFFSET },
			{ "debug-controlmore", no_argument, NULL, DBG_CONTROLMORE + DBG_OFFSET },
			{ "debug-ha", no_argument, NULL, DBG_HA + DBG_OFFSET },
			{ "debug-private", no_argument, NULL, DBG_PRIVATE + DBG_OFFSET },

			{ "impair-delay-adns-key-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_KEY_ANSWER + DBG_OFFSET },
			{ "impair-delay-adns-txt-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_TXT_ANSWER + DBG_OFFSET },
			{ "impair-bust-mi2", no_argument, NULL, IMPAIR_BUST_MI2 + DBG_OFFSET },
			{ "impair-bust-mr2", no_argument, NULL, IMPAIR_BUST_MR2 + DBG_OFFSET },
#endif
			{ 0,0,0,0 }
			};
		/* Note: we don't like the way short options get parsed
		 * by getopt_long, so we simply pass an empty string as
		 * the list.  It could be "hvdenp:l:s:" "NARXPECK".
		 */
		int c = getopt_long(argc, argv, "", long_opts, NULL);

		/* Note: "breaking" from case terminates loop */
		switch (c)
		{
		case EOF:       /* end of flags */
			break;

		case 0: /* long option already handled */
			continue;

		case ':':       /* diagnostic already printed by getopt_long */
		case '?':       /* diagnostic already printed by getopt_long */
			usage("");
			break;   /* not actually reached */

		case 'h':       /* --help */
			usage(NULL);
			break;      /* not actually reached */

		case 'v':       /* --version */
			{
				const char **sp = ipsec_copyright_notice();

				printf("strongSwan "VERSION"%s\n", compile_time_interop_options);
				for (; *sp != NULL; sp++)
					puts(*sp);
			}
			exit_pluto(0);
			break;      /* not actually reached */

		case '+':       /* --optionsfrom <filename> */
			if (!options->from(options, optarg, &argc, &argv, optind))
			{
				exit_pluto(1);
			}
			continue;

		case 'd':       /* --nofork*/
			fork_desired = FALSE;
			continue;

		case 'e':       /* --stderrlog */
			log_to_stderr_desired = TRUE;
			continue;

		case 'n':       /* --noklips */
			no_klips = TRUE;
			continue;

		case 'c':       /* --nocrsend */
			no_cr_send = TRUE;
			continue;

		case 'r':       /* --strictcrlpolicy */
			strict_crl_policy = TRUE;
			continue;

		case 'x':       /* --crlcheckinterval <time>*/
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing interval time");

			{
				char *endptr;
				long interval = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| interval <= 0)
					usage("<interval-time> must be a positive number");
				crl_check_interval = interval;
			}
			continue;

		case 'C':       /* --cachecrls */
			cache_crls = TRUE;
			continue;

		case 'o':       /* --probe-psk */
			probe_psk = TRUE;
			continue;

		case 'u':       /* --uniqueids */
			uniqueIDs = TRUE;
			continue;

		case 'i':       /* --interface <ifname> */
			if (!use_interface(optarg))
				usage("too many --interface specifications");
			continue;

		case 'H':       /* --ha_interface <ifname> */
			if (optarg && strcmp(optarg, "none") != 0)
				ha_interface = optarg;
			continue;

		case 'M':	/* --ha_multicast <ip> */
			ha_mcast_addr.s_addr = inet_addr(optarg);
			if (ha_mcast_addr.s_addr == INADDR_NONE ||
				(((unsigned char *) &ha_mcast_addr.s_addr)[0] & 0xF0) != 0xE0)
				ha_mcast_addr.s_addr = inet_addr(SA_SYNC_MULTICAST);
			continue;

		case 'V':	/* --ha_vips <ip addresses> */
			if(add_ha_vips(optarg))
				usage("misconfigured ha_vip addresses");
			continue;

		case 'S':	/* --ha_seqdiff_in <diff> */
			ha_seqdiff_in = strtoul(optarg, NULL, 0);
			continue;

		case 'O':       /* --ha_seqdiff_out <diff> */
			ha_seqdiff_out = strtoul(optarg, NULL, 0);
			continue;

		case 'p':       /* --port <portnumber> */
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing port number");

			{
				char *endptr;
				long port = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| port <= 0 || port > 0x10000)
					usage("<port-number> must be a number between 1 and 65535");
				pluto_port = port;
			}
			continue;

		case 'b':       /* --ctlbase <path> */
			if (snprintf(ctl_addr.sun_path, sizeof(ctl_addr.sun_path)
			, "%s%s", optarg, CTL_SUFFIX) == -1)
				usage("<path>" CTL_SUFFIX " too long for sun_path");
			if (snprintf(info_addr.sun_path, sizeof(info_addr.sun_path)
			, "%s%s", optarg, INFO_SUFFIX) == -1)
				usage("<path>" INFO_SUFFIX " too long for sun_path");
			if (snprintf(pluto_lock, sizeof(pluto_lock)
			, "%s%s", optarg, LOCK_SUFFIX) == -1)
				usage("<path>" LOCK_SUFFIX " must fit");
			continue;

		case 's':       /* --secretsfile <secrets-file> */
			shared_secrets_file = optarg;
			continue;

		case 'f':       /* --policygroupsdir <policygroups-dir> */
			policygroups_dir = optarg;
			continue;

		case 'a':       /* --adns <pathname> */
			pluto_adns_option = optarg;
			continue;

		case 'm':       /* --pkcs11module <pathname> */
			pkcs11_module_path = optarg;
			continue;

		case 'k':       /* --pkcs11keepstate */
			pkcs11_keep_state = TRUE;
			continue;

		case 'y':       /* --pkcs11proxy */
			pkcs11_proxy = TRUE;
			continue;

		case 'z':       /* --pkcs11initargs */
			pkcs11_init_args = optarg;
			continue;

#ifdef DEBUG
		case 'N':       /* --debug-none */
			base_debugging = DBG_NONE;
			continue;

		case 'A':       /* --debug-all */
			base_debugging = DBG_ALL;
			continue;
#endif

		case 'P':       /* --perpeerlogbase */
			base_perpeer_logdir = optarg;
			continue;

		case 'l':
			log_to_perpeer = TRUE;
			continue;

		case '1':       /* --nat_traversal */
			nat_traversal = TRUE;
			continue;
		case '2':       /* --keep_alive */
			keep_alive = atoi(optarg);
			continue;
		case '3':       /* --force_keepalive */
			force_keepalive = TRUE;
			continue;
		case '4':       /* --disable_port_floating */
			nat_t_spf = FALSE;
			continue;
		case '5':       /* --debug-nat_t */
			base_debugging |= DBG_NATT;
			continue;
		case '6':       /* --virtual_private */
			virtual_private = optarg;
			continue;

		default:
#ifdef DEBUG
			if (c >= DBG_OFFSET)
			{
				base_debugging |= c - DBG_OFFSET;
				continue;
			}
#       undef DBG_OFFSET
#endif
			bad_case(c);
		}
		break;
	}
	if (optind != argc)
		usage("unexpected argument");
	reset_debugging();
	lockfd = create_lock();

	/* select between logging methods */

	if (log_to_stderr_desired)
	{
		log_to_syslog = FALSE;
	}
	else
	{
		log_to_stderr = FALSE;
	}

	/* set the logging function of pfkey debugging */
#ifdef DEBUG
	pfkey_debug_func = DBG_log;
#else
	pfkey_debug_func = NULL;
#endif

	/* create control socket.
	 * We must create it before the parent process returns so that
	 * there will be no race condition in using it.  The easiest
	 * place to do this is before the daemon fork.
	 */
	{
		err_t ugh = init_ctl_socket();

		if (ugh != NULL)
		{
			fprintf(stderr, "pluto: %s", ugh);
			exit_pluto(1);
		}
	}

	/* If not suppressed, do daemon fork */

	if (fork_desired)
	{
		{
			pid_t pid = fork();

			if (pid < 0)
			{
				int e = errno;

				fprintf(stderr, "pluto: fork failed (%d %s)\n",
					errno, strerror(e));
				exit_pluto(1);
			}

			if (pid != 0)
			{
				/* parent: die, after filling PID into lock file.
				 * must not use exit_pluto: lock would be removed!
				 */
				exit(fill_lock(lockfd, pid)? 0 : 1);
			}
		}

		if (setsid() < 0)
		{
			int e = errno;

			fprintf(stderr, "setsid() failed in main(). Errno %d: %s\n",
				errno, strerror(e));
			exit_pluto(1);
		}
	}
	else
	{
		/* no daemon fork: we have to fill in lock file */
		(void) fill_lock(lockfd, getpid());
		fprintf(stdout, "Pluto initialized\n");
		fflush(stdout);
	}

	/* Close everything but ctl_fd and (if needed) stderr.
	 * There is some danger that a library that we don't know
	 * about is using some fd that we don't know about.
	 * I guess we'll soon find out.
	 */
	{
		int i;

		for (i = getdtablesize() - 1; i >= 0; i--)  /* Bad hack */
		{
			if ((!log_to_stderr || i != 2) && i != ctl_fd)
				close(i);
		}

		/* make sure that stdin, stdout, stderr are reserved */
		if (open("/dev/null", O_RDONLY) != 0)
			abort();
		if (dup2(0, 1) != 1)
			abort();
		if (!log_to_stderr && dup2(0, 2) != 2)
			abort();
	}

	init_constants();
	init_log("pluto");

	/* Note: some scripts may look for this exact message -- don't change
	 * ipsec barf was one, but it no longer does.
	 */
	plog("Starting IKEv1 pluto daemon (strongSwan "VERSION")%s",
		 compile_time_interop_options);

	if (lib->integrity)
	{
		plog("integrity tests enabled:");
		plog("lib    'libstrongswan': passed file and segment integrity tests");
		plog("lib    'libhydra': passed file and segment integrity tests");
		plog("daemon 'pluto': passed file integrity test");
	}

	/* load plugins, further infrastructure may need it */
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "pluto.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	print_plugins();

	init_builder();
	if (!init_secret() || !init_crypto())
	{
		plog("initialization failed - aborting pluto");
		exit_pluto(SS_RC_INITIALIZATION_FAILED);
	}
	init_nat_traversal(nat_traversal, keep_alive, force_keepalive, nat_t_spf);
	init_virtual_ip(virtual_private);
	scx_init(pkcs11_module_path, pkcs11_init_args);
	init_states();
	init_demux();
	init_kernel();
	init_adns();
	init_myid();
	fetch_initialize();
	ac_initialize();
	whack_attribute_initialize();

	/* HA System: set sequence number delta and open HA interface */
	if (ha_interface != NULL)
	{
		int version;

		if (kernel_ops->type == KERNEL_TYPE_LINUX
		&& (version = xfrm_aevent_version()) != XFRM_AEVENT_VERSION)
		{
			if (version == 0)
				plog("HA system: XFRM sequence number updates only "
				     "supported with kernel version 2.6.17 and later.");
			else if (version == -1)
				plog("HA system: error reading kernel version. "
				     "Sequence number updates disabled.");
			else
				plog("HA system: Strongswan compiled for wrong kernel "
				     "AEVENT version! Please set XFRM_AEVENT_VERSION "
				     "to %d in src/include/linux/xfrm.h", version);

			ha_seqdiff_in = 0;
			ha_seqdiff_out = 0;
		}
		else
		{
			FILE *etime = fopen("/proc/sys/net/core/xfrm_aevent_etime", "w");
			FILE *rseqth = fopen("/proc/sys/net/core/xfrm_aevent_rseqth", "w");

			if (etime == NULL || rseqth == NULL)
			{
				plog("HA System: no sequence number support in Kernel! "
					"Please use at least kernel 2.6.17.");
				ha_seqdiff_in = 0;
				ha_seqdiff_out = 0;
			}
			else
			{
				/*
				 * Disable etime (otherwise set to a multiple of 100ms,
				 * e.g. 300 for 30 seconds). Using ha_seqdiff_out.
				 */
				fprintf(etime, "0");
				fprintf(rseqth, "%d", ha_seqdiff_out);
			}

			fclose(etime);
			fclose(rseqth);
		}

		if (open_ha_iface() >= 0)
		{
			plog("HA system enabled and listening on interface %s", ha_interface);
			if (access("/var/master", F_OK) == 0)
			{
				plog("Initial HA switch to master mode");
				ha_master = 1;
				event_schedule(EVENT_SA_SYNC_UPDATE, 30, NULL);
			}
		}
		else
		{
			plog("HA system failed to listen on interface %s. "
			     "HA system disabled.", ha_interface);
			ha_interface = NULL;
		}
	}

	/* drop unneeded capabilities and change UID/GID */
	prctl(PR_SET_KEEPCAPS, 1);

#ifdef IPSEC_GROUP
	{
		struct group group, *grp;
	char buf[1024];

		if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
				grp == NULL || setgid(grp->gr_gid) != 0)
		{
			plog("unable to change daemon group");
			abort();
		}
	}
#endif
#ifdef IPSEC_USER
	{
		struct passwd passwd, *pwp;
	char buf[1024];

		if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
				pwp == NULL || setuid(pwp->pw_uid) != 0)
		{
			plog("unable to change daemon user");
			abort();
		}
		}
#endif

#ifdef CAPABILITIES
	caps = cap_init();
	cap_set_flag(caps, CAP_EFFECTIVE, 2, keep, CAP_SET);
	cap_set_flag(caps, CAP_INHERITABLE, 2, keep, CAP_SET);
	cap_set_flag(caps, CAP_PERMITTED, 2, keep, CAP_SET);
	if (cap_set_proc(caps) != 0)
	{
		plog("unable to drop daemon capabilities");
		abort();
	}
	cap_free(caps);
#endif /* CAPABILITIES */

	/* loading X.509 CA certificates */
	load_authcerts("ca", CA_CERT_PATH, X509_CA);
	/* loading X.509 AA certificates */
	load_authcerts("aa", AA_CERT_PATH, X509_AA);
	/* loading X.509 OCSP certificates */
	load_authcerts("ocsp", OCSP_CERT_PATH, X509_OCSP_SIGNER);
	/* loading X.509 CRLs */
	load_crls();
	/* loading attribute certificates (experimental) */
	ac_load_certs();

	daily_log_event();
	call_server();
	return -1;  /* Shouldn't ever reach this */
}
Exemple #11
0
/**
 * Main function, starts NetworkManager backend.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int status = SS_RC_INITIALIZATION_FAILED;

	/* logging for library during initialization, as we have no bus yet */
	dbg = dbg_syslog;

	/* LD causes a crash probably due to Glib */
	setenv("LEAK_DETECTIVE_DISABLE", "1", 1);

	/* initialize library */
	if (!library_init(NULL, "charon-nm"))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}

	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "charon-nm", argv[0]))
	{
		dbg_syslog(DBG_DMN, 1, "integrity check of charon-nm failed");
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}

	if (!libcharon_init())
	{
		dbg_syslog(DBG_DMN, 1, "initialization failed - aborting charon-nm");
		goto deinit;
	}

	if (!lookup_uid_gid())
	{
		dbg_syslog(DBG_DMN, 1, "invalid uid/gid - aborting charon-nm");
		goto deinit;
	}

	/* make sure we log to the DAEMON facility by default */
	lib->settings->set_int(lib->settings, "charon-nm.syslog.daemon.default",
		lib->settings->get_int(lib->settings,
							   "charon-nm.syslog.daemon.default", 1));
	charon->load_loggers(charon);

	/* use random ports to avoid conflicts with regular charon */
	lib->settings->set_int(lib->settings, "charon-nm.port", 0);
	lib->settings->set_int(lib->settings, "charon-nm.port_nat_t", 0);

	DBG1(DBG_DMN, "Starting charon NetworkManager backend (strongSwan "VERSION")");
	if (lib->integrity)
	{
		DBG1(DBG_DMN, "integrity tests enabled:");
		DBG1(DBG_DMN, "lib    'libstrongswan': passed file and segment integrity tests");
		DBG1(DBG_DMN, "lib    'libcharon': passed file and segment integrity tests");
		DBG1(DBG_DMN, "daemon 'charon-nm': passed file integrity test");
	}

	/* register NM backend to be loaded with plugins */
	nm_backend_register();

	/* initialize daemon */
	if (!charon->initialize(charon,
			lib->settings->get_str(lib->settings, "charon-nm.load", PLUGINS)))
	{
		DBG1(DBG_DMN, "initialization failed - aborting charon-nm");
		goto deinit;
	}
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	if (!lib->caps->drop(lib->caps))
	{
		DBG1(DBG_DMN, "capability dropping failed - aborting charon-nm");
		goto deinit;
	}

	/* add handler for SEGV and ILL,
	 * INT and TERM are handled by sigwaitinfo() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start daemon (i.e. the threads in the thread-pool) */
	charon->start(charon);

	/* main thread goes to run loop */
	run();

	status = 0;

deinit:
	libcharon_deinit();
	library_deinit();
	return status;
}
int main(int argc, char *argv[])
{
	database_t *db;
	char *uri, *tnc_session_id;
	int session_id;
	bool start, success;

	/* enable attest debugging hook */
	dbg = stderr_dbg;

	atexit(library_deinit);

	/* initialize library */
	if (!library_init(NULL))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "imv_policy_manager.load",
				 "sqlite")))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	if (argc < 2)
	{
		usage();
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	if (streq(argv[1], "start"))
	{
		start = TRUE;
	}
	else if (streq(argv[1], "stop"))
	{
		start = FALSE;
	}
	else
	{
		usage();
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	/* get session ID */
	tnc_session_id = getenv("TNC_SESSION_ID");
	if (!tnc_session_id)
	{
		fprintf(stderr, "environment variable TNC_SESSION_ID is not defined\n");
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	session_id = atoi(tnc_session_id);

	/* attach IMV database */
	uri = lib->settings->get_str(lib->settings, "libimcv.database", NULL);
	if (!uri)
	{
		fprintf(stderr, "database uri not defined.\n");
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	db = lib->db->create(lib->db, uri);
	if (!db)
	{
		fprintf(stderr, "opening database failed.\n");
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	if (start)
	{
		success = policy_start(db, session_id);
	}
	else
	{
		success = policy_stop(db, session_id);
	}
	db->destroy(db);

	fprintf(stderr, "imv_policy_manager %s %s\n", start ? "start" : "stop",
			success ? "successful" : "failed");

	exit(EXIT_SUCCESS);
}
Exemple #13
0
/**
 * Main function, starts the conftest daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int status = 0;
	sigset_t set;
	int sig;
	char *suite_file = "suite.conf", *test_file = NULL;
	file_logger_t *logger;

	if (!library_init(NULL))
	{
		library_deinit();
		return SS_RC_LIBSTRONGSWAN_INTEGRITY;
	}
	if (!libhydra_init("conftest"))
	{
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}
	if (!libcharon_init("conftest"))
	{
		libcharon_deinit();
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}

	INIT(conftest,
		.creds = mem_cred_create(),
		.config = config_create(),
		.hooks = linked_list_create(),
		.loggers = linked_list_create(),
	);
	lib->credmgr->add_set(lib->credmgr, &conftest->creds->set);

	logger = file_logger_create("stdout");
	logger->set_options(logger, NULL, FALSE);
	logger->open(logger, FALSE, FALSE);
	logger->set_level(logger, DBG_ANY, LEVEL_CTRL);
	charon->bus->add_logger(charon->bus, &logger->logger);
	conftest->loggers->insert_last(conftest->loggers, logger);

	atexit(cleanup);

	while (TRUE)
	{
		struct option long_opts[] = {
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "suite", required_argument, NULL, 's' },
			{ "test", required_argument, NULL, 't' },
			{ 0,0,0,0 }
		};
		switch (getopt_long(argc, argv, "", long_opts, NULL))
		{
			case EOF:
				break;
			case 'h':
				usage(stdout);
				return 0;
			case 'v':
				printf("strongSwan %s conftest\n", VERSION);
				return 0;
			case 's':
				suite_file = optarg;
				continue;
			case 't':
				test_file = optarg;
				continue;
			default:
				usage(stderr);
				return 1;
		}
		break;
	}

	if (!load_configs(suite_file, test_file))
	{
		return 1;
	}
	load_loggers(logger);

	if (!lib->plugins->load(lib->plugins, NULL,
			conftest->test->get_str(conftest->test, "preload", "")))
	{
		return 1;
	}
	if (!charon->initialize(charon, PLUGINS))
	{
		return 1;
	}
	if (!load_certs(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	if (!load_keys(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	load_cdps(conftest->test);
	if (!load_hooks())
	{
		return 1;
	}
	charon->backends->add_backend(charon->backends, &conftest->config->backend);
	conftest->config->load(conftest->config, conftest->test);
	conftest->actions = actions_create();

	/* set up thread specific handlers */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);
	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start thread pool */
	charon->start(charon);

	/* handle SIGINT/SIGTERM in main thread */
	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGTERM);
	sigprocmask(SIG_BLOCK, &set, NULL);

	while (sigwait(&set, &sig) == 0)
	{
		switch (sig)
		{
			case SIGINT:
			case SIGTERM:
				fprintf(stderr, "\nshutting down...\n");
				break;
			default:
				continue;
		}
		break;
	}
	return status;
}
Exemple #14
0
/**
 * Main function, starts the daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int group, status = SS_RC_INITIALIZATION_FAILED;
	struct utsname utsname;

	/* logging for library during initialization, as we have no bus yet */
	dbg = dbg_stderr;

	/* initialize library */
	if (!library_init(NULL, "charon"))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}

	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "charon", argv[0]))
	{
		dbg_stderr(DBG_DMN, 1, "integrity check of charon failed");
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}

	if (!libhydra_init())
	{
		dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
		libhydra_deinit();
		library_deinit();
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	if (!libcharon_init())
	{
		dbg_stderr(DBG_DMN, 1, "initialization failed - aborting charon");
		goto deinit;
	}

	/* use CTRL loglevel for default */
	for (group = 0; group < DBG_MAX; group++)
	{
		levels[group] = LEVEL_CTRL;
	}

	/* handle arguments */
	for (;;)
	{
		struct option long_opts[] = {
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "use-syslog", no_argument, NULL, 'l' },
			/* TODO: handle "debug-all" */
			{ "debug-dmn", required_argument, &group, DBG_DMN },
			{ "debug-mgr", required_argument, &group, DBG_MGR },
			{ "debug-ike", required_argument, &group, DBG_IKE },
			{ "debug-chd", required_argument, &group, DBG_CHD },
			{ "debug-job", required_argument, &group, DBG_JOB },
			{ "debug-cfg", required_argument, &group, DBG_CFG },
			{ "debug-knl", required_argument, &group, DBG_KNL },
			{ "debug-net", required_argument, &group, DBG_NET },
			{ "debug-asn", required_argument, &group, DBG_ASN },
			{ "debug-enc", required_argument, &group, DBG_ENC },
			{ "debug-tnc", required_argument, &group, DBG_TNC },
			{ "debug-imc", required_argument, &group, DBG_IMC },
			{ "debug-imv", required_argument, &group, DBG_IMV },
			{ "debug-pts", required_argument, &group, DBG_PTS },
			{ "debug-tls", required_argument, &group, DBG_TLS },
			{ "debug-esp", required_argument, &group, DBG_ESP },
			{ "debug-lib", required_argument, &group, DBG_LIB },
			{ 0,0,0,0 }
		};

		int c = getopt_long(argc, argv, "", long_opts, NULL);
		switch (c)
		{
			case EOF:
				break;
			case 'h':
				usage(NULL);
				status = 0;
				goto deinit;
			case 'v':
				printf("Linux strongSwan %s\n", VERSION);
				status = 0;
				goto deinit;
			case 'l':
				use_syslog = TRUE;
				continue;
			case 0:
				/* option is in group */
				levels[group] = atoi(optarg);
				continue;
			default:
				usage("");
				status = 1;
				goto deinit;
		}
		break;
	}

	if (!lookup_uid_gid())
	{
		dbg_stderr(DBG_DMN, 1, "invalid uid/gid - aborting charon");
		goto deinit;
	}

	charon->load_loggers(charon, levels, !use_syslog);

	if (uname(&utsname) != 0)
	{
		memset(&utsname, 0, sizeof(utsname));
	}
	DBG1(DBG_DMN, "Starting IKE charon daemon (strongSwan "VERSION", %s %s, %s)",
		  utsname.sysname, utsname.release, utsname.machine);
	if (lib->integrity)
	{
		DBG1(DBG_DMN, "integrity tests enabled:");
		DBG1(DBG_DMN, "lib    'libstrongswan': passed file and segment integrity tests");
		DBG1(DBG_DMN, "lib    'libhydra': passed file and segment integrity tests");
		DBG1(DBG_DMN, "lib    'libcharon': passed file and segment integrity tests");
		DBG1(DBG_DMN, "daemon 'charon': passed file integrity test");
	}

	/* initialize daemon */
	if (!charon->initialize(charon,
				lib->settings->get_str(lib->settings, "charon.load", PLUGINS)))
	{
		DBG1(DBG_DMN, "initialization failed - aborting charon");
		goto deinit;
	}
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	if (check_pidfile())
	{
		DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
		goto deinit;
	}

	if (!lib->caps->drop(lib->caps))
	{
		DBG1(DBG_DMN, "capability dropping failed - aborting charon");
		goto deinit;
	}

	/* add handler for SEGV and ILL,
	 * INT, TERM and HUP are handled by sigwaitinfo() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start daemon (i.e. the threads in the thread-pool) */
	charon->start(charon);

	/* main thread goes to run loop */
	run();

	/* normal termination, cleanup and exit */
	unlink_pidfile();
	status = 0;

deinit:
	libcharon_deinit();
	libhydra_deinit();
	library_deinit();
	return status;
}
Exemple #15
0
/**
 * @brief openac main program
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
	certificate_t *attr_cert   = NULL;
	certificate_t *userCert   = NULL;
	certificate_t *signerCert = NULL;
	private_key_t *signerKey  = NULL;

	time_t notBefore = UNDEFINED_TIME;
	time_t notAfter  = UNDEFINED_TIME;
	time_t validity = 0;

	char *keyfile = NULL;
	char *certfile = NULL;
	char *usercertfile = NULL;
	char *outfile = NULL;
	char *groups = "";
	char buf[BUF_LEN];

	chunk_t passphrase = { buf, 0 };
	chunk_t serial = chunk_empty;
	chunk_t attr_chunk = chunk_empty;

	int status = 1;

	/* enable openac debugging hook */
	dbg = openac_dbg;

	passphrase.ptr[0] = '\0';

	openlog("openac", 0, LOG_AUTHPRIV);

	/* initialize library */
	atexit(library_deinit);
	if (!library_init(NULL))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "openac", argv[0]))
	{
		fprintf(stderr, "integrity check of openac failed\n");
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "openac.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	/* initialize optionsfrom */
	options_t *options = options_create();

	/* handle arguments */
	for (;;)
	{
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "quiet", no_argument, NULL, 'q' },
			{ "cert", required_argument, NULL, 'c' },
			{ "key", required_argument, NULL, 'k' },
			{ "password", required_argument, NULL, 'p' },
			{ "usercert", required_argument, NULL, 'u' },
			{ "groups", required_argument, NULL, 'g' },
			{ "days", required_argument, NULL, 'D' },
			{ "hours", required_argument, NULL, 'H' },
			{ "startdate", required_argument, NULL, 'S' },
			{ "enddate", required_argument, NULL, 'E' },
			{ "out", required_argument, NULL, 'o' },
			{ "debug", required_argument, NULL, 'd' },
			{ 0,0,0,0 }
		};

		int c = getopt_long(argc, argv, "hv+:qc:k:p;u:g:D:H:S:E:o:d:", long_opts, NULL);

		/* Note: "breaking" from case terminates loop */
		switch (c)
		{
			case EOF:	/* end of flags */
				break;

			case 0: /* long option already handled */
				continue;

			case ':':	/* diagnostic already printed by getopt_long */
			case '?':	/* diagnostic already printed by getopt_long */
			case 'h':	/* --help */
				usage(NULL);
				status = 1;
				goto end;

			case 'v':	/* --version */
				printf("openac (strongSwan %s)\n", VERSION);
				status = 0;
				goto end;

			case '+':	/* --optionsfrom <filename> */
				{
					char path[BUF_LEN];

					if (*optarg == '/')	/* absolute pathname */
					{
						strncpy(path, optarg, BUF_LEN);
						path[BUF_LEN-1] = '\0';
					}
					else			/* relative pathname */
					{
						snprintf(path, BUF_LEN, "%s/%s", OPENAC_PATH, optarg);
					}
					if (!options->from(options, path, &argc, &argv, optind))
					{
						status = 1;
						goto end;
					}
				}
				continue;

			case 'q':	/* --quiet */
				stderr_quiet = TRUE;
				continue;

			case 'c':	/* --cert */
				certfile = optarg;
				continue;

			case 'k':	/* --key */
				keyfile = optarg;
				continue;

			case 'p':	/* --key */
				if (strlen(optarg) >= BUF_LEN)
				{
					usage("passphrase too long");
					goto end;
				}
				strncpy(passphrase.ptr, optarg, BUF_LEN);
				passphrase.len = min(strlen(optarg), BUF_LEN);
				continue;

			case 'u':	/* --usercert */
				usercertfile = optarg;
				continue;

			case 'g':	/* --groups */
				groups = optarg;
				continue;

			case 'D':	/* --days */
				if (optarg == NULL || !isdigit(optarg[0]))
				{
					usage("missing number of days");
					goto end;
				}
				else
				{
					char *endptr;
					long days = strtol(optarg, &endptr, 0);

					if (*endptr != '\0' || endptr == optarg || days <= 0)
					{
						usage("<days> must be a positive number");
						goto end;
					}
					validity += 24*3600*days;
				}
				continue;

			case 'H':	/* --hours */
				if (optarg == NULL || !isdigit(optarg[0]))
				{
					usage("missing number of hours");
					goto end;
				}
				else
				{
					char *endptr;
					long hours = strtol(optarg, &endptr, 0);

					if (*endptr != '\0' || endptr == optarg || hours <= 0)
					{
						usage("<hours> must be a positive number");
						goto end;
					}
					validity += 3600*hours;
				}
				continue;

			case 'S':	/* --startdate */
				if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
				{
					usage("date format must be YYYYMMDDHHMMSSZ");
					goto end;
				}
				else
				{
					chunk_t date = { optarg, 15 };

					notBefore = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
				}
				continue;

			case 'E':	/* --enddate */
				if (optarg == NULL || strlen(optarg) != 15 || optarg[14] != 'Z')
				{
					usage("date format must be YYYYMMDDHHMMSSZ");
					goto end;
				}
				else
				{
					chunk_t date = { optarg, 15 };
					notAfter = asn1_to_time(&date, ASN1_GENERALIZEDTIME);
				}
				continue;

			case 'o':	/* --out */
				outfile = optarg;
				continue;

			case 'd':	/* --debug */
				debug_level = atoi(optarg);
				continue;

			default:
				usage("");
				status = 0;
				goto end;
		}
		/* break from loop */
		break;
	}

	if (optind != argc)
	{
		usage("unexpected argument");
		goto end;
	}

	DBG1(DBG_LIB, "starting openac (strongSwan Version %s)", VERSION);

	/* load the signer's RSA private key */
	if (keyfile != NULL)
	{
		mem_cred_t *mem;
		shared_key_t *shared;

		mem = mem_cred_create();
		lib->credmgr->add_set(lib->credmgr, &mem->set);
		shared = shared_key_create(SHARED_PRIVATE_KEY_PASS,
								   chunk_clone(passphrase));
		mem->add_shared(mem, shared, NULL);
		signerKey = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
									   BUILD_FROM_FILE, keyfile,
									   BUILD_END);
		lib->credmgr->remove_set(lib->credmgr, &mem->set);
		mem->destroy(mem);
		if (signerKey == NULL)
		{
			goto end;
		}
		DBG1(DBG_LIB, "  loaded private key file '%s'", keyfile);
	}

	/* load the signer's X.509 certificate */
	if (certfile != NULL)
	{
		signerCert = lib->creds->create(lib->creds,
										CRED_CERTIFICATE, CERT_X509,
										BUILD_FROM_FILE, certfile,
										BUILD_END);
		if (signerCert == NULL)
		{
			goto end;
		}
	}

	/* load the users's X.509 certificate */
	if (usercertfile != NULL)
	{
		userCert = lib->creds->create(lib->creds,
									  CRED_CERTIFICATE, CERT_X509,
									  BUILD_FROM_FILE, usercertfile,
									  BUILD_END);
		if (userCert == NULL)
		{
			goto end;
		}
	}

	/* compute validity interval */
	validity = (validity)? validity : DEFAULT_VALIDITY;
	notBefore = (notBefore == UNDEFINED_TIME) ? time(NULL) : notBefore;
	notAfter =  (notAfter  == UNDEFINED_TIME) ? time(NULL) + validity : notAfter;

	/* build and parse attribute certificate */
	if (userCert != NULL && signerCert != NULL && signerKey != NULL &&
		outfile != NULL)
	{
		/* read the serial number and increment it by one */
		serial = read_serial();

		attr_cert = lib->creds->create(lib->creds,
							CRED_CERTIFICATE, CERT_X509_AC,
							BUILD_CERT, userCert,
							BUILD_NOT_BEFORE_TIME, notBefore,
							BUILD_NOT_AFTER_TIME, notAfter,
							BUILD_SERIAL, serial,
							BUILD_IETF_GROUP_ATTR, groups,
							BUILD_SIGNING_CERT, signerCert,
							BUILD_SIGNING_KEY, signerKey,
							BUILD_END);
		if (!attr_cert)
		{
			goto end;
		}

		/* write the attribute certificate to file */
		if (attr_cert->get_encoding(attr_cert, CERT_ASN1_DER, &attr_chunk))
		{
			if (chunk_write(attr_chunk, outfile, 0022, TRUE))
			{
				DBG1(DBG_APP, "  written attribute cert file '%s' (%d bytes)",
						 outfile, attr_chunk.len);
				write_serial(serial);
				status = 0;
			}
			else
			{
				DBG1(DBG_APP, "  writing attribute cert file '%s' failed: %s",
					 outfile, strerror(errno));
			}
		}
	}
	else
	{
		usage("some of the mandatory parameters --usercert --cert --key --out "
			  "are missing");
	}

end:
	/* delete all dynamically allocated objects */
	DESTROY_IF(signerKey);
	DESTROY_IF(signerCert);
	DESTROY_IF(userCert);
	DESTROY_IF(attr_cert);
	free(attr_chunk.ptr);
	free(serial.ptr);
	closelog();
	dbg = dbg_default;
	options->destroy(options);
	exit(status);
}
Exemple #16
0
int main (int argc, char **argv)
{
	starter_config_t *cfg = NULL;
	starter_config_t *new_cfg;
	starter_conn_t *conn, *conn2;
	starter_ca_t *ca, *ca2;

	struct sigaction action;
	struct stat stb;

	int i;
	int id = 1;
	struct timespec ts;
	unsigned long auto_update = 0;
	time_t last_reload;
	bool no_fork = FALSE;
	bool attach_gdb = FALSE;
	bool load_warning = FALSE;

	library_init(NULL);
	atexit(library_deinit);

	libhydra_init("starter");
	atexit(libhydra_deinit);

	/* parse command line */
	for (i = 1; i < argc; i++)
	{
		if (streq(argv[i], "--debug"))
		{
			current_loglevel = 2;
		}
		else if (streq(argv[i], "--debug-more"))
		{
			current_loglevel = 3;
		}
		else if (streq(argv[i], "--debug-all"))
		{
			current_loglevel = 4;
		}
		else if (streq(argv[i], "--nolog"))
		{
			current_loglevel = 0;
		}
		else if (streq(argv[i], "--nofork"))
		{
			no_fork = TRUE;
		}
		else if (streq(argv[i], "--attach-gdb"))
		{
			no_fork = TRUE;
			attach_gdb = TRUE;
		}
		else if (streq(argv[i], "--auto-update") && i+1 < argc)
		{
			auto_update = atoi(argv[++i]);
			if (!auto_update)
				usage(argv[0]);
		}
		else if (streq(argv[i], "--daemon") && i+1 < argc)
		{
			daemon_name = argv[++i];
		}
		else
		{
			usage(argv[0]);
		}
	}

	if (!set_daemon_name())
	{
		DBG1(DBG_APP, "unable to set daemon name");
		exit(LSB_RC_FAILURE);
	}

	init_log("ipsec_starter");

	DBG1(DBG_APP, "Starting %sSwan "VERSION" IPsec [starter]...",
		lib->settings->get_bool(lib->settings,
			"charon.i_dont_care_about_security_and_use_aggressive_mode_psk",
				FALSE) ? "weak" : "strong");

#ifdef LOAD_WARNING
	load_warning = TRUE;
#endif

	if (lib->settings->get_bool(lib->settings, "starter.load_warning", load_warning))
	{
		if (lib->settings->get_str(lib->settings, "charon.load", NULL))
		{
			DBG1(DBG_APP, "!! Your strongswan.conf contains manual plugin load options for charon.");
			DBG1(DBG_APP, "!! This is recommended for experts only, see");
			DBG1(DBG_APP, "!! http://wiki.strongswan.org/projects/strongswan/wiki/PluginLoad");
		}
	}

	/* verify that we can start */
	if (getuid() != 0)
	{
		DBG1(DBG_APP, "permission denied (must be superuser)");
		cleanup();
		exit(LSB_RC_NOT_ALLOWED);
	}

	if (check_pid(pid_file))
	{
		DBG1(DBG_APP, "%s is already running (%s exists) -- skipping daemon start",
			 daemon_name, pid_file);
	}
	else
	{
		_action_ |= FLAG_ACTION_START_CHARON;
	}
	if (stat(DEV_RANDOM, &stb) != 0)
	{
		DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_RANDOM);
		cleanup();
		exit(LSB_RC_FAILURE);
	}

	if (stat(DEV_URANDOM, &stb)!= 0)
	{
		DBG1(DBG_APP, "unable to start strongSwan IPsec -- no %s!", DEV_URANDOM);
		cleanup();
		exit(LSB_RC_FAILURE);
	}

	cfg = confread_load(CONFIG_FILE);
	if (cfg == NULL || cfg->err > 0)
	{
		DBG1(DBG_APP, "unable to start strongSwan -- fatal errors in config");
		if (cfg)
		{
			confread_free(cfg);
		}
		cleanup();
		exit(LSB_RC_INVALID_ARGUMENT);
	}

	/* determine if we have a native netkey IPsec stack */
	if (!starter_netkey_init())
	{
		DBG1(DBG_APP, "no netkey IPsec stack detected");
		if (!starter_klips_init())
		{
			DBG1(DBG_APP, "no KLIPS IPsec stack detected");
			DBG1(DBG_APP, "no known IPsec stack detected, ignoring!");
		}
	}

	last_reload = time_monotonic(NULL);

	if (check_pid(starter_pid_file))
	{
		DBG1(DBG_APP, "starter is already running (%s exists) -- no fork done",
			 starter_pid_file);
		confread_free(cfg);
		cleanup();
		exit(LSB_RC_SUCCESS);
	}

#ifdef GENERATE_SELFCERT
	generate_selfcert();
#endif

	/* fork if we're not debugging stuff */
	if (!no_fork)
	{
		log_to_stderr = FALSE;

		switch (fork())
		{
			case 0:
			{
				int fnull;

				close_log();
				closefrom(3);

				fnull = open("/dev/null", O_RDWR);
				if (fnull >= 0)
				{
					dup2(fnull, STDIN_FILENO);
					dup2(fnull, STDOUT_FILENO);
					dup2(fnull, STDERR_FILENO);
					close(fnull);
				}

				setsid();
				init_log("ipsec_starter");
			}
			break;
			case -1:
				DBG1(DBG_APP, "can't fork: %s", strerror(errno));
				break;
			default:
				confread_free(cfg);
				cleanup();
				exit(LSB_RC_SUCCESS);
		}
	}

	/* save pid file in /var/run/starter[.daemon_name].pid */
	{
		FILE *fd = fopen(starter_pid_file, "w");

		if (fd)
		{
			fprintf(fd, "%u\n", getpid());
			fclose(fd);
		}
	}

	/* we handle these signals only in pselect() */
	memset(&action, 0, sizeof(action));
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGQUIT);
	sigaddset(&action.sa_mask, SIGALRM);
	sigaddset(&action.sa_mask, SIGUSR1);
	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* install a handler for fatal signals */
	action.sa_handler = fatal_signal_handler;
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	/* install main signal handler */
	action.sa_handler = signal_handler;
	sigaction(SIGHUP, &action, NULL);
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGTERM, &action, NULL);
	sigaction(SIGQUIT, &action, NULL);
	sigaction(SIGALRM, &action, NULL);
	sigaction(SIGUSR1, &action, NULL);
	/* this is not blocked above as we want to receive it asynchronously */
	sigaction(SIGCHLD, &action, NULL);

	/* empty mask for pselect() call below */
	sigemptyset(&action.sa_mask);

	for (;;)
	{
		/*
		 * Stop charon (if started) and exit
		 */
		if (_action_ & FLAG_ACTION_QUIT)
		{
			if (starter_charon_pid())
			{
				starter_stop_charon();
			}
			starter_netkey_cleanup();
			confread_free(cfg);
			unlink(starter_pid_file);
			cleanup();
			DBG1(DBG_APP, "ipsec starter stopped");
			close_log();
			exit(LSB_RC_SUCCESS);
		}

		/*
		 * Delete all connections. Will be added below
		 */
		if (_action_ & FLAG_ACTION_RELOAD)
		{
			if (starter_charon_pid())
			{
				for (conn = cfg->conn_first; conn; conn = conn->next)
				{
					if (conn->state == STATE_ADDED)
					{
						if (starter_charon_pid())
						{
							if (conn->startup == STARTUP_ROUTE)
							{
								starter_stroke_unroute_conn(conn);
							}
							starter_stroke_del_conn(conn);
						}
						conn->state = STATE_TO_ADD;
					}
				}
				for (ca = cfg->ca_first; ca; ca = ca->next)
				{
					if (ca->state == STATE_ADDED)
					{
						if (starter_charon_pid())
						{
							starter_stroke_del_ca(ca);
						}
						ca->state = STATE_TO_ADD;
					}
				}
			}
			_action_ &= ~FLAG_ACTION_RELOAD;
		}

		/*
		 * Update configuration
		 */
		if (_action_ & FLAG_ACTION_UPDATE)
		{
			DBG2(DBG_APP, "Reloading config...");
			new_cfg = confread_load(CONFIG_FILE);

			if (new_cfg && (new_cfg->err == 0))
			{
				/* Switch to new config. New conn will be loaded below */

				/* Look for new connections that are already loaded */
				for (conn = cfg->conn_first; conn; conn = conn->next)
				{
					if (conn->state == STATE_ADDED)
					{
						for (conn2 = new_cfg->conn_first; conn2; conn2 = conn2->next)
						{
							if (conn2->state == STATE_TO_ADD && starter_cmp_conn(conn, conn2))
							{
								conn->state = STATE_REPLACED;
								conn2->state = STATE_ADDED;
								conn2->id = conn->id;
								break;
							}
						}
					}
				}

				/* Remove conn sections that have become unused */
				for (conn = cfg->conn_first; conn; conn = conn->next)
				{
					if (conn->state == STATE_ADDED)
					{
						if (starter_charon_pid())
						{
							if (conn->startup == STARTUP_ROUTE)
							{
								starter_stroke_unroute_conn(conn);
							}
							starter_stroke_del_conn(conn);
						}
					}
				}

				/* Look for new ca sections that are already loaded */
				for (ca = cfg->ca_first; ca; ca = ca->next)
				{
					if (ca->state == STATE_ADDED)
					{
						for (ca2 = new_cfg->ca_first; ca2; ca2 = ca2->next)
						{
							if (ca2->state == STATE_TO_ADD && starter_cmp_ca(ca, ca2))
							{
								ca->state = STATE_REPLACED;
								ca2->state = STATE_ADDED;
								break;
							}
						}
					}
				}

				/* Remove ca sections that have become unused */
				for (ca = cfg->ca_first; ca; ca = ca->next)
				{
					if (ca->state == STATE_ADDED)
					{
						if (starter_charon_pid())
						{
							starter_stroke_del_ca(ca);
						}
					}
				}
				confread_free(cfg);
				cfg = new_cfg;
			}
			else
			{
				DBG1(DBG_APP, "can't reload config file due to errors -- keeping old one");
				if (new_cfg)
				{
					confread_free(new_cfg);
				}
			}
			_action_ &= ~FLAG_ACTION_UPDATE;
			last_reload = time_monotonic(NULL);
		}

		/*
		 * Start daemon
		 */
		if (_action_ & FLAG_ACTION_START_CHARON)
		{
			if (cfg->setup.charonstart && !starter_charon_pid())
			{
				DBG2(DBG_APP, "Attempting to start %s...", daemon_name);
				if (starter_start_charon(cfg, no_fork, attach_gdb))
				{
					/* schedule next try */
					alarm(CHARON_RESTART_DELAY);
				}
				starter_stroke_configure(cfg);
			}
			_action_ &= ~FLAG_ACTION_START_CHARON;

			for (ca = cfg->ca_first; ca; ca = ca->next)
			{
				if (ca->state == STATE_ADDED)
				{
					ca->state = STATE_TO_ADD;
				}
			}

			for (conn = cfg->conn_first; conn; conn = conn->next)
			{
				if (conn->state == STATE_ADDED)
				{
					conn->state = STATE_TO_ADD;
				}
			}
		}

		/*
		 * Add stale conn and ca sections
		 */
		if (starter_charon_pid())
		{
			for (ca = cfg->ca_first; ca; ca = ca->next)
			{
				if (ca->state == STATE_TO_ADD)
				{
					if (starter_charon_pid())
					{
						starter_stroke_add_ca(ca);
					}
					ca->state = STATE_ADDED;
				}
			}

			for (conn = cfg->conn_first; conn; conn = conn->next)
			{
				if (conn->state == STATE_TO_ADD)
				{
					if (conn->id == 0)
					{
						/* affect new unique id */
						conn->id = id++;
					}
					if (starter_charon_pid())
					{
						starter_stroke_add_conn(cfg, conn);
					}
					conn->state = STATE_ADDED;

					if (conn->startup == STARTUP_START)
					{
						if (starter_charon_pid())
						{
							starter_stroke_initiate_conn(conn);
						}
					}
					else if (conn->startup == STARTUP_ROUTE)
					{
						if (starter_charon_pid())
						{
							starter_stroke_route_conn(conn);
						}
					}
				}
			}
		}

		/*
		 * If auto_update activated, when to stop select
		 */
		if (auto_update)
		{
			time_t now = time_monotonic(NULL);

			ts.tv_sec = (now < last_reload + auto_update) ?
						(last_reload + auto_update - now) : 0;
			ts.tv_nsec = 0;
		}

		/*
		 * Wait for something to happen
		 */
		if (!_action_ &&
			pselect(0, NULL, NULL, NULL, auto_update ? &ts : NULL,
					&action.sa_mask) == 0)
		{
			/* timeout -> auto_update */
			_action_ |= FLAG_ACTION_UPDATE;
		}
	}
	exit(LSB_RC_SUCCESS);
}
Exemple #17
0
int main(int argc, char* argv[])
{
    signal(SIGSEGV, crash_sig);
    signal(SIGABRT, crash_sig);
    signal(SIGPIPE, SIG_IGN);

    char cmd[1024];
    int localfd, remotefd;
    library_conf_t conf;
    int opt;
    char* ip = NULL;
    unsigned int port = 6687;
    struct in_addr a;

    struct option long_options[] = {
        {"aes",          1, NULL, 'a'},
        {"des",          1, NULL, 'd'},
        {"gzip",         0, NULL, 'g'},
        {"mask",         1, NULL, 'm'},
        {"localip",      1, NULL, 'l'},
        {"server",       1, NULL, 's'},
        {"port",         1, NULL, 'p'},
        {NULL,           0, NULL,   0}
    };
    char short_options[512] = {0};
    longopt2shortopt(long_options, sizeof(long_options) / sizeof(struct option), short_options);

    conf.localip      = 0;
    conf.netmask      = 24;
    conf.use_gzip     = 0;
    conf.use_aes      = 0;
    conf.aes_key_file = NULL;
    conf.use_des      = 0;
    conf.des_key_file = NULL;

    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
    {
        switch (opt)
        {
        case 'a':
            conf.use_aes = 1;
            conf.aes_key_file = optarg;
            break;
        case 'd':
            conf.use_des = 1;
            conf.des_key_file = optarg;
            break;
        case 'g':
            conf.use_gzip = 1;
            break;
        case 'l':
            conf.localip = inet_addr(optarg);
            break;
        case 's':
            ip = optarg;
            break;
        case 'm':
            conf.netmask = atoi(optarg);
            break;
        case 'p':
            port = atoi(optarg);
            break;
        default:
            fprintf(stderr, "param error\n");
            return 1;
        }
    }

    if (conf.localip == 0)
    {
        fprintf(stderr, "localip is zero\n");
        return 1;
    }
    if (port == 0)
    {
        fprintf(stderr, "port is zero\n");
        return 1;
    }

    memset(this.dev_name, 0, IFNAMSIZ);
    localfd = tun_open(this.dev_name);
    if (localfd == -1) return 1;
    fprintf(stdout, "%s opened\n", this.dev_name);
    a.s_addr = conf.localip;

    if (ip == NULL)
    {
        if (conf.netmask == 0 || conf.netmask > 31)
        {
            fprintf(stderr, "netmask must > 0 and <= 31\n");
            return 1;
        }
        library_init(conf);
        remotefd = bind_and_listen(port);
        if (remotefd == -1) return 1;
        sprintf(cmd, "ifconfig %s %s/%u up", this.dev_name, inet_ntoa(a), conf.netmask);
        SYSTEM_EXIT(cmd);
        a.s_addr = conf.localip & LEN2MASK(conf.netmask);
        sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), conf.netmask, this.dev_name);
        SYSTEM_EXIT(cmd);
        server_loop(remotefd, localfd);
    }
    else
    {
        unsigned char mask;
        int inited = 0;
        library_init(conf);

        while (1)
        {
            remotefd = connect_server(ip, port);
            if (remotefd == -1)
            {
                sleep(5);
                continue;
            }
            if (!inited)
            {
                sprintf(cmd, "ifconfig %s %s up", this.dev_name, inet_ntoa(a));
                SYSTEM_EXIT(cmd);
                mask = netmask();
                a.s_addr = conf.localip & LEN2MASK(mask);
                sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), mask, this.dev_name);
                SYSTEM_EXIT(cmd);
                inited = 1;
            }
            client_loop(remotefd, localfd);
            close(remotefd);
            fprintf(stderr, "retry\n");
        }
    }
    return 0;
}
int main(int argc, char **argv)
{
	bool fork_desired = TRUE;
	bool log_to_stderr_desired = FALSE;
	bool nat_traversal = FALSE;
	bool nat_t_spf = TRUE;  /* support port floating */
	unsigned int keep_alive = 0;
	bool force_keepalive = FALSE;
	char *virtual_private = NULL;
	int lockfd;
#ifdef CAPABILITIES
	int keep[] = { CAP_NET_ADMIN, CAP_NET_BIND_SERVICE };
#endif /* CAPABILITIES */

	/* initialize library and optionsfrom */
	if (!library_init(NULL))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (!libhydra_init("pluto"))
	{
		libhydra_deinit();
		library_deinit();
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	if (!pluto_init(argv[0]))
	{
		pluto_deinit();
		libhydra_deinit();
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}
	options = options_create();

	/* handle arguments */
	for (;;)
	{
#       define DBG_OFFSET 256
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "nofork", no_argument, NULL, 'd' },
			{ "stderrlog", no_argument, NULL, 'e' },
			{ "nocrsend", no_argument, NULL, 'c' },
			{ "strictcrlpolicy", no_argument, NULL, 'r' },
			{ "crlcheckinterval", required_argument, NULL, 'x'},
			{ "cachecrls", no_argument, NULL, 'C' },
			{ "uniqueids", no_argument, NULL, 'u' },
      { "disableuniqreqids", no_argument, NULL, 'Z'},			
			{ "interface", required_argument, NULL, 'i' },
			{ "ikeport", required_argument, NULL, 'p' },
			{ "ctlbase", required_argument, NULL, 'b' },
			{ "secretsfile", required_argument, NULL, 's' },
			{ "foodgroupsdir", required_argument, NULL, 'f' },
			{ "perpeerlogbase", required_argument, NULL, 'P' },
			{ "perpeerlog", no_argument, NULL, 'l' },
			{ "policygroupsdir", required_argument, NULL, 'f' },
#ifdef USE_LWRES
			{ "lwdnsq", required_argument, NULL, 'a' },
#else /* !USE_LWRES */
			{ "adns", required_argument, NULL, 'a' },
#endif /* !USE_LWRES */
			{ "pkcs11module", required_argument, NULL, 'm' },
			{ "pkcs11keepstate", no_argument, NULL, 'k' },
			{ "pkcs11initargs", required_argument, NULL, 'z' },
			{ "pkcs11proxy", no_argument, NULL, 'y' },
			{ "nat_traversal", no_argument, NULL, '1' },
			{ "keep_alive", required_argument, NULL, '2' },
			{ "force_keepalive", no_argument, NULL, '3' },
			{ "disable_port_floating", no_argument, NULL, '4' },
			{ "debug-natt", no_argument, NULL, '5' },
			{ "virtual_private", required_argument, NULL, '6' },
#ifdef DEBUG
			{ "debug-none", no_argument, NULL, 'N' },
			{ "debug-all", no_argument, NULL, 'A' },
			{ "debug-raw", no_argument, NULL, DBG_RAW + DBG_OFFSET },
			{ "debug-crypt", no_argument, NULL, DBG_CRYPT + DBG_OFFSET },
			{ "debug-parsing", no_argument, NULL, DBG_PARSING + DBG_OFFSET },
			{ "debug-emitting", no_argument, NULL, DBG_EMITTING + DBG_OFFSET },
			{ "debug-control", no_argument, NULL, DBG_CONTROL + DBG_OFFSET },
			{ "debug-lifecycle", no_argument, NULL, DBG_LIFECYCLE + DBG_OFFSET },
			{ "debug-klips", no_argument, NULL, DBG_KERNEL + DBG_OFFSET },
			{ "debug-kernel", no_argument, NULL, DBG_KERNEL + DBG_OFFSET },
			{ "debug-dns", no_argument, NULL, DBG_DNS + DBG_OFFSET },
			{ "debug-oppo", no_argument, NULL, DBG_OPPO + DBG_OFFSET },
			{ "debug-controlmore", no_argument, NULL, DBG_CONTROLMORE + DBG_OFFSET },
			{ "debug-private", no_argument, NULL, DBG_PRIVATE + DBG_OFFSET },

			{ "impair-delay-adns-key-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_KEY_ANSWER + DBG_OFFSET },
			{ "impair-delay-adns-txt-answer", no_argument, NULL, IMPAIR_DELAY_ADNS_TXT_ANSWER + DBG_OFFSET },
			{ "impair-bust-mi2", no_argument, NULL, IMPAIR_BUST_MI2 + DBG_OFFSET },
			{ "impair-bust-mr2", no_argument, NULL, IMPAIR_BUST_MR2 + DBG_OFFSET },
#endif
			{ 0,0,0,0 }
			};
		/* Note: we don't like the way short options get parsed
		 * by getopt_long, so we simply pass an empty string as
		 * the list.  It could be "hvdenp:l:s:" "NARXPECK".
		 */
		int c = getopt_long(argc, argv, "", long_opts, NULL);

		/* Note: "breaking" from case terminates loop */
		switch (c)
		{
		case EOF:       /* end of flags */
			break;

		case 0: /* long option already handled */
			continue;

		case ':':       /* diagnostic already printed by getopt_long */
		case '?':       /* diagnostic already printed by getopt_long */
			usage("");
			break;   /* not actually reached */

		case 'h':       /* --help */
			usage(NULL);
			break;      /* not actually reached */

		case 'v':       /* --version */
			{
				const char **sp = ipsec_copyright_notice();

				printf("strongSwan "VERSION"%s\n", compile_time_interop_options);
				for (; *sp != NULL; sp++)
					puts(*sp);
			}
			exit_pluto(0);
			break;      /* not actually reached */

		case '+':       /* --optionsfrom <filename> */
			if (!options->from(options, optarg, &argc, &argv, optind))
			{
				exit_pluto(1);
			}
			continue;

		case 'd':       /* --nofork*/
			fork_desired = FALSE;
			continue;

		case 'e':       /* --stderrlog */
			log_to_stderr_desired = TRUE;
			continue;

		case 'c':       /* --nocrsend */
			no_cr_send = TRUE;
			continue;

		case 'r':       /* --strictcrlpolicy */
			strict_crl_policy = TRUE;
			continue;

		case 'x':       /* --crlcheckinterval <time>*/
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing interval time");

			{
				char *endptr;
				long interval = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| interval <= 0)
					usage("<interval-time> must be a positive number");
				crl_check_interval = interval;
			}
			continue;

		case 'C':       /* --cachecrls */
			cache_crls = TRUE;
			continue;

		case 'u':       /* --uniqueids */
			uniqueIDs = TRUE;
			continue;
	
	  case 'Z':       /* --disableuniqreqids */
	    disable_uniqreqids = TRUE;
	    continue;

		case 'i':       /* --interface <ifname> */
			if (!use_interface(optarg))
				usage("too many --interface specifications");
			continue;

		case 'p':       /* --port <portnumber> */
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing port number");

			{
				char *endptr;
				long port = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| port <= 0 || port > 0x10000)
					usage("<port-number> must be a number between 1 and 65535");
				pluto_port = port;
			}
			continue;

		case 'b':       /* --ctlbase <path> */
			if (snprintf(ctl_addr.sun_path, sizeof(ctl_addr.sun_path)
			, "%s%s", optarg, CTL_SUFFIX) == -1)
				usage("<path>" CTL_SUFFIX " too long for sun_path");
			if (snprintf(info_addr.sun_path, sizeof(info_addr.sun_path)
			, "%s%s", optarg, INFO_SUFFIX) == -1)
				usage("<path>" INFO_SUFFIX " too long for sun_path");
			if (snprintf(pluto_lock, sizeof(pluto_lock)
			, "%s%s", optarg, LOCK_SUFFIX) == -1)
				usage("<path>" LOCK_SUFFIX " must fit");
			continue;

		case 's':       /* --secretsfile <secrets-file> */
			shared_secrets_file = optarg;
			continue;

		case 'f':       /* --policygroupsdir <policygroups-dir> */
			policygroups_dir = optarg;
			continue;

		case 'a':       /* --adns <pathname> */
			pluto_adns_option = optarg;
			continue;

		case 'm':       /* --pkcs11module <pathname> */
			pkcs11_module_path = optarg;
			continue;

		case 'k':       /* --pkcs11keepstate */
			pkcs11_keep_state = TRUE;
			continue;

		case 'y':       /* --pkcs11proxy */
			pkcs11_proxy = TRUE;
			continue;

		case 'z':       /* --pkcs11initargs */
			pkcs11_init_args = optarg;
			continue;

#ifdef DEBUG
		case 'N':       /* --debug-none */
			base_debugging = DBG_NONE;
			continue;

		case 'A':       /* --debug-all */
			base_debugging = DBG_ALL;
			continue;
#endif

		case 'P':       /* --perpeerlogbase */
			base_perpeer_logdir = optarg;
			continue;

		case 'l':
			log_to_perpeer = TRUE;
			continue;

		case '1':       /* --nat_traversal */
			nat_traversal = TRUE;
			continue;
		case '2':       /* --keep_alive */
			keep_alive = atoi(optarg);
			continue;
		case '3':       /* --force_keepalive */
			force_keepalive = TRUE;
			continue;
		case '4':       /* --disable_port_floating */
			nat_t_spf = FALSE;
			continue;
		case '5':       /* --debug-nat_t */
			base_debugging |= DBG_NATT;
			continue;
		case '6':       /* --virtual_private */
			virtual_private = optarg;
			continue;

		default:
#ifdef DEBUG
			if (c >= DBG_OFFSET)
			{
				base_debugging |= c - DBG_OFFSET;
				continue;
			}
#       undef DBG_OFFSET
#endif
			bad_case(c);
		}
		break;
	}
	if (optind != argc)
		usage("unexpected argument");
	reset_debugging();
	lockfd = create_lock();

	/* select between logging methods */

	if (log_to_stderr_desired)
	{
		log_to_syslog = FALSE;
	}
	else
	{
		log_to_stderr = FALSE;
	}

	/* set the logging function of pfkey debugging */
#ifdef DEBUG
	pfkey_debug_func = DBG_log;
#else
	pfkey_debug_func = NULL;
#endif

	/* create control socket.
	 * We must create it before the parent process returns so that
	 * there will be no race condition in using it.  The easiest
	 * place to do this is before the daemon fork.
	 */
	{
		err_t ugh = init_ctl_socket();

		if (ugh != NULL)
		{
			fprintf(stderr, "pluto: %s", ugh);
			exit_pluto(1);
		}
	}

	/* If not suppressed, do daemon fork */

	if (fork_desired)
	{
		{
			pid_t pid = fork();

			if (pid < 0)
			{
				int e = errno;

				fprintf(stderr, "pluto: fork failed (%d %s)\n",
					errno, strerror(e));
				exit_pluto(1);
			}

			if (pid != 0)
			{
				/* parent: die, after filling PID into lock file.
				 * must not use exit_pluto: lock would be removed!
				 */
				exit(fill_lock(lockfd, pid)? 0 : 1);
			}
		}

		if (setsid() < 0)
		{
			int e = errno;

			fprintf(stderr, "setsid() failed in main(). Errno %d: %s\n",
				errno, strerror(e));
			exit_pluto(1);
		}
	}
	else
	{
		/* no daemon fork: we have to fill in lock file */
		(void) fill_lock(lockfd, getpid());
		fprintf(stdout, "Pluto initialized\n");
		fflush(stdout);
	}

	/* Redirect stdin, stdout and stderr to /dev/null
	 */
	{
		int fd;
		if ((fd = open("/dev/null", O_RDWR)) == -1)
			abort();
		if (dup2(fd, 0) != 0)
			abort();
		if (dup2(fd, 1) != 1)
			abort();
		if (!log_to_stderr && dup2(fd, 2) != 2)
			abort();
		close(fd);
	}

	init_constants();
	init_log("pluto");

	/* Note: some scripts may look for this exact message -- don't change
	 * ipsec barf was one, but it no longer does.
	 */
	plog("Starting IKEv1 pluto daemon (strongSwan "VERSION")%s",
		 compile_time_interop_options);

	if (lib->integrity)
	{
		plog("integrity tests enabled:");
		plog("lib    'libstrongswan': passed file and segment integrity tests");
		plog("lib    'libhydra': passed file and segment integrity tests");
		plog("daemon 'pluto': passed file integrity test");
	}

	/* load plugins, further infrastructure may need it */
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "pluto.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	print_plugins();

	init_builder();
	if (!init_secret() || !init_crypto())
	{
		plog("initialization failed - aborting pluto");
		exit_pluto(SS_RC_INITIALIZATION_FAILED);
	}
	init_nat_traversal(nat_traversal, keep_alive, force_keepalive, nat_t_spf);
	init_virtual_ip(virtual_private);
	scx_init(pkcs11_module_path, pkcs11_init_args);
	init_states();
	init_demux();
	init_kernel();
	init_adns();
	init_myid();
	fetch_initialize();
	ac_initialize();
	whack_attribute_initialize();

	/* drop unneeded capabilities and change UID/GID */
	prctl(PR_SET_KEEPCAPS, 1);

#ifdef IPSEC_GROUP
	{
		struct group group, *grp;
	char buf[1024];

		if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
				grp == NULL || setgid(grp->gr_gid) != 0)
		{
			plog("unable to change daemon group");
			abort();
		}
	}
#endif
#ifdef IPSEC_USER
	{
		struct passwd passwd, *pwp;
	char buf[1024];

		if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
				pwp == NULL || setuid(pwp->pw_uid) != 0)
		{
			plog("unable to change daemon user");
			abort();
		}
		}
#endif

#ifdef CAPABILITIES_LIBCAP
	{
		cap_t caps;
		caps = cap_init();
		cap_set_flag(caps, CAP_EFFECTIVE, countof(keep), keep, CAP_SET);
		cap_set_flag(caps, CAP_INHERITABLE, countof(keep), keep, CAP_SET);
		cap_set_flag(caps, CAP_PERMITTED, countof(keep), keep, CAP_SET);
		if (cap_set_proc(caps) != 0)
		{
			plog("unable to drop daemon capabilities");
			abort();
		}
		cap_free(caps);
	}
#endif /* CAPABILITIES_LIBCAP */
#ifdef CAPABILITIES_NATIVE
	{
		struct __user_cap_data_struct caps = { .effective = 0 };
		struct __user_cap_header_struct header = {
			.version = _LINUX_CAPABILITY_VERSION,
		};
		int i;
		for (i = 0; i < countof(keep); i++)
		{
			caps.effective |= 1 << keep[i];
			caps.permitted |= 1 << keep[i];
			caps.inheritable |= 1 << keep[i];
		}
		if (capset(&header, &caps) != 0)
		{
			plog("unable to drop daemon capabilities");
			abort();
		}
	}
#endif /* CAPABILITIES_NATIVE */

	/* loading X.509 CA certificates */
	load_authcerts("ca", CA_CERT_PATH, X509_CA);
	/* loading X.509 AA certificates */
	load_authcerts("aa", AA_CERT_PATH, X509_AA);
	/* loading X.509 OCSP certificates */
	load_authcerts("ocsp", OCSP_CERT_PATH, X509_OCSP_SIGNER);
	/* loading X.509 CRLs */
	load_crls();
	/* loading attribute certificates (experimental) */
	ac_load_certs();

	lib->processor->set_threads(lib->processor,
			lib->settings->get_int(lib->settings, "pluto.threads",
								   DEFAULT_THREADS));

	daily_log_event();
	call_server();
	return -1;  /* Shouldn't ever reach this */
}

/* leave pluto, with status.
 * Once child is launched, parent must not exit this way because
 * the lock would be released.
 *
 *  0 OK
 *  1 general discomfort
 * 10 lock file exists
 */
void exit_pluto(int status)
{
	lib->processor->set_threads(lib->processor, 0);
	reset_globals();    /* needed because we may be called in odd state */
	free_preshared_secrets();
	free_remembered_public_keys();
	delete_every_connection();
	whack_attribute_finalize(); /* free in-memory pools */
	kernel_finalize();
	fetch_finalize();           /* stop fetching thread */
	free_crl_fetch();           /* free chain of crl fetch requests */
	free_ocsp_fetch();          /* free chain of ocsp fetch requests */
	free_authcerts();           /* free chain of X.509 authority certificates */
	free_crls();                /* free chain of X.509 CRLs */
	free_ca_infos();            /* free chain of X.509 CA information records */
	free_ocsp();                /* free ocsp cache */
	free_ifaces();
	ac_finalize();              /* free X.509 attribute certificates */
	scx_finalize();             /* finalize and unload PKCS #11 module */
	stop_adns();
	free_md_pool();
	free_crypto();
	free_myid();                /* free myids */
	free_events();              /* free remaining events */
	free_vendorid();            /* free all vendor id records */
	free_builder();
	delete_lock();
	options->destroy(options);
	pluto_deinit();
	lib->plugins->unload(lib->plugins);
	libhydra_deinit();
	library_deinit();
	close_log();
	exit(status);
}
Exemple #19
0
/**
 * Described in header.
 */
bool libimcv_init(bool is_imv)
{
	/* initialize libstrongswan library only once */
	if (lib)
	{
		/* did main program initialize libstrongswan? */
		if (libstrongswan_ref == 0)
		{
			ref_get(&libstrongswan_ref);
		}
	}
	else
	{
		/* we are the first to initialize libstrongswan */
		if (!library_init(NULL, "libimcv"))
		{
			return FALSE;
		}

		/* set the debug level and stderr output */
		imcv_debug_level =  lib->settings->get_int(lib->settings,
									"libimcv.debug_level", IMCV_DEBUG_LEVEL);
		imcv_stderr_quiet = lib->settings->get_int(lib->settings,
									"libimcv.stderr_quiet", FALSE);

		/* activate the imcv debugging hook */
		dbg = imcv_dbg;
#ifdef HAVE_SYSLOG
		openlog("imcv", 0, LOG_DAEMON);
#endif

		if (!lib->plugins->load(lib->plugins,
				lib->settings->get_str(lib->settings, "libimcv.load",
					"random nonce gmp pubkey x509")))
		{
			library_deinit();
			return FALSE;
		}
	}
	ref_get(&libstrongswan_ref);

	lib->settings->add_fallback(lib->settings, "%s.imcv", "libimcv", lib->ns);
	lib->settings->add_fallback(lib->settings, "%s.plugins", "libimcv.plugins",
								lib->ns);

	if (libimcv_ref == 0)
	{
		char *uri, *script;

		/* initialize the PA-TNC attribute manager */
	 	imcv_pa_tnc_attributes = pa_tnc_attr_manager_create();
		imcv_pa_tnc_attributes->add_vendor(imcv_pa_tnc_attributes, PEN_IETF,
							ietf_attr_create_from_data, ietf_attr_names);
		imcv_pa_tnc_attributes->add_vendor(imcv_pa_tnc_attributes, PEN_ITA,
							ita_attr_create_from_data, ita_attr_names);
		imcv_pa_tnc_attributes->add_vendor(imcv_pa_tnc_attributes, PEN_TCG,
							tcg_attr_create_from_data, tcg_attr_names);

		imcv_pts_components = pts_component_manager_create();
		imcv_pts_components->add_vendor(imcv_pts_components, PEN_TCG,
					pts_tcg_comp_func_names, PTS_TCG_QUALIFIER_TYPE_SIZE,
					pts_tcg_qualifier_flag_names, pts_tcg_qualifier_type_names);
		imcv_pts_components->add_vendor(imcv_pts_components, PEN_ITA,
					pts_ita_comp_func_names, PTS_ITA_QUALIFIER_TYPE_SIZE,
					pts_ita_qualifier_flag_names, pts_ita_qualifier_type_names);

		imcv_pts_components->add_component(imcv_pts_components, PEN_ITA,
									  PTS_ITA_COMP_FUNC_NAME_TGRUB,
									  pts_ita_comp_tgrub_create);
		imcv_pts_components->add_component(imcv_pts_components, PEN_ITA,
									  PTS_ITA_COMP_FUNC_NAME_TBOOT,
									  pts_ita_comp_tboot_create);
		imcv_pts_components->add_component(imcv_pts_components, PEN_ITA,
									  PTS_ITA_COMP_FUNC_NAME_IMA,
									  pts_ita_comp_ima_create);
		if (is_imv)
		{
			/* instantiate global IMV session manager */
			imcv_sessions = imv_session_manager_create();

			/* instantiate and attach global IMV database if URI is valid */
			uri = lib->settings->get_str(lib->settings,
						"%s.imcv.database", NULL, lib->ns);
			script = lib->settings->get_str(lib->settings,
						"%s.imcv.policy_script", IMCV_DEFAULT_POLICY_SCRIPT,
						lib->ns);
			if (uri)
			{
				imcv_db = imv_database_create(uri, script);
			}
		}
		DBG1(DBG_LIB, "libimcv initialized");
	}
	ref_get(&libimcv_ref);

	return TRUE;
}
/**
 * @brief main of scepclient
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
	/* external values */
	extern char * optarg;
	extern int optind;

	/* type of input and output files */
	typedef enum {
		PKCS1      =  0x01,
		PKCS10     =  0x02,
		PKCS7      =  0x04,
		CERT_SELF  =  0x08,
		CERT       =  0x10,
		CACERT_ENC =  0x20,
		CACERT_SIG =  0x40
	} scep_filetype_t;

	/* filetype to read from, defaults to "generate a key" */
	scep_filetype_t filetype_in = 0;

	/* filetype to write to, no default here */
	scep_filetype_t filetype_out = 0;

	/* input files */
	char *file_in_pkcs1      = DEFAULT_FILENAME_PKCS1;
	char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
	char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;

	/* output files */
	char *file_out_pkcs1     = DEFAULT_FILENAME_PKCS1;
	char *file_out_pkcs10    = DEFAULT_FILENAME_PKCS10;
	char *file_out_pkcs7     = DEFAULT_FILENAME_PKCS7;
	char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
	char *file_out_cert      = DEFAULT_FILENAME_CERT;
	char *file_out_prefix_cacert = DEFAULT_FILENAME_PREFIX_CACERT;

	/* by default user certificate is requested */
	bool request_ca_certificate = FALSE;

	/* by default existing files are not overwritten */
	bool force = FALSE;

	/* length of RSA key in bits */
	u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;

	/* validity of self-signed certificate */
	time_t validity  = DEFAULT_CERT_VALIDITY;
	time_t notBefore = 0;
	time_t notAfter  = 0;

	/* distinguished name for requested certificate, ASCII format */
	char *distinguishedName = NULL;

	/* challenge password */
	char challenge_password_buffer[MAX_PASSWORD_LENGTH];

	/* symmetric encryption algorithm used by pkcs7, default is 3DES */
	int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;

	/* digest algorithm used by pkcs7, default is SHA-1 */
	int pkcs7_digest_alg = OID_SHA1;

	/* signature algorithm used by pkcs10, default is SHA-1 */
	hash_algorithm_t pkcs10_signature_alg = HASH_SHA1;

	/* URL of the SCEP-Server */
	char *scep_url = NULL;

	/* http request method, default is GET */
	bool http_get_request = TRUE;

	/* poll interval time in manual mode in seconds */
	u_int poll_interval = DEFAULT_POLL_INTERVAL;

	/* maximum poll time */
	u_int max_poll_time = 0;

	err_t ugh = NULL;

	/* initialize library */
	if (!library_init(NULL))
	{
		library_deinit();
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity &&
		!lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
	{
		fprintf(stderr, "integrity check of scepclient failed\n");
		library_deinit();
		exit(SS_RC_DAEMON_INTEGRITY);
	}

	/* initialize global variables */
	pkcs1             = chunk_empty;
	pkcs7             = chunk_empty;
	serialNumber      = chunk_empty;
	transID           = chunk_empty;
	fingerprint       = chunk_empty;
	encoding          = chunk_empty;
	pkcs10_encoding   = chunk_empty;
	issuerAndSubject  = chunk_empty;
	challengePassword = chunk_empty;
	getCertInitial    = chunk_empty;
	scep_response     = chunk_empty;
	subjectAltNames   = linked_list_create();
	options           = options_create();
	log_to_stderr     = TRUE;

	for (;;)
	{
		static const struct option long_opts[] = {
			/* name, has_arg, flag, val */
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "optionsfrom", required_argument, NULL, '+' },
			{ "quiet", no_argument, NULL, 'q' },
			{ "in", required_argument, NULL, 'i' },
			{ "out", required_argument, NULL, 'o' },
			{ "force", no_argument, NULL, 'f' },
			{ "keylength", required_argument, NULL, 'k' },
			{ "dn", required_argument, NULL, 'd' },
			{ "days", required_argument, NULL, 'D' },
			{ "startdate", required_argument, NULL, 'S' },
			{ "enddate", required_argument, NULL, 'E' },
			{ "subjectAltName", required_argument, NULL, 's' },
			{ "password", required_argument, NULL, 'p' },
			{ "algorithm", required_argument, NULL, 'a' },
			{ "url", required_argument, NULL, 'u' },
			{ "method", required_argument, NULL, 'm' },
			{ "interval", required_argument, NULL, 't' },
			{ "maxpolltime", required_argument, NULL, 'x' },
#ifdef DEBUG
			{ "debug-all", no_argument, NULL, 'A' },
			{ "debug-parsing", no_argument, NULL, 'P'},
			{ "debug-raw", no_argument, NULL, 'R'},
			{ "debug-control", no_argument, NULL, 'C'},
			{ "debug-controlmore", no_argument, NULL, 'M'},
			{ "debug-private", no_argument, NULL, 'X'},
#endif
			{ 0,0,0,0 }
		};

		/* parse next option */
		int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);

		switch (c)
		{
		case EOF:       /* end of flags */
			break;

		case 'h':       /* --help */
			usage(NULL);

		case 'v':       /* --version */
			version();

		case 'q':       /* --quiet */
			log_to_stderr = FALSE;
			continue;

		case 'i':       /* --in <type> [= <filename>] */
			{
				char *filename = strstr(optarg, "=");

				if (filename)
				{
					/* replace '=' by '\0' */
					*filename = '\0';
					/* set pointer to start of filename */
					filename++;
				}
				if (strcaseeq("pkcs1", optarg))
				{
					filetype_in |= PKCS1;
					if (filename)
						file_in_pkcs1 = filename;
				}
				else if (strcaseeq("cacert-enc", optarg))
				{
					filetype_in |= CACERT_ENC;
					if (filename)
						file_in_cacert_enc = filename;
				}
				else if (strcaseeq("cacert-sig", optarg))
				{
					filetype_in |= CACERT_SIG;
					if (filename)
						 file_in_cacert_sig = filename;
				}
				else
				{
					usage("invalid --in file type");
				}
				continue;
			}

		case 'o':       /* --out <type> [= <filename>] */
			{
				char *filename = strstr(optarg, "=");

				if (filename)
				{
					/* replace '=' by '\0' */
					*filename = '\0';
					/* set pointer to start of filename */
					filename++;
				}
				if (strcaseeq("pkcs1", optarg))
				{
					filetype_out |= PKCS1;
					if (filename)
						file_out_pkcs1 = filename;
				}
				else if (strcaseeq("pkcs10", optarg))
				{
					filetype_out |= PKCS10;
					if (filename)
						file_out_pkcs10 = filename;
				}
				else if (strcaseeq("pkcs7", optarg))
				{
					filetype_out |= PKCS7;
					if (filename)
						file_out_pkcs7 = filename;
				}
				else if (strcaseeq("cert-self", optarg))
				{
					filetype_out |= CERT_SELF;
					if (filename)
						file_out_cert_self = filename;
				}
				else if (strcaseeq("cert", optarg))
				{
					filetype_out |= CERT;
					if (filename)
						file_out_cert = filename;
				}
				else if (strcaseeq("cacert", optarg))
				{
					request_ca_certificate = TRUE;
					if (filename)
						file_out_prefix_cacert = filename;
				}
				else
				{
					usage("invalid --out file type");
				}
				continue;
			}

		case 'f':       /* --force */
			force = TRUE;
			continue;

		case '+':       /* --optionsfrom <filename> */
			if (!options->from(options, optarg, &argc, &argv, optind))
			{
				exit_scepclient("optionsfrom failed");
			}
			continue;

		case 'k':        /* --keylength <length> */
			{
				div_t q;

				rsa_keylength = atoi(optarg);
				if (rsa_keylength == 0)
					usage("invalid keylength");

				/* check if key length is a multiple of 8 bits */
				q = div(rsa_keylength, 2*BITS_PER_BYTE);
				if (q.rem != 0)
				{
					exit_scepclient("keylength is not a multiple of %d bits!"
						, 2*BITS_PER_BYTE);
				}
				continue;
			}

		case 'D':       /* --days */
			if (optarg == NULL || !isdigit(optarg[0]))
				usage("missing number of days");
			{
				char *endptr;
				long days = strtol(optarg, &endptr, 0);

				if (*endptr != '\0' || endptr == optarg
				|| days <= 0)
					usage("<days> must be a positive number");
				validity = 24*3600*days;
			}
			continue;

		case 'S':       /* --startdate */
			if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
				usage("date format must be YYMMDDHHMMSSZ");
			{
				chunk_t date = { optarg, 13 };
				notBefore = asn1_to_time(&date, ASN1_UTCTIME);
			}
			continue;

		case 'E':       /* --enddate */
			if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
				usage("date format must be YYMMDDHHMMSSZ");
			{
				chunk_t date = { optarg, 13 };
				notAfter = asn1_to_time(&date, ASN1_UTCTIME);
			}
			continue;

		case 'd':       /* --dn */
			if (distinguishedName)
				usage("only one distinguished name allowed");
			distinguishedName = optarg;
			continue;

		case 's':       /* --subjectAltName */
			{
				char *value = strstr(optarg, "=");

				if (value)
				{
					/* replace '=' by '\0' */
					*value = '\0';
					/* set pointer to start of value */
					value++;
				}

				if (strcaseeq("email", optarg) ||
					strcaseeq("dns", optarg)   ||
					strcaseeq("ip", optarg))
				{
					subjectAltNames->insert_last(subjectAltNames,
								 identification_create_from_string(value));
					continue;
				}
				else
				{
					usage("invalid --subjectAltName type");
					continue;
				}
			}

		case 'p':       /* --password */
			if (challengePassword.len > 0)
			{
				usage("only one challenge password allowed");
			}
			if (strcaseeq("%prompt", optarg))
			{
				printf("Challenge password: "******"challenge password could not be read");
				}
			}
			else
			{
				challengePassword.ptr = optarg;
				challengePassword.len = strlen(optarg);
			}
			continue;

		case 'u':       /* -- url */
			if (scep_url)
			{
				usage("only one URL argument allowed");
			}
			scep_url = optarg;
			continue;

		case 'm':       /* --method */
			if (strcaseeq("get", optarg))
			{
				http_get_request = TRUE;
			}
			else if (strcaseeq("post", optarg))
			{
				http_get_request = FALSE;
			}
			else
			{
				usage("invalid http request method specified");
			}
			continue;

		case 't':       /* --interval */
			poll_interval = atoi(optarg);
			if (poll_interval <= 0)
			{
				usage("invalid interval specified");
			}
			continue;

		case 'x':       /* --maxpolltime */
			max_poll_time = atoi(optarg);
			if (max_poll_time < 0)
			{
				usage("invalid maxpolltime specified");
			}
			continue;

		case 'a':       /*--algorithm */
		{
			const proposal_token_t *token;

			token = proposal_get_token(optarg, strlen(optarg));
			if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
			{
				usage("invalid algorithm specified");
			}
			pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
										token->algorithm, token->keysize);
			if (pkcs7_symmetric_cipher == OID_UNKNOWN)
			{
				usage("unsupported encryption algorithm specified");
			}
			continue;
		}
#ifdef DEBUG
		case 'A':       /* --debug-all */
			base_debugging |= DBG_ALL;
			continue;
		case 'P':       /* debug parsing */
			base_debugging |= DBG_PARSING;
			continue;
		case 'R':       /* debug raw */
			base_debugging |= DBG_RAW;
			continue;
		case 'C':       /* debug control */
			base_debugging |= DBG_CONTROL;
			continue;
		case 'M':       /* debug control more */
			base_debugging |= DBG_CONTROLMORE;
			continue;
		case 'X':       /* debug private */
			base_debugging |= DBG_PRIVATE;
			continue;
#endif
		default:
			usage("unknown option");
		}
		/* break from loop */
		break;
	}
	cur_debugging = base_debugging;

	init_log("scepclient");

	/* load plugins, further infrastructure may need it */
	if (!lib->plugins->load(lib->plugins, NULL,
			lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
	{
		exit_scepclient("plugin loading failed");
	}
	print_plugins();

	if ((filetype_out == 0) && (!request_ca_certificate))
	{
		usage ("--out filetype required");
	}
	if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
	{
		usage("in CA certificate request, no other --in or --out option allowed");
	}

	/* check if url is given, if cert output defined */
	if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
	{
		usage("URL of SCEP server required");
	}

	/* check for sanity of --in/--out */
	if (!filetype_in && (filetype_in > filetype_out))
	{
		usage("cannot generate --out of given --in!");
	}

	/*
	 * input of PKCS#1 file
	 */
	if (filetype_in & PKCS1)    /* load an RSA key pair from file */
	{
		char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);

		private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
										 BUILD_FROM_FILE, path, BUILD_END);
	}
	else                                /* generate an RSA key pair */
	{
		private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
										 BUILD_KEY_SIZE, rsa_keylength,
										 BUILD_END);
	}
	if (private_key == NULL)
	{
		exit_scepclient("no RSA private key available");
	}
	public_key = private_key->get_public_key(private_key);

	/* check for minimum key length */
	if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
	{
		exit_scepclient("length of RSA key has to be at least %d bits"
			,RSA_MIN_OCTETS * BITS_PER_BYTE);
	}

	/*
	 * input of PKCS#10 file
	 */
	if (filetype_in & PKCS10)
	{
		/* user wants to load a pkcs10 request
		 * operation is not yet supported
		 * would require a PKCS#10 parsing function

		pkcs10 = pkcs10_read_from_file(file_in_pkcs10);

		 */
	}
	else
	{
		if (distinguishedName == NULL)
		{
			char buf[BUF_LEN];
			int n = sprintf(buf, DEFAULT_DN);

			/* set the common name to the hostname */
			if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
			{
				exit_scepclient("no hostname defined, use "
								"--dn <distinguished name> option");
			}
			distinguishedName = buf;
		}

		DBG(DBG_CONTROL,
			DBG_log("dn: '%s'", distinguishedName);
		)
		subject = identification_create_from_string(distinguishedName);
		if (subject->get_type(subject) != ID_DER_ASN1_DN)
		{
			exit_scepclient("parsing of distinguished name failed");
		}

		DBG(DBG_CONTROL,
			DBG_log("building pkcs10 object:")
		)
		pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
						CERT_PKCS10_REQUEST,
						BUILD_SIGNING_KEY, private_key,
						BUILD_SUBJECT, subject,
						BUILD_SUBJECT_ALTNAMES, subjectAltNames,
						BUILD_CHALLENGE_PWD, challengePassword,
						BUILD_DIGEST_ALG, pkcs10_signature_alg,
						BUILD_END);
		if (!pkcs10_req)
		{
			exit_scepclient("generating pkcs10 request failed");
		}
		pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
		fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
		plog("  fingerprint:    %s", fingerprint.ptr);
	}
Exemple #21
0
/**
 * Main function, starts TKM backend.
 */
int main(int argc, char *argv[])
{
	char *dmn_name;
	if (argc > 0 && strlen(argv[0]) > 0)
	{
		dmn_name = basename(argv[0]);
	}
	else
	{
		dmn_name = "charon-tkm";
	}

	/* TKM credential set */
	tkm_cred_t *creds;

	struct sigaction action;
	int status = SS_RC_INITIALIZATION_FAILED;

	/* logging for library during initialization, as we have no bus yet */
	dbg = dbg_syslog;

	/* initialize library */
	if (!library_init(NULL, dmn_name))
	{
		library_deinit();
		exit(status);
	}

	if (!libhydra_init())
	{
		dbg_syslog(DBG_DMN, 1, "initialization failed - aborting %s", dmn_name);
		libhydra_deinit();
		library_deinit();
		exit(status);
	}

	if (!libcharon_init())
	{
		dbg_syslog(DBG_DMN, 1, "initialization failed - aborting %s", dmn_name);
		goto deinit;
	}

	if (!lookup_uid_gid())
	{
		dbg_syslog(DBG_DMN, 1, "invalid uid/gid - aborting %s", dmn_name);
		goto deinit;
	}

	/* make sure we log to the DAEMON facility by default */
	lib->settings->set_int(lib->settings, "%s.syslog.daemon.default",
			lib->settings->get_int(lib->settings, "%s.syslog.daemon.default", 1,
								   dmn_name), dmn_name);
	charon->load_loggers(charon, NULL, FALSE);

	DBG1(DBG_DMN, "Starting charon with TKM backend (strongSwan "VERSION")");

	/* register TKM specific plugins */
	static plugin_feature_t features[] = {
		PLUGIN_REGISTER(NONCE_GEN, tkm_nonceg_create),
			PLUGIN_PROVIDE(NONCE_GEN),
		PLUGIN_REGISTER(PUBKEY, tkm_public_key_load, TRUE),
			PLUGIN_PROVIDE(PUBKEY, KEY_RSA),
			PLUGIN_PROVIDE(PUBKEY_VERIFY, SIGN_RSA_EMSA_PKCS1_SHA1),
			PLUGIN_PROVIDE(PUBKEY_VERIFY, SIGN_RSA_EMSA_PKCS1_SHA256),
		PLUGIN_CALLBACK(kernel_ipsec_register, tkm_kernel_ipsec_create),
			PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
	};
	lib->plugins->add_static_features(lib->plugins, "tkm-backend", features,
			countof(features), TRUE);

	if (!register_dh_mapping())
	{
		DBG1(DBG_DMN, "no DH group mapping defined - aborting %s", dmn_name);
		goto deinit;
	}

	/* register TKM keymat variant */
	keymat_register_constructor(IKEV2, (keymat_constructor_t)tkm_keymat_create);

	/* initialize daemon */
	if (!charon->initialize(charon, PLUGINS))
	{
		DBG1(DBG_DMN, "initialization failed - aborting %s", dmn_name);
		goto deinit;
	}
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	/* set global pidfile name depending on daemon name */
	if (asprintf(&pidfile_name, IPSEC_PIDDIR"/%s.pid", dmn_name) < 0)
	{
		DBG1(DBG_DMN, "unable to set pidfile name - aborting %s", dmn_name);
		goto deinit;
	};

	if (check_pidfile())
	{
		DBG1(DBG_DMN, "%s already running (\"%s\" exists)", dmn_name,
			 pidfile_name);
		goto deinit;
	}

	if (!lib->caps->drop(lib->caps))
	{
		DBG1(DBG_DMN, "capability dropping failed - aborting %s", dmn_name);
		goto deinit;
	}

	/* initialize TKM client */
	if (!tkm_init())
	{
		DBG1(DBG_DMN, "init of TKM client failed - aborting %s", dmn_name);
		goto deinit;
	}

	/* register TKM authorization hook */
	listener = tkm_listener_create();
	charon->bus->add_listener(charon->bus, &listener->listener);

	/* register TKM credential set */
	creds = tkm_cred_create();
	lib->credmgr->add_set(lib->credmgr, (credential_set_t*)creds);

	/* register TKM credential encoder */
	lib->encoding->add_encoder(lib->encoding, tkm_encoder_encode);

	/* add handler for SEGV and ILL,
	 * INT and TERM are handled by sigwait() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start daemon (i.e. the threads in the thread-pool) */
	charon->start(charon);

	/* main thread goes to run loop */
	run();

	unlink_pidfile();
	status = 0;
	charon->bus->remove_listener(charon->bus, &listener->listener);
	listener->destroy(listener);
	creds->destroy(creds);
	lib->encoding->remove_encoder(lib->encoding, tkm_encoder_encode);

deinit:
	destroy_dh_mapping();
	libcharon_deinit();
	libhydra_deinit();
	library_deinit();
	tkm_deinit();
	return status;
}
Exemple #22
0
int main(int argc, char *argv[])
{
    int rc = -1, n, priority;
    const char *importer, *scanner, *geo;
    char *endptr;
    size_t nctl;
    double speed;
    struct timecode_def *timecode;
    bool protect, use_mlock, phono;

    struct controller ctl[2];
    struct rt rt;
    struct library library;

#if defined WITH_OSS || WITH_ALSA
    int rate;
#endif

#ifdef WITH_OSS
    int oss_buffers, oss_fragment;
#endif

#ifdef WITH_ALSA
    int alsa_buffer;
#endif

    fprintf(stderr, "%s\n\n" NOTICE "\n\n", banner);

    if (thread_global_init() == -1)
        return -1;

    if (rig_init() == -1)
        return -1;
    rt_init(&rt);
    library_init(&library);

    ndeck = 0;
    geo = "";
    nctl = 0;
    priority = DEFAULT_PRIORITY;
    importer = DEFAULT_IMPORTER;
    scanner = DEFAULT_SCANNER;
    timecode = NULL;
    speed = 1.0;
    protect = false;
    phono = false;
    use_mlock = false;

#if defined WITH_OSS || WITH_ALSA
    rate = DEFAULT_RATE;
#endif

#ifdef WITH_ALSA
    alsa_buffer = DEFAULT_ALSA_BUFFER;
#endif

#ifdef WITH_OSS
    oss_fragment = DEFAULT_OSS_FRAGMENT;
    oss_buffers = DEFAULT_OSS_BUFFERS;
#endif

    /* Skip over command name */

    argv++;
    argc--;

    while (argc > 0) {

        if (!strcmp(argv[0], "-h")) {
            usage(stdout);
            return 0;

#ifdef WITH_OSS
        } else if (!strcmp(argv[0], "-f")) {

            /* Set fragment size for subsequent devices */

            if (argc < 2) {
                fprintf(stderr, "-f requires an integer argument.\n");
                return -1;
            }

            oss_fragment = strtol(argv[1], &endptr, 10);
            if (*endptr != '\0') {
                fprintf(stderr, "-f requires an integer argument.\n");
                return -1;
            }

            /* Fragment sizes greater than the default aren't useful
             * as they are dependent on DEVICE_FRAME */

            if (oss_fragment < DEFAULT_OSS_FRAGMENT) {
                fprintf(stderr, "Fragment size must be %d or more; aborting.\n",
                        DEFAULT_OSS_FRAGMENT);
                return -1;
            }

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-b")) {

            /* Set number of buffers for subsequent devices */

            if (argc < 2) {
                fprintf(stderr, "-b requires an integer argument.\n");
                return -1;
            }

            oss_buffers = strtol(argv[1], &endptr, 10);
            if (*endptr != '\0') {
                fprintf(stderr, "-b requires an integer argument.\n");
                return -1;
            }

            argv += 2;
            argc -= 2;
#endif

#if defined WITH_OSS || WITH_ALSA
        } else if (!strcmp(argv[0], "-r")) {

            /* Set sample rate for subsequence devices */

            if (argc < 2) {
                fprintf(stderr, "-r requires an integer argument.\n");
                return -1;
            }

            rate = strtol(argv[1], &endptr, 10);
            if (*endptr != '\0') {
                fprintf(stderr, "-r requires an integer argument.\n");
                return -1;
            }

            argv += 2;
            argc -= 2;
#endif

#ifdef WITH_ALSA
        } else if (!strcmp(argv[0], "-m")) {

            /* Set size of ALSA buffer for subsequence devices */

            if (argc < 2) {
                fprintf(stderr, "-m requires an integer argument.\n");
                return -1;
            }

            alsa_buffer = strtol(argv[1], &endptr, 10);
            if (*endptr != '\0') {
                fprintf(stderr, "-m requires an integer argument.\n");
                return -1;
            }

            argv += 2;
            argc -= 2;
#endif

        } else if (!strcmp(argv[0], "-d") || !strcmp(argv[0], "-a") ||
                   !strcmp(argv[0], "-j"))
        {
            int r;
            unsigned int sample_rate;
            struct deck *ld;
            struct device *device;
            struct timecoder *timecoder;

            /* Create a deck */

            if (argc < 2) {
                fprintf(stderr, "-%c requires a device name as an argument.\n",
                        argv[0][1]);
                return -1;
            }

            if (ndeck == ARRAY_SIZE(deck)) {
                fprintf(stderr, "Too many decks; aborting.\n");
                return -1;
            }

            fprintf(stderr, "Initialising deck %zd (%s)...\n", ndeck, argv[1]);

            ld = &deck[ndeck];
            device = &ld->device;
            timecoder = &ld->timecoder;
            ld->importer = importer;
            ld->protect = protect;

            /* Work out which device type we are using, and initialise
             * an appropriate device. */

            switch(argv[0][1]) {

#ifdef WITH_OSS
            case 'd':
                r = oss_init(device, argv[1], rate, oss_buffers, oss_fragment);
                break;
#endif
#ifdef WITH_ALSA
            case 'a':
                r = alsa_init(device, argv[1], rate, alsa_buffer);
                break;
#endif
#ifdef WITH_JACK
            case 'j':
                r = jack_init(device, argv[1]);
                break;
#endif
            default:
                fprintf(stderr, "Device type is not supported by this "
                        "distribution of xwax.\n");
                return -1;
            }

            if (r == -1)
                return -1;

            sample_rate = device_sample_rate(device);

            /* Default timecode decoder where none is specified */

            if (timecode == NULL) {
                timecode = timecoder_find_definition(DEFAULT_TIMECODE);
                assert(timecode != NULL);
            }

            timecoder_init(timecoder, timecode, speed, sample_rate, phono);

            /* Connect up the elements to make an operational deck */

            r = deck_init(ld, &rt, ndeck);
            if (r == -1)
                return -1;

            /* Connect this deck to available controllers */

            for (n = 0; n < nctl; n++)
                controller_add_deck(&ctl[n], &deck[ndeck]);

            /* Connect this deck to OSC server */

            osc_add_deck();

            ndeck++;

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-t")) {

            /* Set the timecode definition to use */

            if (argc < 2) {
                fprintf(stderr, "-t requires a name as an argument.\n");
                return -1;
            }

            timecode = timecoder_find_definition(argv[1]);
            if (timecode == NULL) {
                fprintf(stderr, "Timecode '%s' is not known.\n", argv[1]);
                return -1;
            }

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-33")) {

            speed = 1.0;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "-45")) {

            speed = 1.35;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "-c")) {

            protect = true;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "-u")) {

            protect = false;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "--line")) {

            phono = false;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "--phono")) {

            phono = true;

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "-k")) {

            use_mlock = true;
            track_use_mlock();

            argv++;
            argc--;

        } else if (!strcmp(argv[0], "-q")) {

            if (argc < 2) {
                fprintf(stderr, "-q requires an integer argument.\n");
                return -1;
            }

            priority = strtol(argv[1], &endptr, 10);
            if (*endptr != '\0') {
                fprintf(stderr, "-q requires an integer argument.\n");
                return -1;
            }

            if (priority < 0) {
                fprintf(stderr, "Priority (%d) must be zero or positive.\n",
                        priority);
                return -1;
            }

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-g")) {

            if (argc < 2) {
                fprintf(stderr, "-g requires an argument.\n");
                return -1;
            }

            geo = argv[1];

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-i")) {

            /* Importer script for subsequent decks */

            if (argc < 2) {
                fprintf(stderr, "-i requires an executable path "
                        "as an argument.\n");
                return -1;
            }

            importer = argv[1];

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-s")) {

            /* Scan script for subsequent libraries */

            if (argc < 2) {
                fprintf(stderr, "-s requires an executable path "
                        "as an argument.\n");
                return -1;
            }

            scanner = argv[1];

            argv += 2;
            argc -= 2;

        } else if (!strcmp(argv[0], "-l")) {

            /* Load in a music library */

            if (argc < 2) {
                fprintf(stderr, "-%c requires a pathname as an argument.\n",
                        argv[0][1]);
                return -1;
            }

            if (library_import(&library, scanner, argv[1]) == -1)
                return -1;

            argv += 2;
            argc -= 2;

#ifdef WITH_ALSA
        } else if (!strcmp(argv[0], "--dicer")) {

            struct controller *c;

            if (nctl == sizeof ctl) {
                fprintf(stderr, "Too many controllers; aborting.\n");
                return -1;
            }

            c = &ctl[nctl];

            if (argc < 2) {
                fprintf(stderr, "Dicer requires an ALSA device name.\n");
                return -1;
            }

            if (dicer_init(c, &rt, argv[1]) == -1)
                return -1;

            nctl++;

            argv += 2;
            argc -= 2;
#endif

        } else {
            fprintf(stderr, "'%s' argument is unknown; try -h.\n", argv[0]);
            return -1;
        }
    }

#ifdef WITH_ALSA
    alsa_clear_config_cache();
#endif

    if (ndeck == 0) {
        fprintf(stderr, "You need to give at least one audio device to use "
                "as a deck; try -h.\n");
        return -1;
    }

    rc = EXIT_FAILURE; /* until clean exit */

    if (osc_start((struct deck *)&deck, &library) == -1)
        return -1;
    osc_start_updater_thread();

    /* Order is important: launch realtime thread first, then mlock.
     * Don't mlock the interface, use sparingly for audio threads */

    if (rt_start(&rt, priority) == -1)
        return -1;

    if (use_mlock && mlockall(MCL_CURRENT) == -1) {
        perror("mlockall");
        goto out_rt;
    }

    if (interface_start(&library, geo) == -1)
        goto out_rt;

    if (rig_main() == -1)
        goto out_interface;

    rc = EXIT_SUCCESS;
    fprintf(stderr, "Exiting cleanly...\n");

out_interface:
    interface_stop();
out_rt:
    rt_stop(&rt);

    for (n = 0; n < ndeck; n++)
        deck_clear(&deck[n]);

    for (n = 0; n < nctl; n++)
        controller_clear(&ctl[n]);

    timecoder_free_lookup();
    library_clear(&library);
    rt_clear(&rt);
    rig_clear();
    osc_stop();
    thread_global_clear();

    if (rc == EXIT_SUCCESS)
        fprintf(stderr, "Done.\n");

    return rc;
}
Exemple #23
0
/**
 * Main function, starts the daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	struct utsname utsname;
	int group;

	/* handle simple arguments */
	handle_arguments(argc, argv, TRUE);

	dbg = dbg_stderr;
	atexit(library_deinit);
	if (!library_init(NULL, "charon-cmd"))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity)
	{
		if (!lib->integrity->check_file(lib->integrity, "charon-cmd", argv[0]))
		{
			exit(SS_RC_DAEMON_INTEGRITY);
		}
	}
	atexit(libhydra_deinit);
	if (!libhydra_init())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	atexit(libcharon_deinit);
	if (!libcharon_init())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	for (group = 0; group < DBG_MAX; group++)
	{
		levels[group] = default_loglevel;
	}
	charon->load_loggers(charon, levels, TRUE);

	if (!lookup_uid_gid())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	lib->settings->set_default_str(lib->settings, "charon-cmd.port", "0");
	lib->settings->set_default_str(lib->settings, "charon-cmd.port_nat_t", "0");
	if (!charon->initialize(charon,
			lib->settings->get_str(lib->settings, "charon-cmd.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	if (!lib->caps->drop(lib->caps))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	conn = cmd_connection_create();
	atexit(cleanup_conn);
	creds = cmd_creds_create();
	atexit(cleanup_creds);

	/* handle all arguments */
	handle_arguments(argc, argv, FALSE);

	if (uname(&utsname) != 0)
	{
		memset(&utsname, 0, sizeof(utsname));
	}
	DBG1(DBG_DMN, "Starting charon-cmd IKE client (strongSwan %s, %s %s, %s)",
		 VERSION, utsname.sysname, utsname.release, utsname.machine);
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	/* add handler for SEGV and ILL,
	 * INT, TERM and HUP are handled by sigwait() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaddset(&action.sa_mask, SIGUSR1);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start daemon with thread-pool */
	charon->start(charon);
	/* wait for signal */
	return run();
}
Exemple #24
0
/**
 * Main function, starts the daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	struct utsname utsname;
	int group;

	dbg = dbg_stderr;
	atexit(library_deinit);
	if (!library_init(NULL))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity)
	{
		if (!lib->integrity->check_file(lib->integrity, "charon-xpc", argv[0]))
		{
			exit(SS_RC_DAEMON_INTEGRITY);
		}
	}
	atexit(libhydra_deinit);
	if (!libhydra_init("charon-xpc"))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	atexit(libcharon_deinit);
	if (!libcharon_init("charon-xpc"))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	for (group = 0; group < DBG_MAX; group++)
	{
		levels[group] = LEVEL_CTRL;
	}
	charon->load_loggers(charon, levels, TRUE);

	lib->settings->set_default_str(lib->settings, "charon-xpc.port", "0");
	lib->settings->set_default_str(lib->settings, "charon-xpc.port_nat_t", "0");
	lib->settings->set_default_str(lib->settings,
								"charon-xpc.close_ike_on_child_failure", "yes");
	if (!charon->initialize(charon,
			lib->settings->get_str(lib->settings, "charon-xpc.load",
				"random nonce pem pkcs1 openssl kernel-pfkey kernel-pfroute "
				"keychain socket-default eap-identity eap-mschapv2 osx-attr")))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	if (uname(&utsname) != 0)
	{
		memset(&utsname, 0, sizeof(utsname));
	}
	DBG1(DBG_DMN, "Starting charon-xpc IKE daemon (strongSwan %s, %s %s, %s)",
		 VERSION, utsname.sysname, utsname.release, utsname.machine);

	/* add handler for SEGV and ILL,
	 * INT, TERM and HUP are handled by sigwait() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	dispatcher = xpc_dispatch_create();
	if (!dispatcher)
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	atexit(dispatcher_cleanup);

	charon->start(charon);
	return run();
}
Exemple #25
0
int main(int argc, char* argv[])
{
#ifdef HAVE_EXECINFO_H
    signal(SIGSEGV, crash_sig);
    signal(SIGABRT, crash_sig);
    signal(SIGPIPE, SIG_IGN);
#endif

#ifdef WIN32
    HANDLE localfd;
    WSADATA wsa;
    enum_device_t devs[MAX_DEVICE_COUNT];
#else
    int localfd;
#endif
    char cmd[1024];
    int remotefd;
    library_conf_t conf;
    int opt;
    struct in_addr a;

    struct option long_options[] = {
        { "conf", 1, NULL, 'c' },
        { NULL,   0, NULL,  0  }
    };
    char short_options[512] = {0};
    longopt2shortopt(long_options, sizeof(long_options) / sizeof(struct option), short_options);
#ifdef HAVE_SYSLOG_H
    openlog(argv[0], LOG_PERROR | LOG_CONS | LOG_PID, LOG_LOCAL0);
#endif

    qtun = calloc(sizeof(*qtun), 1);

#ifdef WIN32
    remotefd = -1;
    localfd = INVALID_HANDLE_VALUE;
#else
    localfd = remotefd = -1;
#endif
    {
        char path[MAX_PATH] = {0};
#ifdef WIN32
        strcpy(path, argv[0]);
#elif defined(__APPLE__)
        char tmp_path[sizeof(path)] = {0};
        uint32_t len = sizeof(path);
        if (_NSGetExecutablePath(tmp_path, &len) == -1) {
            perror("_NSGetExecutablePath");
            return 1;
        }
        if (readlink(tmp_path, path, sizeof(path)) == -1) {
            if (errno == EINVAL) strcpy(path, tmp_path);
            else {
                perror("readlink");
                return 1;
            }
        }
#else
        if (readlink("/proc/self/exe", path, sizeof(path)) == -1)
        {
            perror("readlink");
            return 1;
        }
#endif
        init_path(path);
    }
    conf_init(&conf);

    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
    {
        switch (opt)
        {
        case 'c':
            {
                char* path = realpath(optarg, NULL);
                if (path == NULL) {
                    perror("realpath");
                    return 1;
                }
                strcpy(conf.conf_file, path);
                free(path);
            }
            break;
        default:
            fprintf(stderr, "param error\n");
            return 1;
        }
    }

#ifdef WIN32
    {
        size_t count = enum_devices(devs);
        if (count == 0)
        {
            fprintf(stderr, "have no QTun Virtual Adapter\n");
            return 1;
        }
        else if (count == 1)
        {
            strcpy(conf.dev_symbol, devs[0].dev_path);
            strcpy(conf.dev_name, devs[0].dev_name);
        }
        else
        {
            size_t i;
            char str[20] = { 0 };
            int n = -1;
            printf("Have Adapters:\n");
            for (i = 0; i < count; ++i)
            {
                printf("%lu: %s\n", i + 1, devs[i].dev_name);
            }
            printf("Choose One[1]: ");
            while (n == -1)
            {
                if (str[0] == '\n' && str[1] == 0) n = 1;
                else
                {
                    if (!is_int(str, sizeof(str))) continue;
                    n = atoi(str);
                    if (n < 1 || n > (int)count)
                    {
                        fprintf(stderr, "Invalid Number must >= 1 and <= %lu\n", count);
                        n = -1;
                        continue;
                    }
                }
            }
            strcpy(conf.dev_symbol, devs[n].dev_path);
            strcpy(conf.dev_name, devs[n].dev_name);
        }
    }
#endif
    
    init_lua();
    show_logo();
    script_load_config(qtun->lua, &conf, conf.conf_file);

#ifdef WIN32
    if (strlen(conf.dev_symbol) == 0)
    {
        fprintf(stderr, "Missing param [-e] or [--device]\n");
        return 1;
    }
#endif

#ifdef WIN32
    localfd = tun_open(conf.dev_symbol);
    if (localfd == INVALID_HANDLE_VALUE) return 1;
    fprintf(stdout, "%s opened\n", conf.dev_name);
#else
    memset(qtun->dev_name, 0, IFNAMSIZ);
    localfd = tun_open(qtun->dev_name);
    if (localfd == -1) return 1;
    syslog(LOG_INFO, "%s opened\n", qtun->dev_name);
#endif
    a.s_addr = conf.localip;

#ifdef WIN32
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    if (strlen(conf.server) == 0)
    {
        if (conf.netmask == 0 || conf.netmask > 31)
        {
#ifdef WIN32
            WSACleanup();
#endif

            fprintf(stderr, "netmask must > 0 and <= 31\n");
            return 1;
        }
        library_init(conf);
        if (conf.localip == 0)
        {
            fprintf(stderr, "localip is zero\n");
            return 1;
        }
        if (strlen(conf.signature_file) == 0) {
            fprintf(stderr, "missing signature file\n");
            return 1;
        }
        qtun->is_server = 1;
        remotefd = bind_and_listen(conf.server_port);
        if (remotefd == -1)
        {
#ifdef WIN32
            WSACleanup();
#endif
            return 1;
        }
#ifdef WIN32
        {
            a.s_addr = conf.localip;
            sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
            SYSTEM_EXIT(cmd);
        }
#elif defined(__APPLE__)
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), conf.netmask, inet_ntoa(a));
            SYSTEM_EXIT(cmd);
        }
#else
        {
            sprintf(cmd, "ifconfig %s %s/%u up", qtun->dev_name, inet_ntoa(a), conf.netmask);
            SYSTEM_EXIT(cmd);
            a.s_addr = conf.localip & LEN2MASK(conf.netmask);
            sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), conf.netmask, qtun->dev_name);
            SYSTEM_EXIT(cmd);
        }
#endif
        server_loop(remotefd, localfd);
    }
    else
    {
#ifdef unix
        unsigned char mask;
#endif
        int inited = 0;
        library_init(conf);
        qtun->is_server = 0;
        while (1)
        {
            remotefd = connect_server(conf.server, conf.server_port);
            if (remotefd == -1)
            {
                SLEEP(5);
                continue;
            }
            a.s_addr = qtun->localip;
            if (qtun->localip == 0)
            {
                fprintf(stderr, "localip is zero\n");
                return 1;
            }
            if (strlen(conf.signature_file) == 0) {
                fprintf(stderr, "missing signature file\n");
                return 1;
            }
            if (!inited)
            {
#ifdef WIN32
                {
                    sprintf(cmd, "netsh interface ip set address name=\"%s\" static %s %s", conf.dev_name, inet_ntoa(a), STR_LEN2MASK(conf.netmask));
                    SYSTEM_EXIT(cmd);
                }
#elif defined(__APPLE__)
                {
                    char ip1[16], ip2[16];
                    a.s_addr = qtun->localip;
                    strcpy(ip1, inet_ntoa(a));
                    a.s_addr = qtun->client.local_ip;
                    strcpy(ip2, inet_ntoa(a));
                    sprintf(cmd, "ifconfig %s inet %s %s up", qtun->dev_name, ip1, ip2);
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u %s", inet_ntoa(a), mask, ip2);
                    SYSTEM_EXIT(cmd);
                }
#else
                {
                    sprintf(cmd, "ifconfig %s %s up", qtun->dev_name, inet_ntoa(a));
                    SYSTEM_EXIT(cmd);
                    mask = netmask();
                    a.s_addr = qtun->localip & LEN2MASK(mask);
                    sprintf(cmd, "route add -net %s/%u dev %s", inet_ntoa(a), mask, qtun->dev_name);
                    SYSTEM_EXIT(cmd);
                }
#endif
                inited = 1;
            }
            client_loop(remotefd, localfd);
            close(remotefd);
            SYSLOG(LOG_WARNING, "retry");
        }
    }
#ifdef WIN32
    WSACleanup();
#endif

#ifdef HAVE_SYSLOG_H
    closelog();
#endif

    library_free();
    return 0;
}
Exemple #26
0
int main(int argc, char *argv[])
{
	test_vector_t test;

	ctx.in = stdin;
	ctx.out = stdout;

	library_init(NULL, "aes-test");
	atexit(library_deinit);

	while (true)
	{
		struct option long_opts[] = {
			{"help",		no_argument,		NULL,	'h' },
			{"debug",		required_argument,	NULL,	'd' },
			{"mode",		required_argument,	NULL,	'm' },
			{"mct",			no_argument,		NULL,	't' },
			{"decrypt",		no_argument,		NULL,	'x' },
			{"in",			required_argument,	NULL,	'i' },
			{"out",			required_argument,	NULL,	'o' },
			{0,0,0,0 },
		};
		switch (getopt_long(argc, argv, "hd:m:txi:o:", long_opts, NULL))
		{
			case EOF:
				break;
			case 'h':
				usage(stdout, argv[0]);
				return 0;
			case 'd':
				dbg_default_set_level(atoi(optarg));
				continue;
			case 'm':
				if (strcaseeq(optarg, "GCM"))
				{
					ctx.use_gcm = TRUE;
				}
				else if (!strcaseeq(optarg, "CBC"))
				{
					usage(stderr, argv[0]);
					return 1;
				}
				continue;
			case 't':
				ctx.use_mct = TRUE;
				continue;
			case 'x':
				ctx.decrypt = TRUE;
				continue;
			case 'i':
				ctx.in = fopen(optarg, "r");
				if (!ctx.in)
				{
					fprintf(stderr, "failed to open '%s': %s\n", optarg,
							strerror(errno));
					usage(stderr, argv[0]);
					return 1;
				}
				continue;
			case 'o':
				ctx.out = fopen(optarg, "w");
				if (!ctx.out)
				{
					fprintf(stderr, "failed to open '%s': %s\n", optarg,
							strerror(errno));
					usage(stderr, argv[0]);
					return 1;
				}
				continue;
			default:
				usage(stderr, argv[0]);
				return 1;
		}
		break;
	}
	/* TODO: maybe make plugins configurable */
	lib->plugins->load(lib->plugins, PLUGINS);
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	while (get_next_test_vector(&test))
	{
		if (verify_test_vector(&test))
		{
			if (do_test(&test))
			{
				print_result(&test);
			}
		}
		else
		{
			DBG1(DBG_APP, "test vector with missing data encountered");
		}
		fprintf(ctx.out, "\n");
		test_vector_free(&test);
	}

	if (ctx.in != stdin)
	{
		fclose(ctx.in);
	}
	if (ctx.out != stdout)
	{
		fclose(ctx.out);
	}
	return 0;
}
Exemple #27
0
/**
 * main routine, parses args and reads from console
 */
int main(int argc, char *argv[])
{
	GtkWidget *menubar, *menu, *menuitem, *vbox;
	GtkWidget *dummMenu, *guestMenu, *switchMenu;
	enumerator_t *enumerator;
	guest_t *guest;

	library_init(NULL);
	gtk_init(&argc, &argv);

	pages = linked_list_create();
	dumm = dumm_create(NULL);

	/* setup window */
	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(quit), NULL);
	gtk_window_set_title(GTK_WINDOW (window), "Dumm");
	gtk_window_set_default_size(GTK_WINDOW (window), 1000, 500);
	g_signal_connect(G_OBJECT(vte_reaper_get()), "child-exited",
					 G_CALLBACK(child_exited), NULL);

	/* add vbox with menubar, notebook */
	vbox = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(window), vbox);
	menubar = gtk_menu_bar_new();
	gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
	notebook = gtk_notebook_new();
	g_object_set(G_OBJECT(notebook), "homogeneous", TRUE, NULL);
	gtk_notebook_set_tab_pos(GTK_NOTEBOOK(notebook), GTK_POS_BOTTOM);
	gtk_container_add(GTK_CONTAINER(vbox), notebook);

	/* Dumm menu */
	menu = gtk_menu_new();
	dummMenu = gtk_menu_item_new_with_mnemonic("_Dumm");
	gtk_menu_bar_append(GTK_MENU_BAR(menubar), dummMenu);
	gtk_widget_show(dummMenu);
	gtk_menu_item_set_submenu(GTK_MENU_ITEM(dummMenu), menu);

	/* Dumm -> exit */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(quit), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest menu */
	menu = gtk_menu_new();
	guestMenu = gtk_menu_item_new_with_mnemonic("_Guest");
	gtk_menu_bar_append(GTK_MENU_BAR(menubar), guestMenu);
	gtk_widget_show(guestMenu);
	gtk_menu_item_set_submenu(GTK_MENU_ITEM(guestMenu), menu);

	/* Guest -> new */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_NEW, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(create_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> delete */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_DELETE, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(delete_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	menuitem = gtk_separator_menu_item_new();
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> start */
	menuitem = gtk_menu_item_new_with_mnemonic("_Start");
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(start_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> startall */
	menuitem = gtk_menu_item_new_with_mnemonic("Start _all");
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(start_all_guests), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> stop */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_STOP, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(stop_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	menuitem = gtk_separator_menu_item_new();
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> connect */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_CONNECT, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(connect_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Guest -> disconnect */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_DISCONNECT, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(disconnect_guest), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_set_sensitive(menuitem, FALSE);
	gtk_widget_show(menuitem);

	/* Switch menu */
	menu = gtk_menu_new();
	switchMenu = gtk_menu_item_new_with_mnemonic("_Switch");
	gtk_menu_bar_append(GTK_MENU_BAR(menubar), switchMenu);
	gtk_widget_show(switchMenu);
	gtk_menu_item_set_submenu(GTK_MENU_ITEM(switchMenu), menu);

	/* Switch -> new */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_NEW, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(create_switch), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_show(menuitem);

	/* Switch -> delete */
	menuitem = gtk_image_menu_item_new_from_stock(GTK_STOCK_DELETE, NULL);
	g_signal_connect(G_OBJECT(menuitem), "activate",
					 G_CALLBACK(delete_switch), NULL);
	gtk_menu_append(GTK_MENU(menu), menuitem);
	gtk_widget_set_sensitive(menuitem, FALSE);
	gtk_widget_show(menuitem);

	/* show widgets */
	gtk_widget_show(menubar);
	gtk_widget_show(notebook);
	gtk_widget_show(vbox);
	gtk_widget_show(window);

	/* fill notebook with guests */
	enumerator = dumm->create_guest_enumerator(dumm);
	while (enumerator->enumerate(enumerator, (void**)&guest))
	{
		create_page(guest);
	}
	enumerator->destroy(enumerator);

	gtk_main();

	dumm->destroy(dumm);
	pages->destroy_function(pages, g_free);

	library_deinit();
	return 0;
}
Exemple #28
0
static void
crawl_linkmap(struct Process *proc, struct lt_r_debug_64 *dbg)
{
	debug (DEBUG_FUNCTION, "crawl_linkmap()");

	if (!dbg || !dbg->r_map) {
		debug(2, "Debug structure or it's linkmap are NULL!");
		return;
	}

	/* XXX The double cast should be removed when
	 * arch_addr_t becomes integral type.  */
	arch_addr_t addr = (arch_addr_t)(uintptr_t)dbg->r_map;

	while (addr != 0) {
		struct lt_link_map_64 rlm = {};
		if (lm_fetcher(proc)(proc, addr, &rlm) < 0) {
			debug(2, "Unable to read link map");
			return;
		}

		arch_addr_t key = addr;
		/* XXX The double cast should be removed when
		 * arch_addr_t becomes integral type.  */
		addr = (arch_addr_t)(uintptr_t)rlm.l_next;
		if (rlm.l_name == 0) {
			debug(2, "Name of mapped library is NULL");
			return;
		}

		char lib_name[BUFSIZ];
		/* XXX The double cast should be removed when
		 * arch_addr_t becomes integral type.  */
		umovebytes(proc, (arch_addr_t)(uintptr_t)rlm.l_name,
			   lib_name, sizeof(lib_name));

		/* Library name can be an empty string, in which case
		 * the entry represents either the main binary, or a
		 * VDSO.  Unfortunately we can't rely on that, as in
		 * recent glibc, that entry is initialized to VDSO
		 * SONAME.
		 *
		 * It's not clear how to detect VDSO in this case.  We
		 * can't assume that l_name of real DSOs will be
		 * either absolute or relative (for LD_LIBRARY_PATH=:
		 * it will be neither).  We can't compare l_addr with
		 * AT_SYSINFO_EHDR either, as l_addr is bias (which
		 * also means it's not unique, and therefore useless
		 * for this).  We could load VDSO from process image
		 * and at least compare actual SONAMEs.  For now, this
		 * kludge is about the best that we can do.  */
		if (*lib_name == 0
		    || strcmp(lib_name, "linux-vdso.so.1") == 0
		    || strcmp(lib_name, "linux-gate.so.1") == 0
		    || strcmp(lib_name, "linux-vdso32.so.1") == 0
		    || strcmp(lib_name, "linux-vdso64.so.1") == 0)
			continue;

		/* Do we have that library already?  */
		if (proc_each_library(proc, NULL, library_with_key_cb, &key))
			continue;

		struct library *lib = malloc(sizeof(*lib));
		if (lib == NULL) {
		fail:
			if (lib != NULL)
				library_destroy(lib);
			fprintf(stderr, "Couldn't load ELF object %s: %s\n",
				lib_name, strerror(errno));
			continue;
		}
		library_init(lib, LT_LIBTYPE_DSO);

		if (ltelf_read_library(lib, proc, lib_name, rlm.l_addr) < 0)
			goto fail;

		lib->key = key;
		proc_add_library(proc, lib);
	}
	return;
}
Exemple #29
0
int main(int argc, char *argv[])
{
	const proposal_token_t *token;
	aead_t *aead;
	crypter_t *crypter;
	char buffer[1024], assoc[8], iv[32];
	size_t bs;
	int i = 0, limit = 0;


	library_init(NULL, "crypt_burn");
	lib->plugins->load(lib->plugins, PLUGINS);
	atexit(library_deinit);

	printf("loaded: %s\n", PLUGINS);

	memset(buffer, 0x12, sizeof(buffer));
	memset(assoc, 0x34, sizeof(assoc));
	memset(iv, 0x56, sizeof(iv));

	if (argc < 2)
	{
		fprintf(stderr, "usage: %s <algorithm>!\n", argv[0]);
		return 1;
	}
	if (argc > 2)
	{
		limit = atoi(argv[2]);
	}

	token = lib->proposal->get_token(lib->proposal, argv[1]);
	if (!token)
	{
		fprintf(stderr, "algorithm '%s' unknown!\n", argv[1]);
		return 1;
	}
	if (token->type != ENCRYPTION_ALGORITHM)
	{
		fprintf(stderr, "'%s' is not an encryption/aead algorithm!\n", argv[1]);
		return 1;
	}

	if (encryption_algorithm_is_aead(token->algorithm))
	{
		aead = lib->crypto->create_aead(lib->crypto,
									token->algorithm, token->keysize / 8, 0);
		if (!aead)
		{
			fprintf(stderr, "aead '%s' not supported!\n", argv[1]);
			return 1;
		}
		while (TRUE)
		{
			if (!aead->encrypt(aead,
				chunk_create(buffer, sizeof(buffer) - aead->get_icv_size(aead)),
				chunk_from_thing(assoc),
				chunk_create(iv, aead->get_iv_size(aead)), NULL))
			{
				fprintf(stderr, "aead encryption failed!\n");
				return 1;
			}
			if (!aead->decrypt(aead, chunk_create(buffer, sizeof(buffer)),
				chunk_from_thing(assoc),
				chunk_create(iv, aead->get_iv_size(aead)), NULL))
			{
				fprintf(stderr, "aead integrity check failed!\n");
				return 1;
			}
			if (limit && ++i == limit)
			{
				break;
			}
		}
		aead->destroy(aead);
	}
	else
	{
		crypter = lib->crypto->create_crypter(lib->crypto,
										token->algorithm, token->keysize / 8);
		if (!crypter)
		{
			fprintf(stderr, "crypter '%s' not supported!\n", argv[1]);
			return 1;
		}
		bs = crypter->get_block_size(crypter);

		while (TRUE)
		{
			if (!crypter->encrypt(crypter,
					chunk_create(buffer, sizeof(buffer) / bs * bs),
					chunk_create(iv, crypter->get_iv_size(crypter)), NULL))
			{
				continue;
			}
			if (!crypter->decrypt(crypter,
					chunk_create(buffer, sizeof(buffer) / bs * bs),
					chunk_create(iv, crypter->get_iv_size(crypter)), NULL))
			{
				continue;
			}
			if (limit && ++i == limit)
			{
				break;
			}
		}
		crypter->destroy(crypter);
	}
	return 0;
}
Exemple #30
0
/**
 * @brief main of scepclient
 *
 * @param argc number of arguments
 * @param argv pointer to the argument values
 */
int main(int argc, char **argv)
{
    /* external values */
    extern char * optarg;
    extern int optind;

    /* type of input and output files */
    typedef enum {
        PKCS1      =  0x01,
        PKCS10     =  0x02,
        PKCS7      =  0x04,
        CERT_SELF  =  0x08,
        CERT       =  0x10,
        CACERT_ENC =  0x20,
        CACERT_SIG =  0x40,
    } scep_filetype_t;

    /* filetype to read from, defaults to "generate a key" */
    scep_filetype_t filetype_in = 0;

    /* filetype to write to, no default here */
    scep_filetype_t filetype_out = 0;

    /* input files */
    char *file_in_pkcs1      = DEFAULT_FILENAME_PKCS1;
    char *file_in_pkcs10     = DEFAULT_FILENAME_PKCS10;
    char *file_in_cert_self  = DEFAULT_FILENAME_CERT_SELF;
    char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
    char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;

    /* output files */
    char *file_out_pkcs1     = DEFAULT_FILENAME_PKCS1;
    char *file_out_pkcs10    = DEFAULT_FILENAME_PKCS10;
    char *file_out_pkcs7     = DEFAULT_FILENAME_PKCS7;
    char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
    char *file_out_cert      = DEFAULT_FILENAME_CERT;
    char *file_out_ca_cert   = DEFAULT_FILENAME_CACERT_ENC;

    /* by default user certificate is requested */
    bool request_ca_certificate = FALSE;

    /* by default existing files are not overwritten */
    bool force = FALSE;

    /* length of RSA key in bits */
    u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;

    /* validity of self-signed certificate */
    time_t validity  = DEFAULT_CERT_VALIDITY;
    time_t notBefore = 0;
    time_t notAfter  = 0;

    /* distinguished name for requested certificate, ASCII format */
    char *distinguishedName = NULL;

    /* challenge password */
    char challenge_password_buffer[MAX_PASSWORD_LENGTH];

    /* symmetric encryption algorithm used by pkcs7, default is DES */
    encryption_algorithm_t pkcs7_symmetric_cipher = ENCR_DES;
    size_t pkcs7_key_size = 0;

    /* digest algorithm used by pkcs7, default is MD5 */
    hash_algorithm_t pkcs7_digest_alg = HASH_MD5;

    /* signature algorithm used by pkcs10, default is MD5 */
    hash_algorithm_t pkcs10_signature_alg = HASH_MD5;

    /* URL of the SCEP-Server */
    char *scep_url = NULL;

    /* Name of CA to fetch CA certs for */
    char *ca_name = "CAIdentifier";

    /* http request method, default is GET */
    bool http_get_request = TRUE;

    /* poll interval time in manual mode in seconds */
    u_int poll_interval = DEFAULT_POLL_INTERVAL;

    /* maximum poll time */
    u_int max_poll_time = 0;

    err_t ugh = NULL;

    /* initialize library */
    if (!library_init(NULL))
    {
        library_deinit();
        exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
    }
    if (lib->integrity &&
            !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
    {
        fprintf(stderr, "integrity check of scepclient failed\n");
        library_deinit();
        exit(SS_RC_DAEMON_INTEGRITY);
    }

    /* initialize global variables */
    pkcs1             = chunk_empty;
    pkcs7             = chunk_empty;
    serialNumber      = chunk_empty;
    transID           = chunk_empty;
    fingerprint       = chunk_empty;
    encoding          = chunk_empty;
    pkcs10_encoding   = chunk_empty;
    issuerAndSubject  = chunk_empty;
    challengePassword = chunk_empty;
    getCertInitial    = chunk_empty;
    scep_response     = chunk_empty;
    subjectAltNames   = linked_list_create();
    options           = options_create();

    for (;;)
    {
        static const struct option long_opts[] = {
            /* name, has_arg, flag, val */
            { "help", no_argument, NULL, 'h' },
            { "version", no_argument, NULL, 'v' },
            { "optionsfrom", required_argument, NULL, '+' },
            { "quiet", no_argument, NULL, 'q' },
            { "debug", required_argument, NULL, 'l' },
            { "in", required_argument, NULL, 'i' },
            { "out", required_argument, NULL, 'o' },
            { "force", no_argument, NULL, 'f' },
            { "httptimeout", required_argument, NULL, 'T' },
            { "keylength", required_argument, NULL, 'k' },
            { "dn", required_argument, NULL, 'd' },
            { "days", required_argument, NULL, 'D' },
            { "startdate", required_argument, NULL, 'S' },
            { "enddate", required_argument, NULL, 'E' },
            { "subjectAltName", required_argument, NULL, 's' },
            { "password", required_argument, NULL, 'p' },
            { "algorithm", required_argument, NULL, 'a' },
            { "url", required_argument, NULL, 'u' },
            { "caname", required_argument, NULL, 'c'},
            { "method", required_argument, NULL, 'm' },
            { "interval", required_argument, NULL, 't' },
            { "maxpolltime", required_argument, NULL, 'x' },
            { 0,0,0,0 }
        };

        /* parse next option */
        int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:c:m:t:x:APRCMS", long_opts, NULL);

        switch (c)
        {
        case EOF:       /* end of flags */
            break;

        case 'h':       /* --help */
            usage(NULL);

        case 'v':       /* --version */
            version();

        case 'q':       /* --quiet */
            log_to_stderr = FALSE;
            continue;

        case 'l':		/* --debug <level> */
            default_loglevel = atoi(optarg);
            continue;

        case 'i':       /* --in <type> [= <filename>] */
        {
            char *filename = strstr(optarg, "=");

            if (filename)
            {
                /* replace '=' by '\0' */
                *filename = '\0';
                /* set pointer to start of filename */
                filename++;
            }
            if (strcaseeq("pkcs1", optarg))
            {
                filetype_in |= PKCS1;
                if (filename)
                    file_in_pkcs1 = filename;
            }
            else if (strcaseeq("pkcs10", optarg))
            {
                filetype_in |= PKCS10;
                if (filename)
                    file_in_pkcs10 = filename;
            }
            else if (strcaseeq("cacert-enc", optarg))
            {
                filetype_in |= CACERT_ENC;
                if (filename)
                    file_in_cacert_enc = filename;
            }
            else if (strcaseeq("cacert-sig", optarg))
            {
                filetype_in |= CACERT_SIG;
                if (filename)
                    file_in_cacert_sig = filename;
            }
            else if (strcaseeq("cert-self", optarg))
            {
                filetype_in |= CERT_SELF;
                if (filename)
                    file_in_cert_self = filename;
            }
            else
            {
                usage("invalid --in file type");
            }
            continue;
        }

        case 'o':       /* --out <type> [= <filename>] */
        {
            char *filename = strstr(optarg, "=");

            if (filename)
            {
                /* replace '=' by '\0' */
                *filename = '\0';
                /* set pointer to start of filename */
                filename++;
            }
            if (strcaseeq("pkcs1", optarg))
            {
                filetype_out |= PKCS1;
                if (filename)
                    file_out_pkcs1 = filename;
            }
            else if (strcaseeq("pkcs10", optarg))
            {
                filetype_out |= PKCS10;
                if (filename)
                    file_out_pkcs10 = filename;
            }
            else if (strcaseeq("pkcs7", optarg))
            {
                filetype_out |= PKCS7;
                if (filename)
                    file_out_pkcs7 = filename;
            }
            else if (strcaseeq("cert-self", optarg))
            {
                filetype_out |= CERT_SELF;
                if (filename)
                    file_out_cert_self = filename;
            }
            else if (strcaseeq("cert", optarg))
            {
                filetype_out |= CERT;
                if (filename)
                    file_out_cert = filename;
            }
            else if (strcaseeq("cacert", optarg))
            {
                request_ca_certificate = TRUE;
                if (filename)
                    file_out_ca_cert = filename;
            }
            else
            {
                usage("invalid --out file type");
            }
            continue;
        }

        case 'f':       /* --force */
            force = TRUE;
            continue;

        case 'T':       /* --httptimeout */
            http_timeout = atoi(optarg);
            if (http_timeout <= 0)
            {
                usage("invalid httptimeout specified");
            }
            continue;

        case '+':       /* --optionsfrom <filename> */
            if (!options->from(options, optarg, &argc, &argv, optind))
            {
                exit_scepclient("optionsfrom failed");
            }
            continue;

        case 'k':        /* --keylength <length> */
        {
            div_t q;

            rsa_keylength = atoi(optarg);
            if (rsa_keylength == 0)
                usage("invalid keylength");

            /* check if key length is a multiple of 8 bits */
            q = div(rsa_keylength, 2*BITS_PER_BYTE);
            if (q.rem != 0)
            {
                exit_scepclient("keylength is not a multiple of %d bits!"
                                , 2*BITS_PER_BYTE);
            }
            continue;
        }

        case 'D':       /* --days */
            if (optarg == NULL || !isdigit(optarg[0]))
            {
                usage("missing number of days");
            }
            else
            {
                char *endptr;
                long days = strtol(optarg, &endptr, 0);

                if (*endptr != '\0' || endptr == optarg
                        || days <= 0)
                    usage("<days> must be a positive number");
                validity = 24*3600*days;
            }
            continue;

        case 'S':       /* --startdate */
            if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
            {
                usage("date format must be YYMMDDHHMMSSZ");
            }
            else
            {
                chunk_t date = { optarg, 13 };
                notBefore = asn1_to_time(&date, ASN1_UTCTIME);
            }
            continue;

        case 'E':       /* --enddate */
            if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
            {
                usage("date format must be YYMMDDHHMMSSZ");
            }
            else
            {
                chunk_t date = { optarg, 13 };
                notAfter = asn1_to_time(&date, ASN1_UTCTIME);
            }
            continue;

        case 'd':       /* --dn */
            if (distinguishedName)
            {
                usage("only one distinguished name allowed");
            }
            distinguishedName = optarg;
            continue;

        case 's':       /* --subjectAltName */
        {
            char *value = strstr(optarg, "=");

            if (value)
            {
                /* replace '=' by '\0' */
                *value = '\0';
                /* set pointer to start of value */
                value++;
            }

            if (strcaseeq("email", optarg) ||
                    strcaseeq("dns", optarg) ||
                    strcaseeq("ip", optarg))
            {
                subjectAltNames->insert_last(subjectAltNames,
                                             identification_create_from_string(value));
                continue;
            }
            else
            {
                usage("invalid --subjectAltName type");
                continue;
            }
        }

        case 'p':       /* --password */
            if (challengePassword.len > 0)
            {
                usage("only one challenge password allowed");
            }
            if (strcaseeq("%prompt", optarg))
            {
                printf("Challenge password: "******"challenge password could not be read");
                }
            }
            else
            {
                challengePassword.ptr = optarg;
                challengePassword.len = strlen(optarg);
            }
            continue;

        case 'u':       /* -- url */
            if (scep_url)
            {
                usage("only one URL argument allowed");
            }
            scep_url = optarg;
            continue;

        case 'c':       /* -- caname */
            ca_name = optarg;
            continue;

        case 'm':       /* --method */
            if (strcaseeq("get", optarg))
            {
                http_get_request = TRUE;
            }
            else if (strcaseeq("post", optarg))
            {
                http_get_request = FALSE;
            }
            else
            {
                usage("invalid http request method specified");
            }
            continue;

        case 't':       /* --interval */
            poll_interval = atoi(optarg);
            if (poll_interval <= 0)
            {
                usage("invalid interval specified");
            }
            continue;

        case 'x':       /* --maxpolltime */
            max_poll_time = atoi(optarg);
            continue;

        case 'a':       /*--algorithm [<type>=]algo */
        {
            const proposal_token_t *token;
            char *type = optarg;
            char *algo = strstr(optarg, "=");

            if (algo)
            {
                *algo = '\0';
                algo++;
            }
            else
            {
                type = "enc";
                algo = optarg;
            }

            if (strcaseeq("enc", type))
            {
                token = lib->proposal->get_token(lib->proposal, algo);
                if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
                {
                    usage("invalid algorithm specified");
                }
                pkcs7_symmetric_cipher = token->algorithm;
                pkcs7_key_size = token->keysize;
                if (encryption_algorithm_to_oid(token->algorithm,
                                                token->keysize) == OID_UNKNOWN)
                {
                    usage("unsupported encryption algorithm specified");
                }
            }
            else if (strcaseeq("dgst", type) ||
                     strcaseeq("sig", type))
            {
                hash_algorithm_t hash;

                token = lib->proposal->get_token(lib->proposal, algo);
                if (token == NULL || token->type != INTEGRITY_ALGORITHM)
                {
                    usage("invalid algorithm specified");
                }
                hash = hasher_algorithm_from_integrity(token->algorithm,
                                                       NULL);
                if (hash == OID_UNKNOWN)
                {
                    usage("invalid algorithm specified");
                }
                if (strcaseeq("dgst", type))
                {
                    pkcs7_digest_alg = hash;
                }
                else
                {
                    pkcs10_signature_alg = hash;
                }
            }
            else
            {
                usage("invalid --algorithm type");
            }
            continue;
        }
        default:
            usage("unknown option");
        }
        /* break from loop */
        break;
    }

    init_log("scepclient");

    /* load plugins, further infrastructure may need it */
    if (!lib->plugins->load(lib->plugins, NULL,
                            lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
    {
        exit_scepclient("plugin loading failed");
    }
    DBG1(DBG_APP, "  loaded plugins: %s",
         lib->plugins->loaded_plugins(lib->plugins));

    if ((filetype_out == 0) && (!request_ca_certificate))
    {
        usage("--out filetype required");
    }
    if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
    {
        usage("in CA certificate request, no other --in or --out option allowed");
    }

    /* check if url is given, if cert output defined */
    if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
    {
        usage("URL of SCEP server required");
    }

    /* check for sanity of --in/--out */
    if (!filetype_in && (filetype_in > filetype_out))
    {
        usage("cannot generate --out of given --in!");
    }

    /* get CA cert */
    if (request_ca_certificate)
    {
        char ca_path[PATH_MAX];
        container_t *container;
        pkcs7_t *pkcs7;

        if (!scep_http_request(scep_url, chunk_create(ca_name, strlen(ca_name)),
                               SCEP_GET_CA_CERT, http_get_request,
                               http_timeout, &scep_response))
        {
            exit_scepclient("did not receive a valid scep response");
        }

        join_paths(ca_path, sizeof(ca_path), CA_CERT_PATH, file_out_ca_cert);

        pkcs7 = lib->creds->create(lib->creds, CRED_CONTAINER, CONTAINER_PKCS7,
                                   BUILD_BLOB_ASN1_DER, scep_response, BUILD_END);

        if (!pkcs7)
        {   /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */

            DBG1(DBG_APP, "unable to parse PKCS#7, assuming plain CA cert");
            if (!chunk_write(scep_response, ca_path, "ca cert",  0022, force))
            {
                exit_scepclient("could not write ca cert file '%s'", ca_path);
            }
        }
        else
        {
            enumerator_t *enumerator;
            certificate_t *cert;
            int ra_certs = 0, ca_certs = 0;
            int ra_index = 1, ca_index = 1;

            enumerator = pkcs7->create_cert_enumerator(pkcs7);
            while (enumerator->enumerate(enumerator, &cert))
            {
                x509_t *x509 = (x509_t*)cert;
                if (x509->get_flags(x509) & X509_CA)
                {
                    ca_certs++;
                }
                else
                {
                    ra_certs++;
                }
            }
            enumerator->destroy(enumerator);

            enumerator = pkcs7->create_cert_enumerator(pkcs7);
            while (enumerator->enumerate(enumerator, &cert))
            {
                x509_t *x509 = (x509_t*)cert;
                bool ca_cert = x509->get_flags(x509) & X509_CA;
                char cert_path[PATH_MAX], *path = ca_path;

                if (ca_cert && ca_certs > 1)
                {
                    add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                    "-%.1d", ca_index++);
                    path = cert_path;
                }
                else if (!ca_cert)
                {   /* use CA name as base for RA certs */
                    if (ra_certs > 1)
                    {
                        add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                        "-ra-%.1d", ra_index++);
                    }
                    else
                    {
                        add_path_suffix(cert_path, sizeof(cert_path), ca_path,
                                        "-ra");
                    }
                    path = cert_path;
                }

                if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
                        !chunk_write(encoding, path,
                                     ca_cert ? "ca cert" : "ra cert", 0022, force))
                {
                    exit_scepclient("could not write cert file '%s'", path);
                }
                chunk_free(&encoding);
            }
            enumerator->destroy(enumerator);
            container = &pkcs7->container;
            container->destroy(container);
        }
        exit_scepclient(NULL); /* no further output required */
    }

    creds = mem_cred_create();
    lib->credmgr->add_set(lib->credmgr, &creds->set);

    /*
     * input of PKCS#1 file
     */
    if (filetype_in & PKCS1)    /* load an RSA key pair from file */
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_in_pkcs1);

        private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
                                         BUILD_FROM_FILE, path, BUILD_END);
    }
    else                                /* generate an RSA key pair */
    {
        private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
                                         BUILD_KEY_SIZE, rsa_keylength,
                                         BUILD_END);
    }
    if (private_key == NULL)
    {
        exit_scepclient("no RSA private key available");
    }
    creds->add_key(creds, private_key->get_ref(private_key));
    public_key = private_key->get_public_key(private_key);

    /* check for minimum key length */
    if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
    {
        exit_scepclient("length of RSA key has to be at least %d bits",
                        RSA_MIN_OCTETS * BITS_PER_BYTE);
    }

    /*
     * input of PKCS#10 file
     */
    if (filetype_in & PKCS10)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_in_pkcs10);

        pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
                                        CERT_PKCS10_REQUEST, BUILD_FROM_FILE,
                                        path, BUILD_END);
        if (!pkcs10_req)
        {
            exit_scepclient("could not read certificate request '%s'", path);
        }
        subject = pkcs10_req->get_subject(pkcs10_req);
        subject = subject->clone(subject);
    }
    else
    {
        if (distinguishedName == NULL)
        {
            char buf[BUF_LEN];
            int n = sprintf(buf, DEFAULT_DN);

            /* set the common name to the hostname */
            if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
            {
                exit_scepclient("no hostname defined, use "
                                "--dn <distinguished name> option");
            }
            distinguishedName = buf;
        }

        DBG2(DBG_APP, "dn: '%s'", distinguishedName);
        subject = identification_create_from_string(distinguishedName);
        if (subject->get_type(subject) != ID_DER_ASN1_DN)
        {
            exit_scepclient("parsing of distinguished name failed");
        }

        DBG2(DBG_APP, "building pkcs10 object:");
        pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
                                        CERT_PKCS10_REQUEST,
                                        BUILD_SIGNING_KEY, private_key,
                                        BUILD_SUBJECT, subject,
                                        BUILD_SUBJECT_ALTNAMES, subjectAltNames,
                                        BUILD_CHALLENGE_PWD, challengePassword,
                                        BUILD_DIGEST_ALG, pkcs10_signature_alg,
                                        BUILD_END);
        if (!pkcs10_req)
        {
            exit_scepclient("generating pkcs10 request failed");
        }
    }
    pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
    fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
    DBG1(DBG_APP, "  fingerprint:    %s", fingerprint.ptr);

    /*
     * output of PKCS#10 file
     */
    if (filetype_out & PKCS10)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs10);

        if (!chunk_write(pkcs10_encoding, path, "pkcs10",  0022, force))
        {
            exit_scepclient("could not write pkcs10 file '%s'", path);
        }
        filetype_out &= ~PKCS10;   /* delete PKCS10 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * output of PKCS#1 file
     */
    if (filetype_out & PKCS1)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), PRIVATE_KEY_PATH, file_out_pkcs1);

        DBG2(DBG_APP, "building pkcs1 object:");
        if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
                !chunk_write(pkcs1, path, "pkcs1", 0066, force))
        {
            exit_scepclient("could not write pkcs1 file '%s'", path);
        }
        filetype_out &= ~PKCS1;   /* delete PKCS1 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    scep_generate_transaction_id(public_key, &transID, &serialNumber);
    DBG1(DBG_APP, "  transaction ID: %.*s", (int)transID.len, transID.ptr);

    /*
     * read or generate self-signed X.509 certificate
     */
    if (filetype_in & CERT_SELF)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), HOST_CERT_PATH, file_in_cert_self);

        x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_signer)
        {
            exit_scepclient("could not read certificate file '%s'", path);
        }
    }
    else
    {
        notBefore = notBefore ? notBefore : time(NULL);
        notAfter  = notAfter  ? notAfter  : (notBefore + validity);
        x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_SIGNING_KEY, private_key,
                                         BUILD_PUBLIC_KEY, public_key,
                                         BUILD_SUBJECT, subject,
                                         BUILD_NOT_BEFORE_TIME, notBefore,
                                         BUILD_NOT_AFTER_TIME, notAfter,
                                         BUILD_SERIAL, serialNumber,
                                         BUILD_SUBJECT_ALTNAMES, subjectAltNames,
                                         BUILD_END);
        if (!x509_signer)
        {
            exit_scepclient("generating certificate failed");
        }
    }
    creds->add_cert(creds, TRUE, x509_signer->get_ref(x509_signer));

    /*
     * output of self-signed X.509 certificate file
     */
    if (filetype_out & CERT_SELF)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert_self);

        if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
        {
            exit_scepclient("encoding certificate failed");
        }
        if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
        {
            exit_scepclient("could not write self-signed cert file '%s'", path);
        }
        chunk_free(&encoding);
        filetype_out &= ~CERT_SELF;   /* delete CERT_SELF flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * load ca encryption certificate
     */
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_enc);

        x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_ca_enc)
        {
            exit_scepclient("could not load encryption cacert file '%s'", path);
        }
    }

    /*
     * input of PKCS#7 file
     */
    if (filetype_in & PKCS7)
    {
        /* user wants to load a pkcs7 encrypted request
         * operation is not yet supported!
         * would require additional parsing of transaction-id

           pkcs7 = pkcs7_read_from_file(file_in_pkcs7);

         */
    }
    else
    {
        DBG2(DBG_APP, "building pkcs7 request");
        pkcs7 = scep_build_request(pkcs10_encoding,
                                   transID, SCEP_PKCSReq_MSG, x509_ca_enc,
                                   pkcs7_symmetric_cipher, pkcs7_key_size,
                                   x509_signer, pkcs7_digest_alg, private_key);
        if (!pkcs7.ptr)
        {
            exit_scepclient("failed to build pkcs7 request");
        }
    }

    /*
     * output pkcs7 encrypted and signed certificate request
     */
    if (filetype_out & PKCS7)
    {
        char path[PATH_MAX];

        join_paths(path, sizeof(path), REQ_PATH, file_out_pkcs7);

        if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
        {
            exit_scepclient("could not write pkcs7 file '%s'", path);
        }
        filetype_out &= ~PKCS7;   /* delete PKCS7 flag */
    }

    if (!filetype_out)
    {
        exit_scepclient(NULL); /* no further output required */
    }

    /*
     * output certificate fetch from SCEP server
     */
    if (filetype_out & CERT)
    {
        bool stored = FALSE;
        certificate_t *cert;
        enumerator_t  *enumerator;
        char path[PATH_MAX];
        time_t poll_start = 0;
        pkcs7_t *p7;
        container_t *container = NULL;
        chunk_t chunk;
        scep_attributes_t attrs = empty_scep_attributes;

        join_paths(path, sizeof(path), CA_CERT_PATH, file_in_cacert_sig);

        x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
                                         BUILD_FROM_FILE, path, BUILD_END);
        if (!x509_ca_sig)
        {
            exit_scepclient("could not load signature cacert file '%s'", path);
        }

        creds->add_cert(creds, TRUE, x509_ca_sig->get_ref(x509_ca_sig));

        if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
                               http_get_request, http_timeout, &scep_response))
        {
            exit_scepclient("did not receive a valid scep response");
        }
        ugh = scep_parse_response(scep_response, transID, &container, &attrs);
        if (ugh != NULL)
        {
            exit_scepclient(ugh);
        }

        /* in case of manual mode, we are going into a polling loop */
        if (attrs.pkiStatus == SCEP_PENDING)
        {
            identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);

            DBG1(DBG_APP, "  scep request pending, polling every %d seconds",
                 poll_interval);
            poll_start = time_monotonic(NULL);
            issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
                                         issuer->get_encoding(issuer),
                                         subject);
        }
        while (attrs.pkiStatus == SCEP_PENDING)
        {
            if (max_poll_time > 0 &&
                    (time_monotonic(NULL) - poll_start >= max_poll_time))
            {
                exit_scepclient("maximum poll time reached: %d seconds"
                                , max_poll_time);
            }
            DBG2(DBG_APP, "going to sleep for %d seconds", poll_interval);
            sleep(poll_interval);
            free(scep_response.ptr);
            container->destroy(container);

            DBG2(DBG_APP, "fingerprint:    %.*s",
                 (int)fingerprint.len, fingerprint.ptr);
            DBG2(DBG_APP, "transaction ID: %.*s",
                 (int)transID.len, transID.ptr);

            chunk_free(&getCertInitial);
            getCertInitial = scep_build_request(issuerAndSubject,
                                                transID, SCEP_GetCertInitial_MSG, x509_ca_enc,
                                                pkcs7_symmetric_cipher, pkcs7_key_size,
                                                x509_signer, pkcs7_digest_alg, private_key);
            if (!getCertInitial.ptr)
            {
                exit_scepclient("failed to build scep request");
            }
            if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
                                   http_get_request, http_timeout, &scep_response))
            {
                exit_scepclient("did not receive a valid scep response");
            }
            ugh = scep_parse_response(scep_response, transID, &container, &attrs);
            if (ugh != NULL)
            {
                exit_scepclient(ugh);
            }
        }

        if (attrs.pkiStatus != SCEP_SUCCESS)
        {
            container->destroy(container);
            exit_scepclient("reply status is not 'SUCCESS'");
        }

        if (!container->get_data(container, &chunk))
        {
            container->destroy(container);
            exit_scepclient("extracting signed-data failed");
        }
        container->destroy(container);

        /* decrypt enveloped-data container */
        container = lib->creds->create(lib->creds,
                                       CRED_CONTAINER, CONTAINER_PKCS7,
                                       BUILD_BLOB_ASN1_DER, chunk,
                                       BUILD_END);
        free(chunk.ptr);
        if (!container)
        {
            exit_scepclient("could not decrypt envelopedData");
        }

        if (!container->get_data(container, &chunk))
        {
            container->destroy(container);
            exit_scepclient("extracting encrypted-data failed");
        }
        container->destroy(container);

        /* parse signed-data container */
        container = lib->creds->create(lib->creds,
                                       CRED_CONTAINER, CONTAINER_PKCS7,
                                       BUILD_BLOB_ASN1_DER, chunk,
                                       BUILD_END);
        free(chunk.ptr);
        if (!container)
        {
            exit_scepclient("could not parse singed-data");
        }
        /* no need to verify the signed-data container, the signature does NOT
         * cover the contained certificates */

        /* store the end entity certificate */
        join_paths(path, sizeof(path), HOST_CERT_PATH, file_out_cert);

        p7 = (pkcs7_t*)container;
        enumerator = p7->create_cert_enumerator(p7);
        while (enumerator->enumerate(enumerator, &cert))
        {
            x509_t *x509 = (x509_t*)cert;

            if (!(x509->get_flags(x509) & X509_CA))
            {
                if (stored)
                {
                    exit_scepclient("multiple certs received, only first stored");
                }
                if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
                        !chunk_write(encoding, path, "requested cert", 0022, force))
                {
                    exit_scepclient("could not write cert file '%s'", path);
                }
                chunk_free(&encoding);
                stored = TRUE;
            }
        }
        enumerator->destroy(enumerator);
        container->destroy(container);
        chunk_free(&attrs.transID);
        chunk_free(&attrs.senderNonce);
        chunk_free(&attrs.recipientNonce);

        filetype_out &= ~CERT;   /* delete CERT flag */
    }

    exit_scepclient(NULL);
    return -1; /* should never be reached */
}