]> granicus.if.org Git - icinga2/blob - lib/cli/nodesetupcommand.cpp
add some object locking to the Dump method (which could theoreticylly suffer from...
[icinga2] / lib / cli / nodesetupcommand.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
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>
17
18 #include <iostream>
19 #include <fstream>
20 #include <vector>
21
22 using namespace icinga;
23 namespace po = boost::program_options;
24
25 REGISTER_CLICOMMAND("node/setup", NodeSetupCommand);
26
27 String NodeSetupCommand::GetDescription() const
28 {
29         return "Sets up an Icinga 2 node.";
30 }
31
32 String NodeSetupCommand::GetShortDescription() const
33 {
34         return "set up node";
35 }
36
37 void NodeSetupCommand::InitParameters(boost::program_options::options_description& visibleDesc,
38         boost::program_options::options_description& hiddenDesc) const
39 {
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");
54
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]");
58 }
59
60 std::vector<String> NodeSetupCommand::GetArgumentSuggestions(const String& argument, const String& word) const
61 {
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);
68         else
69                 return CLICommand::GetArgumentSuggestions(argument, word);
70 }
71
72 ImpersonationLevel NodeSetupCommand::GetImpersonationLevel() const
73 {
74         return ImpersonateIcinga;
75 }
76
77 /**
78  * The entry point for the "node setup" CLI command.
79  *
80  * @returns An exit status.
81  */
82 int NodeSetupCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
83 {
84         if (!ap.empty()) {
85                 Log(LogWarning, "cli")
86                         << "Ignoring parameters: " << boost::algorithm::join(ap, " ");
87         }
88
89         if (vm.count("master"))
90                 return SetupMaster(vm, ap);
91         else
92                 return SetupNode(vm, ap);
93 }
94
95 int NodeSetupCommand::SetupMaster(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
96 {
97         /* Ignore not required parameters */
98         if (vm.count("ticket"))
99                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --ticket");
100
101         if (vm.count("endpoint"))
102                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --endpoint");
103
104         if (vm.count("trustedcert"))
105                 Log(LogWarning, "cli", "Master for Node setup: Ignoring --trustedcert");
106
107         String cn = Utility::GetFQDN();
108
109         if (vm.count("cn"))
110                 cn = vm["cn"].as<std::string>();
111
112         /* Setup command hardcodes this as FQDN */
113         String endpointName = cn;
114
115         /* Allow to specify zone name. */
116         String zoneName = "master";
117
118         if (vm.count("zone"))
119                 zoneName = vm["zone"].as<std::string>();
120
121         /* check whether the user wants to generate a new certificate or not */
122         String existingPath = ApiListener::GetCertsDir() + "/" + cn + ".crt";
123
124         Log(LogInformation, "cli")
125                 << "Checking in existing certificates for common name '" << cn << "'...";
126
127         if (Utility::PathExists(existingPath)) {
128                 Log(LogWarning, "cli")
129                         << "Certificate '" << existingPath << "' for CN '" << cn << "' already exists. Not generating new certificate.";
130         } else {
131                 Log(LogInformation, "cli")
132                         << "Certificates not yet generated. Running 'api setup' now.";
133
134                 ApiSetupUtility::SetupMasterCertificates(cn);
135         }
136
137         Log(LogInformation, "cli", "Generating master configuration for Icinga 2.");
138         ApiSetupUtility::SetupMasterApiUser();
139
140         if (!FeatureUtility::CheckFeatureEnabled("api")) {
141                 ApiSetupUtility::SetupMasterEnableApi();
142         } else {
143                 Log(LogInformation, "cli")
144                         << "'api' feature already enabled.\n";
145         }
146
147         /* write zones.conf and update with zone + endpoint information */
148         Log(LogInformation, "cli", "Generating zone and object configuration.");
149
150         std::vector<String> globalZones { "global-templates", "director-global" };
151         std::vector<std::string> setupGlobalZones;
152
153         if (vm.count("global_zones"))
154                 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
155
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.";
160                         return 1;
161                 }
162         }
163
164         globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
165
166         /* Generate master configuration. */
167         NodeUtility::GenerateNodeMasterIcingaConfig(endpointName, zoneName, globalZones);
168
169         /* Update the ApiListener config. */
170         Log(LogInformation, "cli", "Updating the APIListener feature.");
171
172         String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
173         NodeUtility::CreateBackupFile(apipath);
174
175         std::fstream fp;
176         String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
177
178         fp << "/**\n"
179                 << " * The API listener is used for distributed monitoring setups.\n"
180                 << " */\n"
181                 << "object ApiListener \"api\" {\n";
182
183         if (vm.count("listen")) {
184                 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
185
186                 if (tokens.size() > 0)
187                         fp << "  bind_host = \"" << tokens[0] << "\"\n";
188                 if (tokens.size() > 1)
189                         fp << "  bind_port = " << tokens[1] << "\n";
190         }
191
192         fp << "\n";
193
194         if (vm.count("accept-config"))
195                 fp << "  accept_config = true\n";
196         else
197                 fp << "  accept_config = false\n";
198
199         if (vm.count("accept-commands"))
200                 fp << "  accept_commands = true\n";
201         else
202                 fp << "  accept_commands = false\n";
203
204         fp << "\n"
205                 << "  ticket_salt = TicketSalt\n"
206                 << "}\n";
207
208         fp.close();
209
210 #ifdef _WIN32
211         _unlink(apipath.CStr());
212 #endif /* _WIN32 */
213
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));
219         }
220
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!";
225         }
226
227         NodeUtility::UpdateConstant("NodeName", cn);
228         NodeUtility::UpdateConstant("ZoneName", cn);
229
230         String salt = RandomString(16);
231
232         NodeUtility::UpdateConstant("TicketSalt", salt);
233
234         Log(LogInformation, "cli")
235                 << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
236
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";
242                 } else {
243                         Log(LogWarning, "cli")
244                                 << "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
245                 }
246
247                 /* Include api-users.conf */
248                 String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();
249
250                 if (Utility::PathExists(apiUsersFilePath)) {
251                         NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
252                 } else {
253                         Log(LogWarning, "cli")
254                                 << "Included file doesn't exist " << apiUsersFilePath;
255                 }
256         }
257
258         /* tell the user to reload icinga2 */
259         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
260
261         return 0;
262 }
263
264 int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
265 {
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).");
269                 return 1;
270         }
271
272         if (!vm.count("zone")) {
273                 Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
274                 return 1;
275         }
276
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.");
282
283         String ticket;
284
285         if (vm.count("ticket"))
286                 ticket = vm["ticket"].as<std::string>();
287
288         if (ticket.IsEmpty()) {
289                 Log(LogInformation, "cli")
290                         << "Requesting certificate without a ticket.";
291         } else {
292                 Log(LogInformation, "cli")
293                         << "Requesting certificate with ticket '" << ticket << "'.";
294         }
295
296         /* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
297         bool connectToParent = false;
298         String parentHost;
299         String parentPort = "5665";
300         std::shared_ptr<X509> trustedParentCert;
301
302         /* TODO: remove master_host in 2.10.0. */
303         if (!vm.count("master_host") && !vm.count("parent_host")) {
304                 connectToParent = false;
305
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";
309         } else {
310                 connectToParent = true;
311
312                 String parentHostInfo;
313
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>();
318
319                 std::vector<String> tokens = parentHostInfo.Split(",");
320
321                 if (tokens.size() == 1 || tokens.size() == 2)
322                         parentHost = tokens[0];
323
324                 if (tokens.size() == 2)
325                         parentPort = tokens[1];
326
327                 Log(LogInformation, "cli")
328                         << "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";
329
330         }
331
332         /* retrieve CN and pass it (defaults to FQDN) */
333         String cn = Utility::GetFQDN();
334
335         if (vm.count("cn"))
336                 cn = vm["cn"].as<std::string>();
337
338         Log(LogInformation, "cli")
339                 << "Using the following CN (defaults to FQDN): '" << cn << "'.";
340
341         /* pki request a signed certificate from the master */
342         String certsDir = ApiListener::GetCertsDir();
343         Utility::MkDirP(certsDir, 0700);
344
345         String user = Configuration::RunAsUser;
346         String group = Configuration::RunAsGroup;
347
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!";
351         }
352
353         String key = certsDir + "/" + cn + ".key";
354         String cert = certsDir + "/" + cn + ".crt";
355         String ca = certsDir + "/ca.crt";
356
357         if (Utility::PathExists(key))
358                 NodeUtility::CreateBackupFile(key, true);
359         if (Utility::PathExists(cert))
360                 NodeUtility::CreateBackupFile(cert);
361
362         if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
363                 Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
364                 return 1;
365         }
366
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!";
371         }
372
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').
377                  */
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').";
382                         return 1;
383                 }
384
385                 trustedParentCert = GetX509Certificate(vm["trustedcert"].as<std::string>());
386
387                 Log(LogInformation, "cli")
388                         << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
389
390                 Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
391
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.";
397                         return 1;
398                 }
399         } else {
400                 /* We cannot retrieve the parent certificate.
401                  * Tell the user to manually copy the ca.crt file
402                  * into DataDir + "/certs"
403                  */
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";
408
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";
413                 }
414         }
415
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!";
419         }
420
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!";
425         }
426
427         /* disable the notifications feature */
428         Log(LogInformation, "cli", "Disabling the Notification feature.");
429
430         FeatureUtility::DisableFeatures({ "notification" });
431
432         /* enable the ApiListener config */
433
434         Log(LogInformation, "cli", "Updating the ApiListener feature.");
435
436         FeatureUtility::EnableFeatures({ "api" });
437
438         String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
439         NodeUtility::CreateBackupFile(apipath);
440
441         std::fstream fp;
442         String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
443
444         fp << "/**\n"
445                 << " * The API listener is used for distributed monitoring setups.\n"
446                 << " */\n"
447                 << "object ApiListener \"api\" {\n";
448
449         if (vm.count("listen")) {
450                 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
451
452                 if (tokens.size() > 0)
453                         fp << "  bind_host = \"" << tokens[0] << "\"\n";
454                 if (tokens.size() > 1)
455                         fp << "  bind_port = " << tokens[1] << "\n";
456         }
457
458         fp << "\n";
459
460         if (vm.count("accept-config"))
461                 fp << "  accept_config = true\n";
462         else
463                 fp << "  accept_config = false\n";
464
465         if (vm.count("accept-commands"))
466                 fp << "  accept_commands = true\n";
467         else
468                 fp << "  accept_commands = false\n";
469
470         fp << "\n"
471                 << "}\n";
472
473         fp.close();
474
475 #ifdef _WIN32
476         _unlink(apipath.CStr());
477 #endif /* _WIN32 */
478
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));
484         }
485
486
487         /* Generate zones configuration. */
488         Log(LogInformation, "cli", "Generating zone and object configuration.");
489
490         /* Setup command hardcodes this as FQDN */
491         String endpointName = cn;
492
493         /* Allow to specify zone name. */
494         String zoneName = vm["zone"].as<std::string>();
495
496         /* Allow to specify the parent zone name. */
497         String parentZoneName = "master";
498
499         if (vm.count("parent_zone"))
500                 parentZoneName = vm["parent_zone"].as<std::string>();
501
502         std::vector<String> globalZones { "global-templates", "director-global" };
503         std::vector<std::string> setupGlobalZones;
504
505         if (vm.count("global_zones"))
506                 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
507
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.";
512                         return 1;
513                 }
514         }
515
516         globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
517
518         /* Generate node configuration. */
519         NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);
520
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!";
525         }
526
527         NodeUtility::UpdateConstant("NodeName", cn);
528         NodeUtility::UpdateConstant("ZoneName", vm["zone"].as<std::string>());
529
530         if (!ticket.IsEmpty()) {
531                 String ticketPath = ApiListener::GetCertsDir() + "/ticket";
532
533                 String tempTicketPath = Utility::CreateTempFile(ticketPath + ".XXXXXX", 0600, fp);
534
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!";
540                 }
541
542                 fp << ticket;
543
544                 fp.close();
545
546 #ifdef _WIN32
547                 _unlink(ticketPath.CStr());
548 #endif /* _WIN32 */
549
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));
555                 }
556         }
557
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";
564         } else {
565                 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
566         }
567
568         if (vm.count("disable-confd")) {
569                 /* Disable conf.d inclusion */
570                 NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
571         }
572
573         /* tell the user to reload icinga2 */
574         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
575
576         return 0;
577 }