]> granicus.if.org Git - icinga2/blob - lib/cli/nodesetupcommand.cpp
Added ca restore command+docs to undo effects of ca remove
[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         Utility::RenameFile(tempApiPath, apipath);
211
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!";
216         }
217
218         NodeUtility::UpdateConstant("NodeName", endpointName);
219         NodeUtility::UpdateConstant("ZoneName", zoneName);
220
221         String salt = RandomString(16);
222
223         NodeUtility::UpdateConstant("TicketSalt", salt);
224
225         Log(LogInformation, "cli")
226                 << "Edit the api feature config file '" << apipath << "' and set a secure 'ticket_salt' attribute.";
227
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";
233                 } else {
234                         Log(LogWarning, "cli")
235                                 << "Tried to disable conf.d inclusion but failed, possibly it's already disabled.";
236                 }
237
238                 /* Include api-users.conf */
239                 String apiUsersFilePath = ApiSetupUtility::GetApiUsersConfPath();
240
241                 if (Utility::PathExists(apiUsersFilePath)) {
242                         NodeUtility::UpdateConfiguration("\"conf.d/api-users.conf\"", true, false);
243                 } else {
244                         Log(LogWarning, "cli")
245                                 << "Included file doesn't exist " << apiUsersFilePath;
246                 }
247         }
248
249         /* tell the user to reload icinga2 */
250         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
251
252         return 0;
253 }
254
255 int NodeSetupCommand::SetupNode(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap)
256 {
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).");
260                 return 1;
261         }
262
263         if (!vm.count("zone")) {
264                 Log(LogCritical, "cli", "You need to specify the local zone (--zone).");
265                 return 1;
266         }
267
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.");
273
274         String ticket;
275
276         if (vm.count("ticket"))
277                 ticket = vm["ticket"].as<std::string>();
278
279         if (ticket.IsEmpty()) {
280                 Log(LogInformation, "cli")
281                         << "Requesting certificate without a ticket.";
282         } else {
283                 Log(LogInformation, "cli")
284                         << "Requesting certificate with ticket '" << ticket << "'.";
285         }
286
287         /* Decide whether to directly connect to the parent node for CSR signing, or leave it to the user. */
288         bool connectToParent = false;
289         String parentHost;
290         String parentPort = "5665";
291         std::shared_ptr<X509> trustedParentCert;
292
293         /* TODO: remove master_host in 2.10.0. */
294         if (!vm.count("master_host") && !vm.count("parent_host")) {
295                 connectToParent = false;
296
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";
300         } else {
301                 connectToParent = true;
302
303                 String parentHostInfo;
304
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>();
309
310                 std::vector<String> tokens = parentHostInfo.Split(",");
311
312                 if (tokens.size() == 1 || tokens.size() == 2)
313                         parentHost = tokens[0];
314
315                 if (tokens.size() == 2)
316                         parentPort = tokens[1];
317
318                 Log(LogInformation, "cli")
319                         << "Verifying parent host connection information: host '" << parentHost << "', port '" << parentPort << "'.";
320
321         }
322
323         /* retrieve CN and pass it (defaults to FQDN) */
324         String cn = Utility::GetFQDN();
325
326         if (vm.count("cn"))
327                 cn = vm["cn"].as<std::string>();
328
329         Log(LogInformation, "cli")
330                 << "Using the following CN (defaults to FQDN): '" << cn << "'.";
331
332         /* pki request a signed certificate from the master */
333         String certsDir = ApiListener::GetCertsDir();
334         Utility::MkDirP(certsDir, 0700);
335
336         String user = Configuration::RunAsUser;
337         String group = Configuration::RunAsGroup;
338
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!";
342         }
343
344         String key = certsDir + "/" + cn + ".key";
345         String cert = certsDir + "/" + cn + ".crt";
346         String ca = certsDir + "/ca.crt";
347
348         if (Utility::PathExists(key))
349                 NodeUtility::CreateBackupFile(key, true);
350         if (Utility::PathExists(cert))
351                 NodeUtility::CreateBackupFile(cert);
352
353         if (PkiUtility::NewCert(cn, key, String(), cert) != 0) {
354                 Log(LogCritical, "cli", "Failed to generate new self-signed certificate.");
355                 return 1;
356         }
357
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!";
362         }
363
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').
368                  */
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').";
373                         return 1;
374                 }
375
376                 trustedParentCert = GetX509Certificate(vm["trustedcert"].as<std::string>());
377
378                 Log(LogInformation, "cli")
379                         << "Verifying trusted certificate file '" << vm["trustedcert"].as<std::string>() << "'.";
380
381                 Log(LogInformation, "cli", "Requesting a signed certificate from the parent Icinga node.");
382
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.";
388                         return 1;
389                 }
390         } else {
391                 /* We cannot retrieve the parent certificate.
392                  * Tell the user to manually copy the ca.crt file
393                  * into DataDir + "/certs"
394                  */
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";
399
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";
404                 }
405         }
406
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!";
410         }
411
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!";
416         }
417
418         /* disable the notifications feature */
419         Log(LogInformation, "cli", "Disabling the Notification feature.");
420
421         FeatureUtility::DisableFeatures({ "notification" });
422
423         /* enable the ApiListener config */
424
425         Log(LogInformation, "cli", "Updating the ApiListener feature.");
426
427         FeatureUtility::EnableFeatures({ "api" });
428
429         String apipath = FeatureUtility::GetFeaturesAvailablePath() + "/api.conf";
430         NodeUtility::CreateBackupFile(apipath);
431
432         std::fstream fp;
433         String tempApiPath = Utility::CreateTempFile(apipath + ".XXXXXX", 0644, fp);
434
435         fp << "/**\n"
436                 << " * The API listener is used for distributed monitoring setups.\n"
437                 << " */\n"
438                 << "object ApiListener \"api\" {\n";
439
440         if (vm.count("listen")) {
441                 std::vector<String> tokens = String(vm["listen"].as<std::string>()).Split(",");
442
443                 if (tokens.size() > 0)
444                         fp << "  bind_host = \"" << tokens[0] << "\"\n";
445                 if (tokens.size() > 1)
446                         fp << "  bind_port = " << tokens[1] << "\n";
447         }
448
449         fp << "\n";
450
451         if (vm.count("accept-config"))
452                 fp << "  accept_config = true\n";
453         else
454                 fp << "  accept_config = false\n";
455
456         if (vm.count("accept-commands"))
457                 fp << "  accept_commands = true\n";
458         else
459                 fp << "  accept_commands = false\n";
460
461         fp << "\n"
462                 << "}\n";
463
464         fp.close();
465
466         Utility::RenameFile(tempApiPath, apipath);
467
468         /* Generate zones configuration. */
469         Log(LogInformation, "cli", "Generating zone and object configuration.");
470
471         /* Setup command hardcodes this as FQDN */
472         String endpointName = cn;
473
474         /* Allow to specify zone name. */
475         String zoneName = vm["zone"].as<std::string>();
476
477         /* Allow to specify the parent zone name. */
478         String parentZoneName = "master";
479
480         if (vm.count("parent_zone"))
481                 parentZoneName = vm["parent_zone"].as<std::string>();
482
483         std::vector<String> globalZones { "global-templates", "director-global" };
484         std::vector<std::string> setupGlobalZones;
485
486         if (vm.count("global_zones"))
487                 setupGlobalZones = vm["global_zones"].as<std::vector<std::string> >();
488
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.";
493                         return 1;
494                 }
495         }
496
497         globalZones.insert(globalZones.end(), setupGlobalZones.begin(), setupGlobalZones.end());
498
499         /* Generate node configuration. */
500         NodeUtility::GenerateNodeIcingaConfig(endpointName, zoneName, parentZoneName, vm["endpoint"].as<std::vector<std::string> >(), globalZones);
501
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!";
507         }
508
509         NodeUtility::UpdateConstant("NodeName", endpointName);
510         NodeUtility::UpdateConstant("ZoneName", zoneName);
511
512         if (!ticket.IsEmpty()) {
513                 String ticketPath = ApiListener::GetCertsDir() + "/ticket";
514
515                 String tempTicketPath = Utility::CreateTempFile(ticketPath + ".XXXXXX", 0600, fp);
516
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!";
522                 }
523
524                 fp << ticket;
525
526                 fp.close();
527
528                 Utility::RenameFile(tempTicketPath, ticketPath);
529         }
530
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";
537         } else {
538                 Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
539         }
540
541         if (vm.count("disable-confd")) {
542                 /* Disable conf.d inclusion */
543                 NodeUtility::UpdateConfiguration("\"conf.d\"", false, true);
544         }
545
546         /* tell the user to reload icinga2 */
547         Log(LogInformation, "cli", "Make sure to restart Icinga 2.");
548
549         return 0;
550 }