1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "cli/nodesetupcommand.hpp"
4 #include "cli/nodeutility.hpp"
5 #include "cli/featureutility.hpp"
6 #include "cli/apisetuputility.hpp"
7 #include "remote/apilistener.hpp"
8 #include "remote/pkiutility.hpp"
9 #include "base/logger.hpp"
10 #include "base/console.hpp"
11 #include "base/application.hpp"
12 #include "base/tlsutility.hpp"
13 #include "base/scriptglobal.hpp"
14 #include "base/exception.hpp"
15 #include <boost/algorithm/string/join.hpp>
16 #include <boost/algorithm/string/replace.hpp>
22 using namespace icinga;
23 namespace po = boost::program_options;
25 REGISTER_CLICOMMAND("node/setup", NodeSetupCommand);
27 String NodeSetupCommand::GetDescription() const
29 return "Sets up an Icinga 2 node.";
32 String NodeSetupCommand::GetShortDescription() const
37 void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc,
38 boost::program_options::options_description& hiddenDesc) const
40 visibleDesc.add_options()
41 ("zone", po::value<std::string>(), "The name of the local zone")
42 ("endpoint", po::value<std::vector<std::string> >(), "Connect to remote endpoint; syntax: cn[,host,port]")
43 ("parent_host", po::value<std::string>(), "The name of the parent host for auto-signing the csr; syntax: host[,port]")
44 ("parent_zone", po::value<std::string>(), "The name of the parent zone")
45 ("listen", po::value<std::string>(), "Listen on host,port")
46 ("ticket", po::value<std::string>(), "Generated ticket number for this request (optional)")
47 ("trustedcert", po::value<std::string>(), "Trusted master certificate file")
48 ("cn", po::value<std::string>(), "The certificate's common name")
49 ("accept-config", "Accept config from master")
50 ("accept-commands", "Accept commands from master")
51 ("master", "Use setup for a master instance")
52 ("global_zones", po::value<std::vector<std::string> >(), "The names of the additional global zones to 'global-templates' and 'director-global'.")
53 ("disable-confd", "Disables the conf.d directory during the setup");
55 hiddenDesc.add_options()
56 ("master_zone", po::value<std::string>(), "DEPRECATED: The name of the master zone")
57 ("master_host", po::value<std::string>(), "DEPRECATED: The name of the master host for auto-signing the csr; syntax: host[,port]");
60 std::vector<String> NodeSetupCommand::GetArgumentSuggestions(const String& argument, const String& word) const
62 if (argument == "key" || argument == "cert" || argument == "trustedcert")
63 return GetBashCompletionSuggestions("file", word);
64 else if (argument == "host")
65 return GetBashCompletionSuggestions("hostname", word);
66 else if (argument == "port")
67 return GetBashCompletionSuggestions("service", word);
69 return CLICommand::GetArgumentSuggestions(argument, word);
72 ImpersonationLevel NodeSetupCommand::GetImpersonationLevel() const
74 return ImpersonateIcinga;
78 * The entry point for the "node setup" CLI command.
80 * @returns An exit status.
82 int NodeSetupCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
85 Log(LogWarning, "cli")
86 << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
89 if (vm.count("master"))
90 return SetupMaster(vm, ap);
92 return SetupNode(vm, ap);
95 int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
97 /* Ignore not required parameters */
98 if (vm.count("ticket"))
99 Log(LogWarning, "cli", "Master for Node setup: Ignoring --ticket");
101 if (vm.count("endpoint"))
102 Log(LogWarning, "cli", "Master for Node setup: Ignoring --endpoint");
104 if (vm.count("trustedcert"))
105 Log(LogWarning, "cli", "Master for Node setup: Ignoring --trustedcert");
107 String cn = Utility::GetFQDN();
110 cn = vm["cn"].as<std::string>();
112 /* Setup command hardcodes this as FQDN */
113 String endpointName = cn;
115 /* Allow to specify zone name. */
116 String zoneName = "master";
118 if (vm.count("zone"))
119 zoneName = vm["zone"].as<std::string>();
121 /* check whether the user wants to generate a new certificate or not */
122 String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";
124 Log(LogInformation, "cli")
125 << "Checking in existing certificates for common name '" << cn << "'...";
127 if (Utility::PathExists(existingPath)) {
128 Log(LogWarning, "cli")
129 << "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate.";
131 Log(LogInformation, "cli")
132 << "Certificates not yet generated. Running 'api setup' now.";
134 ApiSetupUtility::SetupMasterCertificates(cn);
137 Log(LogInformation, "cli", "Generating master configuration for Icinga 2.");
138 ApiSetupUtility::SetupMasterApiUser();
140 if (!FeatureUtility::CheckFeatureEnabled("api")) {
141 ApiSetupUtility::SetupMasterEnableApi();
143 Log(LogInformation, "cli")
144 << "'api' feature already enabled.\n";
147 /* write zones.conf and update with zone + endpoint information */
148 Log(LogInformation, "cli", "Generating zone and object configuration.");
150 std::vector<String> globalZones { "global-templates", "director-global" };
151 std::vector<std::string> setupGlobalZones;
153 if (vm.count("global_zones"))
154 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
156 for (decltype(setupGlobalZones.size()) i = 0; i < setupGlobalZones.size(); i++) {
157 if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
158 Log(LogCritical, "cli")
159 << "The global zone '" << setupGlobalZones[i] << "' is already specified.";
164 globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
166 /* Generate master configuration. */
167 NodeUtility::GenerateNodeMasterIcingaConfig(endpointName, zoneName, globalZones);
169 /* Update the ApiListener config. */
170 Log(LogInformation, "cli", "Updating the APIListener feature.");
172 String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
173 NodeUtility::CreateBackupFile(apipath);
176 String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
179 << " * The API listener is used for distributed monitoring setups.\n"
181 << "object ApiListener \"api\" {\n";
183 if (vm.count("listen")) {
184 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
186 if (tokens.size() > 0)
187 fp << " bind_host = \"" << tokens[0] << "\"\n";
188 if (tokens.size() > 1)
189 fp << " bind_port = " << tokens[1] << "\n";
194 if (vm.count("accept-config"))
195 fp << " accept_config = true\n";
197 fp << " accept_config = false\n";
199 if (vm.count("accept-commands"))
200 fp << " accept_commands = true\n";
202 fp << " accept_commands = false\n";
205 << " ticket_salt = TicketSalt\n"
211 _unlink(apipath.CStr());
214 if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
215 BOOST_THROW_EXCEPTION(posix_error()
216 << boost::errinfo_api_function("rename")
217 << boost::errinfo_errno(errno)
218 << boost::errinfo_file_name(tempApiPath));
221 /* update constants.conf with NodeName = CN + TicketSalt = random value */
222 if (cn != Utility::GetFQDN()) {
223 Log(LogWarning, "cli")
224 << "CN '" << cn << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
227 NodeUtility::UpdateConstant("NodeName", cn);
228 NodeUtility::UpdateConstant("ZoneName", cn);
230 String salt = RandomString(16);
232 NodeUtility::UpdateConstant("TicketSalt", salt);
234 Log(LogInformation, "cli")
235 << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
237 if (vm.count("disable-confd")) {
238 /* Disable conf.d inclusion */
239 if (NodeUtility::UpdateConfiguration("\"conf.d\"", false, true)) {
240 Log(LogInformation, "cli")
241 << "Disabled conf.d inclusion";
243 Log(LogWarning, "cli")
244 << "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
247 /* Include api-users.conf */
248 String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();
250 if (Utility::PathExists(apiUsersFilePath)) {
251 NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
253 Log(LogWarning, "cli")
254 << "Included file doesn't exist " << apiUsersFilePath;
258 /* tell the user to reload icinga2 */
259 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
264 int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
266 /* require at least one endpoint. Ticket is optional. */
267 if (!vm.count("endpoint")) {
268 Log(LogCritical, "cli", "You need to specify at least one endpoint (--endpoint).");
272 if (!vm.count("zone")) {
273 Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
277 /* Deprecation warnings. TODO: Remove in 2.10.0. */
278 if (vm.count("master_zone"))
279 Log(LogWarning, "cli", "The 'master_zone' parameter has been deprecated. Use 'parent_zone' instead.");
280 if (vm.count("master_host"))
281 Log(LogWarning, "cli", "The 'master_host' parameter has been deprecated. Use 'parent_host' instead.");
285 if (vm.count("ticket"))
286 ticket = vm["ticket"].as<std::string>();
288 if (ticket.IsEmpty()) {
289 Log(LogInformation, "cli")
290 << "Requesting certificate without a ticket.";
292 Log(LogInformation, "cli")
293 << "Requesting certificate with ticket '" << ticket << "'.";
296 /* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
297 bool connectToParent = false;
299 String parentPort = "5665";
300 std::shared_ptr<X509> trustedParentCert;
302 /* TODO: remove master_host in 2.10.0. */
303 if (!vm.count("master_host") && !vm.count("parent_host")) {
304 connectToParent = false;
306 Log(LogWarning, "cli")
307 << "Node to master/satellite connection setup skipped. Please configure your parent node to\n"
308 << "connect to this node by setting the 'host' attribute for the node Endpoint object.\n";
310 connectToParent = true;
312 String parentHostInfo;
314 if (vm.count("parent_host"))
315 parentHostInfo = vm["parent_host"].as<std::string>();
316 else if (vm.count("master_host")) /* TODO: Remove in 2.10.0. */
317 parentHostInfo = vm["master_host"].as<std::string>();
319 std::vector<String> tokens = parentHostInfo.Split(",");
321 if (tokens.size() == 1 || tokens.size() == 2)
322 parentHost = tokens[0];
324 if (tokens.size() == 2)
325 parentPort = tokens[1];
327 Log(LogInformation, "cli")
328 << "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";
332 /* retrieve CN and pass it (defaults to FQDN) */
333 String cn = Utility::GetFQDN();
336 cn = vm["cn"].as<std::string>();
338 Log(LogInformation, "cli")
339 << "Using the following CN (defaults to FQDN): '" << cn << "'.";
341 /* pki request a signed certificate from the master */
342 String certsDir = ApiListener::GetCertsDir();
343 Utility::MkDirP(certsDir, 0700);
345 String user = Configuration::RunAsUser;
346 String group = Configuration::RunAsGroup;
348 if (!Utility::SetFileOwnership(certsDir, user, group)) {
349 Log(LogWarning, "cli")
350 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << certsDir << "'. Verify it yourself!";
353 String key = certsDir + "/" + cn + ".key";
354 String cert = certsDir + "/" + cn + ".crt";
355 String ca = certsDir + "/ca.crt";
357 if (Utility::PathExists(key))
358 NodeUtility::CreateBackupFile(key, true);
359 if (Utility::PathExists(cert))
360 NodeUtility::CreateBackupFile(cert);
362 if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
363 Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
367 /* fix permissions: root -> icinga daemon user */
368 if (!Utility::SetFileOwnership(key, user, group)) {
369 Log(LogWarning, "cli")
370 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!";
373 /* Send a signing request to the parent immediately, or leave it to the user. */
374 if (connectToParent) {
375 /* In contrast to `node wizard` the user must manually fetch
376 * the trustedParentCert to prove the trust relationship (fetched with 'pki save-cert').
378 if (!vm.count("trustedcert")) {
379 Log(LogCritical, "cli")
380 << "Please pass the trusted cert retrieved from the parent node (master or satellite)\n"
381 << "(Hint: 'icinga2 pki save-cert --host <masterhost> --port <5665> --key local.key --cert local.crt --trustedcert parent.crt').";
385 trustedParentCert = GetX509Certificate(vm["trustedcert"].as<std::string>());
387 Log(LogInformation, "cli")
388 << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
390 Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
392 if (PkiUtility::RequestCertificate(parentHost, parentPort, key, cert, ca, trustedParentCert, ticket) > 0) {
393 Log(LogCritical, "cli")
394 << "Failed to fetch signed certificate from parent Icinga node '"
395 << parentHost << ", "
396 << parentPort << "'. Please try again.";
400 /* We cannot retrieve the parent certificate.
401 * Tell the user to manually copy the ca.crt file
402 * into DataDir + "/certs"
404 Log(LogWarning, "cli")
405 << "\nNo connection to the parent node was specified.\n\n"
406 << "Please copy the public CA certificate from your master/satellite\n"
407 << "into '" << ca << "' before starting Icinga 2.\n";
409 if (Utility::PathExists(ca)) {
410 Log(LogInformation, "cli")
411 << "\nFound public CA certificate in '" << ca << "'.\n"
412 << "Please verify that it is the same as on your master/satellite.\n";
416 if (!Utility::SetFileOwnership(ca, user, group)) {
417 Log(LogWarning, "cli")
418 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!";
421 /* fix permissions (again) when updating the signed certificate */
422 if (!Utility::SetFileOwnership(cert, user, group)) {
423 Log(LogWarning, "cli")
424 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!";
427 /* disable the notifications feature */
428 Log(LogInformation, "cli", "Disabling the Notification feature.");
430 FeatureUtility::DisableFeatures({ "notification" });
432 /* enable the ApiListener config */
434 Log(LogInformation, "cli", "Updating the ApiListener feature.");
436 FeatureUtility::EnableFeatures({ "api" });
438 String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
439 NodeUtility::CreateBackupFile(apipath);
442 String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
445 << " * The API listener is used for distributed monitoring setups.\n"
447 << "object ApiListener \"api\" {\n";
449 if (vm.count("listen")) {
450 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
452 if (tokens.size() > 0)
453 fp << " bind_host = \"" << tokens[0] << "\"\n";
454 if (tokens.size() > 1)
455 fp << " bind_port = " << tokens[1] << "\n";
460 if (vm.count("accept-config"))
461 fp << " accept_config = true\n";
463 fp << " accept_config = false\n";
465 if (vm.count("accept-commands"))
466 fp << " accept_commands = true\n";
468 fp << " accept_commands = false\n";
476 _unlink(apipath.CStr());
479 if (rename(tempApiPath.CStr(), apipath.CStr()) < 0) {
480 BOOST_THROW_EXCEPTION(posix_error()
481 << boost::errinfo_api_function("rename")
482 << boost::errinfo_errno(errno)
483 << boost::errinfo_file_name(tempApiPath));
487 /* Generate zones configuration. */
488 Log(LogInformation, "cli", "Generating zone and object configuration.");
490 /* Setup command hardcodes this as FQDN */
491 String endpointName = cn;
493 /* Allow to specify zone name. */
494 String zoneName = vm["zone"].as<std::string>();
496 /* Allow to specify the parent zone name. */
497 String parentZoneName = "master";
499 if (vm.count("parent_zone"))
500 parentZoneName = vm["parent_zone"].as<std::string>();
502 std::vector<String> globalZones { "global-templates", "director-global" };
503 std::vector<std::string> setupGlobalZones;
505 if (vm.count("global_zones"))
506 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
508 for (decltype(setupGlobalZones.size()) i = 0; i < setupGlobalZones.size(); i++) {
509 if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
510 Log(LogCritical, "cli")
511 << "The global zone '" << setupGlobalZones[i] << "' is already specified.";
516 globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
518 /* Generate node configuration. */
519 NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);
521 /* update constants.conf with NodeName = CN */
522 if (cn != Utility::GetFQDN()) {
523 Log(LogWarning, "cli")
524 << "CN '" << cn << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
527 NodeUtility::UpdateConstant("NodeName", cn);
528 NodeUtility::UpdateConstant("ZoneName", vm["zone"].as<std::string>());
530 if (!ticket.IsEmpty()) {
531 String ticketPath = ApiListener::GetCertsDir() + "/ticket";
533 String tempTicketPath = Utility::CreateTempFile(ticketPath + ".XXXXXX", 0600, fp);
535 if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
536 Log(LogWarning, "cli")
537 << "Cannot set ownership for user '" << user
538 << "' group '" << group
539 << "' on file '" << tempTicketPath << "'. Verify it yourself!";
547 _unlink(ticketPath.CStr());
550 if (rename(tempTicketPath.CStr(), ticketPath.CStr()) < 0) {
551 BOOST_THROW_EXCEPTION(posix_error()
552 << boost::errinfo_api_function("rename")
553 << boost::errinfo_errno(errno)
554 << boost::errinfo_file_name(tempTicketPath));
558 /* If no parent connection was made, the user must supply the ca.crt before restarting Icinga 2.*/
559 if (!connectToParent) {
560 Log(LogWarning, "cli")
561 << "No connection to the parent node was specified.\n\n"
562 << "Please copy the public CA certificate from your master/satellite\n"
563 << "into '" << ca << "' before starting Icinga 2.\n";
565 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
568 if (vm.count("disable-confd")) {
569 /* Disable conf.d inclusion */
570 NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
573 /* tell the user to reload icinga2 */
574 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");