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"
210 Utility::RenameFile(tempApiPath, apipath);
212 /* update constants.conf with NodeName = CN + TicketSalt = random value */
213 if (endpointName != Utility::GetFQDN()) {
214 Log(LogWarning, "cli")
215 << "CN/Endpoint name '" << endpointName << "' does not match the default FQDN '" << Utility::GetFQDN() << "'. Requires update for NodeName constant in constants.conf!";
218 NodeUtility::UpdateConstant("NodeName", endpointName);
219 NodeUtility::UpdateConstant("ZoneName", zoneName);
221 String salt = RandomString(16);
223 NodeUtility::UpdateConstant("TicketSalt", salt);
225 Log(LogInformation, "cli")
226 << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
228 if (vm.count("disable-confd")) {
229 /* Disable conf.d inclusion */
230 if (NodeUtility::UpdateConfiguration("\"conf.d\"", false, true)) {
231 Log(LogInformation, "cli")
232 << "Disabled conf.d inclusion";
234 Log(LogWarning, "cli")
235 << "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
238 /* Include api-users.conf */
239 String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();
241 if (Utility::PathExists(apiUsersFilePath)) {
242 NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
244 Log(LogWarning, "cli")
245 << "Included file doesn't exist " << apiUsersFilePath;
249 /* tell the user to reload icinga2 */
250 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
255 int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
257 /* require at least one endpoint. Ticket is optional. */
258 if (!vm.count("endpoint")) {
259 Log(LogCritical, "cli", "You need to specify at least one endpoint (--endpoint).");
263 if (!vm.count("zone")) {
264 Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
268 /* Deprecation warnings. TODO: Remove in 2.10.0. */
269 if (vm.count("master_zone"))
270 Log(LogWarning, "cli", "The 'master_zone' parameter has been deprecated. Use 'parent_zone' instead.");
271 if (vm.count("master_host"))
272 Log(LogWarning, "cli", "The 'master_host' parameter has been deprecated. Use 'parent_host' instead.");
276 if (vm.count("ticket"))
277 ticket = vm["ticket"].as<std::string>();
279 if (ticket.IsEmpty()) {
280 Log(LogInformation, "cli")
281 << "Requesting certificate without a ticket.";
283 Log(LogInformation, "cli")
284 << "Requesting certificate with ticket '" << ticket << "'.";
287 /* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
288 bool connectToParent = false;
290 String parentPort = "5665";
291 std::shared_ptr<X509> trustedParentCert;
293 /* TODO: remove master_host in 2.10.0. */
294 if (!vm.count("master_host") && !vm.count("parent_host")) {
295 connectToParent = false;
297 Log(LogWarning, "cli")
298 << "Node to master/satellite connection setup skipped. Please configure your parent node to\n"
299 << "connect to this node by setting the 'host' attribute for the node Endpoint object.\n";
301 connectToParent = true;
303 String parentHostInfo;
305 if (vm.count("parent_host"))
306 parentHostInfo = vm["parent_host"].as<std::string>();
307 else if (vm.count("master_host")) /* TODO: Remove in 2.10.0. */
308 parentHostInfo = vm["master_host"].as<std::string>();
310 std::vector<String> tokens = parentHostInfo.Split(",");
312 if (tokens.size() == 1 || tokens.size() == 2)
313 parentHost = tokens[0];
315 if (tokens.size() == 2)
316 parentPort = tokens[1];
318 Log(LogInformation, "cli")
319 << "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";
323 /* retrieve CN and pass it (defaults to FQDN) */
324 String cn = Utility::GetFQDN();
327 cn = vm["cn"].as<std::string>();
329 Log(LogInformation, "cli")
330 << "Using the following CN (defaults to FQDN): '" << cn << "'.";
332 /* pki request a signed certificate from the master */
333 String certsDir = ApiListener::GetCertsDir();
334 Utility::MkDirP(certsDir, 0700);
336 String user = Configuration::RunAsUser;
337 String group = Configuration::RunAsGroup;
339 if (!Utility::SetFileOwnership(certsDir, user, group)) {
340 Log(LogWarning, "cli")
341 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << certsDir << "'. Verify it yourself!";
344 String key = certsDir + "/" + cn + ".key";
345 String cert = certsDir + "/" + cn + ".crt";
346 String ca = certsDir + "/ca.crt";
348 if (Utility::PathExists(key))
349 NodeUtility::CreateBackupFile(key, true);
350 if (Utility::PathExists(cert))
351 NodeUtility::CreateBackupFile(cert);
353 if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
354 Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
358 /* fix permissions: root -> icinga daemon user */
359 if (!Utility::SetFileOwnership(key, user, group)) {
360 Log(LogWarning, "cli")
361 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << key << "'. Verify it yourself!";
364 /* Send a signing request to the parent immediately, or leave it to the user. */
365 if (connectToParent) {
366 /* In contrast to `node wizard` the user must manually fetch
367 * the trustedParentCert to prove the trust relationship (fetched with 'pki save-cert').
369 if (!vm.count("trustedcert")) {
370 Log(LogCritical, "cli")
371 << "Please pass the trusted cert retrieved from the parent node (master or satellite)\n"
372 << "(Hint: 'icinga2 pki save-cert --host <masterhost> --port <5665> --key local.key --cert local.crt --trustedcert parent.crt').";
376 trustedParentCert = GetX509Certificate(vm["trustedcert"].as<std::string>());
378 Log(LogInformation, "cli")
379 << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
381 Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
383 if (PkiUtility::RequestCertificate(parentHost, parentPort, key, cert, ca, trustedParentCert, ticket) > 0) {
384 Log(LogCritical, "cli")
385 << "Failed to fetch signed certificate from parent Icinga node '"
386 << parentHost << ", "
387 << parentPort << "'. Please try again.";
391 /* We cannot retrieve the parent certificate.
392 * Tell the user to manually copy the ca.crt file
393 * into DataDir + "/certs"
395 Log(LogWarning, "cli")
396 << "\nNo connection to the parent node was specified.\n\n"
397 << "Please copy the public CA certificate from your master/satellite\n"
398 << "into '" << ca << "' before starting Icinga 2.\n";
400 if (Utility::PathExists(ca)) {
401 Log(LogInformation, "cli")
402 << "\nFound public CA certificate in '" << ca << "'.\n"
403 << "Please verify that it is the same as on your master/satellite.\n";
407 if (!Utility::SetFileOwnership(ca, user, group)) {
408 Log(LogWarning, "cli")
409 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << ca << "'. Verify it yourself!";
412 /* fix permissions (again) when updating the signed certificate */
413 if (!Utility::SetFileOwnership(cert, user, group)) {
414 Log(LogWarning, "cli")
415 << "Cannot set ownership for user '" << user << "' group '" << group << "' on file '" << cert << "'. Verify it yourself!";
418 /* disable the notifications feature */
419 Log(LogInformation, "cli", "Disabling the Notification feature.");
421 FeatureUtility::DisableFeatures({ "notification" });
423 /* enable the ApiListener config */
425 Log(LogInformation, "cli", "Updating the ApiListener feature.");
427 FeatureUtility::EnableFeatures({ "api" });
429 String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
430 NodeUtility::CreateBackupFile(apipath);
433 String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
436 << " * The API listener is used for distributed monitoring setups.\n"
438 << "object ApiListener \"api\" {\n";
440 if (vm.count("listen")) {
441 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
443 if (tokens.size() > 0)
444 fp << " bind_host = \"" << tokens[0] << "\"\n";
445 if (tokens.size() > 1)
446 fp << " bind_port = " << tokens[1] << "\n";
451 if (vm.count("accept-config"))
452 fp << " accept_config = true\n";
454 fp << " accept_config = false\n";
456 if (vm.count("accept-commands"))
457 fp << " accept_commands = true\n";
459 fp << " accept_commands = false\n";
466 Utility::RenameFile(tempApiPath, apipath);
468 /* Generate zones configuration. */
469 Log(LogInformation, "cli", "Generating zone and object configuration.");
471 /* Setup command hardcodes this as FQDN */
472 String endpointName = cn;
474 /* Allow to specify zone name. */
475 String zoneName = vm["zone"].as<std::string>();
477 /* Allow to specify the parent zone name. */
478 String parentZoneName = "master";
480 if (vm.count("parent_zone"))
481 parentZoneName = vm["parent_zone"].as<std::string>();
483 std::vector<String> globalZones { "global-templates", "director-global" };
484 std::vector<std::string> setupGlobalZones;
486 if (vm.count("global_zones"))
487 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
489 for (decltype(setupGlobalZones.size()) i = 0; i < setupGlobalZones.size(); i++) {
490 if (std::find(globalZones.begin(), globalZones.end(), setupGlobalZones[i]) != globalZones.end()) {
491 Log(LogCritical, "cli")
492 << "The global zone '" << setupGlobalZones[i] << "' is already specified.";
497 globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
499 /* Generate node configuration. */
500 NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);
502 /* update constants.conf with NodeName = CN */
503 if (endpointName != Utility::GetFQDN()) {
504 Log(LogWarning, "cli")
505 << "CN/Endpoint name '" << endpointName << "' does not match the default FQDN '"
506 << Utility::GetFQDN() << "'. Requires an update for the NodeName constant in constants.conf!";
509 NodeUtility::UpdateConstant("NodeName", endpointName);
510 NodeUtility::UpdateConstant("ZoneName", zoneName);
512 if (!ticket.IsEmpty()) {
513 String ticketPath = ApiListener::GetCertsDir() + "/ticket";
515 String tempTicketPath = Utility::CreateTempFile(ticketPath + ".XXXXXX", 0600, fp);
517 if (!Utility::SetFileOwnership(tempTicketPath, user, group)) {
518 Log(LogWarning, "cli")
519 << "Cannot set ownership for user '" << user
520 << "' group '" << group
521 << "' on file '" << tempTicketPath << "'. Verify it yourself!";
528 Utility::RenameFile(tempTicketPath, ticketPath);
531 /* If no parent connection was made, the user must supply the ca.crt before restarting Icinga 2.*/
532 if (!connectToParent) {
533 Log(LogWarning, "cli")
534 << "No connection to the parent node was specified.\n\n"
535 << "Please copy the public CA certificate from your master/satellite\n"
536 << "into '" << ca << "' before starting Icinga 2.\n";
538 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
541 if (vm.count("disable-confd")) {
542 /* Disable conf.d inclusion */
543 NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
546 /* tell the user to reload icinga2 */
547 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");