Exemple #1
0
bool DistributedClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
	std::map<std::wstring,std::wstring> commands;

	try {


		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(_T("distributed"), alias, _T("client"));
		target_path = settings.alias().get_settings_path(_T("targets"));

		settings.alias().add_path_to_settings()
			(_T("Distributed NSCP CLIENT SECTION"), _T("Section for NSCP active/passive check module."))

			(_T("handlers"), sh::fun_values_path(boost::bind(&DistributedClient::add_command, this, _1, _2)), 
			_T("CLIENT HANDLER SECTION"), _T(""))

			(_T("targets"), sh::fun_values_path(boost::bind(&DistributedClient::add_target, this, _1, _2)), 
			_T("REMOTE TARGET DEFINITIONS"), _T(""))

			;

		settings.alias().add_key_to_settings()
			(_T("channel"), sh::wstring_key(&channel_, _T("DNSCP")),
			_T("CHANNEL"), _T("The channel to listen to."))

			;

		settings.register_all();
		settings.notify();

		targets.add_missing(get_settings_proxy(), target_path, _T("default"), _T(""), true);


		get_core()->registerSubmissionListener(get_id(), channel_);
		register_command(_T("dnscp_query"), _T("Submit a query to a remote host via NSCP"));
		register_command(_T("dnscp_forward"), _T("Forward query to remote NSCP host"));
		register_command(_T("dnscp_submit"), _T("Submit a query to a remote host via NSCP"));
		register_command(_T("dnscp_exec"), _T("Execute remote command on a remote host via NSCP"));
		register_command(_T("dnscp_help"), _T("Help on using NSCP Client"));

	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_STD(_T("NSClient API exception: ") + utf8::to_unicode(e.what()));
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what()));
		return false;
	} catch (...) {
		NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
		return false;
	}
	return true;
}
Exemple #2
0
bool CheckWMI::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	sh::settings_registry settings(get_settings_proxy());
	//settings.set_alias(_T("targets"));

	settings.add_path_to_settings()
		("targets", sh::fun_values_path(boost::bind(&target_helper::add_target, &targets, get_settings_proxy(), _1, _2)),
			"TARGET LIST SECTION", "A list of available remote target systems",
			"TARGET DEFENTION", "For more configuration options add a dedicated section")
		;

	settings.register_all();
	settings.notify();
	return true;
}
Exemple #3
0
bool NSCPClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode ) {
	std::map<std::wstring,std::wstring> commands;

	try {

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("nscp", alias, "client");
		target_path = settings.alias().get_settings_path("targets");

		settings.alias().add_path_to_settings()
			("NSCP CLIENT SECTION", "Section for NSCP active/passive check module.")

			("handlers", sh::fun_values_path(boost::bind(&NSCPClient::add_command, this, _1, _2)), 
			"CLIENT HANDLER SECTION", "",
			"CLIENT HANDLER", "For more configuration options add a dedicated section")

			("targets", sh::fun_values_path(boost::bind(&NSCPClient::add_target, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"TARGET", "For more configuration options add a dedicated section")
			;

		settings.alias().add_key_to_settings()
			("channel", sh::string_key(&channel_, "NSCP"),
			"CHANNEL", "The channel to listen to.")

			;

		settings.register_all();
		settings.notify();

		targets.add_samples(get_settings_proxy(), target_path);
		targets.add_missing(get_settings_proxy(), target_path, "default", "", true);
		nscapi::core_helper::core_proxy core(get_core(), get_id());
		core.register_channel(channel_);
	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("load");
		return false;
	}
	return true;
}
Exemple #4
0
void SyslogClient::add_target(std::wstring key, std::wstring arg) {
	try {
		targets.add(get_settings_proxy(), target_path , key, arg);
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key + _T(", ") + utf8::to_unicode(e.what()));
	} catch (...) {
		NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key);
	}
}
Exemple #5
0
bool CheckNSCP::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	start_ = boost::posix_time::microsec_clock::local_time();

	std::string path;
	sh::settings_registry settings(get_settings_proxy());
	crashFolder = get_core()->expand_path(CRASH_ARCHIVE_FOLDER);
	NSC_DEBUG_MSG_STD("Crash folder is: " + crashFolder.string());
	return true;
}
Exemple #6
0
void SyslogClient::add_target(std::string key, std::string arg) {
	try {
		client_.add_target(get_settings_proxy(), key, arg);
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("Failed to add target: " + key, e);
	} catch (...) {
		NSC_LOG_ERROR_EX("Failed to add target: " + key);
	}
}
void CheckMKClient::add_target(std::string key, std::string arg) {
	try {
		targets.add(get_settings_proxy(), target_path , key, arg);
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("Failed to add target: " + key, e);
	} catch (...) {
		NSC_LOG_ERROR_EX("Failed to add target: " + key);
	}
}
Exemple #8
0
void CheckExternalScripts::add_alias(std::string key, std::string arg) {
	try {
		aliases_.add(get_settings_proxy(), key, arg);
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("Failed to add: " + key, e);
	} catch (...) {
		NSC_LOG_ERROR_EX("Failed to add: " + key);
	}
}
Exemple #9
0
void Scheduler::add_schedule(std::string key, std::string arg) {
	try {
		schedules_.add(get_settings_proxy(), key, arg, key == "default");
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("Failed to add target: " + key, e);
	} catch (...) {
		NSC_LOG_ERROR_EX("Failed to add target: " + key);
	}
}
Exemple #10
0
bool SMTPClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	std::wstring template_string, sender, recipient;
	try {
		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("SMTP", alias, "client");
		client_.set_path(settings.alias().get_settings_path("targets"));

		settings.alias().add_path_to_settings()
			("SMTP CLIENT SECTION", "Section for SMTP passive check module.")
			("handlers", sh::fun_values_path(boost::bind(&SMTPClient::add_command, this, _1, _2)),
				"CLIENT HANDLER SECTION", "",
				"CLIENT HANDLER", "For more configuration options add a dedicated section")

			("targets", sh::fun_values_path(boost::bind(&SMTPClient::add_target, this, _1, _2)),
				"REMOTE TARGET DEFINITIONS", "",
				"TARGET", "For more configuration options add a dedicated section")
			;

		settings.alias().add_key_to_settings()
			("channel", sh::string_key(&channel_, "SMTP"),
				"CHANNEL", "The channel to listen to.")

			;

		settings.register_all();
		settings.notify();

		client_.finalize(get_settings_proxy());

		nscapi::core_helper core(get_core(), get_id());
		core.register_channel(channel_);
	} catch (const nsclient::nsclient_exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("NSClient API exception: ", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("NSClient API exception: ");
		return false;
	}
	return true;
}
Exemple #11
0
bool LUAScript::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
	//std::wstring appRoot = file_helpers::folders::get_local_appdata_folder(SZAPPNAME);
	try {

		root_ = get_core()->getBasePath();

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(alias, _T("lua"));

		settings.alias().add_path_to_settings()
			(_T("LUA SCRIPT SECTION"), _T("Section for the LUAScripts module."))

			(_T("scripts"), sh::fun_values_path(boost::bind(&LUAScript::loadScript, this, _1, _2)), 
			_T("LUA SCRIPTS SECTION"), _T("A list of scripts available to run from the LuaSCript module."))
			;

		settings.register_all();
		settings.notify();

// 		if (!scriptDirectory_.empty()) {
// 			addAllScriptsFrom(scriptDirectory_);
// 		}




		BOOST_FOREACH(script_container &script, scripts_) {
			try {
				instances_.push_back(script_wrapper::lua_script::create_instance(get_core(), get_id(), registry, script.alias, script.script.string()));
			} catch (const lua_wrappers::LUAException &e) {
				NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + e.getMessage());
			} catch (const std::exception &e) {
				NSC_LOG_ERROR_STD(_T("Could not load script ") + script.to_wstring() + _T(": ") + utf8::to_unicode(e.what()));
			}
		}

		// 	} catch (nrpe::server::nrpe_exception &e) {
		// 		NSC_LOG_ERROR_STD(_T("Exception caught: ") + e.what());
		// 		return false;
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what()));
		return false;
	} catch (...) {
		NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
		return false;
	}

// 	std::list<std::wstring>::const_iterator it;
// 	for (it = commands.begin(); it != commands.end(); ++it) {
// 		loadScript((*it));
// 	}
	return true;
}
Exemple #12
0
/**
 * New version of the load call.
 * Start the background collector thread and let it run until unloadModule() is called.
 * @return true
 */
bool CheckSystem::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("system", alias, "unix");
	std::string counter_path = settings.alias().get_settings_path("counters");

//	collector.filters_path_ = settings.alias().get_settings_path("real-time/checks");

	//filters::filter_config_handler::add_samples(get_settings_proxy(), collector.filters_path_);
	
	return true;
}
Exemple #13
0
bool NRPEClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {

	try {

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("NRPE", alias, "client");
		target_path = settings.alias().get_settings_path("targets");

		settings.alias().add_path_to_settings()
			("NRPE CLIENT SECTION", "Section for NRPE active/passive check module.")

			("handlers", sh::fun_values_path(boost::bind(&NRPEClient::add_command, this, _1, _2)), 
			"CLIENT HANDLER SECTION", "")

			("targets", sh::fun_values_path(boost::bind(&NRPEClient::add_target, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "")
			;

		settings.alias().add_key_to_settings()
			("channel", sh::string_key(&channel_, "NRPE"),
			"CHANNEL", "The channel to listen to.")

			;

		settings.register_all();
		settings.notify();

		nscapi::core_helper::core_proxy core(get_core(), get_id());
		targets.add_samples(get_settings_proxy(), target_path);
		targets.ensure_default(get_settings_proxy(), target_path);
		core.register_channel(channel_);
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("loading", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("loading");
		return false;
	}
	return true;
}
Exemple #14
0
bool NSCPServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("nscp", alias, "server");

	settings.alias().add_path_to_settings()
		("NSCP SERVER SECTION", "Section for NSCP (NSCPListener.dll) (check_nscp) protocol options.")
		;

	settings.alias().add_key_to_settings()
		("port", sh::string_key(&info_.port_, "5668"),
		"PORT NUMBER", "Port to use for NSCP.")

		("allow arguments", sh::bool_fun_key<bool>(boost::bind(&handler_impl::set_allow_arguments, handler_, _1), false),
		"COMMAND ARGUMENT PROCESSING", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.")

		;

	socket_helpers::settings_helper::add_core_server_opts(settings, info_);
	socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, true);

	settings.register_all();
	settings.notify();


#ifndef USE_SSL
	if (info_.use_ssl) {
		NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)"));
		return false;
	}
#endif

	boost::asio::io_service io_service_;

	if (mode == NSCAPI::normalStart) {

		NSC_LOG_ERROR_LISTS(info_.validate());

		std::list<std::string> errors;
		info_.allowed_hosts.refresh(errors);
		NSC_LOG_ERROR_LISTS(errors);
		NSC_DEBUG_MSG_STD("Allowed hosts definition: " + info_.allowed_hosts.to_string());

		server_.reset(new nscp::server::server(info_, handler_));
		if (!server_) {
			NSC_LOG_ERROR_STD("Failed to create server instance!");
			return false;
		}
		server_->start();
	}
	return true;
}
Exemple #15
0
void CheckExternalScripts::add_command(std::string key, std::string arg) {
	try {
		commands_.add(get_settings_proxy(), commands_path, key, arg, key == "default");
		if (arg.find("$ARG") != std::string::npos) {
			if (!allowArgs_) {
				NSC_DEBUG_MSG_STD("Detected a $ARG??$ expression with allowed arguments flag set to false (perhaps this is not the intent)");
			}
		}
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("Failed to add: " + key, e);
	} catch (...) {
		NSC_LOG_ERROR_EX("Failed to add: " + key);
	}
}
Exemple #16
0
bool CheckLogFile::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	thread_.reset(new real_time_thread);

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias(alias, "logfile");

	thread_->filters_path_ = settings.alias().get_settings_path("real-time/checks");

	settings.alias().add_path_to_settings()
		("LOG FILE SECTION", "Section for log file checker")

		("real-time", "CONFIGURE REALTIME CHECKING", "A set of options to configure the real time checks")

		("real-time/checks", sh::fun_values_path(boost::bind(&real_time_thread::add_realtime_filter, thread_, get_settings_proxy(), _1, _2)),  
		"REALTIME FILTERS", "A set of filters to use in real-time mode",
		"REALTIME FILTER DEFENTION", "For more configuration options add a dedicated section"
		)
		;

	settings.alias().add_key_to_settings("real-time")

		("enabled", sh::bool_fun_key<bool>(boost::bind(&real_time_thread::set_enabled, thread_, _1), false),
		"REAL TIME CHECKING", "Spawns a background thread which waits for file changes.")

		;

	settings.register_all();
	settings.notify();

	filters::filter_config_handler::add_samples(get_settings_proxy(), thread_->filters_path_);

	if (mode == NSCAPI::normalStart) {
		if (!thread_->start())
			NSC_LOG_ERROR_STD("Failed to start collection thread");
	}
	return true;
}
Exemple #17
0
bool DistributedServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	std::wstring host, suffix, server_mode;
	unsigned int thread_count;
	try {
		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(_T("distributed"), alias, _T("server"));

		settings.alias().add_path_to_settings()
			(_T("DISTRIBUTED NSCP SERVER SECTION"), _T("Section for Distributed NSCP (DistributedServer) (check_nscp) protocol options."))
			;

		settings.alias().add_key_to_settings()
			(_T("host"), sh::wstring_key(&host, _T("tcp://*:5555")),
			_T("HOST TO BIND/CONNECT TO"), _T("The host to bind/connect to"))

			(_T("suffix"), sh::wstring_key(&suffix, _T("ncsp.dist")),
			_T("SUFFIX FOR INTERNAL CHANNELS"), _T("Has to be uniq on each server"))

			(_T("worker pool size"), sh::uint_key(&thread_count, 10),
			_T("WORKER POOL SIZE"), _T("Number of threads to spawn for the worker pool"))

			(_T("mode"), sh::wstring_key(&server_mode, _T("master")),
			_T("OPERATION MODE"), _T("Mode of operation can only be master now but will add more later on (such as slave)"))
			;

		settings.register_all();
		settings.notify();

		if (mode == NSCAPI::normalStart) {
			context = new zmq::context_t(2);

			zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix));
			zeromq_queue::queue_manager queue;
			queue.start(context, threads, queue_info);

			zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count);
			zeromq_worker::worker_manager workers;
			workers.start(context, threads, worker_info);
		}

	} catch (std::exception &e) {
		NSC_LOG_ERROR_STD(_T("Exception caught: ") + to_wstring(e.what()));
		return false;
	} catch (...) {
		NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
		return false;
	}
	return true;
}
bool NSClientServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("NSClient", alias, "server");

	settings.alias().add_path_to_settings()
		("NSCLIENT SERVER SECTION", "Section for NSClient (NSClientServer.dll) (check_nt) protocol options.")
		;

	settings.alias().add_key_to_settings()

		("performance data", sh::bool_fun_key<bool>(boost::bind(&NSClientServer::set_perf_data, this, _1), true),
		"PERFORMANCE DATA", "Send performance data back to Nagios (set this to 0 to remove all performance data).")

		;

	socket_helpers::settings_helper::add_port_server_opts(settings, info_, "12489");
	socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, false);
	socket_helpers::settings_helper::add_core_server_opts(settings, info_);

	settings.alias().add_parent("/settings/default").add_key_to_settings()

		("password", sh::string_fun_key<std::string>(boost::bind(&NSClientServer::set_password, this, _1), ""),
		"PASSWORD", "Password used to authenticate against server")

		;

	settings.register_all();
	settings.notify();

#ifndef USE_SSL
	if (info_.use_ssl) {
		NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)"));
	}
#endif
	NSC_LOG_ERROR_LISTS(info_.validate());

	std::list<std::string> errors;
	info_.allowed_hosts.refresh(errors);
	BOOST_FOREACH(const std::string &e, errors) {
		NSC_LOG_ERROR_STD(e);
	}
Exemple #19
0
bool LUAScript::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	try {

		root_ = get_base_path();
		nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
		lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
		scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(alias, "lua");

		settings.alias().add_path_to_settings()
			("LUA SCRIPT SECTION", "Section for the LUAScripts module.")

			("scripts", sh::fun_values_path(boost::bind(&LUAScript::loadScript, this, _1, _2)), 
			"LUA SCRIPTS SECTION", "A list of scripts available to run from the LuaSCript module.",
			"SCRIPT DEFENTION", "For more configuration options add a dedicated section")
			;

		settings.register_all();
		settings.notify();

// 		if (!scriptDirectory_.empty()) {
// 			addAllScriptsFrom(scriptDirectory_);
// 		}

		scripts_->load_all();
	} catch (const std::exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("load");
		return false;
	}

	return true;
}
bool CheckMKClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	std::map<std::wstring,std::wstring> commands;

	try {
		root_ = get_base_path();
		nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
		lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
		lua_runtime_->register_plugin(boost::shared_ptr<check_mk::check_mk_plugin>(new check_mk::check_mk_plugin()));
		scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));


		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("check_mk", alias, "client");
		target_path = settings.alias().get_settings_path("targets");

		settings.alias().add_path_to_settings()
			("CHECK MK CLIENT SECTION", "Section for NSCP active/passive check module.")

			("handlers", sh::fun_values_path(boost::bind(&CheckMKClient::add_command, this, _1, _2)), 
			"CLIENT HANDLER SECTION", "",
			"CLIENT", "For more configuration options add a dedicated section")

			("targets", sh::fun_values_path(boost::bind(&CheckMKClient::add_target, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"TARGET", "For more configuration options add a dedicated section")

			("scripts", sh::fun_values_path(boost::bind(&CheckMKClient::add_script, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"SCRIPT", "For more configuration options add a dedicated section")
			;

		settings.alias().add_key_to_settings()
			("channel", sh::string_key(&channel_, "CheckMK"),
			"CHANNEL", "The channel to listen to.")

			;


		settings.register_all();
		settings.notify();

		targets.add_samples(get_settings_proxy(), target_path);
		targets.add_missing(get_settings_proxy(), target_path, "default", "", true);

		if (scripts_->empty()) {
			add_script("default", "default_check_mk.lua");
		}

		nscapi::core_helper core(get_core(), get_id());
		core.register_channel(channel_);

		scripts_->load_all();

	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_EXR("Load", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("Load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("Load");
		return false;
	}
	return true;
}
Exemple #21
0
bool CheckExternalScripts::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	try {
		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(alias, "external scripts");

		aliases_.set_path(settings.alias().get_settings_path("alias"));
		std::string wrappings_path = settings.alias().get_settings_path("wrappings");
		boost::filesystem::path scriptRoot;
		std::string scriptDirectory;
		std::map<std::string, std::string> wrappings;

		settings.alias().add_path_to_settings()

			("wrappings", sh::string_map_path(&wrappings)
				, "Script wrappings", "A list of templates for defining script commands.\nEnter any command line here and they will be expanded by scripts placed under the wrapped scripts section. %SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.",
				"WRAPPING", "An external script wrapping")

			("alias", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)),
				"Command aliases", "A list of aliases for already defined commands (with arguments).\n"
				"An alias is an internal command that has been predefined to provide a single command without arguments. Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)",
				"ALIAS", "Query alias")

			;

		settings.register_all();
		settings.notify();
		settings.clear();

		if (wrappings.find("ps1") == wrappings.end()) {
			wrappings["ps1"] = "cmd /c echo If (-Not (Test-Path \"scripts\\%SCRIPT%\") ) { Write-Host \"UNKNOWN: Script `\"%SCRIPT%`\" not found.\"; exit(3) }; scripts\\%SCRIPT% $ARGS$; exit($lastexitcode) | powershell.exe /noprofile -command -";
			settings.register_key(wrappings_path, "ps1", NSCAPI::key_string, "POWERSHELL WRAPPING", "Command line used for executing wrapped ps1 (powershell) scripts", "cmd /c echo If (-Not (Test-Path \"scripts\\%SCRIPT%\") ) { Write-Host \"UNKNOWN: Script `\"%SCRIPT%`\" not found.\"; exit(3) }; scripts\\%SCRIPT% $ARGS$; exit($lastexitcode) | powershell.exe /noprofile -command -", false);
			settings.set_static_key(wrappings_path, "ps1", wrappings["ps1"]);
		}
		if (wrappings.find("vbs") == wrappings.end()) {
			wrappings["vbs"] = "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%";
			settings.register_key(wrappings_path, "vbs", NSCAPI::key_string, "Visual basic script", "Command line used for wrapped vbs scripts", "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%", false);
			settings.set_static_key(wrappings_path, "vbs", wrappings["vbs"]);
		}
		if (wrappings.find("bat") == wrappings.end()) {
			wrappings["bat"] = "scripts\\\\%SCRIPT% %ARGS%";
			settings.register_key(wrappings_path, "bat", NSCAPI::key_string, "Batch file", "Command used for executing wrapped batch files", "scripts\\\\%SCRIPT% %ARGS%", false);
			settings.set_static_key(wrappings_path, "bat", wrappings["bat"]);
		}

		if (aliases_.empty()) {
			NSC_DEBUG_MSG("No aliases found (adding default)");

			add_alias("alias_cpu", "check_cpu");
			add_alias("alias_cpu_ex", "check_cpu \"warn=load > $ARG1$\" \"crit=load > $ARG2$\" time=5m time=1m time=30s");
			add_alias("alias_mem", "check_memory");
			add_alias("alias_up", "check_uptime");
			add_alias("alias_disk", "check_drivesize");
			add_alias("alias_disk_loose", "check_drivesize");
			add_alias("alias_volumes", "check_drivesize");
			add_alias("alias_volumes_loose", "check_drivesize");
			add_alias("alias_service", "check_service");
			add_alias("alias_service_ex", "check_service \"exclude=Net Driver HPZ12\" \"exclude=Pml Driver HPZ12\" exclude=stisvc");
			add_alias("alias_process", "check_process \"process=$ARG1$\" \"crit=state != 'started'\"");
			add_alias("alias_process_stopped", "check_process \"process=$ARG1$\" \"crit=state != 'stopped'\"");
			add_alias("alias_process_count", "check_process \"process=$ARG1$\" \"warn=count > $ARG2$\" \"crit=count > $ARG3$\"");
			add_alias("alias_process_hung", "check_process \"filter=is_hung\" \"crit=count>0\"");
			add_alias("alias_event_log", "check_eventlog");
			add_alias("alias_file_size", "check_files \"path=$ARG1$\" \"crit=size > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${size}\" max-dir-depth=10");
			add_alias("alias_file_age", "check_files \"path=$ARG1$\" \"crit=written > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${written}\" max-dir-depth=10");
			add_alias("alias_sched_all", "check_tasksched show-all \"syntax=${title}: ${exit_code}\" \"crit=exit_code ne 0\"");
			add_alias("alias_sched_long", "check_tasksched \"filter=status = 'running'\" \"detail-syntax=${title} (${most_recent_run_time})\" \"crit=most_recent_run_time < -$ARG1$\"");
			add_alias("alias_sched_task", "check_tasksched show-all \"filter=title eq '$ARG1$'\" \"detail-syntax=${title} (${exit_code})\" \"crit=exit_code ne 0\"");
			//			add_alias("alias_updates", "check_updates -warning 0 -critical 0");
		}

		settings.alias().add_key_to_settings()
			("timeout", sh::uint_key(&timeout, 60),
				"Command timeout", "The maximum time in seconds that a command can execute. (if more then this execution will be aborted). NOTICE this only affects external commands not internal ones.")

			("allow arguments", sh::bool_key(&allowArgs_, false),
				"Allow arguments when executing external scripts", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.")

			("allow nasty characters", sh::bool_key(&allowNasty_, false),
				"Allow certain potentially dangerous characters in arguments", "This option determines whether or not the we will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.")

			("script path", sh::string_key(&scriptDirectory),
			"Load all scripts in a given folder", "Load all scripts in a given directory and use them as commands.")

			("script root", sh::path_key(&scriptRoot, "${scripts}"),
			"Script root folder", "Root path where all scripts are contained (You can not upload/download scripts outside this folder).")
			;

		settings.register_all();
		settings.notify();
		settings.clear();
		provider_.reset(new script_provider(get_id(), get_core(), settings.alias().get_settings_path("scripts"), scriptRoot, wrappings));


		settings.alias().add_path_to_settings()

			("External script settings", "General settings for the external scripts module (CheckExternalScripts).")

			("scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_command, this, _1, _2)),
			"External scripts", "A list of scripts available to run from the CheckExternalScripts module. Syntax is: `command=script arguments`",
			"SCRIPT", "For more configuration options add a dedicated section (if you add a new section you can customize the user and various other advanced features)")

			("wrapped scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)),
			"Wrapped scripts", "A list of wrapped scripts (ie. script using a template mechanism).\nThe template used will be defined by the extension of the script. Thus a foo.ps1 will use the ps1 wrapping from the wrappings section.",
			"WRAPPED SCRIPT", "A wrapped script definitions")

			;


		settings.alias().add_templates()
			("scripts", "plus", "Add a simple script",
				"Add binding for a simple script",
				"{"
				"\"fields\": [ "
				" { \"id\": \"alias\",		\"title\" : \"Alias\",		\"type\" : \"input\",		\"desc\" : \"This will identify the command\"} , "
				" { \"id\": \"script\",		\"title\" : \"Script\",		\"type\" : \"data-choice\",	\"desc\" : \"The name of the script\",\"exec\" : \"CheckExternalScripts list --json\" } , "
				" { \"id\": \"args\",		\"title\" : \"Arguments\",	\"type\" : \"input\",		\"desc\" : \"Command line arguments for the script use $ARG1$ to specify arguments\" } , "
				" { \"id\": \"cmd\",		\"key\" : \"command\", \"title\" : \"A\",	\"type\" : \"hidden\",		\"desc\" : \"A\" } "
				" ], "
				"\"events\": { "
				"\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('script').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\""
				"}"
				"}")
			("alias", "plus", "Add an alias",
				"Add binding for an alias",
				"{"
				"\"fields\": [ "
				" { \"id\": \"alias\",		\"title\" : \"Alias\",		\"type\" : \"input\",		\"desc\" : \"This will identify the command\"} , "
				" { \"id\": \"command\",	\"title\" : \"Command\",	\"type\" : \"data-choice\",	\"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , "
				" { \"id\": \"args\",		\"title\" : \"Arguments\",	\"type\" : \"input\",		\"desc\" : \"Command line arguments for the command. use $ARG1$ to specify arguments\" } , "
				" { \"id\": \"cmd\",		\"key\" : \"command\", \"title\" : \"A\",	\"type\" : \"hidden\",		\"desc\" : \"A\" } "
				" ], "
				"\"events\": { "
				"\"onSave\": \"(function (node) { node.save_path = self.path; \nvar f = node.get_field('cmd'); \nf.key = node.get_field('alias').value(); \nvar val = node.get_field('command').value(); \nif (node.get_field('args').value()) { \nval += ' ' + node.get_field('args').value(); }; \nf.value(val)})\""
				"}"
				"}")
			;

		settings.register_all();
		settings.notify();

		if (!scriptDirectory.empty()) {
			addAllScriptsFrom(scriptDirectory);
		}

		aliases_.add_samples(get_settings_proxy());
		aliases_.add_missing(get_settings_proxy(), "default", "");

		root_ = get_base_path();

		nscapi::core_helper core(get_core(), get_id());
		BOOST_FOREACH(const boost::shared_ptr<alias::command_object> &o, aliases_.get_object_list()) {
			core.register_alias(o->get_alias(), "Alias for: " + o->command);
		}
	} catch (...) {
		NSC_LOG_ERROR_EX("loading");
		return false;
	}
	return true;
}
Exemple #22
0
bool SyslogClient::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {



	try {
		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias("syslog", alias, "client");
		target_path = settings.alias().get_settings_path("targets");

		settings.alias().add_path_to_settings()
			("SYSLOG CLIENT SECTION", "Section for SYSLOG passive check module.")
			("handlers", sh::fun_values_path(boost::bind(&SyslogClient::add_command, this, _1, _2)), 
			"CLIENT HANDLER SECTION", "",
			"CLIENT", "For more configuration options add a dedicated section")

			("targets", sh::fun_values_path(boost::bind(&SyslogClient::add_target, this, _1, _2)), 
			"REMOTE TARGET DEFINITIONS", "",
			"TARGET", "For more configuration options add a dedicated section")
			;

		settings.alias().add_key_to_settings()
			("hostname", sh::string_key(&hostname_, "auto"),
			"HOSTNAME", "The host name of the monitored computer.\nSet this to auto (default) to use the windows name of the computer.\n\n"
			"auto\tHostname\n"
			"${host}\tHostname\n"
			"${host_lc}\nHostname in lowercase\n"
			"${host_uc}\tHostname in uppercase\n"
			"${domain}\tDomainname\n"
			"${domain_lc}\tDomainname in lowercase\n"
			"${domain_uc}\tDomainname in uppercase\n"
			)

			("channel", sh::string_key(&channel_, "syslog"),
			"CHANNEL", "The channel to listen to.")
			;

		settings.register_all();
		settings.notify();

		client_.finalize(get_settings_proxy());

		nscapi::core_helper core(get_core(), get_id());
		core.register_channel(channel_);

		if (hostname_ == "auto") {
			hostname_ = boost::asio::ip::host_name();
		} else if (hostname_ == "auto-lc") {
			hostname_ = boost::asio::ip::host_name();
			std::transform(hostname_.begin(), hostname_.end(), hostname_.begin(), ::tolower);
		} else if (hostname_ == "auto-uc") {
			hostname_ = boost::asio::ip::host_name();
			std::transform(hostname_.begin(), hostname_.end(), hostname_.begin(), ::toupper);
		} else {
			strEx::s::token dn = strEx::s::getToken(boost::asio::ip::host_name(), '.');

			try {
				boost::asio::io_service svc;
				boost::asio::ip::tcp::resolver resolver (svc);
				boost::asio::ip::tcp::resolver::query query (boost::asio::ip::host_name(), "");
				boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve (query), end;

				std::string s;
				while (iter != end) {
					s += iter->host_name();
					s += " - ";
					s += iter->endpoint().address().to_string();
					iter++;
				}
			} catch (const std::exception& e) {
				NSC_LOG_ERROR_EXR("Failed to resolve: ", e);
			}


			strEx::replace(hostname_, "${host}", dn.first);
			strEx::replace(hostname_, "${domain}", dn.second);
			std::transform(dn.first.begin(), dn.first.end(), dn.first.begin(), ::toupper);
			std::transform(dn.second.begin(), dn.second.end(), dn.second.begin(), ::toupper);
			strEx::replace(hostname_, "${host_uc}", dn.first);
			strEx::replace(hostname_, "${domain_uc}", dn.second);
			std::transform(dn.first.begin(), dn.first.end(), dn.first.begin(), ::tolower);
			std::transform(dn.second.begin(), dn.second.end(), dn.second.begin(), ::tolower);
			strEx::replace(hostname_, "${host_lc}", dn.first);
			strEx::replace(hostname_, "${domain_lc}", dn.second);
		}


	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_EXR("NSClient API exception: ", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("NSClient API exception: ", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("NSClient API exception: ");
		return false;
	}
	return true;
}
Exemple #23
0
bool SimpleFileWriter::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	std::string primary_key;
	std::string channel;
	try {
		sh::settings_registry settings(get_settings_proxy());
		
		settings.set_alias(alias, "writers/file");
		
		settings.alias().add_path_to_settings()
			("FILE WRITER", "Section for simple file writer module (SimpleFileWriter.dll).")

			;

		settings.alias().add_key_to_settings()
			("syntax", sh::string_key(&primary_key, "${alias-or-command} ${result} ${message}"),
			"MESSAGE SYNTAX", "The syntax of the message to write to the line.\nCan be any arbitrary string as well as include any of the following special keywords:"
			"${command} = The command name, ${host} the host, ${channel} the recieving channel, ${alias} the alias for the command, ${alias-or-command} = alias if set otherweise command, ${message} = the message data (no escape), ${result} = The result status (number).")

			("file", sh::path_key(&filename_, "output.txt"),
			"FILE TO WRITE TO", "The filename to write output to.")

			("channel", sh::string_key(&channel, "FILE"),
			"CHANNEL", "The channel to listen to.")

			;

		settings.register_all();
		settings.notify();

		nscapi::core_helper::core_proxy core(get_core(), get_id());
		core.register_channel(channel);

		parsers::simple_expression parser;
		parsers::simple_expression::result_type result;
		if (!parser.parse(primary_key, result)) {
			NSC_LOG_ERROR_STD("Failed to parse primary key: " + primary_key)
		}
		BOOST_FOREACH(parsers::simple_expression::entry &e, result) {
			if (!e.is_variable) {
				index_lookup_.push_back(simple_string_functor(e.name));
			} else if (e.name == "command") {
				index_lookup_.push_back(payload_command_functor());
			} else if (e.name == "host") {
				index_lookup_.push_back(header_host_functor());
			} else if (e.name == "channel") {
				index_lookup_.push_back(channel_functor());
			} else if (e.name == "alias") {
				index_lookup_.push_back(payload_alias_functor());
			} else if (e.name == "alias-or-command") {
				index_lookup_.push_back(payload_alias_or_command_functor());
			} else if (e.name == "message") {
				index_lookup_.push_back(payload_message_functor());
			} else if (e.name == "result") {
				index_lookup_.push_back(payload_result_functor());
			} else {
				NSC_LOG_ERROR_STD("Invalid index: " + e.name);
			}
		}
	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_EXR("Failed to register command: ", e);
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_EXR("load", e);
		return false;
	} catch (...) {
		NSC_LOG_ERROR_EX("load");
		return false;
	}
	return true;
}
Exemple #24
0
bool CheckMKServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	root_ = get_base_path();
	nscp_runtime_.reset(new scripts::nscp::nscp_runtime_impl(get_id(), get_core()));
	lua_runtime_.reset(new lua::lua_runtime(utf8::cvt<std::string>(root_.string())));
	lua_runtime_->register_plugin(boost::shared_ptr<check_mk::check_mk_plugin>(new check_mk::check_mk_plugin()));
	scripts_.reset(new scripts::script_manager<lua::lua_traits>(lua_runtime_, nscp_runtime_, get_id(), utf8::cvt<std::string>(alias)));
	handler_.reset(new handler_impl(scripts_));

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("check_mk", alias, "server");

	settings.alias().add_path_to_settings()
		("CHECK MK SERVER SECTION", "Section for check_mk (CheckMKServer.dll) protocol options.")

		("scripts", sh::fun_values_path(boost::bind(&CheckMKServer::add_script, this, _1, _2)), 
		"REMOTE TARGET DEFINITIONS", "",
		"TARGET", "For more configuration options add a dedicated section")

		;

	settings.alias().add_key_to_settings()
		("port", sh::string_key(&info_.port_, "6556"),
		"PORT NUMBER", "Port to use for check_mk.")

		;

	socket_helpers::settings_helper::add_core_server_opts(settings, info_);
	socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, false);

	settings.register_all();
	settings.notify();

	if (scripts_->empty()) {
		add_script("default", "default_check_mk.lua");
	}

#ifndef USE_SSL
	if (info_.use_ssl) {
		NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)"));
		return false;
	}
#endif
	NSC_LOG_ERROR_LISTS(info_.validate());

	std::list<std::string> errors;
	info_.allowed_hosts.refresh(errors);
	NSC_LOG_ERROR_LISTS(errors);
	NSC_DEBUG_MSG_STD("Allowed hosts definition: " + info_.allowed_hosts.to_string());

	boost::asio::io_service io_service_;

	scripts_->load_all();


	if (mode == NSCAPI::normalStart) {
		server_.reset(new check_mk::server::server(info_, handler_));
		if (!server_) {
			NSC_LOG_ERROR_STD("Failed to create server instance!");
			return false;
		}
		server_->start();
	}
	return true;
}
Exemple #25
0
bool SyslogClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {

	facilities["kernel"] = 0;
	facilities["user"] = 1;
	facilities["mail"] = 2;
	facilities["system"] = 3;
	facilities["security"] = 4;
	facilities["internal"] = 5;
	facilities["printer"] = 6;
	facilities["news"] = 7;
	facilities["UUCP"] = 8;
	facilities["clock"] = 9;
	facilities["authorization"] = 10;
	facilities["FTP"] = 11;
	facilities["NTP"] = 12;
	facilities["audit"] = 13;
	facilities["alert"] = 14;
	facilities["clock"] = 15;
	facilities["local0"] = 16;
	facilities["local1"] = 17;
	facilities["local2"] = 18;
	facilities["local3"] = 19;
	facilities["local4"] = 20;
	facilities["local5"] = 21;
	facilities["local6"] = 22;
	facilities["local7"] = 23;
	severities["emergency"] = 0;
	severities["alert"] = 1;
	severities["critical"] = 2;
	severities["error"] = 3;
	severities["warning"] = 4;
	severities["notice"] = 5;
	severities["informational"] = 6;
	severities["debug"] = 7;

	try {
		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(_T("syslog"), alias, _T("client"));
		target_path = settings.alias().get_settings_path(_T("targets"));

		settings.alias().add_path_to_settings()
			(_T("SYSLOG CLIENT SECTION"), _T("Section for SYSLOG passive check module."))
			(_T("handlers"), sh::fun_values_path(boost::bind(&SyslogClient::add_command, this, _1, _2)), 
			_T("CLIENT HANDLER SECTION"), _T(""))

			(_T("targets"), sh::fun_values_path(boost::bind(&SyslogClient::add_target, this, _1, _2)), 
			_T("REMOTE TARGET DEFINITIONS"), _T(""))
			;

		settings.alias().add_key_to_settings()
			(_T("hostname"), sh::string_key(&hostname_),
			_T("HOSTNAME"), _T("The host name of this host if set to blank (default) the windows name of the computer will be used."))

			(_T("channel"), sh::wstring_key(&channel_, _T("syslog")),
			_T("CHANNEL"), _T("The channel to listen to."))

			;
		settings.register_all();
		settings.notify();

		targets.add_missing(get_settings_proxy(), target_path, _T("default"), _T(""), true);


		get_core()->registerSubmissionListener(get_id(), channel_);
		register_command(_T("syslog_query"), _T("Check remote NRPE host"));
		register_command(_T("syslog_submit"), _T("Submit (via query) remote NRPE host"));
		register_command(_T("syslog_forward"), _T("Forward query to remote NRPE host"));
		register_command(_T("syslog_exec"), _T("Execute (via query) remote NRPE host"));
		register_command(_T("syslog_help"), _T("Help on using NRPE Client"));
	} catch (nscapi::nscapi_exception &e) {
		NSC_LOG_ERROR_STD(_T("NSClient API exception: ") + utf8::to_unicode(e.what()));
		return false;
	} catch (std::exception &e) {
		NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what()));
		return false;
	} catch (...) {
		NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
		return false;
	}
	return true;
}
Exemple #26
0
bool NSCAServer::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {

	try {
		if (server_) {
			server_->stop();
			server_.reset();
		}
	} catch (...) {
		NSC_LOG_ERROR_STD("Failed to stop server");
		return false;
	}

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias("NSCA", alias, "server");

	settings.alias().add_path_to_settings()
		("NSCA SERVER SECTION", "Section for NSCA (NSCAServer) (check_nsca) protocol options.")
		;

	settings.alias().add_key_to_settings()
		("port", sh::string_key(&info_.port_, "5667"),
		"PORT NUMBER", "Port to use for NSCA.")

		("payload length", sh::uint_key(&payload_length_, 512),
		"PAYLOAD LENGTH", "Length of payload to/from the NSCA agent. This is a hard specific value so you have to \"configure\" (read recompile) your NSCA agent to use the same value for it to work.")

		("performance data", sh::bool_fun_key<bool>(boost::bind(&NSCAServer::set_perf_data, this, _1), true),
		"PERFORMANCE DATA", "Send performance data back to nagios (set this to false to remove all performance data).")

		("encryption", sh::string_fun_key<std::string>(boost::bind(&NSCAServer::set_encryption, this, _1), "aes"),
		"ENCRYPTION", std::string("Name of encryption algorithm to use.\nHas to be the same as your agent i using or it wont work at all."
			"This is also independent of SSL and generally used instead of SSL.\nAvailable encryption algorithms are:\n") + nscp::encryption::helpers::get_crypto_string("\n"))

		;

	socket_helpers::settings_helper::add_core_server_opts(settings, info_);
	socket_helpers::settings_helper::add_ssl_server_opts(settings, info_, false);

	settings.alias().add_parent("/settings/default").add_key_to_settings()

		("password", sh::string_key(&password_, ""),
		"PASSWORD", "Password to use")

		("inbox", sh::string_key(&channel_, "inbox"),
		"INBOX", "The default channel to post incoming messages on")

		;

	settings.register_all();
	settings.notify();


#ifndef USE_SSL
	if (info_.ssl.enabled) {
		NSC_LOG_ERROR_STD(_T("SSL not avalible! (not compiled with openssl support)"));
		return false;
	}
#endif
	if (payload_length_ != 512)
		NSC_DEBUG_MSG_STD("Non-standard buffer length (hope you have recompiled check_nsca changing #define MAX_PACKETBUFFER_LENGTH = " + strEx::s::xtos(payload_length_));
	NSC_LOG_ERROR_LISTS(info_.validate());

	std::list<std::string> errors;
	info_.allowed_hosts.refresh(errors);
	NSC_LOG_ERROR_LISTS(errors);
	NSC_DEBUG_MSG_STD("Allowed hosts definition: " + info_.allowed_hosts.to_string());

	if (mode == NSCAPI::normalStart || mode == NSCAPI::reloadStart) {

		server_.reset(new nsca::server::server(info_, this));
		if (!server_) {
			NSC_LOG_ERROR_STD("Failed to create server instance!");
			return false;
		}
		server_->start();
	}
	return true;
}
Exemple #27
0
bool Scheduler::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	if (mode == NSCAPI::reloadStart) {
		scheduler_.unset_handler();
		scheduler_.clear();
	}


	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias(alias, "scheduler");
	schedules_.set_path(settings.alias().get_settings_path("schedules"));

	settings.alias().add_path_to_settings()
		("SCHEDULER SECTION", "Section for the Scheduler module.")

		;

	settings.alias().add_key_to_settings()
		("threads", sh::int_fun_key<unsigned int>(boost::bind(&schedules::scheduler::set_threads, &scheduler_, _1), 5),
			"THREAD COUNT", "Number of threads to use.")
		;

	settings.alias().add_path_to_settings()
		("schedules", sh::fun_values_path(boost::bind(&Scheduler::add_schedule, this, _1, _2)),
			"SCHEDULER SECTION", "Section for the Scheduler module.",
			"SCHEDULE", "For more configuration options add a dedicated section")
		;

	settings.alias().add_templates()
		("schedules", "plus", "Add a simple schedule",
			"Add a simple scheduled job for passive monitoring",
			"{"
			"\"fields\": [ "
			" { \"id\": \"alias\",		\"title\" : \"Alias\",		\"type\" : \"input\",		\"desc\" : \"This will identify the command\"} , "
			" { \"id\": \"command\",	\"title\" : \"Command\",	\"type\" : \"data-choice\",	\"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , "
			" { \"id\": \"args\",		\"title\" : \"Arguments\",	\"type\" : \"input\",		\"desc\" : \"Command line arguments for the command\" } , "
			" { \"id\": \"cmd\",		\"key\" : \"command\", \"title\" : \"A\",	\"type\" : \"hidden\",		\"desc\" : \"A\" } "
			" ], "
			"\"events\": { "
			"\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('command').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\""
			"}"
			"}")
		;
	settings.register_all();
	settings.notify();

	schedules_.ensure_default();

	BOOST_FOREACH(const schedules::schedule_handler::object_list_type::value_type &o, schedules_.get_object_list()) {
		if (o->duration && (*o->duration).total_seconds() == 0) {
			NSC_LOG_ERROR("WE cant add schedules with 0 duration: " + o->to_string());
			continue;
		}
		if (o->duration && o->schedule) {
			NSC_LOG_ERROR("WE cant add schedules with both duration and schedule: " + o->to_string());
			continue;
		}
		if (!o->duration && !o->schedule) {
			NSC_LOG_ERROR("WE need wither duration or schedule: " + o->to_string());
			continue;
		}
		NSC_DEBUG_MSG("Adding scheduled item: " + o->to_string());
		scheduler_.add_task(o);
	}

	if (mode == NSCAPI::normalStart) {
		scheduler_.set_handler(this);
		scheduler_.start();
	}
	if (mode == NSCAPI::reloadStart) {
		scheduler_.set_handler(this);
		scheduler_.start();
	}
	return true;
}
Exemple #28
0
bool CheckEventLog::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) {
	eventlog::api::load_procs();

	sh::settings_registry settings(get_settings_proxy());
	settings.set_alias(alias, "eventlog");

	thread_.reset(new real_time_thread(get_core(), get_id()));
	if (!thread_) {
		NSC_LOG_ERROR_STD("Failed to create thread container");
		return false;
	}
	thread_->set_path(settings.alias().get_settings_path("real-time/filters"));

	settings.alias().add_path_to_settings()
		("Eventlog configuration", "Section for the EventLog Checker (CheckEventLog.dll).")

		("real-time", "Real-time monitoring", "A set of options to configure the real time checks")

		("real-time/filters", sh::fun_values_path(boost::bind(&real_time_thread::add_realtime_filter, thread_, get_settings_proxy(), _1, _2)),
			"Real-time filters", "A set of filters to use in real-time mode",
			"FILTER DEFENITION", "For more configuration options add a dedicated section")
		;

	settings.alias().add_key_to_settings()
		("debug", sh::bool_key(&debug_, false),
			"DEBUG", "Log more information when filtering (useful to detect issues with filters) not useful in production as it is a bit of a resource hog.")

		("lookup names", sh::bool_key(&lookup_names_, true),
			"LOOKUP NAMES", "Lookup the names of eventlog files")

		("syntax", sh::string_key(&syntax_),
			"SYNTAX", "Set this to use a specific syntax string for all commands (that don't specify one).")

		("buffer size", sh::int_key(&buffer_length_, 128 * 1024),
			"BUFFER_SIZE", "The size of the buffer to use when getting messages this affects the speed and maximum size of messages you can recieve.")

		;

	settings.alias().add_key_to_settings("real-time")

		("enabled", sh::bool_fun_key(boost::bind(&real_time_thread::set_enabled, thread_, _1), false),
			"REAL TIME CHECKING", "Spawns a background thread which detects issues and reports them back instantly.")

		("startup age", sh::string_fun_key(boost::bind(&real_time_thread::set_start_age, thread_, _1), "30m"),
			"STARTUP AGE", "The initial age to scan when starting NSClient++")

		("log", sh::string_key(&thread_->logs_, "application,system"),
			"LOGS TO CHECK", "Comma separated list of logs to check")

		("debug", sh::bool_key(&thread_->debug_, false),
			"DEBUG", "Log missed records (useful to detect issues with filters) not useful in production as it is a bit of a resource hog.")

		;
	std::string filter_path = settings.alias().get_settings_path("real-time/filters");

	settings.register_all();
	settings.notify();

	thread_->filters_.add_samples(get_settings_proxy());
	thread_->filters_.add_missing(get_settings_proxy(), "default", "");

	if (mode == NSCAPI::normalStart) {

		nscapi::core_helper core(get_core(), get_id());
		BOOST_FOREACH(const nscapi::core_helper::storage_map::value_type &e, core.get_storage_strings("eventlog.bookmarks")) {
			bookmarks_.add(e.first, e.second);
		}

		if (!thread_->start())
			NSC_LOG_ERROR_STD("Failed to start collection thread");
	}
Exemple #29
0
bool CheckExternalScripts::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode) {
	try {

		sh::settings_registry settings(get_settings_proxy());
		settings.set_alias(alias, "external scripts");

		commands_path = settings.alias().get_settings_path("scripts");
		aliases_path = settings.alias().get_settings_path("alias");
		std::string wrappings_path = settings.alias().get_settings_path("wrappings");

		settings.alias().add_path_to_settings()

			("wrappings", sh::string_map_path(&wrappings_)
			, "EXTERNAL SCRIPT WRAPPINGS SECTION", "A list of templates for wrapped scripts.\n%SCRIPT% will be replaced by the actual script an %ARGS% will be replaced by any given arguments.",
			"WRAPPING", "An external script wrapping")

			("alias", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)), 
			"ALIAS SECTION", "A list of aliases available.\n"
			"An alias is an internal command that has been predefined to provide a single command without arguments. Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)",
			"ALIAS", "Query alias")

			;

		settings.register_all();
		settings.notify();
		settings.clear();
        
        if (wrappings_.find("ps1") == wrappings_.end()) {
            wrappings_["ps1"] = "cmd /c echo scripts\\\\%SCRIPT% %ARGS%; exit($lastexitcode) | powershell.exe -command -";
            settings.register_key(wrappings_path, "ps1", NSCAPI::key_string, "POWERSHELL WRAPPING", "", "", false);
            settings.set_static_key(wrappings_path, "ps1", wrappings_["ps1"]);
        }
        if (wrappings_.find("vbs") == wrappings_.end()) {
            wrappings_["vbs"] = "cscript.exe //T:30 //NoLogo scripts\\\\lib\\\\wrapper.vbs %SCRIPT% %ARGS%";
            settings.register_key(wrappings_path, "vbs", NSCAPI::key_string, "VISUAL BASIC WRAPPING", "", "", false);
            settings.set_static_key(wrappings_path, "vbs", wrappings_["vbs"]);
        }
        if (wrappings_.find("bat") == wrappings_.end()) {
            wrappings_["bat"] = "scripts\\\\%SCRIPT% %ARGS%";
            settings.register_key(wrappings_path, "bat", NSCAPI::key_string, "BATCH FILE WRAPPING", "", "", false);
            settings.set_static_key(wrappings_path, "bat", wrappings_["bat"]);
        }

		if (aliases_.empty()) {
			NSC_DEBUG_MSG("No aliases found (adding default)");

			add_alias("alias_cpu", "check_cpu");
			add_alias("alias_cpu_ex", "check_cpu \"warn=load > $ARG1$\" \"crit=load > $ARG2$\" time=5m time=1m time=30s");
			add_alias("alias_mem", "check_memory");
			add_alias("alias_up", "check_uptime");
			add_alias("alias_disk", "check_drivesize");
			add_alias("alias_disk_loose", "check_drivesize");
			add_alias("alias_volumes", "check_drivesize");
			add_alias("alias_volumes_loose", "check_drivesize");
			add_alias("alias_service", "check_service");
			add_alias("alias_service_ex", "check_service \"exclude=Net Driver HPZ12\" \"exclude=Pml Driver HPZ12\" exclude=stisvc");
			add_alias("alias_process", "check_process \"process=$ARG1$\" \"crit=state != 'started'\"");
			add_alias("alias_process_stopped", "check_process \"process=$ARG1$\" \"crit=state != 'stopped'\"");
			add_alias("alias_process_count", "check_process \"process=$ARG1$\" \"warn=count > $ARG2$\" \"crit=count > $ARG3$\"");
			add_alias("alias_process_hung", "check_process \"filter=is_hung\" \"crit=count>0\"");
			add_alias("alias_event_log", "check_eventlog");
			add_alias("alias_file_size", "check_files \"path=$ARG1$\" \"crit=size > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${size}\" max-dir-depth=10");
			add_alias("alias_file_age", "check_files \"path=$ARG1$\" \"crit=written > $ARG2$\" \"top-syntax=${list}\" \"detail-syntax=${filename] ${written}\" max-dir-depth=10");
			add_alias("alias_sched_all", "check_tasksched show-all \"syntax=${title}: ${exit_code}\" \"crit=exit_code ne 0\"");
			add_alias("alias_sched_long", "check_tasksched \"filter=status = 'running'\" \"detail-syntax=${title} (${most_recent_run_time})\" \"crit=most_recent_run_time < -$ARG1$\"");
			add_alias("alias_sched_task", "check_tasksched show-all \"filter=title eq '$ARG1$'\" \"detail-syntax=${title} (${exit_code})\" \"crit=exit_code ne 0\"");
//			add_alias("alias_updates", "check_updates -warning 0 -critical 0");
		}

		settings.alias().add_path_to_settings()
			("EXTERNAL SCRIPT SECTION", "Section for external scripts configuration options (CheckExternalScripts).")

			("scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_command, this, _1, _2)),
			"SCRIPT SECTION", "A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>",
			"SCRIPT", "For more configuration options add a dedicated section (if you add a new section you can customize the user and various other advanced features)")

			("wrapped scripts", sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)), 
			"WRAPPED SCRIPTS SECTION", "A list of wrapped scripts (ie. scruts using a template mechanism). The template used will be defined by the extension of the script.",
			"WRAPPED SCRIPT", "A wrapped script defenitions")

			;

		settings.alias().add_key_to_settings()
			("timeout", sh::uint_key(&timeout, 60),
			"COMMAND TIMEOUT", "The maximum time in seconds that a command can execute. (if more then this execution will be aborted). NOTICE this only affects external commands not internal ones.")

			("allow arguments", sh::bool_key(&allowArgs_, false),
			"COMMAND ARGUMENT PROCESSING", "This option determines whether or not the we will allow clients to specify arguments to commands that are executed.")

			("allow nasty characters", sh::bool_key(&allowNasty_, false),
			"COMMAND ALLOW NASTY META CHARS", "This option determines whether or not the we will allow clients to specify nasty (as in |`&><'\"\\[]{}) characters in arguments.")

			("script path", sh::string_key(&scriptDirectory_),
			"SCRIPT DIRECTORY", "Load all scripts in a directory and use them as commands. Probably dangerous but useful if you have loads of scripts :)")
			;

		settings.register_all();
		settings.notify();


		if (!scriptDirectory_.empty()) {
			addAllScriptsFrom(scriptDirectory_);
		}
		root_ = get_base_path();

		nscapi::core_helper core(get_core(), get_id());
		BOOST_FOREACH(const commands::command_handler::object_list_type::value_type &o, commands_.object_list) {
			core.register_alias(o.second.tpl.alias, "External script: " + o.second.command);
		}
		BOOST_FOREACH(const alias::command_handler::object_list_type::value_type &o, aliases_.object_list) {
			core.register_alias(o.second.tpl.alias, "Alias for: " + o.second.command);
		}
	} catch (...) {
		NSC_LOG_ERROR_EX("loading");
		return false;
	}
	return true;
}