コード例 #1
0
/**
 * Initialize library
 */
static void init()
{
	plugin_feature_t features[] = {
		PLUGIN_NOOP,
			PLUGIN_PROVIDE(CUSTOM, "pt-tls-client"),
				PLUGIN_DEPENDS(CUSTOM, "tnccs-manager"),
	};
	library_init(NULL, "pt-tls-client");
	libtnccs_init();

	init_log("pt-tls-client");
	options = options_create();

	lib->plugins->add_static_features(lib->plugins, "pt-tls-client", features,
									  countof(features), TRUE, NULL, NULL);
	if (!lib->plugins->load(lib->plugins,
			lib->settings->get_str(lib->settings, "pt-tls-client.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

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

	atexit(cleanup);
}
コード例 #2
0
ファイル: tmux.c プロジェクト: abergmann/tmate-slave
void tmux_server_init(void)
{
	global_hooks = hooks_create(NULL);

	global_environ = environ_create();

	global_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_SERVER, global_options);

	global_s_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_SESSION, global_s_options);
	options_set_string(global_s_options, "default-shell", "%s", "/bin/false");

	global_w_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_WINDOW, global_w_options);

	options_set_number(global_s_options, "status-keys", MODEKEY_VI);
	options_set_number(global_w_options, "mode-keys", MODEKEY_VI);
}
コード例 #3
0
ファイル: menubar.c プロジェクト: BruceJawn/FlashNES-nesemu
void menubar_create(menubar_t *m)
{
	memset(m,0,sizeof(menubar_t));

	m->info.type = G_MENUBAR;
	m->info.x = 0;
	m->info.y = 0;
	m->info.w = 256;
	m->info.h = 14;
	m->info.draw = (drawfunc_t)menubar_draw;
	m->info.event = (eventfunc_t)menubar_event;

	//this needs to be configurable, passed thru in a struct
	menu_create(&m->menus[0],"\x1",4,recentitems);
	menu_create(&m->menus[1],"Game",m->menus[0].info.x + m->menus[0].info.w + 4,gameitems);
	menu_create(&m->menus[2],"Config",m->menus[1].info.x + m->menus[1].info.w + 4,configitems);
	menu_create(&m->menus[3],"Cheat",m->menus[2].info.x + m->menus[2].info.w + 4,miscitems);
	menu_create(&m->menus[4],"Debug",m->menus[3].info.x + m->menus[3].info.w + 4,debugitems);
	button_create(&m->buttons[0],"x",(256 - 9) - 3,3,click_quit);
	button_create(&m->buttons[1],"\x9",(256 - 33) - 1,3,click_minimize);
	button_create(&m->buttons[2],"\x8",(256 - 21) - 3,3,click_togglefullscreen);
	load_create(&m->load);
	video_create(&m->video);
	input_create(&m->input);
	gui_input_create(&m->guiinput);
	sound_create(&m->sound);
	devices_create(&m->devices);
	palette_create(&m->palette);
	options_create(&m->options);
	mappers_create(&m->mappers);
	paths_create(&m->paths);
	supported_mappers_create(&m->supported_mappers);
	rom_info_create(&m->rom_info);
	tracer_create(&m->tracer);
	memory_viewer_create(&m->memory_viewer);
	nt_create(&m->nametable_viewer);
	pt_create(&m->patterntable_viewer);
	about_create(&m->about);

	m->menus[0].click = click_recent;
	m->menus[1].click = click_game;
	m->menus[2].click = click_config;
	m->menus[3].click = click_debug;
	m->menus[4].click = click_misc;
	m->menus[0].user = m;
	m->menus[1].user = m;
	m->menus[2].user = m;
	m->menus[3].user = m;
	m->menus[4].user = m;

	//'hack' to update the 'freeze data' caption
	click_freezedata();
	click_freezedata();
}
コード例 #4
0
ファイル: main.c プロジェクト: kkalmaz/psmame
int CLIB_DECL main(int argc, char *argv[])
{
	int result = -1;
	clock_t begin_time;
	double elapsed_time;
	core_options *messtest_options = NULL;

	test_count = 0;
	failure_count = 0;
	messtest_options = NULL;

	/* register options */
	messtest_options = options_create(messtest_fail);
	options_add_entries(messtest_options, messtest_option_entries);
	options_set_option_callback(messtest_options, OPTION_GAMENAME, handle_arg);

	/* run MAME's validity checks; if these fail cop out now */
	/* NPW 16-Sep-2006 - commenting this out because this cannot be run outside of MAME */
	//if (mame_validitychecks(-1))
	//  goto done;
	/* run Imgtool's validity checks; if these fail cop out now */
	if (imgtool_validitychecks())
		goto done;

	begin_time = clock();

	/* parse the commandline */
	if (options_parse_command_line(messtest_options, argc, argv, OPTION_PRIORITY_CMDLINE,TRUE))
	{
		fprintf(stderr, "Error while parsing cmdline\n");
		goto done;
	}

	if (test_count > 0)
	{
		elapsed_time = ((double) (clock() - begin_time)) / CLOCKS_PER_SEC;

		fprintf(stderr, "Tests complete; %i test(s), %i failure(s), elapsed time %.2f\n",
			test_count, failure_count, elapsed_time);
	}
	else
	{
		fprintf(stderr, "Usage: %s [test1] [test2]...\n", argv[0]);
	}
	result = failure_count;

done:
	if (messtest_options)
		options_free(messtest_options);
	return result;
}
コード例 #5
0
ファイル: emuopts.c プロジェクト: bji/libmame
core_options *mame_options_init(const options_entry *entries)
{
	/* create MAME core options */
	core_options *opts = options_create(memory_error);

	/* set up output callbacks */
	options_set_output_callback(opts, OPTMSG_INFO, mame_puts_info);
	options_set_output_callback(opts, OPTMSG_WARNING, mame_puts_warning);
	options_set_output_callback(opts, OPTMSG_ERROR, mame_puts_error);

	options_add_entries(opts, mame_core_options);
	if (entries != NULL)
		options_add_entries(opts, entries);

	/* we need to dynamically add options when the device name is parsed */
	options_set_option_callback(opts, OPTION_GAMENAME, image_driver_name_callback);
	return opts;
}
コード例 #6
0
static options_t * init_options(char * version) {
    options_t * options;

    // Building the command line options
    if (!(options = options_create(NULL))) {
        goto ERR_OPTIONS_CREATE;
    }

    options_add_optspecs(options, runnable_options);
    options_add_optspecs(options, traceroute_get_options());
    options_add_optspecs(options, mda_get_options());
    options_add_optspecs(options, network_get_options());
    options_add_common  (options, version);
    return options;

ERR_OPTIONS_CREATE:
    return NULL;
}
コード例 #7
0
ファイル: emuopts.c プロジェクト: cdenix/ps3-mame-0125
core_options *mame_options_init(const options_entry *entries)
{
	/* create MAME core options */
	core_options *opts = options_create(memory_error);

	/* set up output callbacks */
	options_set_output_callback(opts, OPTMSG_INFO, mame_puts_info);
	options_set_output_callback(opts, OPTMSG_WARNING, mame_puts_warning);
	options_set_output_callback(opts, OPTMSG_ERROR, mame_puts_error);

	options_add_entries(opts, mame_core_options);
	if (entries != NULL)
		options_add_entries(opts, entries);

#ifdef MESS
	mess_options_init(opts);
#endif /* MESS */

	return opts;
}
コード例 #8
0
ファイル: command.c プロジェクト: LeiYuan/strongswan
/**
 * Dispatch commands.
 */
int command_dispatch(int c, char *v[])
{
	int op, i;

	options = options_create();
	atexit(cleanup);
	active = help_idx = registered;
	argc = c;
	argv = v;
	command_register((command_t){help, 'h', "help", "show usage information"});

	build_opts();
	op = getopt_long(c, v, command_optstring, command_opts, NULL);
	for (i = 0; cmds[i].cmd; i++)
	{
		if (cmds[i].op == op)
		{
			active = i;
			build_opts();
			return cmds[i].call();
		}
	}
	return command_usage(c > 1 ? "invalid operation" : NULL);
}
コード例 #9
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
	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 */
}
コード例 #10
0
ファイル: openac.c プロジェクト: LeiYuan/strongswan
/**
 * @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);
}
コード例 #11
0
ファイル: scepclient.c プロジェクト: spmadden/strongswan
/**
 * @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 */
}
コード例 #12
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);
}
コード例 #13
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_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);
	}
コード例 #14
0
ファイル: vecsum.c プロジェクト: simonzhangsm/CDH5.1.x
/*
 * vecsum is a microbenchmark which measures the speed of various ways of
 * reading from HDFS.  It creates a file containing floating-point 'doubles',
 * and computes the sum of all the doubles several times.  For some CPUs,
 * assembly optimizations are used for the summation (SSE, etc).
 */
int main(void)
{
    int ret = 1;
    struct options *opts = NULL;
    struct local_data *cdata = NULL;
    struct libhdfs_data *ldata = NULL;
    struct stopwatch *watch = NULL;

    if (check_byte_size(VECSUM_CHUNK_SIZE, "VECSUM_CHUNK_SIZE") ||
        check_byte_size(ZCR_READ_CHUNK_SIZE,
                "ZCR_READ_CHUNK_SIZE") ||
        check_byte_size(NORMAL_READ_CHUNK_SIZE,
                "NORMAL_READ_CHUNK_SIZE")) {
        goto done;
    }
    opts = options_create();
    if (!opts)
        goto done;
    if (opts->ty == VECSUM_LOCAL) {
        cdata = local_data_create(opts);
        if (!cdata)
            goto done;
    } else {
        ldata = libhdfs_data_create(opts);
        if (!ldata)
            goto done;
    }
    watch = stopwatch_create();
    if (!watch)
        goto done;
    switch (opts->ty) {
    case VECSUM_LOCAL:
        vecsum_local(cdata, opts);
        ret = 0;
        break;
    case VECSUM_LIBHDFS:
        ret = vecsum_libhdfs(ldata, opts);
        break;
    case VECSUM_ZCR:
        ret = vecsum_zcr(ldata, opts);
        break;
    }
    if (ret) {
        fprintf(stderr, "vecsum failed with error %d\n", ret);
        goto done;
    }
    ret = 0;
done:
    fprintf(stderr, "cleaning up...\n");
    if (watch && (ret == 0)) {
        long long length = vecsum_length(opts, ldata);
        if (length >= 0) {
            stopwatch_stop(watch, length * opts->passes);
        }
    }
    if (cdata)
        local_data_free(cdata);
    if (ldata)
        libhdfs_data_free(ldata);
    if (opts)
        options_free(opts);
    return ret;
}
コード例 #15
0
ファイル: tmux.c プロジェクト: wilywampa/tmux
int
main(int argc, char **argv)
{
	char					*path, *label, tmp[PATH_MAX];
	char					*shellcmd = NULL, **var;
	const char				*s, *shell;
	int					 opt, flags, keys;
	const struct options_table_entry	*oe;

	if (setlocale(LC_CTYPE, "en_US.UTF-8") == NULL) {
		if (setlocale(LC_CTYPE, "") == NULL)
			errx(1, "invalid LC_ALL, LC_CTYPE or LANG");
		s = nl_langinfo(CODESET);
		if (strcasecmp(s, "UTF-8") != 0 && strcasecmp(s, "UTF8") != 0)
			errx(1, "need UTF-8 locale (LC_CTYPE) but have %s", s);
	}

	setlocale(LC_TIME, "");
	tzset();

	if (**argv == '-')
		flags = CLIENT_LOGIN;
	else
		flags = 0;

	label = path = NULL;
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= CLIENT_256COLOURS;
			break;
		case 'c':
			free(shellcmd);
			shellcmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & CLIENT_CONTROL)
				flags |= CLIENT_CONTROLCONTROL;
			else
				flags |= CLIENT_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", getprogname(), VERSION);
			exit(0);
		case 'f':
			set_cfg_file(optarg);
			break;
		case 'l':
			flags |= CLIENT_LOGIN;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= CLIENT_UTF8;
			break;
		case 'v':
			log_add_level();
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shellcmd != NULL && argc != 0)
		usage();

	if ((ptm_fd = getptmfd()) == -1)
		err(1, "getptmfd");
	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
	    "recvfd proc exec tty ps", NULL) != 0)
		err(1, "pledge");

	/*
	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
	 * UTF-8, it is a safe assumption that either they are using a UTF-8
	 * terminal, or if not they know that output from UTF-8-capable
	 * programs may be wrong.
	 */
	if (getenv("TMUX") != NULL)
		flags |= CLIENT_UTF8;
	else {
		s = getenv("LC_ALL");
		if (s == NULL || *s == '\0')
			s = getenv("LC_CTYPE");
		if (s == NULL || *s == '\0')
			s = getenv("LANG");
		if (s == NULL || *s == '\0')
			s = "";
		if (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL)
			flags |= CLIENT_UTF8;
	}

	global_hooks = hooks_create(NULL);

	global_environ = environ_create();
	for (var = environ; *var != NULL; var++)
		environ_put(global_environ, *var);
	if (getcwd(tmp, sizeof tmp) != NULL)
		environ_set(global_environ, "PWD", "%s", tmp);

	global_options = options_create(NULL);
	global_s_options = options_create(NULL);
	global_w_options = options_create(NULL);
	for (oe = options_table; oe->name != NULL; oe++) {
		if (oe->scope == OPTIONS_TABLE_SERVER)
			options_default(global_options, oe);
		if (oe->scope == OPTIONS_TABLE_SESSION)
			options_default(global_s_options, oe);
		if (oe->scope == OPTIONS_TABLE_WINDOW)
			options_default(global_w_options, oe);
	}

	/*
	 * The default shell comes from SHELL or from the user's passwd entry
	 * if available.
	 */
	shell = getshell();
	options_set_string(global_s_options, "default-shell", 0, "%s", shell);

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(global_s_options, "status-keys", keys);
		options_set_number(global_w_options, "mode-keys", keys);
	}

	/*
	 * If socket is specified on the command-line with -S or -L, it is
	 * used. Otherwise, $TMUX is checked and if that fails "default" is
	 * used.
	 */
	if (path == NULL && label == NULL) {
		s = getenv("TMUX");
		if (s != NULL && *s != '\0' && *s != ',') {
			path = xstrdup(s);
			path[strcspn(path, ",")] = '\0';
		}
	}
	if (path == NULL && (path = make_label(label)) == NULL) {
		fprintf(stderr, "can't create socket: %s\n", strerror(errno));
		exit(1);
	}
	socket_path = path;
	free(label);

	/* Pass control to the client. */
	exit(client_main(osdep_event_init(), argc, argv, flags, shellcmd));
}
コード例 #16
0
ファイル: tmux.c プロジェクト: alexfalcucci-archive/tmate
int
main(int argc, char **argv)
{
	char		*path, *label, **var, tmp[PATH_MAX], *shellcmd = NULL;
	const char	*s;
	int		 opt, flags, keys;

#if defined(DEBUG) && defined(__OpenBSD__)
	malloc_options = (char *) "AFGJPX";
#endif

	setlocale(LC_TIME, "");
	tzset();

	if (**argv == '-')
		flags = CLIENT_LOGIN;
	else
		flags = 0;

#ifdef TMATE
	tmate_catch_sigsegv();
	flags |= CLIENT_256COLOURS | CLIENT_UTF8;
#endif

	label = path = NULL;
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= CLIENT_256COLOURS;
			break;
		case 'c':
			free(shellcmd);
			shellcmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & CLIENT_CONTROL)
				flags |= CLIENT_CONTROLCONTROL;
			else
				flags |= CLIENT_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", __progname, VERSION);
			exit(0);
		case 'f':
			set_cfg_file(optarg);
			break;
		case 'l':
			flags |= CLIENT_LOGIN;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= CLIENT_UTF8;
			break;
		case 'v':
			log_add_level();
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shellcmd != NULL && argc != 0)
		usage();

#ifdef __OpenBSD__
	if (pledge("stdio rpath wpath cpath flock fattr unix getpw sendfd "
	    "recvfd proc exec tty ps", NULL) != 0)
		err(1, "pledge");
#endif

	/*
	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
	 * UTF-8, it is a safe assumption that either they are using a UTF-8
	 * terminal, or if not they know that output from UTF-8-capable
	 * programs may be wrong.
	 */
	if (getenv("TMUX") != NULL)
		flags |= CLIENT_UTF8;
	else {
		s = getenv("LC_ALL");
		if (s == NULL || *s == '\0')
			s = getenv("LC_CTYPE");
		if (s == NULL || *s == '\0')
			s = getenv("LANG");
		if (s == NULL || *s == '\0')
			s = "";
		if (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL)
			flags |= CLIENT_UTF8;
	}

	global_hooks = hooks_create(NULL);

	global_environ = environ_create();
	for (var = environ; *var != NULL; var++)
		environ_put(global_environ, *var);
	if (getcwd(tmp, sizeof tmp) != NULL)
		environ_set(global_environ, "PWD", "%s", tmp);

	global_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_SERVER, global_options);

	global_s_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_SESSION, global_s_options);
	options_set_string(global_s_options, "default-shell", "%s", getshell());

	global_w_options = options_create(NULL);
	options_table_populate_tree(OPTIONS_TABLE_WINDOW, global_w_options);

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(global_s_options, "status-keys", keys);
		options_set_number(global_w_options, "mode-keys", keys);
	}

	/*
	 * If socket is specified on the command-line with -S or -L, it is
	 * used. Otherwise, $TMUX is checked and if that fails "default" is
	 * used.
	 */
	if (path == NULL && label == NULL) {
		s = getenv("TMUX");
		if (s != NULL && *s != '\0' && *s != ',') {
			path = xstrdup(s);
			path[strcspn (path, ",")] = '\0';
		}
	}
	if (path == NULL && (path = make_label(label)) == NULL) {
		fprintf(stderr, "can't create socket: %s\n", strerror(errno));
		exit(1);
	}
	socket_path = path;
	free(label);

	/* Pass control to the client. */
	exit(client_main(event_init(), argc, argv, flags, shellcmd));
}
コード例 #17
0
ファイル: tmux.c プロジェクト: bronzdoc/tmux
int
main(int argc, char **argv)
{
	char		*path, *label, **var, tmp[PATH_MAX];
	const char	*s;
	int		 opt, flags, keys;

#if defined(DEBUG) && defined(__OpenBSD__)
	malloc_options = (char *) "AFGJPX";
#endif

	setlocale(LC_TIME, "");
	tzset();

	if (**argv == '-')
		flags = CLIENT_LOGIN;
	else
		flags = 0;

	label = path = NULL;
	while ((opt = getopt(argc, argv, "2c:Cdf:lL:qS:uUVv")) != -1) {
		switch (opt) {
		case '2':
			flags |= CLIENT_256COLOURS;
			break;
		case 'c':
			free(shell_cmd);
			shell_cmd = xstrdup(optarg);
			break;
		case 'C':
			if (flags & CLIENT_CONTROL)
				flags |= CLIENT_CONTROLCONTROL;
			else
				flags |= CLIENT_CONTROL;
			break;
		case 'V':
			printf("%s %s\n", __progname, VERSION);
			exit(0);
		case 'f':
			set_cfg_file(optarg);
			break;
		case 'l':
			flags |= CLIENT_LOGIN;
			break;
		case 'L':
			free(label);
			label = xstrdup(optarg);
			break;
		case 'q':
			break;
		case 'S':
			free(path);
			path = xstrdup(optarg);
			break;
		case 'u':
			flags |= CLIENT_UTF8;
			break;
		case 'v':
			debug_level++;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (shell_cmd != NULL && argc != 0)
		usage();

#ifdef __OpenBSD__
	if (pledge("stdio rpath wpath cpath flock fattr unix sendfd recvfd "
	    "proc exec tty ps", NULL) != 0)
		err(1, "pledge");
#endif

	/*
	 * tmux is a UTF-8 terminal, so if TMUX is set, assume UTF-8.
	 * Otherwise, if the user has set LC_ALL, LC_CTYPE or LANG to contain
	 * UTF-8, it is a safe assumption that either they are using a UTF-8
	 * terminal, or if not they know that output from UTF-8-capable
	 * programs may be wrong.
	 */
	if (getenv("TMUX") != NULL)
		flags |= CLIENT_UTF8;
	else {
		s = getenv("LC_ALL");
		if (s == NULL || *s == '\0')
			s = getenv("LC_CTYPE");
		if (s == NULL || *s == '\0')
			s = getenv("LANG");
		if (s == NULL || *s == '\0')
			s = "";
		if (strcasestr(s, "UTF-8") != NULL ||
		    strcasestr(s, "UTF8") != NULL)
			flags |= CLIENT_UTF8;
	}

	global_environ = environ_create();
	for (var = environ; *var != NULL; var++)
		environ_put(global_environ, *var);
	if (getcwd(tmp, sizeof tmp) != NULL)
		environ_set(global_environ, "PWD", tmp);

	global_options = options_create(NULL);
	options_table_populate_tree(server_options_table, global_options);

	global_s_options = options_create(NULL);
	options_table_populate_tree(session_options_table, global_s_options);
	options_set_string(global_s_options, "default-shell", "%s", getshell());

	global_w_options = options_create(NULL);
	options_table_populate_tree(window_options_table, global_w_options);

	/* Override keys to vi if VISUAL or EDITOR are set. */
	if ((s = getenv("VISUAL")) != NULL || (s = getenv("EDITOR")) != NULL) {
		if (strrchr(s, '/') != NULL)
			s = strrchr(s, '/') + 1;
		if (strstr(s, "vi") != NULL)
			keys = MODEKEY_VI;
		else
			keys = MODEKEY_EMACS;
		options_set_number(global_s_options, "status-keys", keys);
		options_set_number(global_w_options, "mode-keys", keys);
	}

	/*
	 * Figure out the socket path. If specified on the command-line with -S
	 * or -L, use it, otherwise try $TMUX or assume -L default.
	 */
	if (path == NULL) {
		/* If no -L, use the environment. */
		if (label == NULL) {
			s = getenv("TMUX");
			if (s != NULL) {
				path = xstrdup(s);
				path[strcspn (path, ",")] = '\0';
				if (*path == '\0') {
					free(path);
					label = xstrdup("default");
				}
			} else
				label = xstrdup("default");
		}

		/* -L or default set. */
		if (label != NULL) {
			if ((path = makesocketpath(label)) == NULL) {
				fprintf(stderr, "can't create socket: %s\n",
				    strerror(errno));
				exit(1);
			}
		}
	}
	free(label);

	if (strlcpy(socket_path, path, sizeof socket_path) >=
	    sizeof socket_path) {
		fprintf(stderr, "socket path too long: %s\n", path);
		exit(1);
	}
	free(path);

	/* Pass control to the client. */
	exit(client_main(osdep_event_init(), argc, argv, flags));
}